Add unit test for the Settings API Bubble.
[chromium-blink-merge.git] / chrome / browser / ui / autofill / autofill_dialog_controller_impl.cc
blob188f72c2ed56d1f8e52fccd8a70cb138e15ff676
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.
5 #include "chrome/browser/ui/autofill/autofill_dialog_controller_impl.h"
7 #include <algorithm>
8 #include <map>
9 #include <string>
11 #include "apps/app_window.h"
12 #include "apps/app_window_registry.h"
13 #include "apps/ui/native_app_window.h"
14 #include "base/base64.h"
15 #include "base/bind.h"
16 #include "base/bind_helpers.h"
17 #include "base/i18n/case_conversion.h"
18 #include "base/i18n/rtl.h"
19 #include "base/logging.h"
20 #include "base/prefs/pref_registry_simple.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/prefs/scoped_user_pref_update.h"
23 #include "base/rand_util.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_split.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/time/time.h"
28 #include "chrome/browser/autofill/personal_data_manager_factory.h"
29 #include "chrome/browser/autofill/validation_rules_storage_factory.h"
30 #include "chrome/browser/browser_process.h"
31 #include "chrome/browser/profiles/profile.h"
32 #include "chrome/browser/ui/autofill/autofill_dialog_common.h"
33 #include "chrome/browser/ui/autofill/autofill_dialog_i18n_input.h"
34 #include "chrome/browser/ui/autofill/autofill_dialog_view.h"
35 #include "chrome/browser/ui/autofill/data_model_wrapper.h"
36 #include "chrome/browser/ui/autofill/generated_credit_card_bubble_controller.h"
37 #include "chrome/browser/ui/autofill/new_credit_card_bubble_controller.h"
38 #include "chrome/browser/ui/browser.h"
39 #include "chrome/browser/ui/browser_finder.h"
40 #include "chrome/browser/ui/browser_navigator.h"
41 #include "chrome/browser/ui/browser_window.h"
42 #include "chrome/common/chrome_content_client.h"
43 #include "chrome/common/chrome_version_info.h"
44 #include "chrome/common/pref_names.h"
45 #include "chrome/common/render_messages.h"
46 #include "chrome/common/url_constants.h"
47 #include "components/autofill/content/browser/risk/fingerprint.h"
48 #include "components/autofill/content/browser/risk/proto/fingerprint.pb.h"
49 #include "components/autofill/content/browser/wallet/form_field_error.h"
50 #include "components/autofill/content/browser/wallet/full_wallet.h"
51 #include "components/autofill/content/browser/wallet/gaia_account.h"
52 #include "components/autofill/content/browser/wallet/instrument.h"
53 #include "components/autofill/content/browser/wallet/wallet_address.h"
54 #include "components/autofill/content/browser/wallet/wallet_items.h"
55 #include "components/autofill/content/browser/wallet/wallet_service_url.h"
56 #include "components/autofill/content/browser/wallet/wallet_signin_helper.h"
57 #include "components/autofill/core/browser/autofill_country.h"
58 #include "components/autofill/core/browser/autofill_data_model.h"
59 #include "components/autofill/core/browser/autofill_manager.h"
60 #include "components/autofill/core/browser/autofill_type.h"
61 #include "components/autofill/core/browser/personal_data_manager.h"
62 #include "components/autofill/core/browser/phone_number_i18n.h"
63 #include "components/autofill/core/browser/validation.h"
64 #include "components/autofill/core/common/autofill_pref_names.h"
65 #include "components/autofill/core/common/form_data.h"
66 #include "components/user_prefs/pref_registry_syncable.h"
67 #include "content/public/browser/browser_thread.h"
68 #include "content/public/browser/geolocation_provider.h"
69 #include "content/public/browser/navigation_controller.h"
70 #include "content/public/browser/navigation_details.h"
71 #include "content/public/browser/navigation_entry.h"
72 #include "content/public/browser/notification_service.h"
73 #include "content/public/browser/notification_types.h"
74 #include "content/public/browser/render_view_host.h"
75 #include "content/public/browser/web_contents.h"
76 #include "content/public/browser/web_contents_view.h"
77 #include "content/public/common/url_constants.h"
78 #include "grit/chromium_strings.h"
79 #include "grit/component_scaled_resources.h"
80 #include "grit/component_strings.h"
81 #include "grit/generated_resources.h"
82 #include "grit/libaddressinput_strings.h"
83 #include "grit/platform_locale_settings.h"
84 #include "grit/theme_resources.h"
85 #include "net/cert/cert_status_flags.h"
86 #include "third_party/libaddressinput/chromium/chrome_downloader_impl.h"
87 #include "third_party/libaddressinput/chromium/chrome_storage_impl.h"
88 #include "third_party/libaddressinput/chromium/cpp/include/libaddressinput/address_data.h"
89 #include "third_party/libaddressinput/chromium/cpp/include/libaddressinput/address_problem.h"
90 #include "ui/base/base_window.h"
91 #include "ui/base/l10n/l10n_util.h"
92 #include "ui/base/models/combobox_model.h"
93 #include "ui/base/resource/resource_bundle.h"
94 #include "ui/events/event.h"
95 #include "ui/gfx/canvas.h"
96 #include "ui/gfx/image/image_skia_operations.h"
97 #include "ui/gfx/skia_util.h"
99 using ::i18n::addressinput::AddressData;
100 using ::i18n::addressinput::AddressField;
101 using ::i18n::addressinput::AddressProblem;
102 using ::i18n::addressinput::AddressProblemFilter;
103 using ::i18n::addressinput::AddressProblems;
104 using ::i18n::addressinput::AddressValidator;
106 namespace autofill {
108 namespace {
110 const char kAddNewItemKey[] = "add-new-item";
111 const char kManageItemsKey[] = "manage-items";
112 const char kSameAsBillingKey[] = "same-as-billing";
114 // URLs for Wallet error messages.
115 const char kBuyerLegalAddressStatusUrl[] =
116 "https://wallet.google.com/manage/settings";
117 const char kKnowYourCustomerStatusUrl[] = "https://wallet.google.com/kyc";
119 // Keys for the kAutofillDialogAutofillDefault pref dictionary (do not change
120 // these values).
121 const char kGuidPrefKey[] = "guid";
123 // This string is stored along with saved addresses and credit cards in the
124 // WebDB, and hence should not be modified, so that it remains consistent over
125 // time.
126 const char kAutofillDialogOrigin[] = "Chrome Autofill dialog";
128 // HSL shift to gray out an image.
129 const color_utils::HSL kGrayImageShift = {-1, 0, 0.8};
131 // Limit Wallet items refresh rate to at most once per minute.
132 const int64 kWalletItemsRefreshRateSeconds = 60;
134 // The number of milliseconds to delay enabling the submit button after showing
135 // the dialog. This delay prevents users from accidentally clicking the submit
136 // button on startup.
137 const int kSubmitButtonDelayMs = 1000;
139 // A helper class to make sure an AutofillDialogView knows when a series of
140 // updates is incoming.
141 class ScopedViewUpdates {
142 public:
143 explicit ScopedViewUpdates(AutofillDialogView* view) : view_(view) {
144 if (view_)
145 view_->UpdatesStarted();
148 ~ScopedViewUpdates() {
149 if (view_)
150 view_->UpdatesFinished();
153 private:
154 AutofillDialogView* view_;
156 DISALLOW_COPY_AND_ASSIGN(ScopedViewUpdates);
159 base::string16 NullGetInfo(const AutofillType& type) {
160 return base::string16();
163 // Extract |type| from |inputs| using |section| to determine whether the info
164 // should be billing or shipping specific (for sections with address info).
165 base::string16 GetInfoFromInputs(const FieldValueMap& inputs,
166 DialogSection section,
167 const AutofillType& type) {
168 ServerFieldType field_type = type.GetStorableType();
169 if (section != SECTION_SHIPPING)
170 field_type = AutofillType::GetEquivalentBillingFieldType(field_type);
172 base::string16 info;
173 FieldValueMap::const_iterator it = inputs.find(field_type);
174 if (it != inputs.end())
175 info = it->second;
177 if (!info.empty() && type.html_type() == HTML_TYPE_COUNTRY_CODE) {
178 info = base::ASCIIToUTF16(AutofillCountry::GetCountryCode(
179 info, g_browser_process->GetApplicationLocale()));
182 return info;
185 // Returns true if |input| should be used to fill a site-requested |field| which
186 // is notated with a "shipping" tag, for use when the user has decided to use
187 // the billing address as the shipping address.
188 bool ServerTypeMatchesShippingField(ServerFieldType type,
189 const AutofillField& field) {
190 // Equivalent billing field type is used to support UseBillingAsShipping
191 // usecase.
192 return common::ServerTypeEncompassesFieldType(
193 type,
194 AutofillType(AutofillType::GetEquivalentBillingFieldType(
195 field.Type().GetStorableType())));
198 // Initializes |form_group| from user-entered data.
199 void FillFormGroupFromOutputs(const FieldValueMap& detail_outputs,
200 FormGroup* form_group) {
201 for (FieldValueMap::const_iterator iter = detail_outputs.begin();
202 iter != detail_outputs.end(); ++iter) {
203 ServerFieldType type = iter->first;
204 if (!iter->second.empty()) {
205 if (type == ADDRESS_HOME_COUNTRY || type == ADDRESS_BILLING_COUNTRY) {
206 form_group->SetInfo(AutofillType(type),
207 iter->second,
208 g_browser_process->GetApplicationLocale());
209 } else {
210 form_group->SetRawInfo(
211 AutofillType(type).GetStorableType(), iter->second);
217 // Get billing info from |output| and put it into |card|, |cvc|, and |profile|.
218 // These outparams are required because |card|/|profile| accept different types
219 // of raw info, and CreditCard doesn't save CVCs.
220 void GetBillingInfoFromOutputs(const FieldValueMap& output,
221 CreditCard* card,
222 base::string16* cvc,
223 AutofillProfile* profile) {
224 for (FieldValueMap::const_iterator it = output.begin();
225 it != output.end(); ++it) {
226 const ServerFieldType type = it->first;
227 base::string16 trimmed;
228 base::TrimWhitespace(it->second, base::TRIM_ALL, &trimmed);
230 // Special case CVC as CreditCard just swallows it.
231 if (type == CREDIT_CARD_VERIFICATION_CODE) {
232 if (cvc)
233 cvc->assign(trimmed);
234 } else if (type == ADDRESS_HOME_COUNTRY ||
235 type == ADDRESS_BILLING_COUNTRY) {
236 if (profile) {
237 profile->SetInfo(AutofillType(type),
238 trimmed,
239 g_browser_process->GetApplicationLocale());
241 } else {
242 // Copy the credit card name to |profile| in addition to |card| as
243 // wallet::Instrument requires a recipient name for its billing address.
244 if (card && type == NAME_FULL)
245 card->SetRawInfo(CREDIT_CARD_NAME, trimmed);
247 if (common::IsCreditCardType(type)) {
248 if (card)
249 card->SetRawInfo(type, trimmed);
250 } else if (profile) {
251 profile->SetRawInfo(AutofillType(type).GetStorableType(), trimmed);
257 // Returns the containing window for the given |web_contents|. The containing
258 // window might be a browser window for a Chrome tab, or it might be an app
259 // window for a platform app.
260 ui::BaseWindow* GetBaseWindowForWebContents(
261 const content::WebContents* web_contents) {
262 Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
263 if (browser)
264 return browser->window();
266 gfx::NativeWindow native_window =
267 web_contents->GetView()->GetTopLevelNativeWindow();
268 apps::AppWindow* app_window =
269 apps::AppWindowRegistry::GetAppWindowForNativeWindowAnyProfile(
270 native_window);
271 return app_window->GetBaseWindow();
274 // Returns a string descriptor for a DialogSection, for use with prefs (do not
275 // change these values).
276 std::string SectionToPrefString(DialogSection section) {
277 switch (section) {
278 case SECTION_CC:
279 return "cc";
281 case SECTION_BILLING:
282 return "billing";
284 case SECTION_CC_BILLING:
285 // The SECTION_CC_BILLING section isn't active when using Autofill.
286 NOTREACHED();
287 return std::string();
289 case SECTION_SHIPPING:
290 return "shipping";
293 NOTREACHED();
294 return std::string();
297 // Check if a given MaskedInstrument is allowed for the purchase.
298 bool IsInstrumentAllowed(
299 const wallet::WalletItems::MaskedInstrument& instrument) {
300 switch (instrument.status()) {
301 case wallet::WalletItems::MaskedInstrument::VALID:
302 case wallet::WalletItems::MaskedInstrument::PENDING:
303 case wallet::WalletItems::MaskedInstrument::EXPIRED:
304 case wallet::WalletItems::MaskedInstrument::BILLING_INCOMPLETE:
305 return true;
306 default:
307 return false;
311 // Signals that the user has opted in to geolocation services. Factored out
312 // into a separate method because all interaction with the geolocation provider
313 // needs to happen on the IO thread, which is not the thread
314 // AutofillDialogViewDelegate lives on.
315 void UserDidOptIntoLocationServices() {
316 content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
319 // Loops through |addresses_| comparing to |address| ignoring ID. If a match
320 // is not found, NULL is returned.
321 const wallet::Address* FindDuplicateAddress(
322 const std::vector<wallet::Address*>& addresses,
323 const wallet::Address& address) {
324 for (size_t i = 0; i < addresses.size(); ++i) {
325 if (addresses[i]->EqualsIgnoreID(address))
326 return addresses[i];
328 return NULL;
331 bool IsCardHolderNameValidForWallet(const base::string16& name) {
332 base::string16 whitespace_collapsed_name =
333 base::CollapseWhitespace(name, true);
334 std::vector<base::string16> split_name;
335 base::SplitString(whitespace_collapsed_name, ' ', &split_name);
336 return split_name.size() >= 2;
339 DialogSection SectionFromLocation(wallet::FormFieldError::Location location) {
340 switch (location) {
341 case wallet::FormFieldError::PAYMENT_INSTRUMENT:
342 case wallet::FormFieldError::LEGAL_ADDRESS:
343 return SECTION_CC_BILLING;
345 case wallet::FormFieldError::SHIPPING_ADDRESS:
346 return SECTION_SHIPPING;
348 case wallet::FormFieldError::UNKNOWN_LOCATION:
349 NOTREACHED();
350 return SECTION_MAX;
353 NOTREACHED();
354 return SECTION_MAX;
357 scoped_ptr<DialogNotification> GetWalletError(
358 wallet::WalletClient::ErrorType error_type) {
359 base::string16 text;
360 GURL url;
362 switch (error_type) {
363 case wallet::WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS:
364 text = l10n_util::GetStringUTF16(
365 IDS_AUTOFILL_WALLET_UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS);
366 url = GURL(kKnowYourCustomerStatusUrl);
367 break;
369 case wallet::WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED:
370 text = l10n_util::GetStringUTF16(
371 IDS_AUTOFILL_WALLET_BUYER_COUNTRY_NOT_SUPPORTED);
372 url = GURL(kBuyerLegalAddressStatusUrl);
373 break;
375 default:
376 // The notification will not have a link; it's handled in the next
377 // switch statement.
378 break;
381 if (!text.empty()) {
382 scoped_ptr<DialogNotification> notification(new DialogNotification(
383 DialogNotification::WALLET_ERROR,
384 text));
385 notification->set_link_url(url);
386 return notification.Pass();
389 int error_ids = 0;
390 int error_code = 0;
392 switch (error_type) {
393 case wallet::WalletClient::UNSUPPORTED_MERCHANT:
394 error_ids = IDS_AUTOFILL_WALLET_UNSUPPORTED_MERCHANT;
395 break;
397 case wallet::WalletClient::BAD_REQUEST:
398 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
399 error_code = 71;
400 break;
402 case wallet::WalletClient::INVALID_PARAMS:
403 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
404 error_code = 42;
405 break;
407 case wallet::WalletClient::BUYER_ACCOUNT_ERROR:
408 error_ids = IDS_AUTOFILL_WALLET_BUYER_ACCOUNT_ERROR;
409 error_code = 12;
410 break;
412 case wallet::WalletClient::UNSUPPORTED_API_VERSION:
413 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
414 error_code = 43;
415 break;
417 case wallet::WalletClient::SERVICE_UNAVAILABLE:
418 error_ids = IDS_AUTOFILL_WALLET_SERVICE_UNAVAILABLE_ERROR;
419 error_code = 61;
420 break;
422 case wallet::WalletClient::INTERNAL_ERROR:
423 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
424 error_code = 62;
425 break;
427 case wallet::WalletClient::MALFORMED_RESPONSE:
428 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
429 error_code = 72;
430 break;
432 case wallet::WalletClient::NETWORK_ERROR:
433 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
434 error_code = 73;
435 break;
437 case wallet::WalletClient::UNKNOWN_ERROR:
438 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
439 error_code = 74;
440 break;
442 case wallet::WalletClient::UNSUPPORTED_USER_AGENT_OR_API_KEY:
443 error_ids = IDS_AUTOFILL_WALLET_UNSUPPORTED_AGENT_OR_API_KEY;
444 error_code = 75;
445 break;
447 default:
448 break;
451 DCHECK_NE(0, error_ids);
453 // The other error types are strings of the form "XXX. You can pay without
454 // wallet."
455 scoped_ptr<DialogNotification> notification(new DialogNotification(
456 DialogNotification::WALLET_ERROR,
457 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_COMPLETE_WITHOUT_WALLET,
458 l10n_util::GetStringUTF16(error_ids))));
460 if (error_code) {
461 notification->set_tooltip_text(
462 l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_ERROR_CODE_TOOLTIP,
463 base::IntToString16(error_code)));
466 return notification.Pass();
469 // Returns the ID of the address or instrument that should be selected in the
470 // UI, given that the |default_id| is currently the default ID on the Wallet
471 // server, |previous_default_id| was the default ID prior to re-fetching the
472 // Wallet data, and |previously_selected_id| was the ID of the item selected in
473 // the dialog prior to re-fetching the Wallet data.
474 std::string GetIdToSelect(const std::string& default_id,
475 const std::string& previous_default_id,
476 const std::string& previously_selected_id) {
477 // If the default ID changed since the last fetch of the Wallet data, select
478 // it rather than the previously selected item, as the user's intention in
479 // changing the default was probably to use it.
480 if (default_id != previous_default_id)
481 return default_id;
483 // Otherwise, prefer the previously selected item, if there was one.
484 return !previously_selected_id.empty() ? previously_selected_id : default_id;
487 // Generate a random card number in a user displayable format.
488 base::string16 GenerateRandomCardNumber() {
489 std::string card_number;
490 for (size_t i = 0; i < 4; ++i) {
491 int part = base::RandInt(0, 10000);
492 base::StringAppendF(&card_number, "%04d ", part);
494 return base::ASCIIToUTF16(card_number);
497 gfx::Image CreditCardIconForType(const std::string& credit_card_type) {
498 const int input_card_idr = CreditCard::IconResourceId(credit_card_type);
499 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
500 gfx::Image result = rb.GetImageNamed(input_card_idr);
501 if (input_card_idr == IDR_AUTOFILL_CC_GENERIC) {
502 // When the credit card type is unknown, no image should be shown. However,
503 // to simplify the view code on Mac, save space for the credit card image by
504 // returning a transparent image of the appropriate size. Not all credit
505 // card images are the same size, but none is larger than the Visa icon.
506 result = gfx::Image(gfx::ImageSkiaOperations::CreateTransparentImage(
507 rb.GetImageNamed(IDR_AUTOFILL_CC_VISA).AsImageSkia(), 0));
509 return result;
512 gfx::Image CvcIconForCreditCardType(const base::string16& credit_card_type) {
513 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
514 if (credit_card_type == l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX))
515 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT_AMEX);
517 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT);
520 ServerFieldType CountryTypeForSection(DialogSection section) {
521 return section == SECTION_SHIPPING ? ADDRESS_HOME_COUNTRY :
522 ADDRESS_BILLING_COUNTRY;
525 // profile.GetInfo() thunk.
526 base::string16 GetInfoFromProfile(const AutofillProfile& profile,
527 const AutofillType& type) {
528 return profile.GetInfo(type, g_browser_process->GetApplicationLocale());
531 // Attempts to canonicalize the administrative area name in |profile| using the
532 // rules in |validator|.
533 void CanonicalizeState(const AddressValidator* validator,
534 AutofillProfile* profile) {
535 base::string16 administrative_area;
536 AddressData address_data;
537 i18ninput::CreateAddressData(base::Bind(&GetInfoFromProfile, *profile),
538 &address_data);
540 validator->CanonicalizeAdministrativeArea(&address_data);
541 administrative_area = base::UTF8ToUTF16(address_data.administrative_area);
543 profile->SetInfo(AutofillType(ADDRESS_HOME_STATE),
544 administrative_area,
545 g_browser_process->GetApplicationLocale());
548 ValidityMessage GetPhoneValidityMessage(const base::string16& country_name,
549 const base::string16& number) {
550 std::string region = AutofillCountry::GetCountryCode(
551 country_name,
552 g_browser_process->GetApplicationLocale());
553 i18n::PhoneObject phone_object(number, region);
554 ValidityMessage phone_message(base::string16(), true);
556 // Check if the phone number is invalid. Allow valid international
557 // numbers that don't match the address's country only if they have an
558 // international calling code.
559 if (!phone_object.IsValidNumber() ||
560 (phone_object.country_code().empty() &&
561 phone_object.region() != region)) {
562 phone_message.text = l10n_util::GetStringUTF16(
563 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER);
566 return phone_message;
569 } // namespace
571 AutofillDialogViewDelegate::~AutofillDialogViewDelegate() {}
573 AutofillDialogControllerImpl::~AutofillDialogControllerImpl() {
574 if (popup_controller_)
575 popup_controller_->Hide();
577 GetMetricLogger().LogDialogInitialUserState(initial_user_state_);
580 bool CountryFilter(const std::set<base::string16>& possible_values,
581 const std::string& country_code) {
582 if (!i18ninput::CountryIsFullySupported(country_code))
583 return false;
585 if (!possible_values.empty() &&
586 !possible_values.count(base::ASCIIToUTF16(country_code))) {
587 return false;
590 return true;
593 // static
594 base::WeakPtr<AutofillDialogControllerImpl>
595 AutofillDialogControllerImpl::Create(
596 content::WebContents* contents,
597 const FormData& form_structure,
598 const GURL& source_url,
599 const base::Callback<void(const FormStructure*)>& callback) {
600 // AutofillDialogControllerImpl owns itself.
601 AutofillDialogControllerImpl* autofill_dialog_controller =
602 new AutofillDialogControllerImpl(contents,
603 form_structure,
604 source_url,
605 callback);
606 return autofill_dialog_controller->weak_ptr_factory_.GetWeakPtr();
609 // static
610 void AutofillDialogController::RegisterPrefs(PrefRegistrySimple* registry) {
611 registry->RegisterListPref(::prefs::kAutofillDialogWalletLocationAcceptance);
614 // static
615 void AutofillDialogController::RegisterProfilePrefs(
616 user_prefs::PrefRegistrySyncable* registry) {
617 registry->RegisterBooleanPref(
618 ::prefs::kAutofillDialogPayWithoutWallet,
619 false,
620 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
621 registry->RegisterDictionaryPref(
622 ::prefs::kAutofillDialogAutofillDefault,
623 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
624 registry->RegisterBooleanPref(
625 ::prefs::kAutofillDialogSaveData,
626 true,
627 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
628 registry->RegisterBooleanPref(
629 ::prefs::kAutofillDialogWalletShippingSameAsBilling,
630 false,
631 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
634 // static
635 base::WeakPtr<AutofillDialogController> AutofillDialogController::Create(
636 content::WebContents* contents,
637 const FormData& form_structure,
638 const GURL& source_url,
639 const base::Callback<void(const FormStructure*)>& callback) {
640 return AutofillDialogControllerImpl::Create(contents,
641 form_structure,
642 source_url,
643 callback);
646 void AutofillDialogControllerImpl::Show() {
647 dialog_shown_timestamp_ = base::Time::Now();
649 // Determine what field types should be included in the dialog.
650 bool has_types = false;
651 bool has_sections = false;
652 form_structure_.ParseFieldTypesFromAutocompleteAttributes(
653 &has_types, &has_sections);
655 // Fail if the author didn't specify autocomplete types.
656 if (!has_types) {
657 callback_.Run(NULL);
658 delete this;
659 return;
662 billing_country_combobox_model_.reset(new CountryComboboxModel(
663 *GetManager(),
664 base::Bind(CountryFilter,
665 form_structure_.PossibleValues(ADDRESS_BILLING_COUNTRY))));
666 shipping_country_combobox_model_.reset(new CountryComboboxModel(
667 *GetManager(),
668 base::Bind(CountryFilter,
669 form_structure_.PossibleValues(ADDRESS_HOME_COUNTRY))));
671 // Log any relevant UI metrics and security exceptions.
672 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_SHOWN);
674 GetMetricLogger().LogDialogSecurityMetric(
675 AutofillMetrics::SECURITY_METRIC_DIALOG_SHOWN);
677 // The Autofill dialog is shown in response to a message from the renderer and
678 // as such, it can only be made in the context of the current document. A call
679 // to GetActiveEntry would return a pending entry, if there was one, which
680 // would be a security bug. Therefore, we use the last committed URL for the
681 // access checks.
682 const GURL& current_url = web_contents()->GetLastCommittedURL();
683 invoked_from_same_origin_ =
684 current_url.GetOrigin() == source_url_.GetOrigin();
686 if (!invoked_from_same_origin_) {
687 GetMetricLogger().LogDialogSecurityMetric(
688 AutofillMetrics::SECURITY_METRIC_CROSS_ORIGIN_FRAME);
691 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
692 DialogSection section = static_cast<DialogSection>(i);
694 std::string country_code;
695 CountryComboboxModel* model = CountryComboboxModelForSection(section);
696 if (model)
697 country_code = model->GetDefaultCountryCode();
699 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
700 common::BuildInputsForSection(section, country_code, inputs);
703 // Test whether we need to show the shipping section. If filling that section
704 // would be a no-op, don't show it.
705 cares_about_shipping_ = form_structure_.FillFields(
706 RequestedTypesForSection(SECTION_SHIPPING),
707 base::Bind(common::ServerTypeMatchesField, SECTION_SHIPPING),
708 base::Bind(NullGetInfo),
709 g_browser_process->GetApplicationLocale());
711 account_chooser_model_.reset(
712 new AccountChooserModel(this,
713 profile_,
714 !ShouldShowAccountChooser(),
715 metric_logger_));
717 if (account_chooser_model_->WalletIsSelected())
718 FetchWalletCookie();
720 scoped_ptr< ::i18n::addressinput::Downloader> downloader(
721 new autofill::ChromeDownloaderImpl(profile_->GetRequestContext()));
722 validator_ = AddressValidator::Build(
723 downloader.Pass(),
724 ValidationRulesStorageFactory::CreateStorage(),
725 this);
726 GetValidator()->LoadRules(
727 GetManager()->GetDefaultCountryCodeForNewAddress());
729 // TODO(estade): don't show the dialog if the site didn't specify the right
730 // fields. First we must figure out what the "right" fields are.
731 SuggestionsUpdated();
732 SubmitButtonDelayBegin();
733 view_.reset(CreateView());
734 view_->Show();
735 GetManager()->AddObserver(this);
737 if (!account_chooser_model_->WalletIsSelected())
738 LogDialogLatencyToShow();
741 void AutofillDialogControllerImpl::Hide() {
742 if (view_)
743 view_->Hide();
746 void AutofillDialogControllerImpl::TabActivated() {
747 // If the user switched away from this tab and then switched back, reload the
748 // Wallet items, in case they've changed.
749 int64 seconds_elapsed_since_last_refresh =
750 (base::TimeTicks::Now() - last_wallet_items_fetch_timestamp_).InSeconds();
751 if (IsPayingWithWallet() && wallet_items_ &&
752 seconds_elapsed_since_last_refresh >= kWalletItemsRefreshRateSeconds) {
753 GetWalletItems();
757 ////////////////////////////////////////////////////////////////////////////////
758 // AutofillDialogViewDelegate implementation.
760 base::string16 AutofillDialogControllerImpl::DialogTitle() const {
761 if (ShouldShowSpinner())
762 return base::string16();
764 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TITLE);
767 base::string16 AutofillDialogControllerImpl::AccountChooserText() const {
768 if (!account_chooser_model_->WalletIsSelected())
769 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PAYING_WITHOUT_WALLET);
771 if (SignedInState() == SIGNED_IN)
772 return account_chooser_model_->GetActiveWalletAccountName();
774 // In this case, the account chooser should be showing the signin link.
775 return base::string16();
778 base::string16 AutofillDialogControllerImpl::SignInLinkText() const {
779 int ids = SignedInState() == NOT_CHECKED ?
780 IDS_AUTOFILL_DIALOG_USE_WALLET_LINK :
781 ShouldShowSignInWebView() ? IDS_AUTOFILL_DIALOG_CANCEL_SIGN_IN :
782 IDS_AUTOFILL_DIALOG_SIGN_IN;
784 return l10n_util::GetStringUTF16(ids);
787 base::string16 AutofillDialogControllerImpl::SpinnerText() const {
788 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_LOADING);
791 base::string16 AutofillDialogControllerImpl::EditSuggestionText() const {
792 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_EDIT);
795 base::string16 AutofillDialogControllerImpl::CancelButtonText() const {
796 return l10n_util::GetStringUTF16(IDS_CANCEL);
799 base::string16 AutofillDialogControllerImpl::ConfirmButtonText() const {
800 return l10n_util::GetStringUTF16(IsSubmitPausedOn(wallet::VERIFY_CVV) ?
801 IDS_AUTOFILL_DIALOG_VERIFY_BUTTON : IDS_AUTOFILL_DIALOG_SUBMIT_BUTTON);
804 base::string16 AutofillDialogControllerImpl::SaveLocallyText() const {
805 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_CHECKBOX);
808 base::string16 AutofillDialogControllerImpl::SaveLocallyTooltip() const {
809 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_TOOLTIP);
812 base::string16 AutofillDialogControllerImpl::LegalDocumentsText() {
813 if (!IsPayingWithWallet() || ShouldShowSignInWebView())
814 return base::string16();
816 return legal_documents_text_;
819 bool AutofillDialogControllerImpl::ShouldShowSpinner() const {
820 return SignedInState() == REQUIRES_RESPONSE ||
821 SignedInState() == REQUIRES_PASSIVE_SIGN_IN;
824 bool AutofillDialogControllerImpl::ShouldShowAccountChooser() const {
825 return !ShouldShowSpinner() && GetManager()->IsCountryOfInterest("US");
828 bool AutofillDialogControllerImpl::ShouldShowSignInWebView() const {
829 return !signin_registrar_.IsEmpty();
832 GURL AutofillDialogControllerImpl::SignInUrl() const {
833 return wallet::GetSignInUrl();
836 bool AutofillDialogControllerImpl::ShouldOfferToSaveInChrome() const {
837 return IsAutofillEnabled() &&
838 !IsPayingWithWallet() &&
839 !profile_->IsOffTheRecord() &&
840 IsManuallyEditingAnySection() &&
841 !ShouldShowSpinner();
844 bool AutofillDialogControllerImpl::ShouldSaveInChrome() const {
845 return profile_->GetPrefs()->GetBoolean(::prefs::kAutofillDialogSaveData);
848 int AutofillDialogControllerImpl::GetDialogButtons() const {
849 if (waiting_for_explicit_sign_in_response_)
850 return ui::DIALOG_BUTTON_NONE;
852 if (ShouldShowSpinner() && !handling_use_wallet_link_click_)
853 return ui::DIALOG_BUTTON_CANCEL;
855 return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
858 bool AutofillDialogControllerImpl::IsDialogButtonEnabled(
859 ui::DialogButton button) const {
860 if (button == ui::DIALOG_BUTTON_OK) {
861 if (IsSubmitPausedOn(wallet::VERIFY_CVV))
862 return true;
864 if (ShouldShowSpinner() || is_submitting_)
865 return false;
867 if (submit_button_delay_timer_.IsRunning())
868 return false;
870 return true;
873 DCHECK_EQ(ui::DIALOG_BUTTON_CANCEL, button);
874 return !is_submitting_ || IsSubmitPausedOn(wallet::VERIFY_CVV);
877 DialogOverlayState AutofillDialogControllerImpl::GetDialogOverlay() {
878 bool show_wallet_interstitial = IsPayingWithWallet() && is_submitting_ &&
879 !(full_wallet_ && !full_wallet_->required_actions().empty());
880 if (!show_wallet_interstitial) {
881 card_scrambling_delay_.Stop();
882 card_scrambling_refresher_.Stop();
883 return DialogOverlayState();
886 ui::ResourceBundle* rb = &ui::ResourceBundle::GetSharedInstance();
887 DialogOverlayState state;
888 state.string.font_list = rb->GetFontList(ui::ResourceBundle::MediumFont);
890 const SkColor start_top_color = SkColorSetRGB(0xD6, 0xD6, 0xD6);
891 const SkColor start_bottom_color = SkColorSetRGB(0x98, 0x98, 0x98);
892 const SkColor final_top_color = SkColorSetRGB(0x52, 0x9F, 0xF8);
893 const SkColor final_bottom_color = SkColorSetRGB(0x22, 0x75, 0xE5);
895 if (full_wallet_ && full_wallet_->required_actions().empty()) {
896 card_scrambling_delay_.Stop();
897 card_scrambling_refresher_.Stop();
899 base::string16 cc_number = base::ASCIIToUTF16(full_wallet_->GetPan());
900 DCHECK_GE(cc_number.size(), 4U);
901 state.image = GetGeneratedCardImage(
902 base::ASCIIToUTF16("XXXX XXXX XXXX ") +
903 cc_number.substr(cc_number.size() - 4),
904 full_wallet_->billing_address()->recipient_name(),
905 color_utils::AlphaBlend(
906 final_top_color,
907 start_top_color,
908 255 * card_generated_animation_.GetCurrentValue()),
909 color_utils::AlphaBlend(
910 final_bottom_color,
911 start_bottom_color,
912 255 * card_generated_animation_.GetCurrentValue()));
914 state.string.text = l10n_util::GetStringUTF16(
915 IDS_AUTOFILL_DIALOG_CARD_GENERATION_DONE);
916 } else {
917 // Start the refresher if it isn't running. Wait one second before pumping
918 // updates to the view.
919 if (!card_scrambling_delay_.IsRunning() &&
920 !card_scrambling_refresher_.IsRunning()) {
921 scrambled_card_number_ = GenerateRandomCardNumber();
922 card_scrambling_delay_.Start(
923 FROM_HERE,
924 base::TimeDelta::FromSeconds(1),
925 this,
926 &AutofillDialogControllerImpl::StartCardScramblingRefresher);
929 DCHECK(!scrambled_card_number_.empty());
930 state.image = GetGeneratedCardImage(
931 scrambled_card_number_,
932 submitted_cardholder_name_,
933 start_top_color,
934 start_bottom_color);
936 // "Submitting" waiting page.
937 state.string.text = l10n_util::GetStringUTF16(
938 IDS_AUTOFILL_DIALOG_CARD_GENERATION_IN_PROGRESS);
941 return state;
944 const std::vector<gfx::Range>& AutofillDialogControllerImpl::
945 LegalDocumentLinks() {
946 return legal_document_link_ranges_;
949 bool AutofillDialogControllerImpl::SectionIsActive(DialogSection section)
950 const {
951 if (IsSubmitPausedOn(wallet::VERIFY_CVV))
952 return section == SECTION_CC_BILLING;
954 if (!FormStructureCaresAboutSection(section))
955 return false;
957 if (IsPayingWithWallet())
958 return section == SECTION_CC_BILLING || section == SECTION_SHIPPING;
960 return section != SECTION_CC_BILLING;
963 void AutofillDialogControllerImpl::GetWalletItems() {
964 ScopedViewUpdates updates(view_.get());
966 wallet_items_requested_ = true;
967 wallet::WalletClient* wallet_client = GetWalletClient();
968 wallet_client->CancelRequest();
970 previously_selected_instrument_id_.clear();
971 previously_selected_shipping_address_id_.clear();
972 if (wallet_items_) {
973 previous_default_instrument_id_ = wallet_items_->default_instrument_id();
974 previous_default_shipping_address_id_ = wallet_items_->default_address_id();
976 const wallet::WalletItems::MaskedInstrument* instrument =
977 ActiveInstrument();
978 if (instrument)
979 previously_selected_instrument_id_ = instrument->object_id();
981 const wallet::Address* address = ActiveShippingAddress();
982 if (address)
983 previously_selected_shipping_address_id_ = address->object_id();
986 last_wallet_items_fetch_timestamp_ = base::TimeTicks::Now();
987 passive_failed_ = false;
988 wallet_items_.reset();
990 // The "Loading..." page should be showing now, which should cause the
991 // account chooser to hide.
992 view_->UpdateAccountChooser();
993 wallet_client->GetWalletItems();
996 void AutofillDialogControllerImpl::HideSignIn() {
997 ScopedViewUpdates updates(view_.get());
998 signin_registrar_.RemoveAll();
999 view_->HideSignIn();
1000 view_->UpdateAccountChooser();
1003 AutofillDialogControllerImpl::DialogSignedInState
1004 AutofillDialogControllerImpl::SignedInState() const {
1005 if (wallet_error_notification_)
1006 return SIGN_IN_DISABLED;
1008 if (signin_helper_ || (wallet_items_requested_ && !wallet_items_))
1009 return REQUIRES_RESPONSE;
1011 if (!wallet_items_requested_)
1012 return NOT_CHECKED;
1014 if (wallet_items_->HasRequiredAction(wallet::GAIA_AUTH) ||
1015 passive_failed_) {
1016 return REQUIRES_SIGN_IN;
1019 if (wallet_items_->HasRequiredAction(wallet::PASSIVE_GAIA_AUTH))
1020 return REQUIRES_PASSIVE_SIGN_IN;
1022 return SIGNED_IN;
1025 void AutofillDialogControllerImpl::SignedInStateUpdated() {
1026 if (!ShouldShowSpinner())
1027 waiting_for_explicit_sign_in_response_ = false;
1029 switch (SignedInState()) {
1030 case SIGNED_IN:
1031 LogDialogLatencyToShow();
1032 break;
1034 case REQUIRES_SIGN_IN:
1035 if (handling_use_wallet_link_click_)
1036 SignInLinkClicked();
1037 // Fall through.
1038 case SIGN_IN_DISABLED:
1039 // Switch to the local account and refresh the dialog.
1040 signin_helper_.reset();
1041 OnWalletSigninError();
1042 handling_use_wallet_link_click_ = false;
1043 break;
1045 case REQUIRES_PASSIVE_SIGN_IN:
1046 // Attempt to passively sign in the user.
1047 DCHECK(!signin_helper_);
1048 signin_helper_.reset(new wallet::WalletSigninHelper(
1049 this,
1050 profile_->GetRequestContext()));
1051 signin_helper_->StartPassiveSignin(GetWalletClient()->user_index());
1052 break;
1054 case NOT_CHECKED:
1055 case REQUIRES_RESPONSE:
1056 break;
1060 void AutofillDialogControllerImpl::OnWalletOrSigninUpdate() {
1061 ScopedViewUpdates updates(view_.get());
1062 SignedInStateUpdated();
1063 SuggestionsUpdated();
1064 UpdateAccountChooserView();
1066 if (view_) {
1067 view_->UpdateButtonStrip();
1068 view_->UpdateOverlay();
1071 // On the first successful response, compute the initial user state metric.
1072 if (initial_user_state_ == AutofillMetrics::DIALOG_USER_STATE_UNKNOWN)
1073 initial_user_state_ = GetInitialUserState();
1076 void AutofillDialogControllerImpl::OnWalletFormFieldError(
1077 const std::vector<wallet::FormFieldError>& form_field_errors) {
1078 if (form_field_errors.empty())
1079 return;
1081 for (std::vector<wallet::FormFieldError>::const_iterator it =
1082 form_field_errors.begin();
1083 it != form_field_errors.end(); ++it) {
1084 if (it->error_type() == wallet::FormFieldError::UNKNOWN_ERROR ||
1085 it->GetAutofillType() == MAX_VALID_FIELD_TYPE ||
1086 it->location() == wallet::FormFieldError::UNKNOWN_LOCATION) {
1087 wallet_server_validation_recoverable_ = false;
1088 break;
1090 DialogSection section = SectionFromLocation(it->location());
1091 wallet_errors_[section][it->GetAutofillType()] =
1092 std::make_pair(it->GetErrorMessage(),
1093 GetValueFromSection(section, it->GetAutofillType()));
1096 // Unrecoverable validation errors.
1097 if (!wallet_server_validation_recoverable_)
1098 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
1100 UpdateForErrors();
1103 void AutofillDialogControllerImpl::ConstructLegalDocumentsText() {
1104 legal_documents_text_.clear();
1105 legal_document_link_ranges_.clear();
1107 if (!wallet_items_)
1108 return;
1110 PrefService* local_state = g_browser_process->local_state();
1111 // List of users who have accepted location sharing for fraud protection
1112 // on this device.
1113 const base::ListValue* accepted =
1114 local_state->GetList(::prefs::kAutofillDialogWalletLocationAcceptance);
1115 bool has_accepted_location_sharing =
1116 accepted->Find(base::StringValue(
1117 account_chooser_model_->GetActiveWalletAccountName())) !=
1118 accepted->end();
1120 if (wallet_items_->legal_documents().empty()) {
1121 if (!has_accepted_location_sharing) {
1122 legal_documents_text_ = l10n_util::GetStringUTF16(
1123 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE);
1126 return;
1129 const std::vector<wallet::WalletItems::LegalDocument*>& documents =
1130 wallet_items_->legal_documents();
1131 // There should never be just one document because the privacy policy doc gets
1132 // tacked on the end of other documents.
1133 DCHECK_GE(documents.size(), 2U);
1135 std::vector<base::string16> link_names;
1136 for (size_t i = 0; i < documents.size(); ++i) {
1137 link_names.push_back(documents[i]->display_name());
1140 int resource_id = 0;
1141 switch (documents.size()) {
1142 case 2U:
1143 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_2;
1144 break;
1145 case 3U:
1146 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_3;
1147 break;
1148 case 4U:
1149 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_4;
1150 break;
1151 case 5U:
1152 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_5;
1153 break;
1154 case 6U:
1155 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_6;
1156 break;
1157 default:
1158 // We can only handle so many documents. For lack of a better way of
1159 // handling document overflow, just error out if there are too many.
1160 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
1161 return;
1164 std::vector<size_t> offsets;
1165 base::string16 text =
1166 l10n_util::GetStringFUTF16(resource_id, link_names,&offsets);
1168 // Tack on the location string if need be.
1169 size_t base_offset = 0;
1170 if (!has_accepted_location_sharing) {
1171 text = l10n_util::GetStringFUTF16(
1172 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE_WITH_LEGAL_DOCS,
1173 text,
1174 &base_offset);
1177 for (size_t i = 0; i < documents.size(); ++i) {
1178 size_t link_start = offsets[i] + base_offset;
1179 legal_document_link_ranges_.push_back(gfx::Range(
1180 link_start, link_start + documents[i]->display_name().size()));
1182 legal_documents_text_ = text;
1185 void AutofillDialogControllerImpl::ResetSectionInput(DialogSection section) {
1186 SetEditingExistingData(section, false);
1187 needs_validation_.erase(section);
1189 CountryComboboxModel* model = CountryComboboxModelForSection(section);
1190 if (model) {
1191 base::string16 country = model->GetItemAt(model->GetDefaultIndex());
1192 RebuildInputsForCountry(section, country, false);
1195 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1196 for (DetailInputs::iterator it = inputs->begin();
1197 it != inputs->end(); ++it) {
1198 if (it->length != DetailInput::NONE)
1199 it->initial_value.clear();
1203 void AutofillDialogControllerImpl::ShowEditUiIfBadSuggestion(
1204 DialogSection section) {
1205 // |CreateWrapper()| returns an empty wrapper if |IsEditingExistingData()|, so
1206 // get the wrapper before this potentially happens below.
1207 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1209 // If the chosen item in |model| yields an empty suggestion text, it is
1210 // invalid. In this case, show the edit UI and highlight invalid fields.
1211 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1212 base::string16 unused, unused2;
1213 if (IsASuggestionItemKey(model->GetItemKeyForCheckedItem()) &&
1214 !SuggestionTextForSection(section, &unused, &unused2)) {
1215 SetEditingExistingData(section, true);
1218 if (wrapper && IsEditingExistingData(section)) {
1219 base::string16 country =
1220 wrapper->GetInfo(AutofillType(CountryTypeForSection(section)));
1221 if (!country.empty()) {
1222 // There's no user input to restore here as this is only called after
1223 // resetting all section input.
1224 if (RebuildInputsForCountry(section, country, false))
1225 UpdateSection(section);
1227 wrapper->FillInputs(MutableRequestedFieldsForSection(section));
1231 bool AutofillDialogControllerImpl::InputWasEdited(ServerFieldType type,
1232 const base::string16& value) {
1233 if (value.empty())
1234 return false;
1236 // If this is a combobox at the default value, don't preserve it.
1237 ui::ComboboxModel* model = ComboboxModelForAutofillType(type);
1238 if (model && model->GetItemAt(model->GetDefaultIndex()) == value)
1239 return false;
1241 return true;
1244 FieldValueMap AutofillDialogControllerImpl::TakeUserInputSnapshot() {
1245 FieldValueMap snapshot;
1246 if (!view_)
1247 return snapshot;
1249 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1250 DialogSection section = static_cast<DialogSection>(i);
1251 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1252 if (model->GetItemKeyForCheckedItem() != kAddNewItemKey)
1253 continue;
1255 FieldValueMap outputs;
1256 view_->GetUserInput(section, &outputs);
1257 // Remove fields that are empty, at their default values, or invalid.
1258 for (FieldValueMap::iterator it = outputs.begin(); it != outputs.end();
1259 ++it) {
1260 if (InputWasEdited(it->first, it->second) &&
1261 InputValidityMessage(section, it->first, it->second).empty()) {
1262 snapshot.insert(std::make_pair(it->first, it->second));
1267 return snapshot;
1270 void AutofillDialogControllerImpl::RestoreUserInputFromSnapshot(
1271 const FieldValueMap& snapshot) {
1272 if (snapshot.empty())
1273 return;
1275 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1276 DialogSection section = static_cast<DialogSection>(i);
1277 if (!SectionIsActive(section))
1278 continue;
1280 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1281 for (size_t i = 0; i < inputs->size(); ++i) {
1282 DetailInput* input = &(*inputs)[i];
1283 if (input->length != DetailInput::NONE) {
1284 input->initial_value =
1285 GetInfoFromInputs(snapshot, section, AutofillType(input->type));
1287 if (InputWasEdited(input->type, input->initial_value))
1288 SuggestionsMenuModelForSection(section)->SetCheckedItem(kAddNewItemKey);
1293 void AutofillDialogControllerImpl::UpdateSection(DialogSection section) {
1294 if (view_)
1295 view_->UpdateSection(section);
1298 void AutofillDialogControllerImpl::UpdateForErrors() {
1299 if (!view_)
1300 return;
1302 // Currently, the view should only need to be updated if there are
1303 // |wallet_errors_| or validating a suggestion that's based on existing data.
1304 bool should_update = !wallet_errors_.empty();
1305 if (!should_update) {
1306 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1307 if (IsEditingExistingData(static_cast<DialogSection>(i))) {
1308 should_update = true;
1309 break;
1314 if (should_update)
1315 view_->UpdateForErrors();
1318 gfx::Image AutofillDialogControllerImpl::GetGeneratedCardImage(
1319 const base::string16& card_number,
1320 const base::string16& name,
1321 const SkColor& gradient_top,
1322 const SkColor& gradient_bottom) {
1323 const int kCardWidthPx = 300;
1324 const int kCardHeightPx = 190;
1325 const gfx::Size size(kCardWidthPx, kCardHeightPx);
1326 ui::ScaleFactor scale_factor = ui::GetScaleFactorForNativeView(
1327 web_contents()->GetView()->GetNativeView());
1328 gfx::Canvas canvas(size, ui::GetImageScale(scale_factor), false);
1330 gfx::Rect display_rect(size);
1332 skia::RefPtr<SkShader> shader = gfx::CreateGradientShader(
1333 0, size.height(), gradient_top, gradient_bottom);
1334 SkPaint paint;
1335 paint.setShader(shader.get());
1336 canvas.DrawRoundRect(display_rect, 8, paint);
1338 display_rect.Inset(20, 0, 0, 0);
1339 gfx::Font font(l10n_util::GetStringUTF8(IDS_FIXED_FONT_FAMILY), 18);
1340 gfx::FontList font_list(font);
1341 gfx::ShadowValues shadows;
1342 shadows.push_back(gfx::ShadowValue(gfx::Point(0, 1), 1.0, SK_ColorBLACK));
1343 canvas.DrawStringRectWithShadows(
1344 card_number,
1345 font_list,
1346 SK_ColorWHITE,
1347 display_rect, 0, 0, shadows);
1349 base::string16 capitalized_name = base::i18n::ToUpper(name);
1350 display_rect.Inset(0, size.height() / 2, 0, 0);
1351 canvas.DrawStringRectWithShadows(
1352 capitalized_name,
1353 font_list,
1354 SK_ColorWHITE,
1355 display_rect, 0, 0, shadows);
1357 gfx::ImageSkia skia(canvas.ExtractImageRep());
1358 return gfx::Image(skia);
1361 void AutofillDialogControllerImpl::StartCardScramblingRefresher() {
1362 RefreshCardScramblingOverlay();
1363 card_scrambling_refresher_.Start(
1364 FROM_HERE,
1365 base::TimeDelta::FromMilliseconds(75),
1366 this,
1367 &AutofillDialogControllerImpl::RefreshCardScramblingOverlay);
1370 void AutofillDialogControllerImpl::RefreshCardScramblingOverlay() {
1371 scrambled_card_number_ = GenerateRandomCardNumber();
1372 PushOverlayUpdate();
1375 void AutofillDialogControllerImpl::PushOverlayUpdate() {
1376 if (view_) {
1377 ScopedViewUpdates updates(view_.get());
1378 view_->UpdateOverlay();
1382 const DetailInputs& AutofillDialogControllerImpl::RequestedFieldsForSection(
1383 DialogSection section) const {
1384 switch (section) {
1385 case SECTION_CC:
1386 return requested_cc_fields_;
1387 case SECTION_BILLING:
1388 return requested_billing_fields_;
1389 case SECTION_CC_BILLING:
1390 return requested_cc_billing_fields_;
1391 case SECTION_SHIPPING:
1392 return requested_shipping_fields_;
1395 NOTREACHED();
1396 return requested_billing_fields_;
1399 ui::ComboboxModel* AutofillDialogControllerImpl::ComboboxModelForAutofillType(
1400 ServerFieldType type) {
1401 switch (type) {
1402 case CREDIT_CARD_EXP_MONTH:
1403 return &cc_exp_month_combobox_model_;
1405 case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1406 return &cc_exp_year_combobox_model_;
1408 case ADDRESS_BILLING_COUNTRY:
1409 return billing_country_combobox_model_.get();
1411 case ADDRESS_HOME_COUNTRY:
1412 return shipping_country_combobox_model_.get();
1414 default:
1415 return NULL;
1419 ui::MenuModel* AutofillDialogControllerImpl::MenuModelForSection(
1420 DialogSection section) {
1421 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1422 // The shipping section menu is special. It will always show because there is
1423 // a choice between "Use billing" and "enter new".
1424 if (section == SECTION_SHIPPING)
1425 return model;
1427 // For other sections, only show a menu if there's at least one suggestion.
1428 for (int i = 0; i < model->GetItemCount(); ++i) {
1429 if (IsASuggestionItemKey(model->GetItemKeyAt(i)))
1430 return model;
1433 return NULL;
1436 ui::MenuModel* AutofillDialogControllerImpl::MenuModelForAccountChooser() {
1437 // If there were unrecoverable Wallet errors, or if there are choices other
1438 // than "Pay without the wallet", show the full menu.
1439 // TODO(estade): this can present a braindead menu (only 1 option) when
1440 // there's a wallet error.
1441 if (wallet_error_notification_ ||
1442 (SignedInState() == SIGNED_IN &&
1443 account_chooser_model_->HasAccountsToChoose() &&
1444 !ShouldShowSignInWebView())) {
1445 return account_chooser_model_.get();
1448 // Otherwise, there is no menu, just a sign in link.
1449 return NULL;
1452 gfx::Image AutofillDialogControllerImpl::AccountChooserImage() {
1453 if (!MenuModelForAccountChooser() && !ShouldShowSignInWebView()) {
1454 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1455 IDR_WALLET_ICON);
1458 return gfx::Image();
1461 gfx::Image AutofillDialogControllerImpl::ButtonStripImage() const {
1462 if (IsPayingWithWallet()) {
1463 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1464 IDR_WALLET_LOGO);
1467 return gfx::Image();
1470 base::string16 AutofillDialogControllerImpl::LabelForSection(
1471 DialogSection section) const {
1472 switch (section) {
1473 case SECTION_CC:
1474 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_CC);
1475 case SECTION_BILLING:
1476 case SECTION_CC_BILLING:
1477 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_BILLING);
1478 case SECTION_SHIPPING:
1479 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_SHIPPING);
1481 NOTREACHED();
1482 return base::string16();
1485 SuggestionState AutofillDialogControllerImpl::SuggestionStateForSection(
1486 DialogSection section) {
1487 base::string16 vertically_compact, horizontally_compact;
1488 bool show_suggestion = SuggestionTextForSection(section,
1489 &vertically_compact,
1490 &horizontally_compact);
1491 return SuggestionState(show_suggestion,
1492 vertically_compact,
1493 horizontally_compact,
1494 SuggestionIconForSection(section),
1495 ExtraSuggestionTextForSection(section),
1496 ExtraSuggestionIconForSection(section));
1499 bool AutofillDialogControllerImpl::SuggestionTextForSection(
1500 DialogSection section,
1501 base::string16* vertically_compact,
1502 base::string16* horizontally_compact) {
1503 base::string16 action_text = RequiredActionTextForSection(section);
1504 if (!action_text.empty()) {
1505 *vertically_compact = *horizontally_compact = action_text;
1506 return true;
1509 // When the user has clicked 'edit' or a suggestion is somehow invalid (e.g. a
1510 // user selects a credit card that has expired), don't show a suggestion (even
1511 // though there is a profile selected in the model).
1512 if (IsEditingExistingData(section))
1513 return false;
1515 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1516 std::string item_key = model->GetItemKeyForCheckedItem();
1517 if (item_key == kSameAsBillingKey) {
1518 *vertically_compact = *horizontally_compact = l10n_util::GetStringUTF16(
1519 IDS_AUTOFILL_DIALOG_USING_BILLING_FOR_SHIPPING);
1520 return true;
1523 if (!IsASuggestionItemKey(item_key))
1524 return false;
1526 if (!IsPayingWithWallet() &&
1527 (section == SECTION_BILLING || section == SECTION_SHIPPING)) {
1528 // Also check if the address is invalid (rules may have loaded since
1529 // the dialog was shown).
1530 if (HasInvalidAddress(*GetManager()->GetProfileByGUID(item_key)))
1531 return false;
1534 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1535 return wrapper->GetDisplayText(vertically_compact, horizontally_compact);
1538 base::string16 AutofillDialogControllerImpl::RequiredActionTextForSection(
1539 DialogSection section) const {
1540 if (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV)) {
1541 const wallet::WalletItems::MaskedInstrument* current_instrument =
1542 wallet_items_->GetInstrumentById(active_instrument_id_);
1543 if (current_instrument)
1544 return current_instrument->TypeAndLastFourDigits();
1546 FieldValueMap output;
1547 view_->GetUserInput(section, &output);
1548 CreditCard card;
1549 GetBillingInfoFromOutputs(output, &card, NULL, NULL);
1550 return card.TypeAndLastFourDigits();
1553 return base::string16();
1556 base::string16 AutofillDialogControllerImpl::ExtraSuggestionTextForSection(
1557 DialogSection section) const {
1558 if (section == SECTION_CC ||
1559 (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV))) {
1560 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC);
1563 return base::string16();
1566 const wallet::WalletItems::MaskedInstrument* AutofillDialogControllerImpl::
1567 ActiveInstrument() const {
1568 if (!IsPayingWithWallet())
1569 return NULL;
1571 const SuggestionsMenuModel* model =
1572 SuggestionsMenuModelForSection(SECTION_CC_BILLING);
1573 const std::string item_key = model->GetItemKeyForCheckedItem();
1574 if (!IsASuggestionItemKey(item_key))
1575 return NULL;
1577 int index;
1578 if (!base::StringToInt(item_key, &index) || index < 0 ||
1579 static_cast<size_t>(index) >= wallet_items_->instruments().size()) {
1580 NOTREACHED();
1581 return NULL;
1584 return wallet_items_->instruments()[index];
1587 const wallet::Address* AutofillDialogControllerImpl::
1588 ActiveShippingAddress() const {
1589 if (!IsPayingWithWallet() || !IsShippingAddressRequired())
1590 return NULL;
1592 const SuggestionsMenuModel* model =
1593 SuggestionsMenuModelForSection(SECTION_SHIPPING);
1594 const std::string item_key = model->GetItemKeyForCheckedItem();
1595 if (!IsASuggestionItemKey(item_key))
1596 return NULL;
1598 int index;
1599 if (!base::StringToInt(item_key, &index) || index < 0 ||
1600 static_cast<size_t>(index) >= wallet_items_->addresses().size()) {
1601 NOTREACHED();
1602 return NULL;
1605 return wallet_items_->addresses()[index];
1608 scoped_ptr<DataModelWrapper> AutofillDialogControllerImpl::CreateWrapper(
1609 DialogSection section) {
1610 if (IsPayingWithWallet() && full_wallet_ &&
1611 full_wallet_->required_actions().empty()) {
1612 if (section == SECTION_CC_BILLING) {
1613 return scoped_ptr<DataModelWrapper>(
1614 new FullWalletBillingWrapper(full_wallet_.get()));
1616 if (section == SECTION_SHIPPING) {
1617 return scoped_ptr<DataModelWrapper>(
1618 new FullWalletShippingWrapper(full_wallet_.get()));
1622 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1623 std::string item_key = model->GetItemKeyForCheckedItem();
1624 if (!IsASuggestionItemKey(item_key) || IsManuallyEditingSection(section))
1625 return scoped_ptr<DataModelWrapper>();
1627 if (IsPayingWithWallet()) {
1628 if (section == SECTION_CC_BILLING) {
1629 return scoped_ptr<DataModelWrapper>(
1630 new WalletInstrumentWrapper(ActiveInstrument()));
1633 if (section == SECTION_SHIPPING) {
1634 return scoped_ptr<DataModelWrapper>(
1635 new WalletAddressWrapper(ActiveShippingAddress()));
1638 return scoped_ptr<DataModelWrapper>();
1641 if (section == SECTION_CC) {
1642 CreditCard* card = GetManager()->GetCreditCardByGUID(item_key);
1643 DCHECK(card);
1644 return scoped_ptr<DataModelWrapper>(new AutofillCreditCardWrapper(card));
1647 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key);
1648 DCHECK(profile);
1649 if (section == SECTION_SHIPPING) {
1650 return scoped_ptr<DataModelWrapper>(
1651 new AutofillShippingAddressWrapper(profile));
1653 DCHECK_EQ(SECTION_BILLING, section);
1654 return scoped_ptr<DataModelWrapper>(
1655 new AutofillProfileWrapper(profile));
1658 gfx::Image AutofillDialogControllerImpl::SuggestionIconForSection(
1659 DialogSection section) {
1660 scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1661 if (!model.get())
1662 return gfx::Image();
1664 return model->GetIcon();
1667 gfx::Image AutofillDialogControllerImpl::ExtraSuggestionIconForSection(
1668 DialogSection section) {
1669 if (section != SECTION_CC && section != SECTION_CC_BILLING)
1670 return gfx::Image();
1672 scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1673 if (!model.get())
1674 return gfx::Image();
1676 return CvcIconForCreditCardType(
1677 model->GetInfo(AutofillType(CREDIT_CARD_TYPE)));
1680 FieldIconMap AutofillDialogControllerImpl::IconsForFields(
1681 const FieldValueMap& user_inputs) const {
1682 FieldIconMap result;
1683 base::string16 credit_card_type;
1685 FieldValueMap::const_iterator credit_card_iter =
1686 user_inputs.find(CREDIT_CARD_NUMBER);
1687 if (credit_card_iter != user_inputs.end()) {
1688 const base::string16& number = credit_card_iter->second;
1689 const std::string type = CreditCard::GetCreditCardType(number);
1690 credit_card_type = CreditCard::TypeForDisplay(type);
1691 result[CREDIT_CARD_NUMBER] = CreditCardIconForType(type);
1694 if (!user_inputs.count(CREDIT_CARD_VERIFICATION_CODE))
1695 return result;
1697 result[CREDIT_CARD_VERIFICATION_CODE] =
1698 CvcIconForCreditCardType(credit_card_type);
1700 return result;
1703 bool AutofillDialogControllerImpl::FieldControlsIcons(
1704 ServerFieldType type) const {
1705 return type == CREDIT_CARD_NUMBER;
1708 base::string16 AutofillDialogControllerImpl::TooltipForField(
1709 ServerFieldType type) const {
1710 if (type == PHONE_HOME_WHOLE_NUMBER || type == PHONE_BILLING_WHOLE_NUMBER)
1711 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TOOLTIP_PHONE_NUMBER);
1713 return base::string16();
1716 bool AutofillDialogControllerImpl::InputIsEditable(
1717 const DetailInput& input,
1718 DialogSection section) {
1719 if (section != SECTION_CC_BILLING || !IsPayingWithWallet())
1720 return true;
1722 if (input.type == CREDIT_CARD_NUMBER)
1723 return !IsEditingExistingData(section);
1725 // For CVC, only require (allow) input if the user has edited some other
1726 // aspect of the card.
1727 if (input.type == CREDIT_CARD_VERIFICATION_CODE &&
1728 IsEditingExistingData(section)) {
1729 FieldValueMap output;
1730 view_->GetUserInput(section, &output);
1731 WalletInstrumentWrapper wrapper(ActiveInstrument());
1733 for (FieldValueMap::iterator iter = output.begin(); iter != output.end();
1734 ++iter) {
1735 if (iter->first == input.type)
1736 continue;
1738 AutofillType type(iter->first);
1739 if (type.group() == CREDIT_CARD &&
1740 iter->second != wrapper.GetInfo(type)) {
1741 return true;
1745 return false;
1748 return true;
1751 // TODO(groby): Add more tests.
1752 base::string16 AutofillDialogControllerImpl::InputValidityMessage(
1753 DialogSection section,
1754 ServerFieldType type,
1755 const base::string16& value) {
1756 // If the field is edited, clear any Wallet errors.
1757 if (IsPayingWithWallet()) {
1758 WalletValidationErrors::iterator it = wallet_errors_.find(section);
1759 if (it != wallet_errors_.end()) {
1760 TypeErrorInputMap::const_iterator iter = it->second.find(type);
1761 if (iter != it->second.end()) {
1762 if (iter->second.second == value)
1763 return iter->second.first;
1764 it->second.erase(type);
1769 AutofillType autofill_type(type);
1770 if (autofill_type.group() == ADDRESS_HOME ||
1771 autofill_type.group() == ADDRESS_BILLING) {
1772 return base::string16();
1775 switch (autofill_type.GetStorableType()) {
1776 case EMAIL_ADDRESS:
1777 if (!value.empty() && !IsValidEmailAddress(value)) {
1778 return l10n_util::GetStringUTF16(
1779 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_EMAIL_ADDRESS);
1781 break;
1783 case CREDIT_CARD_NUMBER: {
1784 if (!value.empty()) {
1785 base::string16 message = CreditCardNumberValidityMessage(value);
1786 if (!message.empty())
1787 return message;
1789 break;
1792 case CREDIT_CARD_EXP_MONTH:
1793 if (!InputWasEdited(CREDIT_CARD_EXP_MONTH, value)) {
1794 return l10n_util::GetStringUTF16(
1795 IDS_LIBADDRESSINPUT_I18N_MISSING_REQUIRED_FIELD);
1797 break;
1799 case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1800 if (!InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR, value)) {
1801 return l10n_util::GetStringUTF16(
1802 IDS_LIBADDRESSINPUT_I18N_MISSING_REQUIRED_FIELD);
1804 break;
1806 case CREDIT_CARD_VERIFICATION_CODE:
1807 if (!value.empty() && !autofill::IsValidCreditCardSecurityCode(value)) {
1808 return l10n_util::GetStringUTF16(
1809 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
1811 break;
1813 case NAME_FULL:
1814 // Wallet requires a first and last billing name.
1815 if (section == SECTION_CC_BILLING && !value.empty() &&
1816 !IsCardHolderNameValidForWallet(value)) {
1817 DCHECK(IsPayingWithWallet());
1818 return l10n_util::GetStringUTF16(
1819 IDS_AUTOFILL_DIALOG_VALIDATION_WALLET_REQUIRES_TWO_NAMES);
1821 break;
1823 case PHONE_HOME_WHOLE_NUMBER: // Used in shipping section.
1824 break;
1826 case PHONE_BILLING_WHOLE_NUMBER: // Used in billing section.
1827 break;
1829 default:
1830 NOTREACHED(); // Trying to validate unknown field.
1831 break;
1834 return value.empty() ? l10n_util::GetStringUTF16(
1835 IDS_LIBADDRESSINPUT_I18N_MISSING_REQUIRED_FIELD) :
1836 base::string16();
1839 // TODO(groby): Also add tests.
1840 ValidityMessages AutofillDialogControllerImpl::InputsAreValid(
1841 DialogSection section,
1842 const FieldValueMap& inputs) {
1843 ValidityMessages messages;
1844 if (inputs.empty())
1845 return messages;
1847 AddressValidator::Status status = AddressValidator::SUCCESS;
1848 if (section != SECTION_CC) {
1849 AutofillProfile profile;
1850 FillFormGroupFromOutputs(inputs, &profile);
1851 AddressData address_data;
1852 i18ninput::CreateAddressData(base::Bind(&GetInfoFromProfile, profile),
1853 &address_data);
1855 AddressProblems problems;
1856 status = GetValidator()->ValidateAddress(address_data,
1857 AddressProblemFilter(),
1858 &problems);
1859 common::AddressType address_type = section == SECTION_SHIPPING ?
1860 common::ADDRESS_TYPE_SHIPPING : common::ADDRESS_TYPE_BILLING;
1861 for (size_t i = 0; i < problems.size(); ++i) {
1862 const AddressProblem& problem = problems[i];
1863 bool sure = problem.type != AddressProblem::MISSING_REQUIRED_FIELD;
1864 base::string16 text = l10n_util::GetStringUTF16(problem.description_id);
1865 messages.Set(i18ninput::TypeForField(problem.field, address_type),
1866 ValidityMessage(text, sure));
1870 for (FieldValueMap::const_iterator iter = inputs.begin();
1871 iter != inputs.end(); ++iter) {
1872 const ServerFieldType type = iter->first;
1873 base::string16 text = InputValidityMessage(section, type, iter->second);
1875 // Skip empty/unchanged fields in edit mode. If the individual field does
1876 // not have validation errors, assume it to be valid unless later proven
1877 // otherwise.
1878 bool sure = InputWasEdited(type, iter->second);
1880 if (sure && status == AddressValidator::RULES_NOT_READY &&
1881 !ComboboxModelForAutofillType(type) &&
1882 (AutofillType(type).group() == ADDRESS_HOME ||
1883 AutofillType(type).group() == ADDRESS_BILLING)) {
1884 DCHECK(text.empty());
1885 text = l10n_util::GetStringUTF16(
1886 IDS_AUTOFILL_DIALOG_VALIDATION_WAITING_FOR_RULES);
1887 sure = false;
1888 needs_validation_.insert(section);
1891 messages.Set(type, ValidityMessage(text, sure));
1894 // For the convenience of using operator[].
1895 FieldValueMap& field_values = const_cast<FieldValueMap&>(inputs);
1896 // Validate the date formed by month and year field. (Autofill dialog is
1897 // never supposed to have 2-digit years, so not checked).
1898 if (field_values.count(CREDIT_CARD_EXP_4_DIGIT_YEAR) &&
1899 field_values.count(CREDIT_CARD_EXP_MONTH) &&
1900 InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR,
1901 field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR]) &&
1902 InputWasEdited(CREDIT_CARD_EXP_MONTH,
1903 field_values[CREDIT_CARD_EXP_MONTH])) {
1904 ValidityMessage year_message(base::string16(), true);
1905 ValidityMessage month_message(base::string16(), true);
1906 if (!IsCreditCardExpirationValid(field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR],
1907 field_values[CREDIT_CARD_EXP_MONTH])) {
1908 // The dialog shows the same error message for the month and year fields.
1909 year_message.text = l10n_util::GetStringUTF16(
1910 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
1911 month_message.text = l10n_util::GetStringUTF16(
1912 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
1914 messages.Set(CREDIT_CARD_EXP_4_DIGIT_YEAR, year_message);
1915 messages.Set(CREDIT_CARD_EXP_MONTH, month_message);
1918 // If there is a credit card number and a CVC, validate them together.
1919 if (field_values.count(CREDIT_CARD_NUMBER) &&
1920 field_values.count(CREDIT_CARD_VERIFICATION_CODE)) {
1921 ValidityMessage ccv_message(base::string16(), true);
1922 if (!autofill::IsValidCreditCardSecurityCode(
1923 field_values[CREDIT_CARD_VERIFICATION_CODE],
1924 field_values[CREDIT_CARD_NUMBER])) {
1925 ccv_message.text = l10n_util::GetStringUTF16(
1926 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
1928 messages.Set(CREDIT_CARD_VERIFICATION_CODE, ccv_message);
1931 // Validate the shipping phone number against the country code of the address.
1932 if (field_values.count(ADDRESS_HOME_COUNTRY) &&
1933 field_values.count(PHONE_HOME_WHOLE_NUMBER)) {
1934 messages.Set(
1935 PHONE_HOME_WHOLE_NUMBER,
1936 GetPhoneValidityMessage(field_values[ADDRESS_HOME_COUNTRY],
1937 field_values[PHONE_HOME_WHOLE_NUMBER]));
1940 // Validate the billing phone number against the country code of the address.
1941 if (field_values.count(ADDRESS_BILLING_COUNTRY) &&
1942 field_values.count(PHONE_BILLING_WHOLE_NUMBER)) {
1943 messages.Set(
1944 PHONE_BILLING_WHOLE_NUMBER,
1945 GetPhoneValidityMessage(field_values[ADDRESS_BILLING_COUNTRY],
1946 field_values[PHONE_BILLING_WHOLE_NUMBER]));
1949 return messages;
1952 void AutofillDialogControllerImpl::UserEditedOrActivatedInput(
1953 DialogSection section,
1954 ServerFieldType type,
1955 gfx::NativeView parent_view,
1956 const gfx::Rect& content_bounds,
1957 const base::string16& field_contents,
1958 bool was_edit) {
1959 ScopedViewUpdates updates(view_.get());
1961 if (type == ADDRESS_BILLING_COUNTRY || type == ADDRESS_HOME_COUNTRY) {
1962 const FieldValueMap& snapshot = TakeUserInputSnapshot();
1964 // Clobber the inputs because the view's already been updated.
1965 RebuildInputsForCountry(section, field_contents, true);
1966 RestoreUserInputFromSnapshot(snapshot);
1967 UpdateSection(section);
1969 GetValidator()->LoadRules(AutofillCountry::GetCountryCode(
1970 field_contents, g_browser_process->GetApplicationLocale()));
1973 // The rest of this method applies only to textfields while Autofill is
1974 // enabled. If a combobox or Autofill is disabled, bail.
1975 if (ComboboxModelForAutofillType(type) || !IsAutofillEnabled())
1976 return;
1978 // If the field is edited down to empty, don't show a popup.
1979 if (was_edit && field_contents.empty()) {
1980 HidePopup();
1981 return;
1984 // If the user clicks while the popup is already showing, be sure to hide
1985 // it.
1986 if (!was_edit && popup_controller_.get()) {
1987 HidePopup();
1988 return;
1991 std::vector<base::string16> popup_values, popup_labels, popup_icons;
1992 if (common::IsCreditCardType(type)) {
1993 GetManager()->GetCreditCardSuggestions(AutofillType(type),
1994 field_contents,
1995 &popup_values,
1996 &popup_labels,
1997 &popup_icons,
1998 &popup_guids_);
1999 } else {
2000 GetManager()->GetProfileSuggestions(
2001 AutofillType(type),
2002 field_contents,
2003 false,
2004 RequestedTypesForSection(section),
2005 base::Bind(&AutofillDialogControllerImpl::ShouldSuggestProfile,
2006 base::Unretained(this), section),
2007 &popup_values,
2008 &popup_labels,
2009 &popup_icons,
2010 &popup_guids_);
2012 GetI18nValidatorSuggestions(section, type, &popup_values, &popup_labels,
2013 &popup_icons);
2016 if (popup_values.empty()) {
2017 HidePopup();
2018 return;
2021 // |popup_input_type_| must be set before calling |Show()|.
2022 popup_input_type_ = type;
2024 // TODO(estade): do we need separators and control rows like 'Clear
2025 // Form'?
2026 std::vector<int> popup_ids;
2027 for (size_t i = 0; i < popup_values.size(); ++i) {
2028 popup_ids.push_back(i);
2031 popup_controller_ = AutofillPopupControllerImpl::GetOrCreate(
2032 popup_controller_,
2033 weak_ptr_factory_.GetWeakPtr(),
2034 NULL,
2035 parent_view,
2036 content_bounds,
2037 base::i18n::IsRTL() ?
2038 base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT);
2039 popup_controller_->set_hide_on_outside_click(true);
2040 popup_controller_->Show(popup_values,
2041 popup_labels,
2042 popup_icons,
2043 popup_ids);
2046 void AutofillDialogControllerImpl::FocusMoved() {
2047 HidePopup();
2050 bool AutofillDialogControllerImpl::ShouldShowErrorBubble() const {
2051 return popup_input_type_ == UNKNOWN_TYPE;
2054 void AutofillDialogControllerImpl::ViewClosed() {
2055 GetManager()->RemoveObserver(this);
2057 // Called from here rather than in ~AutofillDialogControllerImpl as this
2058 // relies on virtual methods that change to their base class in the dtor.
2059 MaybeShowCreditCardBubble();
2061 delete this;
2064 std::vector<DialogNotification> AutofillDialogControllerImpl::
2065 CurrentNotifications() {
2066 std::vector<DialogNotification> notifications;
2068 // TODO(dbeam): figure out a way to dismiss this error after a while.
2069 if (wallet_error_notification_)
2070 notifications.push_back(*wallet_error_notification_);
2072 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2073 notifications.push_back(DialogNotification(
2074 DialogNotification::REQUIRED_ACTION,
2075 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VERIFY_CVV)));
2078 if (!wallet_server_validation_recoverable_) {
2079 notifications.push_back(DialogNotification(
2080 DialogNotification::REQUIRED_ACTION,
2081 l10n_util::GetStringUTF16(
2082 IDS_AUTOFILL_DIALOG_FAILED_TO_SAVE_WALLET_DATA)));
2085 if (choose_another_instrument_or_address_) {
2086 notifications.push_back(DialogNotification(
2087 DialogNotification::REQUIRED_ACTION,
2088 l10n_util::GetStringUTF16(
2089 IDS_AUTOFILL_DIALOG_CHOOSE_DIFFERENT_WALLET_INSTRUMENT)));
2092 if (notifications.empty() && MenuModelForAccountChooser()) {
2093 base::string16 text = l10n_util::GetStringUTF16(
2094 IsManuallyEditingAnySection() ?
2095 IDS_AUTOFILL_DIALOG_SAVE_DETAILS_IN_WALLET :
2096 IDS_AUTOFILL_DIALOG_USE_WALLET);
2097 DialogNotification notification(
2098 DialogNotification::WALLET_USAGE_CONFIRMATION,
2099 text);
2100 notification.set_tooltip_text(
2101 l10n_util::GetStringUTF16(
2102 IDS_AUTOFILL_DIALOG_SAVE_IN_WALLET_TOOLTIP));
2103 notification.set_checked(IsPayingWithWallet());
2104 notifications.push_back(notification);
2107 if (IsPayingWithWallet() && !wallet::IsUsingProd()) {
2108 notifications.push_back(DialogNotification(
2109 DialogNotification::DEVELOPER_WARNING,
2110 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_NOT_PROD_WARNING)));
2113 if (!invoked_from_same_origin_) {
2114 notifications.push_back(DialogNotification(
2115 DialogNotification::SECURITY_WARNING,
2116 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_SITE_WARNING,
2117 base::UTF8ToUTF16(source_url_.host()))));
2120 return notifications;
2123 void AutofillDialogControllerImpl::LinkClicked(const GURL& url) {
2124 OpenTabWithUrl(url);
2127 void AutofillDialogControllerImpl::SignInLinkClicked() {
2128 ScopedViewUpdates updates(view_.get());
2130 if (SignedInState() == NOT_CHECKED) {
2131 handling_use_wallet_link_click_ = true;
2132 account_chooser_model_->SelectWalletAccount(0);
2133 FetchWalletCookie();
2134 } else if (signin_registrar_.IsEmpty()) {
2135 // Start sign in.
2136 waiting_for_explicit_sign_in_response_ = true;
2137 content::Source<content::NavigationController> source(view_->ShowSignIn());
2138 signin_registrar_.Add(
2139 this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, source);
2141 GetMetricLogger().LogDialogUiEvent(
2142 AutofillMetrics::DIALOG_UI_SIGNIN_SHOWN);
2143 } else {
2144 waiting_for_explicit_sign_in_response_ = false;
2145 HideSignIn();
2148 view_->UpdateAccountChooser();
2149 view_->UpdateButtonStrip();
2152 void AutofillDialogControllerImpl::NotificationCheckboxStateChanged(
2153 DialogNotification::Type type, bool checked) {
2154 if (type == DialogNotification::WALLET_USAGE_CONFIRMATION) {
2155 if (checked) {
2156 account_chooser_model_->SelectWalletAccount(
2157 GetWalletClient()->user_index());
2158 } else {
2159 account_chooser_model_->SelectUseAutofill();
2162 AccountChoiceChanged();
2166 void AutofillDialogControllerImpl::LegalDocumentLinkClicked(
2167 const gfx::Range& range) {
2168 for (size_t i = 0; i < legal_document_link_ranges_.size(); ++i) {
2169 if (legal_document_link_ranges_[i] == range) {
2170 OpenTabWithUrl(wallet_items_->legal_documents()[i]->url());
2171 return;
2175 NOTREACHED();
2178 bool AutofillDialogControllerImpl::OnCancel() {
2179 HidePopup();
2180 if (!is_submitting_)
2181 LogOnCancelMetrics();
2182 callback_.Run(NULL);
2183 return true;
2186 bool AutofillDialogControllerImpl::OnAccept() {
2187 ScopedViewUpdates updates(view_.get());
2188 choose_another_instrument_or_address_ = false;
2189 wallet_server_validation_recoverable_ = true;
2190 HidePopup();
2192 // This must come before SetIsSubmitting().
2193 if (IsPayingWithWallet()) {
2194 // In the VERIFY_CVV case, hold onto the previously submitted cardholder
2195 // name.
2196 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2197 submitted_cardholder_name_ =
2198 GetValueFromSection(SECTION_CC_BILLING, NAME_BILLING_FULL);
2200 // Snag the last four digits of the backing card now as it could be wiped
2201 // out if a CVC challenge happens.
2202 if (ActiveInstrument()) {
2203 backing_card_last_four_ = ActiveInstrument()->TypeAndLastFourDigits();
2204 } else {
2205 FieldValueMap output;
2206 view_->GetUserInput(SECTION_CC_BILLING, &output);
2207 CreditCard card;
2208 GetBillingInfoFromOutputs(output, &card, NULL, NULL);
2209 backing_card_last_four_ = card.TypeAndLastFourDigits();
2212 DCHECK(!submitted_cardholder_name_.empty());
2213 DCHECK(!backing_card_last_four_.empty());
2216 SetIsSubmitting(true);
2218 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2219 DCHECK(!active_instrument_id_.empty());
2220 full_wallet_.reset();
2221 GetWalletClient()->AuthenticateInstrument(
2222 active_instrument_id_,
2223 base::UTF16ToUTF8(view_->GetCvc()));
2224 view_->UpdateOverlay();
2225 } else if (IsPayingWithWallet()) {
2226 AcceptLegalTerms();
2227 } else {
2228 FinishSubmit();
2231 return false;
2234 Profile* AutofillDialogControllerImpl::profile() {
2235 return profile_;
2238 content::WebContents* AutofillDialogControllerImpl::GetWebContents() {
2239 return web_contents();
2242 ////////////////////////////////////////////////////////////////////////////////
2243 // AutofillPopupDelegate implementation.
2245 void AutofillDialogControllerImpl::OnPopupShown() {
2246 ScopedViewUpdates update(view_.get());
2247 view_->UpdateErrorBubble();
2249 GetMetricLogger().LogDialogPopupEvent(AutofillMetrics::DIALOG_POPUP_SHOWN);
2252 void AutofillDialogControllerImpl::OnPopupHidden() {}
2254 bool AutofillDialogControllerImpl::ShouldRepostEvent(
2255 const ui::MouseEvent& event) {
2256 DCHECK_NE(UNKNOWN_TYPE, popup_input_type_);
2257 // If the event would be reposted inside the input showing an Autofill popup,
2258 // just ignore.
2259 return !view_->HitTestInput(popup_input_type_, event.location());
2262 void AutofillDialogControllerImpl::DidSelectSuggestion(
2263 const base::string16& value,
2264 int identifier) {
2265 // TODO(estade): implement.
2268 void AutofillDialogControllerImpl::DidAcceptSuggestion(
2269 const base::string16& value,
2270 int identifier) {
2271 DCHECK_NE(UNKNOWN_TYPE, popup_input_type_);
2272 // Because |HidePopup()| can be called from |UpdateSection()|, remember the
2273 // type of the input for later here.
2274 const ServerFieldType popup_input_type = popup_input_type_;
2276 ScopedViewUpdates updates(view_.get());
2277 scoped_ptr<DataModelWrapper> wrapper;
2279 if (static_cast<size_t>(identifier) < popup_guids_.size()) {
2280 const PersonalDataManager::GUIDPair& pair = popup_guids_[identifier];
2281 if (common::IsCreditCardType(popup_input_type)) {
2282 wrapper.reset(new AutofillCreditCardWrapper(
2283 GetManager()->GetCreditCardByGUID(pair.first)));
2284 } else {
2285 wrapper.reset(new AutofillProfileWrapper(
2286 GetManager()->GetProfileByGUID(pair.first),
2287 AutofillType(popup_input_type),
2288 pair.second));
2290 } else {
2291 wrapper.reset(new I18nAddressDataWrapper(
2292 &i18n_validator_suggestions_[identifier - popup_guids_.size()]));
2295 // If the user hasn't switched away from the default country and |wrapper|'s
2296 // country differs from the |view_|'s, rebuild inputs and restore user data.
2297 const FieldValueMap snapshot = TakeUserInputSnapshot();
2298 bool billing_rebuilt = false, shipping_rebuilt = false;
2300 base::string16 billing_country =
2301 wrapper->GetInfo(AutofillType(ADDRESS_BILLING_COUNTRY));
2302 if (!snapshot.count(ADDRESS_BILLING_COUNTRY) &&
2303 !billing_country.empty()) {
2304 billing_rebuilt = RebuildInputsForCountry(
2305 ActiveBillingSection(), billing_country, false);
2308 base::string16 shipping_country =
2309 wrapper->GetInfo(AutofillType(ADDRESS_HOME_COUNTRY));
2310 if (!snapshot.count(ADDRESS_HOME_COUNTRY) &&
2311 !shipping_country.empty()) {
2312 shipping_rebuilt = RebuildInputsForCountry(
2313 SECTION_SHIPPING, shipping_country, false);
2316 if (billing_rebuilt || shipping_rebuilt) {
2317 RestoreUserInputFromSnapshot(snapshot);
2318 if (billing_rebuilt)
2319 UpdateSection(ActiveBillingSection());
2320 if (shipping_rebuilt)
2321 UpdateSection(SECTION_SHIPPING);
2324 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2325 DialogSection section = static_cast<DialogSection>(i);
2326 if (!SectionIsActive(section))
2327 continue;
2329 wrapper->FillInputs(MutableRequestedFieldsForSection(section));
2330 view_->FillSection(section, popup_input_type);
2333 GetMetricLogger().LogDialogPopupEvent(
2334 AutofillMetrics::DIALOG_POPUP_FORM_FILLED);
2336 // TODO(estade): not sure why it's necessary to do this explicitly.
2337 HidePopup();
2340 void AutofillDialogControllerImpl::RemoveSuggestion(
2341 const base::string16& value,
2342 int identifier) {
2343 // TODO(estade): implement.
2346 void AutofillDialogControllerImpl::ClearPreviewedForm() {
2347 // TODO(estade): implement.
2350 ////////////////////////////////////////////////////////////////////////////////
2351 // content::NotificationObserver implementation.
2353 void AutofillDialogControllerImpl::Observe(
2354 int type,
2355 const content::NotificationSource& source,
2356 const content::NotificationDetails& details) {
2357 DCHECK_EQ(type, content::NOTIFICATION_NAV_ENTRY_COMMITTED);
2358 content::LoadCommittedDetails* load_details =
2359 content::Details<content::LoadCommittedDetails>(details).ptr();
2360 size_t user_index = 0;
2361 if (IsSignInContinueUrl(load_details->entry->GetVirtualURL(), &user_index)) {
2362 GetWalletClient()->SetUserIndex(user_index);
2363 FetchWalletCookie();
2365 // NOTE: |HideSignIn()| may delete the WebContents which doesn't expect to
2366 // be deleted while committing a nav entry. Just call |HideSignIn()| later.
2367 base::MessageLoop::current()->PostTask(FROM_HERE,
2368 base::Bind(&AutofillDialogControllerImpl::HideSignIn,
2369 base::Unretained(this)));
2373 ////////////////////////////////////////////////////////////////////////////////
2374 // SuggestionsMenuModelDelegate implementation.
2376 void AutofillDialogControllerImpl::SuggestionsMenuWillShow() {
2377 HidePopup();
2380 void AutofillDialogControllerImpl::SuggestionItemSelected(
2381 SuggestionsMenuModel* model,
2382 size_t index) {
2383 ScopedViewUpdates updates(view_.get());
2385 if (model->GetItemKeyAt(index) == kManageItemsKey) {
2386 GURL url;
2387 if (!IsPayingWithWallet()) {
2388 DCHECK(IsAutofillEnabled());
2389 GURL settings_url(chrome::kChromeUISettingsURL);
2390 url = settings_url.Resolve(chrome::kAutofillSubPage);
2391 } else {
2392 // Reset |last_wallet_items_fetch_timestamp_| to ensure that the Wallet
2393 // data is refreshed as soon as the user switches back to this tab after
2394 // potentially editing his data.
2395 last_wallet_items_fetch_timestamp_ = base::TimeTicks();
2396 size_t user_index = GetWalletClient()->user_index();
2397 url = SectionForSuggestionsMenuModel(*model) == SECTION_SHIPPING ?
2398 wallet::GetManageAddressesUrl(user_index) :
2399 wallet::GetManageInstrumentsUrl(user_index);
2402 OpenTabWithUrl(url);
2403 return;
2406 model->SetCheckedIndex(index);
2407 DialogSection section = SectionForSuggestionsMenuModel(*model);
2409 ResetSectionInput(section);
2410 ShowEditUiIfBadSuggestion(section);
2411 UpdateSection(section);
2412 view_->UpdateNotificationArea();
2413 UpdateForErrors();
2415 LogSuggestionItemSelectedMetric(*model);
2418 ////////////////////////////////////////////////////////////////////////////////
2419 // wallet::WalletClientDelegate implementation.
2421 const AutofillMetrics& AutofillDialogControllerImpl::GetMetricLogger() const {
2422 return metric_logger_;
2425 std::string AutofillDialogControllerImpl::GetRiskData() const {
2426 DCHECK(!risk_data_.empty());
2427 return risk_data_;
2430 std::string AutofillDialogControllerImpl::GetWalletCookieValue() const {
2431 return wallet_cookie_value_;
2434 bool AutofillDialogControllerImpl::IsShippingAddressRequired() const {
2435 return cares_about_shipping_;
2438 void AutofillDialogControllerImpl::OnDidAcceptLegalDocuments() {
2439 DCHECK(is_submitting_ && IsPayingWithWallet());
2440 has_accepted_legal_documents_ = true;
2441 LoadRiskFingerprintData();
2444 void AutofillDialogControllerImpl::OnDidAuthenticateInstrument(bool success) {
2445 DCHECK(is_submitting_ && IsPayingWithWallet());
2447 // TODO(dbeam): use the returned full wallet. http://crbug.com/224992
2448 if (success) {
2449 GetFullWallet();
2450 } else {
2451 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2452 SuggestionsUpdated();
2456 void AutofillDialogControllerImpl::OnDidGetFullWallet(
2457 scoped_ptr<wallet::FullWallet> full_wallet) {
2458 DCHECK(is_submitting_ && IsPayingWithWallet());
2459 ScopedViewUpdates updates(view_.get());
2461 full_wallet_ = full_wallet.Pass();
2463 if (full_wallet_->required_actions().empty()) {
2464 FinishSubmit();
2465 return;
2468 switch (full_wallet_->required_actions()[0]) {
2469 case wallet::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS:
2470 choose_another_instrument_or_address_ = true;
2471 SetIsSubmitting(false);
2472 GetWalletItems();
2473 break;
2475 case wallet::VERIFY_CVV:
2476 SuggestionsUpdated();
2477 break;
2479 default:
2480 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2481 return;
2484 view_->UpdateNotificationArea();
2485 view_->UpdateButtonStrip();
2486 view_->UpdateOverlay();
2489 void AutofillDialogControllerImpl::OnPassiveSigninSuccess() {
2490 FetchWalletCookie();
2493 void AutofillDialogControllerImpl::OnPassiveSigninFailure(
2494 const GoogleServiceAuthError& error) {
2495 signin_helper_.reset();
2496 passive_failed_ = true;
2498 if (handling_use_wallet_link_click_ ||
2499 GetWalletClient()->user_index() != 0) {
2500 // TODO(estade): When a secondary account is selected and fails passive
2501 // auth, we show a sign in page. Currently we show the generic add account
2502 // page, but we should instead show sign in for the selected account.
2503 // http://crbug.com/323327
2504 SignInLinkClicked();
2505 handling_use_wallet_link_click_ = false;
2508 OnWalletSigninError();
2511 void AutofillDialogControllerImpl::OnDidFetchWalletCookieValue(
2512 const std::string& cookie_value) {
2513 wallet_cookie_value_ = cookie_value;
2514 signin_helper_.reset();
2515 GetWalletItems();
2518 void AutofillDialogControllerImpl::OnDidGetWalletItems(
2519 scoped_ptr<wallet::WalletItems> wallet_items) {
2520 legal_documents_text_.clear();
2521 legal_document_link_ranges_.clear();
2522 has_accepted_legal_documents_ = false;
2524 wallet_items_ = wallet_items.Pass();
2526 if (wallet_items_ && !wallet_items_->ObfuscatedGaiaId().empty()) {
2527 // Making sure the user index is in sync shouldn't be necessary, but is an
2528 // extra precaution. But if there is no active account (such as in the
2529 // PASSIVE_AUTH case), stick with the old active account.
2530 GetWalletClient()->SetUserIndex(wallet_items_->active_account_index());
2532 std::vector<std::string> usernames;
2533 for (size_t i = 0; i < wallet_items_->gaia_accounts().size(); ++i) {
2534 usernames.push_back(wallet_items_->gaia_accounts()[i]->email_address());
2536 account_chooser_model_->SetWalletAccounts(
2537 usernames, wallet_items_->active_account_index());
2540 ConstructLegalDocumentsText();
2541 OnWalletOrSigninUpdate();
2544 void AutofillDialogControllerImpl::OnDidSaveToWallet(
2545 const std::string& instrument_id,
2546 const std::string& address_id,
2547 const std::vector<wallet::RequiredAction>& required_actions,
2548 const std::vector<wallet::FormFieldError>& form_field_errors) {
2549 DCHECK(is_submitting_ && IsPayingWithWallet());
2551 if (required_actions.empty()) {
2552 if (!address_id.empty())
2553 active_address_id_ = address_id;
2554 if (!instrument_id.empty())
2555 active_instrument_id_ = instrument_id;
2556 GetFullWallet();
2557 } else {
2558 OnWalletFormFieldError(form_field_errors);
2559 HandleSaveOrUpdateRequiredActions(required_actions);
2563 void AutofillDialogControllerImpl::OnWalletError(
2564 wallet::WalletClient::ErrorType error_type) {
2565 DisableWallet(error_type);
2568 ////////////////////////////////////////////////////////////////////////////////
2569 // PersonalDataManagerObserver implementation.
2571 void AutofillDialogControllerImpl::OnPersonalDataChanged() {
2572 if (is_submitting_)
2573 return;
2575 SuggestionsUpdated();
2578 ////////////////////////////////////////////////////////////////////////////////
2579 // AccountChooserModelDelegate implementation.
2581 void AutofillDialogControllerImpl::AccountChooserWillShow() {
2582 HidePopup();
2585 void AutofillDialogControllerImpl::AccountChoiceChanged() {
2586 ScopedViewUpdates updates(view_.get());
2587 wallet::WalletClient* client = GetWalletClient();
2589 if (is_submitting_)
2590 client->CancelRequest();
2592 SetIsSubmitting(false);
2594 size_t selected_user_index =
2595 account_chooser_model_->GetActiveWalletAccountIndex();
2596 if (account_chooser_model_->WalletIsSelected() &&
2597 client->user_index() != selected_user_index) {
2598 client->SetUserIndex(selected_user_index);
2599 // Clear |wallet_items_| so we don't try to restore the selected instrument
2600 // and address.
2601 wallet_items_.reset();
2602 GetWalletItems();
2603 } else {
2604 SuggestionsUpdated();
2605 UpdateAccountChooserView();
2609 void AutofillDialogControllerImpl::AddAccount() {
2610 SignInLinkClicked();
2613 void AutofillDialogControllerImpl::UpdateAccountChooserView() {
2614 if (view_) {
2615 ScopedViewUpdates updates(view_.get());
2616 view_->UpdateAccountChooser();
2617 view_->UpdateNotificationArea();
2621 ////////////////////////////////////////////////////////////////////////////////
2623 bool AutofillDialogControllerImpl::HandleKeyPressEventInInput(
2624 const content::NativeWebKeyboardEvent& event) {
2625 if (popup_controller_.get())
2626 return popup_controller_->HandleKeyPressEvent(event);
2628 return false;
2631 bool AutofillDialogControllerImpl::IsSubmitPausedOn(
2632 wallet::RequiredAction required_action) const {
2633 return full_wallet_ && full_wallet_->HasRequiredAction(required_action);
2636 void AutofillDialogControllerImpl::ShowNewCreditCardBubble(
2637 scoped_ptr<CreditCard> new_card,
2638 scoped_ptr<AutofillProfile> billing_profile) {
2639 NewCreditCardBubbleController::Show(web_contents(),
2640 new_card.Pass(),
2641 billing_profile.Pass());
2644 void AutofillDialogControllerImpl::SubmitButtonDelayBegin() {
2645 submit_button_delay_timer_.Start(
2646 FROM_HERE,
2647 base::TimeDelta::FromMilliseconds(kSubmitButtonDelayMs),
2648 this,
2649 &AutofillDialogControllerImpl::OnSubmitButtonDelayEnd);
2652 void AutofillDialogControllerImpl::SubmitButtonDelayEndForTesting() {
2653 DCHECK(submit_button_delay_timer_.IsRunning());
2654 submit_button_delay_timer_.user_task().Run();
2655 submit_button_delay_timer_.Stop();
2658 void AutofillDialogControllerImpl::
2659 ClearLastWalletItemsFetchTimestampForTesting() {
2660 last_wallet_items_fetch_timestamp_ = base::TimeTicks();
2663 AccountChooserModel* AutofillDialogControllerImpl::
2664 AccountChooserModelForTesting() {
2665 return account_chooser_model_.get();
2668 bool AutofillDialogControllerImpl::IsSignInContinueUrl(
2669 const GURL& url,
2670 size_t* user_index) const {
2671 return wallet::IsSignInContinueUrl(url, user_index);
2674 AutofillDialogControllerImpl::AutofillDialogControllerImpl(
2675 content::WebContents* contents,
2676 const FormData& form_structure,
2677 const GURL& source_url,
2678 const base::Callback<void(const FormStructure*)>& callback)
2679 : WebContentsObserver(contents),
2680 profile_(Profile::FromBrowserContext(contents->GetBrowserContext())),
2681 initial_user_state_(AutofillMetrics::DIALOG_USER_STATE_UNKNOWN),
2682 form_structure_(form_structure),
2683 invoked_from_same_origin_(true),
2684 source_url_(source_url),
2685 callback_(callback),
2686 wallet_client_(profile_->GetRequestContext(), this, source_url),
2687 wallet_items_requested_(false),
2688 handling_use_wallet_link_click_(false),
2689 passive_failed_(false),
2690 suggested_cc_(this),
2691 suggested_billing_(this),
2692 suggested_cc_billing_(this),
2693 suggested_shipping_(this),
2694 cares_about_shipping_(true),
2695 popup_input_type_(UNKNOWN_TYPE),
2696 waiting_for_explicit_sign_in_response_(false),
2697 has_accepted_legal_documents_(false),
2698 is_submitting_(false),
2699 choose_another_instrument_or_address_(false),
2700 wallet_server_validation_recoverable_(true),
2701 data_was_passed_back_(false),
2702 was_ui_latency_logged_(false),
2703 card_generated_animation_(2000, 60, this),
2704 weak_ptr_factory_(this) {
2705 DCHECK(!callback_.is_null());
2708 AutofillDialogView* AutofillDialogControllerImpl::CreateView() {
2709 return AutofillDialogView::Create(this);
2712 PersonalDataManager* AutofillDialogControllerImpl::GetManager() const {
2713 return PersonalDataManagerFactory::GetForProfile(profile_);
2716 AddressValidator* AutofillDialogControllerImpl::GetValidator() {
2717 return validator_.get();
2720 const wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient()
2721 const {
2722 return const_cast<AutofillDialogControllerImpl*>(this)->GetWalletClient();
2725 wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient() {
2726 return &wallet_client_;
2729 bool AutofillDialogControllerImpl::IsPayingWithWallet() const {
2730 return account_chooser_model_->WalletIsSelected() &&
2731 SignedInState() == SIGNED_IN;
2734 void AutofillDialogControllerImpl::LoadRiskFingerprintData() {
2735 risk_data_.clear();
2737 uint64 obfuscated_gaia_id = 0;
2738 bool success = base::StringToUint64(wallet_items_->ObfuscatedGaiaId(),
2739 &obfuscated_gaia_id);
2740 DCHECK(success);
2742 gfx::Rect window_bounds;
2743 window_bounds = GetBaseWindowForWebContents(web_contents())->GetBounds();
2745 PrefService* user_prefs = profile_->GetPrefs();
2746 std::string charset = user_prefs->GetString(::prefs::kDefaultCharset);
2747 std::string accept_languages =
2748 user_prefs->GetString(::prefs::kAcceptLanguages);
2749 base::Time install_time = base::Time::FromTimeT(
2750 g_browser_process->local_state()->GetInt64(::prefs::kInstallDate));
2752 risk::GetFingerprint(
2753 obfuscated_gaia_id, window_bounds, *web_contents(),
2754 chrome::VersionInfo().Version(), charset, accept_languages, install_time,
2755 g_browser_process->GetApplicationLocale(), GetUserAgent(),
2756 base::Bind(&AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData,
2757 weak_ptr_factory_.GetWeakPtr()));
2760 void AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData(
2761 scoped_ptr<risk::Fingerprint> fingerprint) {
2762 DCHECK(AreLegalDocumentsCurrent());
2764 std::string proto_data;
2765 fingerprint->SerializeToString(&proto_data);
2766 base::Base64Encode(proto_data, &risk_data_);
2768 SubmitWithWallet();
2771 void AutofillDialogControllerImpl::OpenTabWithUrl(const GURL& url) {
2772 chrome::NavigateParams params(
2773 chrome::FindBrowserWithWebContents(web_contents()),
2774 url,
2775 content::PAGE_TRANSITION_LINK);
2776 params.disposition = NEW_FOREGROUND_TAB;
2777 chrome::Navigate(&params);
2780 DialogSection AutofillDialogControllerImpl::ActiveBillingSection() const {
2781 return IsPayingWithWallet() ? SECTION_CC_BILLING : SECTION_BILLING;
2784 bool AutofillDialogControllerImpl::IsEditingExistingData(
2785 DialogSection section) const {
2786 return section_editing_state_.count(section) > 0;
2789 bool AutofillDialogControllerImpl::IsManuallyEditingSection(
2790 DialogSection section) const {
2791 return IsEditingExistingData(section) ||
2792 SuggestionsMenuModelForSection(section)->
2793 GetItemKeyForCheckedItem() == kAddNewItemKey;
2796 void AutofillDialogControllerImpl::OnWalletSigninError() {
2797 account_chooser_model_->SetHadWalletSigninError();
2798 GetWalletClient()->CancelRequest();
2799 LogDialogLatencyToShow();
2802 void AutofillDialogControllerImpl::DisableWallet(
2803 wallet::WalletClient::ErrorType error_type) {
2804 signin_helper_.reset();
2805 wallet_items_.reset();
2806 wallet_errors_.clear();
2807 GetWalletClient()->CancelRequest();
2808 SetIsSubmitting(false);
2809 wallet_error_notification_ = GetWalletError(error_type);
2810 account_chooser_model_->SetHadWalletError();
2813 void AutofillDialogControllerImpl::SuggestionsUpdated() {
2814 ScopedViewUpdates updates(view_.get());
2816 const FieldValueMap snapshot = TakeUserInputSnapshot();
2818 suggested_cc_.Reset();
2819 suggested_billing_.Reset();
2820 suggested_cc_billing_.Reset();
2821 suggested_shipping_.Reset();
2822 HidePopup();
2824 suggested_shipping_.AddKeyedItem(
2825 kSameAsBillingKey,
2826 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_USE_BILLING_FOR_SHIPPING));
2828 if (IsPayingWithWallet()) {
2829 const std::vector<wallet::Address*>& addresses =
2830 wallet_items_->addresses();
2832 bool shipping_same_as_billing = profile_->GetPrefs()->GetBoolean(
2833 ::prefs::kAutofillDialogWalletShippingSameAsBilling);
2835 if (shipping_same_as_billing)
2836 suggested_shipping_.SetCheckedItem(kSameAsBillingKey);
2838 for (size_t i = 0; i < addresses.size(); ++i) {
2839 std::string key = base::IntToString(i);
2840 suggested_shipping_.AddKeyedItemWithMinorText(
2841 key,
2842 addresses[i]->DisplayName(),
2843 addresses[i]->DisplayNameDetail());
2844 suggested_shipping_.SetEnabled(
2845 key,
2846 CanAcceptCountry(SECTION_SHIPPING,
2847 addresses[i]->country_name_code()));
2849 // TODO(scr): Move this assignment outside the loop or comment why it
2850 // can't be there.
2851 const std::string default_shipping_address_id =
2852 GetIdToSelect(wallet_items_->default_address_id(),
2853 previous_default_shipping_address_id_,
2854 previously_selected_shipping_address_id_);
2856 if (!shipping_same_as_billing &&
2857 addresses[i]->object_id() == default_shipping_address_id) {
2858 suggested_shipping_.SetCheckedItem(key);
2862 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2863 const std::vector<wallet::WalletItems::MaskedInstrument*>& instruments =
2864 wallet_items_->instruments();
2865 std::string first_active_instrument_key;
2866 std::string default_instrument_key;
2867 for (size_t i = 0; i < instruments.size(); ++i) {
2868 bool allowed = IsInstrumentAllowed(*instruments[i]) &&
2869 CanAcceptCountry(SECTION_BILLING,
2870 instruments[i]->address().country_name_code());
2871 gfx::Image icon = instruments[i]->CardIcon();
2872 if (!allowed && !icon.IsEmpty()) {
2873 // Create a grayed disabled icon.
2874 SkBitmap disabled_bitmap = SkBitmapOperations::CreateHSLShiftedBitmap(
2875 *icon.ToSkBitmap(), kGrayImageShift);
2876 icon = gfx::Image(
2877 gfx::ImageSkia::CreateFrom1xBitmap(disabled_bitmap));
2879 std::string key = base::IntToString(i);
2880 suggested_cc_billing_.AddKeyedItemWithMinorTextAndIcon(
2881 key,
2882 instruments[i]->DisplayName(),
2883 instruments[i]->DisplayNameDetail(),
2884 icon);
2885 suggested_cc_billing_.SetEnabled(key, allowed);
2887 if (allowed) {
2888 if (first_active_instrument_key.empty())
2889 first_active_instrument_key = key;
2891 const std::string default_instrument_id =
2892 GetIdToSelect(wallet_items_->default_instrument_id(),
2893 previous_default_instrument_id_,
2894 previously_selected_instrument_id_);
2895 if (instruments[i]->object_id() == default_instrument_id)
2896 default_instrument_key = key;
2900 suggested_cc_billing_.AddKeyedItem(
2901 kAddNewItemKey,
2902 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_DETAILS));
2903 if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
2904 suggested_cc_billing_.AddKeyedItemWithMinorText(
2905 kManageItemsKey,
2906 l10n_util::GetStringUTF16(
2907 IDS_AUTOFILL_DIALOG_MANAGE_BILLING_DETAILS),
2908 base::UTF8ToUTF16(wallet::GetManageInstrumentsUrl(0U).host()));
2911 // Determine which instrument item should be selected.
2912 if (!default_instrument_key.empty())
2913 suggested_cc_billing_.SetCheckedItem(default_instrument_key);
2914 else if (!first_active_instrument_key.empty())
2915 suggested_cc_billing_.SetCheckedItem(first_active_instrument_key);
2916 else
2917 suggested_cc_billing_.SetCheckedItem(kAddNewItemKey);
2919 } else {
2920 if (IsAutofillEnabled()) {
2921 PersonalDataManager* manager = GetManager();
2922 const std::vector<CreditCard*>& cards = manager->GetCreditCards();
2923 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
2924 for (size_t i = 0; i < cards.size(); ++i) {
2925 if (!i18ninput::CardHasCompleteAndVerifiedData(*cards[i]))
2926 continue;
2928 suggested_cc_.AddKeyedItemWithIcon(
2929 cards[i]->guid(),
2930 cards[i]->Label(),
2931 rb.GetImageNamed(CreditCard::IconResourceId(cards[i]->type())));
2934 const std::vector<AutofillProfile*>& profiles = manager->GetProfiles();
2935 std::vector<base::string16> labels;
2936 AutofillProfile::CreateDifferentiatingLabels(profiles, &labels);
2937 DCHECK_EQ(labels.size(), profiles.size());
2938 for (size_t i = 0; i < profiles.size(); ++i) {
2939 const AutofillProfile& profile = *profiles[i];
2940 if (!i18ninput::AddressHasCompleteAndVerifiedData(profile) ||
2941 !i18ninput::CountryIsFullySupported(
2942 base::UTF16ToASCII(profile.GetRawInfo(ADDRESS_HOME_COUNTRY)))) {
2943 continue;
2946 // Don't add variants for addresses: name is part of credit card and
2947 // we'll just ignore email and phone number variants.
2948 suggested_shipping_.AddKeyedItem(profile.guid(), labels[i]);
2949 suggested_shipping_.SetEnabled(
2950 profile.guid(),
2951 CanAcceptCountry(
2952 SECTION_SHIPPING,
2953 base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_COUNTRY))));
2954 if (!profile.GetRawInfo(EMAIL_ADDRESS).empty() &&
2955 !profile.IsPresentButInvalid(EMAIL_ADDRESS)) {
2956 suggested_billing_.AddKeyedItem(profile.guid(), labels[i]);
2957 suggested_billing_.SetEnabled(
2958 profile.guid(),
2959 CanAcceptCountry(
2960 SECTION_BILLING,
2961 base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_COUNTRY))));
2966 suggested_cc_.AddKeyedItem(
2967 kAddNewItemKey,
2968 l10n_util::GetStringUTF16(IsAutofillEnabled() ?
2969 IDS_AUTOFILL_DIALOG_ADD_CREDIT_CARD :
2970 IDS_AUTOFILL_DIALOG_ENTER_CREDIT_CARD));
2971 suggested_cc_.AddKeyedItem(
2972 kManageItemsKey,
2973 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_CREDIT_CARD));
2974 suggested_billing_.AddKeyedItem(
2975 kAddNewItemKey,
2976 l10n_util::GetStringUTF16(IsAutofillEnabled() ?
2977 IDS_AUTOFILL_DIALOG_ADD_BILLING_ADDRESS :
2978 IDS_AUTOFILL_DIALOG_ENTER_BILLING_DETAILS));
2979 suggested_billing_.AddKeyedItem(
2980 kManageItemsKey,
2981 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_BILLING_ADDRESS));
2984 suggested_shipping_.AddKeyedItem(
2985 kAddNewItemKey,
2986 l10n_util::GetStringUTF16(IsPayingWithWallet() || IsAutofillEnabled() ?
2987 IDS_AUTOFILL_DIALOG_ADD_SHIPPING_ADDRESS :
2988 IDS_AUTOFILL_DIALOG_USE_DIFFERENT_SHIPPING_ADDRESS));
2990 if (!IsPayingWithWallet()) {
2991 if (IsAutofillEnabled()) {
2992 suggested_shipping_.AddKeyedItem(
2993 kManageItemsKey,
2994 l10n_util::GetStringUTF16(
2995 IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS));
2997 } else if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
2998 suggested_shipping_.AddKeyedItemWithMinorText(
2999 kManageItemsKey,
3000 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS),
3001 base::UTF8ToUTF16(wallet::GetManageAddressesUrl(0U).host()));
3004 if (!IsPayingWithWallet() && IsAutofillEnabled()) {
3005 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3006 DialogSection section = static_cast<DialogSection>(i);
3007 if (!SectionIsActive(section))
3008 continue;
3010 // Set the starting choice for the menu. First set to the default in case
3011 // the GUID saved in prefs refers to a profile that no longer exists.
3012 std::string guid;
3013 GetDefaultAutofillChoice(section, &guid);
3014 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3015 model->SetCheckedItem(guid);
3016 if (GetAutofillChoice(section, &guid))
3017 model->SetCheckedItem(guid);
3021 if (view_)
3022 view_->ModelChanged();
3024 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3025 ResetSectionInput(static_cast<DialogSection>(i));
3028 FieldValueMap::const_iterator billing_it =
3029 snapshot.find(ADDRESS_BILLING_COUNTRY);
3030 if (billing_it != snapshot.end())
3031 RebuildInputsForCountry(ActiveBillingSection(), billing_it->second, true);
3033 FieldValueMap::const_iterator shipping_it =
3034 snapshot.find(ADDRESS_HOME_COUNTRY);
3035 if (shipping_it != snapshot.end())
3036 RebuildInputsForCountry(SECTION_SHIPPING, shipping_it->second, true);
3038 RestoreUserInputFromSnapshot(snapshot);
3040 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3041 DialogSection section = static_cast<DialogSection>(i);
3042 if (!SectionIsActive(section))
3043 continue;
3045 ShowEditUiIfBadSuggestion(section);
3046 UpdateSection(section);
3049 UpdateForErrors();
3052 void AutofillDialogControllerImpl::FillOutputForSectionWithComparator(
3053 DialogSection section,
3054 const FormStructure::InputFieldComparator& compare) {
3055 if (!SectionIsActive(section))
3056 return;
3058 DetailInputs inputs;
3059 std::string country_code = CountryCodeForSection(section);
3060 common::BuildInputsForSection(section, country_code, &inputs);
3061 std::vector<ServerFieldType> types = common::TypesFromInputs(inputs);
3063 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3064 if (wrapper) {
3065 // Only fill in data that is associated with this section.
3066 wrapper->FillFormStructure(types, compare, &form_structure_);
3068 // CVC needs special-casing because the CreditCard class doesn't store or
3069 // handle them. This isn't necessary when filling the combined CC and
3070 // billing section as CVC comes from |full_wallet_| in this case.
3071 if (section == SECTION_CC)
3072 SetOutputForFieldsOfType(CREDIT_CARD_VERIFICATION_CODE, view_->GetCvc());
3074 // When filling from Wallet data, use the email address associated with the
3075 // account. There is no other email address stored as part of a Wallet
3076 // address.
3077 if (section == SECTION_CC_BILLING) {
3078 SetOutputForFieldsOfType(
3079 EMAIL_ADDRESS, account_chooser_model_->GetActiveWalletAccountName());
3081 } else {
3082 // The user manually input data. If using Autofill, save the info as new or
3083 // edited data. Always fill local data into |form_structure_|.
3084 FieldValueMap output;
3085 view_->GetUserInput(section, &output);
3087 if (section == SECTION_CC) {
3088 CreditCard card;
3089 FillFormGroupFromOutputs(output, &card);
3091 // The card holder name comes from the billing address section.
3092 card.SetRawInfo(CREDIT_CARD_NAME,
3093 GetValueFromSection(SECTION_BILLING, NAME_BILLING_FULL));
3095 if (ShouldSaveDetailsLocally()) {
3096 card.set_origin(kAutofillDialogOrigin);
3098 std::string guid = GetManager()->SaveImportedCreditCard(card);
3099 newly_saved_data_model_guids_[section] = guid;
3100 DCHECK(!profile()->IsOffTheRecord());
3101 newly_saved_card_.reset(new CreditCard(card));
3104 AutofillCreditCardWrapper card_wrapper(&card);
3105 card_wrapper.FillFormStructure(types, compare, &form_structure_);
3107 // Again, CVC needs special-casing. Fill it in directly from |output|.
3108 SetOutputForFieldsOfType(
3109 CREDIT_CARD_VERIFICATION_CODE,
3110 output[CREDIT_CARD_VERIFICATION_CODE]);
3111 } else {
3112 AutofillProfile profile;
3113 FillFormGroupFromOutputs(output, &profile);
3115 if (ShouldSaveDetailsLocally()) {
3116 profile.set_origin(RulesAreLoaded(section) ?
3117 kAutofillDialogOrigin : source_url_.GetOrigin().spec());
3119 std::string guid = GetManager()->SaveImportedProfile(profile);
3120 newly_saved_data_model_guids_[section] = guid;
3123 AutofillProfileWrapper profile_wrapper(&profile);
3124 profile_wrapper.FillFormStructure(types, compare, &form_structure_);
3129 void AutofillDialogControllerImpl::FillOutputForSection(DialogSection section) {
3130 FillOutputForSectionWithComparator(
3131 section, base::Bind(common::ServerTypeMatchesField, section));
3134 bool AutofillDialogControllerImpl::FormStructureCaresAboutSection(
3135 DialogSection section) const {
3136 // For now, only SECTION_SHIPPING may be omitted due to a site not asking for
3137 // any of the fields.
3138 if (section == SECTION_SHIPPING)
3139 return cares_about_shipping_;
3141 return true;
3144 void AutofillDialogControllerImpl::SetOutputForFieldsOfType(
3145 ServerFieldType type,
3146 const base::string16& output) {
3147 for (size_t i = 0; i < form_structure_.field_count(); ++i) {
3148 AutofillField* field = form_structure_.field(i);
3149 if (field->Type().GetStorableType() == type)
3150 field->value = output;
3154 base::string16 AutofillDialogControllerImpl::GetValueFromSection(
3155 DialogSection section,
3156 ServerFieldType type) {
3157 DCHECK(SectionIsActive(section));
3159 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3160 if (wrapper)
3161 return wrapper->GetInfo(AutofillType(type));
3163 FieldValueMap output;
3164 view_->GetUserInput(section, &output);
3165 return output[type];
3168 bool AutofillDialogControllerImpl::CanAcceptCountry(
3169 DialogSection section,
3170 const std::string& country_code) {
3171 DCHECK_EQ(2U, country_code.size());
3173 if (section == SECTION_CC_BILLING)
3174 return LowerCaseEqualsASCII(country_code, "us");
3176 CountryComboboxModel* model = CountryComboboxModelForSection(section);
3177 const std::vector<AutofillCountry*>& countries = model->countries();
3178 for (size_t i = 0; i < countries.size(); ++i) {
3179 if (countries[i] && countries[i]->country_code() == country_code)
3180 return true;
3183 return false;
3186 bool AutofillDialogControllerImpl::ShouldSuggestProfile(
3187 DialogSection section,
3188 const AutofillProfile& profile) {
3189 std::string country_code =
3190 base::UTF16ToASCII(profile.GetRawInfo(ADDRESS_HOME_COUNTRY));
3191 return country_code.empty() || CanAcceptCountry(section, country_code);
3194 SuggestionsMenuModel* AutofillDialogControllerImpl::
3195 SuggestionsMenuModelForSection(DialogSection section) {
3196 switch (section) {
3197 case SECTION_CC:
3198 return &suggested_cc_;
3199 case SECTION_BILLING:
3200 return &suggested_billing_;
3201 case SECTION_SHIPPING:
3202 return &suggested_shipping_;
3203 case SECTION_CC_BILLING:
3204 return &suggested_cc_billing_;
3207 NOTREACHED();
3208 return NULL;
3211 const SuggestionsMenuModel* AutofillDialogControllerImpl::
3212 SuggestionsMenuModelForSection(DialogSection section) const {
3213 return const_cast<AutofillDialogControllerImpl*>(this)->
3214 SuggestionsMenuModelForSection(section);
3217 DialogSection AutofillDialogControllerImpl::SectionForSuggestionsMenuModel(
3218 const SuggestionsMenuModel& model) {
3219 if (&model == &suggested_cc_)
3220 return SECTION_CC;
3222 if (&model == &suggested_billing_)
3223 return SECTION_BILLING;
3225 if (&model == &suggested_cc_billing_)
3226 return SECTION_CC_BILLING;
3228 DCHECK_EQ(&model, &suggested_shipping_);
3229 return SECTION_SHIPPING;
3232 CountryComboboxModel* AutofillDialogControllerImpl::
3233 CountryComboboxModelForSection(DialogSection section) {
3234 if (section == SECTION_BILLING)
3235 return billing_country_combobox_model_.get();
3237 if (section == SECTION_SHIPPING)
3238 return shipping_country_combobox_model_.get();
3240 return NULL;
3243 void AutofillDialogControllerImpl::GetI18nValidatorSuggestions(
3244 DialogSection section,
3245 ServerFieldType type,
3246 std::vector<base::string16>* popup_values,
3247 std::vector<base::string16>* popup_labels,
3248 std::vector<base::string16>* popup_icons) {
3249 AddressField focused_field;
3250 if (!i18ninput::FieldForType(type, &focused_field))
3251 return;
3253 FieldValueMap inputs;
3254 view_->GetUserInput(section, &inputs);
3256 AutofillProfile profile;
3257 FillFormGroupFromOutputs(inputs, &profile);
3259 AddressData user_input;
3260 i18ninput::CreateAddressData(
3261 base::Bind(&GetInfoFromProfile, profile), &user_input);
3263 static const size_t kSuggestionsLimit = 10;
3264 AddressValidator::Status status = GetValidator()->GetSuggestions(
3265 user_input, focused_field, kSuggestionsLimit,
3266 &i18n_validator_suggestions_);
3268 if (status != AddressValidator::SUCCESS)
3269 return;
3271 for (size_t i = 0; i < i18n_validator_suggestions_.size(); ++i) {
3272 popup_values->push_back(base::UTF8ToUTF16(
3273 i18n_validator_suggestions_[i].GetFieldValue(focused_field)));
3275 // Disambiguate the suggestion by showing the smallest administrative
3276 // region of the suggested address:
3277 // ADMIN_AREA > LOCALITY > DEPENDENT_LOCALITY
3278 popup_labels->push_back(base::string16());
3279 for (int field = ::i18n::addressinput::DEPENDENT_LOCALITY;
3280 field >= ::i18n::addressinput::ADMIN_AREA;
3281 --field) {
3282 const std::string& field_value =
3283 i18n_validator_suggestions_[i].GetFieldValue(
3284 static_cast<AddressField>(field));
3285 if (focused_field != field && !field_value.empty()) {
3286 popup_labels->back().assign(base::UTF8ToUTF16(field_value));
3287 break;
3291 popup_icons->resize(popup_values->size());
3294 DetailInputs* AutofillDialogControllerImpl::MutableRequestedFieldsForSection(
3295 DialogSection section) {
3296 return const_cast<DetailInputs*>(&RequestedFieldsForSection(section));
3299 std::vector<ServerFieldType> AutofillDialogControllerImpl::
3300 RequestedTypesForSection(DialogSection section) const {
3301 return common::TypesFromInputs(RequestedFieldsForSection(section));
3304 std::string AutofillDialogControllerImpl::CountryCodeForSection(
3305 DialogSection section) {
3306 base::string16 country;
3308 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3309 if (wrapper) {
3310 country = wrapper->GetInfo(AutofillType(CountryTypeForSection(section)));
3311 } else {
3312 FieldValueMap outputs;
3313 view_->GetUserInput(section, &outputs);
3314 country = outputs[CountryTypeForSection(section)];
3317 return AutofillCountry::GetCountryCode(
3318 country, g_browser_process->GetApplicationLocale());
3321 bool AutofillDialogControllerImpl::RebuildInputsForCountry(
3322 DialogSection section,
3323 const base::string16& country_name,
3324 bool should_clobber) {
3325 CountryComboboxModel* model = CountryComboboxModelForSection(section);
3326 if (!model)
3327 return false;
3329 std::string country_code = AutofillCountry::GetCountryCode(
3330 country_name, g_browser_process->GetApplicationLocale());
3331 DCHECK(CanAcceptCountry(section, country_code));
3333 if (view_ && !should_clobber) {
3334 FieldValueMap outputs;
3335 view_->GetUserInput(section, &outputs);
3337 // If |country_name| is the same as the view, no-op and let the caller know.
3338 if (outputs[CountryTypeForSection(section)] == country_name)
3339 return false;
3342 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
3343 inputs->clear();
3344 common::BuildInputsForSection(section, country_code, inputs);
3345 return true;
3348 void AutofillDialogControllerImpl::HidePopup() {
3349 if (popup_controller_.get())
3350 popup_controller_->Hide();
3351 popup_input_type_ = UNKNOWN_TYPE;
3354 void AutofillDialogControllerImpl::SetEditingExistingData(
3355 DialogSection section, bool editing) {
3356 if (editing)
3357 section_editing_state_.insert(section);
3358 else
3359 section_editing_state_.erase(section);
3362 bool AutofillDialogControllerImpl::IsASuggestionItemKey(
3363 const std::string& key) const {
3364 return !key.empty() &&
3365 key != kAddNewItemKey &&
3366 key != kManageItemsKey &&
3367 key != kSameAsBillingKey;
3370 bool AutofillDialogControllerImpl::IsAutofillEnabled() const {
3371 return profile_->GetPrefs()->GetBoolean(prefs::kAutofillEnabled);
3374 bool AutofillDialogControllerImpl::IsManuallyEditingAnySection() const {
3375 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
3376 if (IsManuallyEditingSection(static_cast<DialogSection>(section)))
3377 return true;
3379 return false;
3382 base::string16 AutofillDialogControllerImpl::CreditCardNumberValidityMessage(
3383 const base::string16& number) const {
3384 if (!number.empty() && !autofill::IsValidCreditCardNumber(number)) {
3385 return l10n_util::GetStringUTF16(
3386 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_NUMBER);
3389 base::string16 message;
3390 if (IsPayingWithWallet() && !wallet_items_->SupportsCard(number, &message))
3391 return message;
3393 // Card number is good and supported.
3394 return base::string16();
3397 bool AutofillDialogControllerImpl::AllSectionsAreValid() {
3398 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
3399 if (!SectionIsValid(static_cast<DialogSection>(section)))
3400 return false;
3402 return true;
3405 bool AutofillDialogControllerImpl::SectionIsValid(
3406 DialogSection section) {
3407 if (!IsManuallyEditingSection(section))
3408 return true;
3410 FieldValueMap detail_outputs;
3411 view_->GetUserInput(section, &detail_outputs);
3412 return !InputsAreValid(section, detail_outputs).HasSureErrors();
3415 bool AutofillDialogControllerImpl::RulesAreLoaded(DialogSection section) {
3416 AddressData address_data;
3417 address_data.country_code = CountryCodeForSection(section);
3418 AddressValidator::Status status = GetValidator()->ValidateAddress(
3419 address_data, AddressProblemFilter(), NULL);
3420 return status == AddressValidator::SUCCESS;
3423 bool AutofillDialogControllerImpl::IsCreditCardExpirationValid(
3424 const base::string16& year,
3425 const base::string16& month) const {
3426 // If the expiration is in the past as per the local clock, it's invalid.
3427 base::Time now = base::Time::Now();
3428 if (!autofill::IsValidCreditCardExpirationDate(year, month, now))
3429 return false;
3431 const wallet::WalletItems::MaskedInstrument* instrument =
3432 ActiveInstrument();
3433 if (instrument) {
3434 const std::string& locale = g_browser_process->GetApplicationLocale();
3435 int month_int;
3436 if (base::StringToInt(month, &month_int) &&
3437 instrument->status() ==
3438 wallet::WalletItems::MaskedInstrument::EXPIRED &&
3439 year ==
3440 instrument->GetInfo(
3441 AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), locale) &&
3442 month_int == instrument->expiration_month()) {
3443 // Otherwise, if the user is editing an instrument that's deemed expired
3444 // by the Online Wallet server, mark it invalid on selection.
3445 return false;
3449 return true;
3452 bool AutofillDialogControllerImpl::HasInvalidAddress(
3453 const AutofillProfile& profile) {
3454 AddressData address_data;
3455 i18ninput::CreateAddressData(base::Bind(&GetInfoFromProfile, profile),
3456 &address_data);
3458 AddressProblems problems;
3459 GetValidator()->ValidateAddress(address_data,
3460 AddressProblemFilter(),
3461 &problems);
3462 return !problems.empty();
3465 bool AutofillDialogControllerImpl::ShouldUseBillingForShipping() {
3466 return SectionIsActive(SECTION_SHIPPING) &&
3467 suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey;
3470 bool AutofillDialogControllerImpl::ShouldSaveDetailsLocally() {
3471 // It's possible that the user checked [X] Save details locally before
3472 // switching payment methods, so only ask the view whether to save details
3473 // locally if that checkbox is showing (currently if not paying with wallet).
3474 // Also, if the user isn't editing any sections, there's no data to save
3475 // locally.
3476 return ShouldOfferToSaveInChrome() && view_->SaveDetailsLocally();
3479 void AutofillDialogControllerImpl::SetIsSubmitting(bool submitting) {
3480 is_submitting_ = submitting;
3482 if (!submitting)
3483 full_wallet_.reset();
3485 if (view_) {
3486 ScopedViewUpdates updates(view_.get());
3487 view_->UpdateButtonStrip();
3488 view_->UpdateOverlay();
3489 view_->UpdateNotificationArea();
3493 bool AutofillDialogControllerImpl::AreLegalDocumentsCurrent() const {
3494 return has_accepted_legal_documents_ ||
3495 (wallet_items_ && wallet_items_->legal_documents().empty());
3498 void AutofillDialogControllerImpl::AcceptLegalTerms() {
3499 content::BrowserThread::PostTask(
3500 content::BrowserThread::IO, FROM_HERE,
3501 base::Bind(&UserDidOptIntoLocationServices));
3502 PrefService* local_state = g_browser_process->local_state();
3503 ListPrefUpdate accepted(
3504 local_state, ::prefs::kAutofillDialogWalletLocationAcceptance);
3505 accepted->AppendIfNotPresent(new base::StringValue(
3506 account_chooser_model_->GetActiveWalletAccountName()));
3508 if (AreLegalDocumentsCurrent()) {
3509 LoadRiskFingerprintData();
3510 } else {
3511 GetWalletClient()->AcceptLegalDocuments(
3512 wallet_items_->legal_documents(),
3513 wallet_items_->google_transaction_id());
3517 void AutofillDialogControllerImpl::SubmitWithWallet() {
3518 active_instrument_id_.clear();
3519 active_address_id_.clear();
3520 full_wallet_.reset();
3522 const wallet::WalletItems::MaskedInstrument* active_instrument =
3523 ActiveInstrument();
3524 if (!IsManuallyEditingSection(SECTION_CC_BILLING)) {
3525 active_instrument_id_ = active_instrument->object_id();
3526 DCHECK(!active_instrument_id_.empty());
3529 const wallet::Address* active_address = ActiveShippingAddress();
3530 if (!IsManuallyEditingSection(SECTION_SHIPPING) &&
3531 !ShouldUseBillingForShipping() &&
3532 IsShippingAddressRequired()) {
3533 active_address_id_ = active_address->object_id();
3534 DCHECK(!active_address_id_.empty());
3537 scoped_ptr<wallet::Instrument> inputted_instrument =
3538 CreateTransientInstrument();
3540 scoped_ptr<wallet::Address> inputted_address;
3541 if (active_address_id_.empty() && IsShippingAddressRequired()) {
3542 if (ShouldUseBillingForShipping()) {
3543 const wallet::Address& address = inputted_instrument ?
3544 *inputted_instrument->address() : active_instrument->address();
3545 // Try to find an exact matched shipping address and use it for shipping,
3546 // otherwise save it as a new shipping address. http://crbug.com/225442
3547 const wallet::Address* duplicated_address =
3548 FindDuplicateAddress(wallet_items_->addresses(), address);
3549 if (duplicated_address) {
3550 active_address_id_ = duplicated_address->object_id();
3551 DCHECK(!active_address_id_.empty());
3552 } else {
3553 inputted_address.reset(new wallet::Address(address));
3554 DCHECK(inputted_address->object_id().empty());
3556 } else {
3557 inputted_address = CreateTransientAddress();
3561 // If there's neither an address nor instrument to save, |GetFullWallet()|
3562 // is called when the risk fingerprint is loaded.
3563 if (!active_instrument_id_.empty() &&
3564 (!active_address_id_.empty() || !IsShippingAddressRequired())) {
3565 GetFullWallet();
3566 return;
3569 GetWalletClient()->SaveToWallet(
3570 inputted_instrument.Pass(),
3571 inputted_address.Pass(),
3572 IsEditingExistingData(SECTION_CC_BILLING) ? active_instrument : NULL,
3573 IsEditingExistingData(SECTION_SHIPPING) ? active_address : NULL);
3576 scoped_ptr<wallet::Instrument> AutofillDialogControllerImpl::
3577 CreateTransientInstrument() {
3578 if (!active_instrument_id_.empty())
3579 return scoped_ptr<wallet::Instrument>();
3581 FieldValueMap output;
3582 view_->GetUserInput(SECTION_CC_BILLING, &output);
3584 CreditCard card;
3585 AutofillProfile profile;
3586 base::string16 cvc;
3587 GetBillingInfoFromOutputs(output, &card, &cvc, &profile);
3588 CanonicalizeState(validator_.get(), &profile);
3590 return scoped_ptr<wallet::Instrument>(
3591 new wallet::Instrument(card, cvc, profile));
3594 scoped_ptr<wallet::Address>AutofillDialogControllerImpl::
3595 CreateTransientAddress() {
3596 // If not using billing for shipping, just scrape the view.
3597 FieldValueMap output;
3598 view_->GetUserInput(SECTION_SHIPPING, &output);
3600 AutofillProfile profile;
3601 FillFormGroupFromOutputs(output, &profile);
3602 CanonicalizeState(validator_.get(), &profile);
3604 return scoped_ptr<wallet::Address>(new wallet::Address(profile));
3607 void AutofillDialogControllerImpl::GetFullWallet() {
3608 DCHECK(is_submitting_);
3609 DCHECK(IsPayingWithWallet());
3610 DCHECK(wallet_items_);
3611 DCHECK(!active_instrument_id_.empty());
3612 DCHECK(!active_address_id_.empty() || !IsShippingAddressRequired());
3614 std::vector<wallet::WalletClient::RiskCapability> capabilities;
3615 capabilities.push_back(wallet::WalletClient::VERIFY_CVC);
3617 GetWalletClient()->GetFullWallet(wallet::WalletClient::FullWalletRequest(
3618 active_instrument_id_,
3619 active_address_id_,
3620 wallet_items_->google_transaction_id(),
3621 capabilities,
3622 wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)));
3625 void AutofillDialogControllerImpl::HandleSaveOrUpdateRequiredActions(
3626 const std::vector<wallet::RequiredAction>& required_actions) {
3627 DCHECK(!required_actions.empty());
3629 // TODO(ahutter): Investigate if we need to support more generic actions on
3630 // this call such as GAIA_AUTH. See crbug.com/243457.
3631 for (std::vector<wallet::RequiredAction>::const_iterator iter =
3632 required_actions.begin();
3633 iter != required_actions.end(); ++iter) {
3634 if (*iter != wallet::INVALID_FORM_FIELD) {
3635 // TODO(dbeam): handle this more gracefully.
3636 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
3639 SetIsSubmitting(false);
3642 void AutofillDialogControllerImpl::FinishSubmit() {
3643 if (IsPayingWithWallet()) {
3644 ScopedViewUpdates updates(view_.get());
3645 view_->UpdateOverlay();
3647 card_generated_animation_.Start();
3648 return;
3650 DoFinishSubmit();
3653 void AutofillDialogControllerImpl::AnimationProgressed(
3654 const gfx::Animation* animation) {
3655 DCHECK_EQ(animation, &card_generated_animation_);
3656 PushOverlayUpdate();
3659 void AutofillDialogControllerImpl::AnimationEnded(
3660 const gfx::Animation* animation) {
3661 DCHECK_EQ(animation, &card_generated_animation_);
3662 DoFinishSubmit();
3665 void AutofillDialogControllerImpl::OnAddressValidationRulesLoaded(
3666 const std::string& country_code,
3667 bool success) {
3668 // Rules may load instantly (during initialization, before the view is
3669 // even ready). We'll validate when the view is created.
3670 if (!view_)
3671 return;
3673 ScopedViewUpdates updates(view_.get());
3675 // TODO(dbeam): should we retry on failure?
3676 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3677 DialogSection section = static_cast<DialogSection>(i);
3678 if (!SectionIsActive(section) ||
3679 CountryCodeForSection(section) != country_code) {
3680 continue;
3683 if (IsManuallyEditingSection(section) &&
3684 needs_validation_.count(section)) {
3685 view_->ValidateSection(section);
3686 needs_validation_.erase(section);
3687 } else if (success) {
3688 ShowEditUiIfBadSuggestion(section);
3689 UpdateSection(section);
3694 void AutofillDialogControllerImpl::DoFinishSubmit() {
3695 FillOutputForSection(SECTION_CC);
3696 FillOutputForSection(SECTION_BILLING);
3697 FillOutputForSection(SECTION_CC_BILLING);
3699 if (ShouldUseBillingForShipping()) {
3700 FillOutputForSectionWithComparator(
3701 SECTION_BILLING,
3702 base::Bind(ServerTypeMatchesShippingField));
3703 FillOutputForSectionWithComparator(
3704 SECTION_CC,
3705 base::Bind(ServerTypeMatchesShippingField));
3706 FillOutputForSectionWithComparator(
3707 SECTION_CC_BILLING,
3708 base::Bind(ServerTypeMatchesShippingField));
3709 } else {
3710 FillOutputForSection(SECTION_SHIPPING);
3713 if (IsPayingWithWallet()) {
3714 if (SectionIsActive(SECTION_SHIPPING)) {
3715 profile_->GetPrefs()->SetBoolean(
3716 ::prefs::kAutofillDialogWalletShippingSameAsBilling,
3717 suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey);
3719 } else if (ShouldOfferToSaveInChrome()) {
3720 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3721 DialogSection section = static_cast<DialogSection>(i);
3722 if (!SectionIsActive(section))
3723 continue;
3725 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3726 std::string item_key = model->GetItemKeyForCheckedItem();
3727 if (IsASuggestionItemKey(item_key) || item_key == kSameAsBillingKey) {
3728 PersistAutofillChoice(section, item_key);
3729 } else if (item_key == kAddNewItemKey && ShouldSaveDetailsLocally()) {
3730 DCHECK(newly_saved_data_model_guids_.count(section));
3731 PersistAutofillChoice(section, newly_saved_data_model_guids_[section]);
3735 profile_->GetPrefs()->SetBoolean(::prefs::kAutofillDialogSaveData,
3736 view_->SaveDetailsLocally());
3739 // On a successful submit, if the user manually selected "pay without wallet",
3740 // stop trying to pay with Wallet on future runs of the dialog. On the other
3741 // hand, if there was an error that prevented the user from having the choice
3742 // of using Wallet, leave the pref alone.
3743 if (!wallet_error_notification_ &&
3744 account_chooser_model_->HasAccountsToChoose()) {
3745 profile_->GetPrefs()->SetBoolean(
3746 ::prefs::kAutofillDialogPayWithoutWallet,
3747 !account_chooser_model_->WalletIsSelected());
3750 LogOnFinishSubmitMetrics();
3752 // Callback should be called as late as possible.
3753 callback_.Run(&form_structure_);
3754 data_was_passed_back_ = true;
3756 // This might delete us.
3757 Hide();
3760 void AutofillDialogControllerImpl::PersistAutofillChoice(
3761 DialogSection section,
3762 const std::string& guid) {
3763 DCHECK(!IsPayingWithWallet() && ShouldOfferToSaveInChrome());
3764 scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
3765 value->SetString(kGuidPrefKey, guid);
3767 DictionaryPrefUpdate updater(profile()->GetPrefs(),
3768 ::prefs::kAutofillDialogAutofillDefault);
3769 base::DictionaryValue* autofill_choice = updater.Get();
3770 autofill_choice->Set(SectionToPrefString(section), value.release());
3773 void AutofillDialogControllerImpl::GetDefaultAutofillChoice(
3774 DialogSection section,
3775 std::string* guid) {
3776 DCHECK(!IsPayingWithWallet() && IsAutofillEnabled());
3777 // The default choice is the first thing in the menu that is a suggestion
3778 // item.
3779 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3780 for (int i = 0; i < model->GetItemCount(); ++i) {
3781 // Try the first suggestion item that is enabled.
3782 if (IsASuggestionItemKey(model->GetItemKeyAt(i)) && model->IsEnabledAt(i)) {
3783 *guid = model->GetItemKeyAt(i);
3784 return;
3785 // Fall back to the first non-suggestion key.
3786 } else if (!IsASuggestionItemKey(model->GetItemKeyAt(i)) && guid->empty()) {
3787 *guid = model->GetItemKeyAt(i);
3792 bool AutofillDialogControllerImpl::GetAutofillChoice(DialogSection section,
3793 std::string* guid) {
3794 DCHECK(!IsPayingWithWallet() && IsAutofillEnabled());
3795 const base::DictionaryValue* choices = profile()->GetPrefs()->GetDictionary(
3796 ::prefs::kAutofillDialogAutofillDefault);
3797 if (!choices)
3798 return false;
3800 const base::DictionaryValue* choice = NULL;
3801 if (!choices->GetDictionary(SectionToPrefString(section), &choice))
3802 return false;
3804 choice->GetString(kGuidPrefKey, guid);
3805 return true;
3808 void AutofillDialogControllerImpl::LogOnFinishSubmitMetrics() {
3809 GetMetricLogger().LogDialogUiDuration(
3810 base::Time::Now() - dialog_shown_timestamp_,
3811 AutofillMetrics::DIALOG_ACCEPTED);
3813 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_ACCEPTED);
3815 AutofillMetrics::DialogDismissalState dismissal_state;
3816 if (!IsManuallyEditingAnySection()) {
3817 dismissal_state = IsPayingWithWallet() ?
3818 AutofillMetrics::DIALOG_ACCEPTED_EXISTING_WALLET_DATA :
3819 AutofillMetrics::DIALOG_ACCEPTED_EXISTING_AUTOFILL_DATA;
3820 } else if (IsPayingWithWallet()) {
3821 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_WALLET;
3822 } else if (ShouldSaveDetailsLocally()) {
3823 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_AUTOFILL;
3824 } else {
3825 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_NO_SAVE;
3828 GetMetricLogger().LogDialogDismissalState(dismissal_state);
3831 void AutofillDialogControllerImpl::LogOnCancelMetrics() {
3832 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_CANCELED);
3834 AutofillMetrics::DialogDismissalState dismissal_state;
3835 if (ShouldShowSignInWebView())
3836 dismissal_state = AutofillMetrics::DIALOG_CANCELED_DURING_SIGNIN;
3837 else if (!IsManuallyEditingAnySection())
3838 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_EDITS;
3839 else if (AllSectionsAreValid())
3840 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_INVALID_FIELDS;
3841 else
3842 dismissal_state = AutofillMetrics::DIALOG_CANCELED_WITH_INVALID_FIELDS;
3844 GetMetricLogger().LogDialogDismissalState(dismissal_state);
3846 GetMetricLogger().LogDialogUiDuration(
3847 base::Time::Now() - dialog_shown_timestamp_,
3848 AutofillMetrics::DIALOG_CANCELED);
3851 void AutofillDialogControllerImpl::LogSuggestionItemSelectedMetric(
3852 const SuggestionsMenuModel& model) {
3853 DialogSection section = SectionForSuggestionsMenuModel(model);
3855 AutofillMetrics::DialogUiEvent dialog_ui_event;
3856 if (model.GetItemKeyForCheckedItem() == kAddNewItemKey) {
3857 // Selected to add a new item.
3858 dialog_ui_event = common::DialogSectionToUiItemAddedEvent(section);
3859 } else if (IsASuggestionItemKey(model.GetItemKeyForCheckedItem())) {
3860 // Selected an existing item.
3861 dialog_ui_event = common::DialogSectionToUiSelectionChangedEvent(section);
3862 } else {
3863 // TODO(estade): add logging for "Manage items" or "Use billing for
3864 // shipping"?
3865 return;
3868 GetMetricLogger().LogDialogUiEvent(dialog_ui_event);
3871 void AutofillDialogControllerImpl::LogDialogLatencyToShow() {
3872 if (was_ui_latency_logged_)
3873 return;
3875 GetMetricLogger().LogDialogLatencyToShow(
3876 base::Time::Now() - dialog_shown_timestamp_);
3877 was_ui_latency_logged_ = true;
3880 AutofillMetrics::DialogInitialUserStateMetric
3881 AutofillDialogControllerImpl::GetInitialUserState() const {
3882 // Consider a user to be an Autofill user if the user has any credit cards
3883 // or addresses saved. Check that the item count is greater than 2 because
3884 // an "empty" menu still has the "add new" menu item and "manage" menu item.
3885 const bool has_autofill_profiles =
3886 suggested_cc_.GetItemCount() > 2 ||
3887 suggested_billing_.GetItemCount() > 2;
3889 if (SignedInState() != SIGNED_IN) {
3890 // Not signed in.
3891 return has_autofill_profiles ?
3892 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_HAS_AUTOFILL :
3893 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_NO_AUTOFILL;
3896 // Signed in.
3897 if (wallet_items_->instruments().empty()) {
3898 // No Wallet items.
3899 return has_autofill_profiles ?
3900 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_HAS_AUTOFILL :
3901 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_NO_AUTOFILL;
3904 // Has Wallet items.
3905 return has_autofill_profiles ?
3906 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_HAS_AUTOFILL :
3907 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_NO_AUTOFILL;
3910 void AutofillDialogControllerImpl::MaybeShowCreditCardBubble() {
3911 if (!data_was_passed_back_)
3912 return;
3914 if (newly_saved_card_) {
3915 scoped_ptr<AutofillProfile> billing_profile;
3916 if (IsManuallyEditingSection(SECTION_BILLING)) {
3917 // Scrape the view as the user's entering or updating information.
3918 FieldValueMap outputs;
3919 view_->GetUserInput(SECTION_BILLING, &outputs);
3920 billing_profile.reset(new AutofillProfile);
3921 FillFormGroupFromOutputs(outputs, billing_profile.get());
3922 } else {
3923 // Just snag the currently suggested profile.
3924 std::string item_key = SuggestionsMenuModelForSection(SECTION_BILLING)->
3925 GetItemKeyForCheckedItem();
3926 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key);
3927 billing_profile.reset(new AutofillProfile(*profile));
3930 ShowNewCreditCardBubble(newly_saved_card_.Pass(),
3931 billing_profile.Pass());
3932 return;
3935 if (!full_wallet_ || !full_wallet_->billing_address())
3936 return;
3938 GeneratedCreditCardBubbleController::Show(
3939 web_contents(),
3940 full_wallet_->TypeAndLastFourDigits(),
3941 backing_card_last_four_);
3944 void AutofillDialogControllerImpl::OnSubmitButtonDelayEnd() {
3945 if (!view_)
3946 return;
3947 ScopedViewUpdates updates(view_.get());
3948 view_->UpdateButtonStrip();
3951 void AutofillDialogControllerImpl::FetchWalletCookie() {
3952 net::URLRequestContextGetter* request_context = profile_->GetRequestContext();
3953 signin_helper_.reset(new wallet::WalletSigninHelper(this, request_context));
3954 signin_helper_->StartWalletCookieValueFetch();
3957 } // namespace autofill