Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / ui / autofill / autofill_dialog_controller_impl.cc
blob4d7986eba0599f95606b56c768dde1c64e5b08ca
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/shell_window.h"
12 #include "apps/shell_window_registry.h"
13 #include "apps/ui/native_app_window.h"
14 #include "base/base64.h"
15 #include "base/bind.h"
16 #include "base/i18n/case_conversion.h"
17 #include "base/i18n/rtl.h"
18 #include "base/logging.h"
19 #include "base/prefs/pref_registry_simple.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/prefs/scoped_user_pref_update.h"
22 #include "base/rand_util.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_split.h"
25 #include "base/strings/string_util.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/browser_process.h"
30 #include "chrome/browser/profiles/profile.h"
31 #include "chrome/browser/ui/autofill/autofill_dialog_common.h"
32 #include "chrome/browser/ui/autofill/autofill_dialog_i18n_input.h"
33 #include "chrome/browser/ui/autofill/autofill_dialog_view.h"
34 #include "chrome/browser/ui/autofill/data_model_wrapper.h"
35 #if !defined(OS_ANDROID)
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 #endif
39 #include "chrome/browser/ui/browser.h"
40 #include "chrome/browser/ui/browser_finder.h"
41 #include "chrome/browser/ui/browser_navigator.h"
42 #include "chrome/browser/ui/browser_window.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/form_data.h"
65 #include "components/user_prefs/pref_registry_syncable.h"
66 #include "content/public/browser/browser_thread.h"
67 #include "content/public/browser/geolocation_provider.h"
68 #include "content/public/browser/navigation_controller.h"
69 #include "content/public/browser/navigation_details.h"
70 #include "content/public/browser/navigation_entry.h"
71 #include "content/public/browser/notification_service.h"
72 #include "content/public/browser/notification_types.h"
73 #include "content/public/browser/render_view_host.h"
74 #include "content/public/browser/web_contents.h"
75 #include "content/public/browser/web_contents_view.h"
76 #include "content/public/common/url_constants.h"
77 #include "grit/chromium_strings.h"
78 #include "grit/component_strings.h"
79 #include "grit/generated_resources.h"
80 #include "grit/platform_locale_settings.h"
81 #include "grit/theme_resources.h"
82 #include "grit/webkit_resources.h"
83 #include "net/cert/cert_status_flags.h"
84 #include "ui/base/base_window.h"
85 #include "ui/base/l10n/l10n_util.h"
86 #include "ui/base/models/combobox_model.h"
87 #include "ui/base/resource/resource_bundle.h"
88 #include "ui/events/event.h"
89 #include "ui/gfx/canvas.h"
90 #include "ui/gfx/image/image_skia_operations.h"
91 #include "ui/gfx/skia_util.h"
93 namespace autofill {
95 namespace {
97 const char kAddNewItemKey[] = "add-new-item";
98 const char kManageItemsKey[] = "manage-items";
99 const char kSameAsBillingKey[] = "same-as-billing";
101 // URLs for Wallet error messages.
102 const char kBuyerLegalAddressStatusUrl[] =
103 "https://wallet.google.com/manage/settings";
104 const char kKnowYourCustomerStatusUrl[] = "https://wallet.google.com/kyc";
106 // Keys for the kAutofillDialogAutofillDefault pref dictionary (do not change
107 // these values).
108 const char kGuidPrefKey[] = "guid";
110 // This string is stored along with saved addresses and credit cards in the
111 // WebDB, and hence should not be modified, so that it remains consistent over
112 // time.
113 const char kAutofillDialogOrigin[] = "Chrome Autofill dialog";
115 // HSL shift to gray out an image.
116 const color_utils::HSL kGrayImageShift = {-1, 0, 0.8};
118 // Limit Wallet items refresh rate to at most once per minute.
119 const int64 kWalletItemsRefreshRateSeconds = 60;
121 // The number of milliseconds to delay enabling the submit button after showing
122 // the dialog. This delay prevents users from accidentally clicking the submit
123 // button on startup.
124 const int kSubmitButtonDelayMs = 1000;
126 // A helper class to make sure an AutofillDialogView knows when a series of
127 // updates is incoming.
128 class ScopedViewUpdates {
129 public:
130 explicit ScopedViewUpdates(AutofillDialogView* view) : view_(view) {
131 if (view_)
132 view_->UpdatesStarted();
135 ~ScopedViewUpdates() {
136 if (view_)
137 view_->UpdatesFinished();
140 private:
141 AutofillDialogView* view_;
143 DISALLOW_COPY_AND_ASSIGN(ScopedViewUpdates);
146 // Returns true if |input| should be used to fill a site-requested |field| which
147 // is notated with a "shipping" tag, for use when the user has decided to use
148 // the billing address as the shipping address.
149 bool DetailInputMatchesShippingField(const DetailInput& input,
150 const AutofillField& field) {
151 // Equivalent billing field type is used to support UseBillingAsShipping
152 // usecase.
153 ServerFieldType field_type =
154 AutofillType::GetEquivalentBillingFieldType(
155 field.Type().GetStorableType());
157 return common::InputTypeMatchesFieldType(input, AutofillType(field_type));
160 // Initializes |form_group| from user-entered data.
161 void FillFormGroupFromOutputs(const FieldValueMap& detail_outputs,
162 FormGroup* form_group) {
163 for (FieldValueMap::const_iterator iter = detail_outputs.begin();
164 iter != detail_outputs.end(); ++iter) {
165 ServerFieldType type = iter->first;
166 if (!iter->second.empty()) {
167 if (type == ADDRESS_HOME_COUNTRY || type == ADDRESS_BILLING_COUNTRY) {
168 form_group->SetInfo(AutofillType(type),
169 iter->second,
170 g_browser_process->GetApplicationLocale());
171 } else {
172 form_group->SetRawInfo(
173 AutofillType(type).GetStorableType(), iter->second);
179 // Get billing info from |output| and put it into |card|, |cvc|, and |profile|.
180 // These outparams are required because |card|/|profile| accept different types
181 // of raw info, and CreditCard doesn't save CVCs.
182 void GetBillingInfoFromOutputs(const FieldValueMap& output,
183 CreditCard* card,
184 base::string16* cvc,
185 AutofillProfile* profile) {
186 for (FieldValueMap::const_iterator it = output.begin();
187 it != output.end(); ++it) {
188 const ServerFieldType type = it->first;
189 base::string16 trimmed;
190 TrimWhitespace(it->second, TRIM_ALL, &trimmed);
192 // Special case CVC as CreditCard just swallows it.
193 if (type == CREDIT_CARD_VERIFICATION_CODE) {
194 if (cvc)
195 cvc->assign(trimmed);
196 } else if (type == ADDRESS_HOME_COUNTRY ||
197 type == ADDRESS_BILLING_COUNTRY) {
198 if (profile) {
199 profile->SetInfo(AutofillType(type),
200 trimmed,
201 g_browser_process->GetApplicationLocale());
203 } else {
204 // Copy the credit card name to |profile| in addition to |card| as
205 // wallet::Instrument requires a recipient name for its billing address.
206 if (card && type == NAME_FULL)
207 card->SetRawInfo(CREDIT_CARD_NAME, trimmed);
209 if (common::IsCreditCardType(type)) {
210 if (card)
211 card->SetRawInfo(type, trimmed);
212 } else if (profile) {
213 profile->SetRawInfo(AutofillType(type).GetStorableType(), trimmed);
219 // Returns the containing window for the given |web_contents|. The containing
220 // window might be a browser window for a Chrome tab, or it might be a shell
221 // window for a platform app.
222 ui::BaseWindow* GetBaseWindowForWebContents(
223 const content::WebContents* web_contents) {
224 Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
225 if (browser)
226 return browser->window();
228 gfx::NativeWindow native_window =
229 web_contents->GetView()->GetTopLevelNativeWindow();
230 apps::ShellWindow* shell_window =
231 apps::ShellWindowRegistry::
232 GetShellWindowForNativeWindowAnyProfile(native_window);
233 return shell_window->GetBaseWindow();
236 // Returns a string descriptor for a DialogSection, for use with prefs (do not
237 // change these values).
238 std::string SectionToPrefString(DialogSection section) {
239 switch (section) {
240 case SECTION_CC:
241 return "cc";
243 case SECTION_BILLING:
244 return "billing";
246 case SECTION_CC_BILLING:
247 // The SECTION_CC_BILLING section isn't active when using Autofill.
248 NOTREACHED();
249 return std::string();
251 case SECTION_SHIPPING:
252 return "shipping";
255 NOTREACHED();
256 return std::string();
259 // Check if a given MaskedInstrument is allowed for the purchase.
260 bool IsInstrumentAllowed(
261 const wallet::WalletItems::MaskedInstrument& instrument) {
262 switch (instrument.status()) {
263 case wallet::WalletItems::MaskedInstrument::VALID:
264 case wallet::WalletItems::MaskedInstrument::PENDING:
265 case wallet::WalletItems::MaskedInstrument::EXPIRED:
266 case wallet::WalletItems::MaskedInstrument::BILLING_INCOMPLETE:
267 return true;
268 default:
269 return false;
273 // Signals that the user has opted in to geolocation services. Factored out
274 // into a separate method because all interaction with the geolocation provider
275 // needs to happen on the IO thread, which is not the thread
276 // AutofillDialogViewDelegate lives on.
277 void UserDidOptIntoLocationServices() {
278 content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
281 // Returns whether |data_model| is complete, i.e. can fill out all the
282 // |requested_fields|, and verified, i.e. not just automatically aggregated.
283 // Incomplete or unverifed data will not be displayed in the dropdown menu.
284 bool HasCompleteAndVerifiedData(const AutofillDataModel& data_model,
285 const DetailInputs& requested_fields) {
286 if (!data_model.IsVerified())
287 return false;
289 for (size_t i = 0; i < requested_fields.size(); ++i) {
290 ServerFieldType type =
291 AutofillType(requested_fields[i].type).GetStorableType();
292 if (type != ADDRESS_HOME_LINE2 &&
293 type != CREDIT_CARD_VERIFICATION_CODE &&
294 data_model.GetRawInfo(type).empty()) {
295 return false;
299 return true;
302 // Returns true if |profile| has an invalid address, i.e. an invalid state, zip
303 // code, phone number, or email address. Otherwise returns false. Profiles with
304 // invalid addresses are not suggested in the dropdown menu for billing and
305 // shipping addresses.
306 bool HasInvalidAddress(const AutofillProfile& profile) {
307 return profile.IsPresentButInvalid(ADDRESS_HOME_STATE) ||
308 profile.IsPresentButInvalid(ADDRESS_HOME_ZIP) ||
309 profile.IsPresentButInvalid(PHONE_HOME_WHOLE_NUMBER);
312 // Loops through |addresses_| comparing to |address| ignoring ID. If a match
313 // is not found, NULL is returned.
314 const wallet::Address* FindDuplicateAddress(
315 const std::vector<wallet::Address*>& addresses,
316 const wallet::Address& address) {
317 for (size_t i = 0; i < addresses.size(); ++i) {
318 if (addresses[i]->EqualsIgnoreID(address))
319 return addresses[i];
321 return NULL;
324 bool IsCardHolderNameValidForWallet(const base::string16& name) {
325 base::string16 whitespace_collapsed_name = CollapseWhitespace(name, true);
326 std::vector<base::string16> split_name;
327 base::SplitString(whitespace_collapsed_name, ' ', &split_name);
328 return split_name.size() >= 2;
331 DialogSection SectionFromLocation(wallet::FormFieldError::Location location) {
332 switch (location) {
333 case wallet::FormFieldError::PAYMENT_INSTRUMENT:
334 case wallet::FormFieldError::LEGAL_ADDRESS:
335 return SECTION_CC_BILLING;
337 case wallet::FormFieldError::SHIPPING_ADDRESS:
338 return SECTION_SHIPPING;
340 case wallet::FormFieldError::UNKNOWN_LOCATION:
341 NOTREACHED();
342 return SECTION_MAX;
345 NOTREACHED();
346 return SECTION_MAX;
349 scoped_ptr<DialogNotification> GetWalletError(
350 wallet::WalletClient::ErrorType error_type) {
351 base::string16 text;
352 GURL url;
354 switch (error_type) {
355 case wallet::WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS:
356 text = l10n_util::GetStringUTF16(
357 IDS_AUTOFILL_WALLET_UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS);
358 url = GURL(kKnowYourCustomerStatusUrl);
359 break;
361 case wallet::WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED:
362 text = l10n_util::GetStringUTF16(
363 IDS_AUTOFILL_WALLET_BUYER_COUNTRY_NOT_SUPPORTED);
364 url = GURL(kBuyerLegalAddressStatusUrl);
365 break;
367 default:
368 // The notification will not have a link; it's handled in the next
369 // switch statement.
370 break;
373 if (!text.empty()) {
374 scoped_ptr<DialogNotification> notification(new DialogNotification(
375 DialogNotification::WALLET_ERROR,
376 text));
377 notification->set_link_url(url);
378 return notification.Pass();
381 int error_ids = 0;
382 int error_code = 0;
384 switch (error_type) {
385 case wallet::WalletClient::UNSUPPORTED_MERCHANT:
386 error_ids = IDS_AUTOFILL_WALLET_UNSUPPORTED_MERCHANT;
387 break;
389 case wallet::WalletClient::BAD_REQUEST:
390 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
391 error_code = 71;
392 break;
394 case wallet::WalletClient::INVALID_PARAMS:
395 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
396 error_code = 42;
397 break;
399 case wallet::WalletClient::BUYER_ACCOUNT_ERROR:
400 error_ids = IDS_AUTOFILL_WALLET_BUYER_ACCOUNT_ERROR;
401 error_code = 12;
402 break;
404 case wallet::WalletClient::UNSUPPORTED_API_VERSION:
405 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
406 error_code = 43;
407 break;
409 case wallet::WalletClient::SERVICE_UNAVAILABLE:
410 error_ids = IDS_AUTOFILL_WALLET_SERVICE_UNAVAILABLE_ERROR;
411 error_code = 61;
412 break;
414 case wallet::WalletClient::INTERNAL_ERROR:
415 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
416 error_code = 62;
417 break;
419 case wallet::WalletClient::MALFORMED_RESPONSE:
420 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
421 error_code = 72;
422 break;
424 case wallet::WalletClient::NETWORK_ERROR:
425 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
426 error_code = 73;
427 break;
429 case wallet::WalletClient::UNKNOWN_ERROR:
430 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
431 error_code = 74;
432 break;
434 default:
435 break;
438 DCHECK_NE(0, error_ids);
440 // The other error types are strings of the form "XXX. You can pay without
441 // wallet."
442 scoped_ptr<DialogNotification> notification(new DialogNotification(
443 DialogNotification::WALLET_ERROR,
444 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_COMPLETE_WITHOUT_WALLET,
445 l10n_util::GetStringUTF16(error_ids))));
447 if (error_code) {
448 notification->set_tooltip_text(
449 l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_ERROR_CODE_TOOLTIP,
450 base::IntToString16(error_code)));
453 return notification.Pass();
456 // Returns the ID of the address or instrument that should be selected in the
457 // UI, given that the |default_id| is currently the default ID on the Wallet
458 // server, |previous_default_id| was the default ID prior to re-fetching the
459 // Wallet data, and |previously_selected_id| was the ID of the item selected in
460 // the dialog prior to re-fetching the Wallet data.
461 std::string GetIdToSelect(const std::string& default_id,
462 const std::string& previous_default_id,
463 const std::string& previously_selected_id) {
464 // If the default ID changed since the last fetch of the Wallet data, select
465 // it rather than the previously selected item, as the user's intention in
466 // changing the default was probably to use it.
467 if (default_id != previous_default_id)
468 return default_id;
470 // Otherwise, prefer the previously selected item, if there was one.
471 return !previously_selected_id.empty() ? previously_selected_id : default_id;
474 // Generate a random card number in a user displayable format.
475 base::string16 GenerateRandomCardNumber() {
476 std::string card_number;
477 for (size_t i = 0; i < 4; ++i) {
478 int part = base::RandInt(0, 10000);
479 base::StringAppendF(&card_number, "%04d ", part);
481 return base::ASCIIToUTF16(card_number);
484 gfx::Image CreditCardIconForType(const std::string& credit_card_type) {
485 const int input_card_idr = CreditCard::IconResourceId(credit_card_type);
486 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
487 gfx::Image result = rb.GetImageNamed(input_card_idr);
488 if (input_card_idr == IDR_AUTOFILL_CC_GENERIC) {
489 // When the credit card type is unknown, no image should be shown. However,
490 // to simplify the view code on Mac, save space for the credit card image by
491 // returning a transparent image of the appropriate size. Not all credit
492 // card images are the same size, but none is larger than the Visa icon.
493 result = gfx::Image(gfx::ImageSkiaOperations::CreateTransparentImage(
494 rb.GetImageNamed(IDR_AUTOFILL_CC_VISA).AsImageSkia(), 0));
496 return result;
499 gfx::Image CvcIconForCreditCardType(const base::string16& credit_card_type) {
500 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
501 if (credit_card_type == l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX))
502 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT_AMEX);
504 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT);
507 } // namespace
509 AutofillDialogViewDelegate::~AutofillDialogViewDelegate() {}
511 AutofillDialogControllerImpl::~AutofillDialogControllerImpl() {
512 if (popup_controller_)
513 popup_controller_->Hide();
515 GetMetricLogger().LogDialogInitialUserState(initial_user_state_);
518 // static
519 base::WeakPtr<AutofillDialogControllerImpl>
520 AutofillDialogControllerImpl::Create(
521 content::WebContents* contents,
522 const FormData& form_structure,
523 const GURL& source_url,
524 const base::Callback<void(const FormStructure*)>& callback) {
525 // AutofillDialogControllerImpl owns itself.
526 AutofillDialogControllerImpl* autofill_dialog_controller =
527 new AutofillDialogControllerImpl(contents,
528 form_structure,
529 source_url,
530 callback);
531 return autofill_dialog_controller->weak_ptr_factory_.GetWeakPtr();
534 // static
535 void AutofillDialogController::RegisterPrefs(PrefRegistrySimple* registry) {
536 registry->RegisterListPref(::prefs::kAutofillDialogWalletLocationAcceptance);
539 // static
540 void AutofillDialogController::RegisterProfilePrefs(
541 user_prefs::PrefRegistrySyncable* registry) {
542 registry->RegisterBooleanPref(
543 ::prefs::kAutofillDialogPayWithoutWallet,
544 false,
545 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
546 registry->RegisterDictionaryPref(
547 ::prefs::kAutofillDialogAutofillDefault,
548 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
549 registry->RegisterBooleanPref(
550 ::prefs::kAutofillDialogSaveData,
551 true,
552 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
553 registry->RegisterBooleanPref(
554 ::prefs::kAutofillDialogWalletShippingSameAsBilling,
555 false,
556 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
559 // static
560 base::WeakPtr<AutofillDialogController> AutofillDialogController::Create(
561 content::WebContents* contents,
562 const FormData& form_structure,
563 const GURL& source_url,
564 const base::Callback<void(const FormStructure*)>& callback) {
565 return AutofillDialogControllerImpl::Create(contents,
566 form_structure,
567 source_url,
568 callback);
571 void AutofillDialogControllerImpl::Show() {
572 dialog_shown_timestamp_ = base::Time::Now();
574 // Determine what field types should be included in the dialog.
575 bool has_types = false;
576 bool has_sections = false;
577 form_structure_.ParseFieldTypesFromAutocompleteAttributes(
578 &has_types, &has_sections);
580 // Fail if the author didn't specify autocomplete types.
581 if (!has_types) {
582 callback_.Run(NULL);
583 delete this;
584 return;
587 // Log any relevant UI metrics and security exceptions.
588 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_SHOWN);
590 GetMetricLogger().LogDialogSecurityMetric(
591 AutofillMetrics::SECURITY_METRIC_DIALOG_SHOWN);
593 // The Autofill dialog is shown in response to a message from the renderer and
594 // as such, it can only be made in the context of the current document. A call
595 // to GetActiveEntry would return a pending entry, if there was one, which
596 // would be a security bug. Therefore, we use the last committed URL for the
597 // access checks.
598 const GURL& current_url = web_contents()->GetLastCommittedURL();
599 invoked_from_same_origin_ =
600 current_url.GetOrigin() == source_url_.GetOrigin();
602 if (!invoked_from_same_origin_) {
603 GetMetricLogger().LogDialogSecurityMetric(
604 AutofillMetrics::SECURITY_METRIC_CROSS_ORIGIN_FRAME);
607 common::BuildInputsForSection(SECTION_CC,
608 std::string(),
609 &requested_cc_fields_);
610 OnComboboxModelChanged(&billing_country_combobox_model_);
611 OnComboboxModelChanged(&shipping_country_combobox_model_);
613 // Test whether we need to show the shipping section. If filling that section
614 // would be a no-op, don't show it.
615 const DetailInputs& inputs = RequestedFieldsForSection(SECTION_SHIPPING);
616 cares_about_shipping_ = EmptyDataModelWrapper().FillFormStructure(
617 inputs,
618 base::Bind(common::DetailInputMatchesField, SECTION_SHIPPING),
619 &form_structure_);
621 account_chooser_model_.reset(
622 new AccountChooserModel(this,
623 profile_,
624 !ShouldShowAccountChooser(),
625 metric_logger_));
627 if (account_chooser_model_->WalletIsSelected())
628 FetchWalletCookie();
630 // TODO(estade): don't show the dialog if the site didn't specify the right
631 // fields. First we must figure out what the "right" fields are.
632 SuggestionsUpdated();
633 SubmitButtonDelayBegin();
634 view_.reset(CreateView());
635 view_->Show();
637 GetManager()->AddObserver(this);
638 observer_.Add(&billing_country_combobox_model_);
639 observer_.Add(&shipping_country_combobox_model_);
641 if (!account_chooser_model_->WalletIsSelected())
642 LogDialogLatencyToShow();
645 void AutofillDialogControllerImpl::Hide() {
646 if (view_)
647 view_->Hide();
650 void AutofillDialogControllerImpl::TabActivated() {
651 // If the user switched away from this tab and then switched back, reload the
652 // Wallet items, in case they've changed.
653 int64 seconds_elapsed_since_last_refresh =
654 (base::TimeTicks::Now() - last_wallet_items_fetch_timestamp_).InSeconds();
655 if (IsPayingWithWallet() && wallet_items_ &&
656 seconds_elapsed_since_last_refresh >= kWalletItemsRefreshRateSeconds) {
657 GetWalletItems();
661 TestableAutofillDialogView* AutofillDialogControllerImpl::GetTestableView() {
662 return view_ ? view_->GetTestableView() : NULL;
665 ////////////////////////////////////////////////////////////////////////////////
666 // AutofillDialogViewDelegate implementation.
668 base::string16 AutofillDialogControllerImpl::DialogTitle() const {
669 if (ShouldShowSpinner())
670 return base::string16();
672 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TITLE);
675 base::string16 AutofillDialogControllerImpl::AccountChooserText() const {
676 if (!account_chooser_model_->WalletIsSelected())
677 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PAYING_WITHOUT_WALLET);
679 if (SignedInState() == SIGNED_IN)
680 return account_chooser_model_->GetActiveWalletAccountName();
682 // In this case, the account chooser should be showing the signin link.
683 return base::string16();
686 base::string16 AutofillDialogControllerImpl::SignInLinkText() const {
687 int ids = SignedInState() == NOT_CHECKED ?
688 IDS_AUTOFILL_DIALOG_USE_WALLET_LINK :
689 ShouldShowSignInWebView() ? IDS_AUTOFILL_DIALOG_CANCEL_SIGN_IN :
690 IDS_AUTOFILL_DIALOG_SIGN_IN;
692 return l10n_util::GetStringUTF16(ids);
695 base::string16 AutofillDialogControllerImpl::SpinnerText() const {
696 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_LOADING);
699 base::string16 AutofillDialogControllerImpl::EditSuggestionText() const {
700 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_EDIT);
703 base::string16 AutofillDialogControllerImpl::CancelButtonText() const {
704 return l10n_util::GetStringUTF16(IDS_CANCEL);
707 base::string16 AutofillDialogControllerImpl::ConfirmButtonText() const {
708 return l10n_util::GetStringUTF16(IsSubmitPausedOn(wallet::VERIFY_CVV) ?
709 IDS_AUTOFILL_DIALOG_VERIFY_BUTTON : IDS_AUTOFILL_DIALOG_SUBMIT_BUTTON);
712 base::string16 AutofillDialogControllerImpl::SaveLocallyText() const {
713 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_CHECKBOX);
716 base::string16 AutofillDialogControllerImpl::SaveLocallyTooltip() const {
717 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_TOOLTIP);
720 base::string16 AutofillDialogControllerImpl::LegalDocumentsText() {
721 if (!IsPayingWithWallet() || ShouldShowSignInWebView())
722 return base::string16();
724 return legal_documents_text_;
727 bool AutofillDialogControllerImpl::ShouldShowSpinner() const {
728 return SignedInState() == REQUIRES_RESPONSE ||
729 SignedInState() == REQUIRES_PASSIVE_SIGN_IN;
732 bool AutofillDialogControllerImpl::ShouldShowAccountChooser() const {
733 return !ShouldShowSpinner() && GetManager()->IsCountryOfInterest("US");
736 bool AutofillDialogControllerImpl::ShouldShowSignInWebView() const {
737 return !signin_registrar_.IsEmpty();
740 GURL AutofillDialogControllerImpl::SignInUrl() const {
741 return wallet::GetSignInUrl();
744 bool AutofillDialogControllerImpl::ShouldOfferToSaveInChrome() const {
745 return !IsPayingWithWallet() &&
746 !profile_->IsOffTheRecord() &&
747 IsManuallyEditingAnySection() &&
748 !ShouldShowSpinner();
751 bool AutofillDialogControllerImpl::ShouldSaveInChrome() const {
752 return profile_->GetPrefs()->GetBoolean(::prefs::kAutofillDialogSaveData);
755 int AutofillDialogControllerImpl::GetDialogButtons() const {
756 if (waiting_for_explicit_sign_in_response_)
757 return ui::DIALOG_BUTTON_NONE;
759 if (ShouldShowSpinner() && !handling_use_wallet_link_click_)
760 return ui::DIALOG_BUTTON_CANCEL;
762 return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
765 bool AutofillDialogControllerImpl::IsDialogButtonEnabled(
766 ui::DialogButton button) const {
767 if (button == ui::DIALOG_BUTTON_OK) {
768 if (IsSubmitPausedOn(wallet::VERIFY_CVV))
769 return true;
771 if (ShouldShowSpinner() || is_submitting_)
772 return false;
774 if (submit_button_delay_timer_.IsRunning())
775 return false;
777 return true;
780 DCHECK_EQ(ui::DIALOG_BUTTON_CANCEL, button);
781 return !is_submitting_ || IsSubmitPausedOn(wallet::VERIFY_CVV);
784 DialogOverlayState AutofillDialogControllerImpl::GetDialogOverlay() {
785 bool show_wallet_interstitial = IsPayingWithWallet() && is_submitting_ &&
786 !(full_wallet_ && !full_wallet_->required_actions().empty());
787 if (!show_wallet_interstitial) {
788 card_scrambling_delay_.Stop();
789 card_scrambling_refresher_.Stop();
790 return DialogOverlayState();
793 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
794 DialogOverlayState state;
795 state.string.font = rb.GetFont(ui::ResourceBundle::BaseFont).DeriveFont(3);
797 const SkColor start_top_color = SkColorSetRGB(0xD6, 0xD6, 0xD6);
798 const SkColor start_bottom_color = SkColorSetRGB(0x98, 0x98, 0x98);
799 const SkColor final_top_color = SkColorSetRGB(0x52, 0x9F, 0xF8);
800 const SkColor final_bottom_color = SkColorSetRGB(0x22, 0x75, 0xE5);
802 if (full_wallet_ && full_wallet_->required_actions().empty()) {
803 card_scrambling_delay_.Stop();
804 card_scrambling_refresher_.Stop();
806 base::string16 cc_number =
807 full_wallet_->GetInfo(AutofillType(CREDIT_CARD_NUMBER));
808 DCHECK_GE(cc_number.size(), 4U);
809 state.image = GetGeneratedCardImage(
810 base::ASCIIToUTF16("XXXX XXXX XXXX ") +
811 cc_number.substr(cc_number.size() - 4),
812 full_wallet_->billing_address()->recipient_name(),
813 color_utils::AlphaBlend(
814 final_top_color,
815 start_top_color,
816 255 * card_generated_animation_.GetCurrentValue()),
817 color_utils::AlphaBlend(
818 final_bottom_color,
819 start_bottom_color,
820 255 * card_generated_animation_.GetCurrentValue()));
822 state.string.text = l10n_util::GetStringUTF16(
823 IDS_AUTOFILL_DIALOG_CARD_GENERATION_DONE);
824 } else {
825 // Start the refresher if it isn't running. Wait one second before pumping
826 // updates to the view.
827 if (!card_scrambling_delay_.IsRunning() &&
828 !card_scrambling_refresher_.IsRunning()) {
829 scrambled_card_number_ = GenerateRandomCardNumber();
830 card_scrambling_delay_.Start(
831 FROM_HERE,
832 base::TimeDelta::FromSeconds(1),
833 this,
834 &AutofillDialogControllerImpl::StartCardScramblingRefresher);
837 DCHECK(!scrambled_card_number_.empty());
838 state.image = GetGeneratedCardImage(
839 scrambled_card_number_,
840 submitted_cardholder_name_,
841 start_top_color,
842 start_bottom_color);
844 // "Submitting" waiting page.
845 state.string.text = l10n_util::GetStringUTF16(
846 IDS_AUTOFILL_DIALOG_CARD_GENERATION_IN_PROGRESS);
849 return state;
852 const std::vector<gfx::Range>& AutofillDialogControllerImpl::
853 LegalDocumentLinks() {
854 return legal_document_link_ranges_;
857 bool AutofillDialogControllerImpl::SectionIsActive(DialogSection section)
858 const {
859 if (IsSubmitPausedOn(wallet::VERIFY_CVV))
860 return section == SECTION_CC_BILLING;
862 if (!FormStructureCaresAboutSection(section))
863 return false;
865 if (IsPayingWithWallet())
866 return section == SECTION_CC_BILLING || section == SECTION_SHIPPING;
868 return section != SECTION_CC_BILLING;
871 void AutofillDialogControllerImpl::GetWalletItems() {
872 ScopedViewUpdates updates(view_.get());
874 wallet_items_requested_ = true;
875 wallet::WalletClient* wallet_client = GetWalletClient();
876 wallet_client->CancelRequest();
878 previously_selected_instrument_id_.clear();
879 previously_selected_shipping_address_id_.clear();
880 if (wallet_items_) {
881 previous_default_instrument_id_ = wallet_items_->default_instrument_id();
882 previous_default_shipping_address_id_ = wallet_items_->default_address_id();
884 const wallet::WalletItems::MaskedInstrument* instrument =
885 ActiveInstrument();
886 if (instrument)
887 previously_selected_instrument_id_ = instrument->object_id();
889 const wallet::Address* address = ActiveShippingAddress();
890 if (address)
891 previously_selected_shipping_address_id_ = address->object_id();
894 last_wallet_items_fetch_timestamp_ = base::TimeTicks::Now();
895 passive_failed_ = false;
896 wallet_items_.reset();
898 // The "Loading..." page should be showing now, which should cause the
899 // account chooser to hide.
900 view_->UpdateAccountChooser();
901 wallet_client->GetWalletItems();
904 void AutofillDialogControllerImpl::HideSignIn() {
905 ScopedViewUpdates updates(view_.get());
906 signin_registrar_.RemoveAll();
907 view_->HideSignIn();
908 view_->UpdateAccountChooser();
911 AutofillDialogControllerImpl::DialogSignedInState
912 AutofillDialogControllerImpl::SignedInState() const {
913 if (wallet_error_notification_)
914 return SIGN_IN_DISABLED;
916 if (signin_helper_ || (wallet_items_requested_ && !wallet_items_))
917 return REQUIRES_RESPONSE;
919 if (!wallet_items_requested_)
920 return NOT_CHECKED;
922 if (wallet_items_->HasRequiredAction(wallet::GAIA_AUTH) ||
923 passive_failed_) {
924 return REQUIRES_SIGN_IN;
927 if (wallet_items_->HasRequiredAction(wallet::PASSIVE_GAIA_AUTH))
928 return REQUIRES_PASSIVE_SIGN_IN;
930 return SIGNED_IN;
933 void AutofillDialogControllerImpl::SignedInStateUpdated() {
934 if (!ShouldShowSpinner())
935 waiting_for_explicit_sign_in_response_ = false;
937 switch (SignedInState()) {
938 case SIGNED_IN:
939 LogDialogLatencyToShow();
940 break;
942 case REQUIRES_SIGN_IN:
943 if (handling_use_wallet_link_click_)
944 SignInLinkClicked();
945 // Fall through.
946 case SIGN_IN_DISABLED:
947 // Switch to the local account and refresh the dialog.
948 signin_helper_.reset();
949 OnWalletSigninError();
950 handling_use_wallet_link_click_ = false;
951 break;
953 case REQUIRES_PASSIVE_SIGN_IN:
954 // Attempt to passively sign in the user.
955 DCHECK(!signin_helper_);
956 signin_helper_.reset(new wallet::WalletSigninHelper(
957 this,
958 profile_->GetRequestContext()));
959 signin_helper_->StartPassiveSignin(GetWalletClient()->user_index());
960 break;
962 case NOT_CHECKED:
963 case REQUIRES_RESPONSE:
964 break;
968 void AutofillDialogControllerImpl::OnWalletOrSigninUpdate() {
969 ScopedViewUpdates updates(view_.get());
970 SignedInStateUpdated();
971 SuggestionsUpdated();
972 UpdateAccountChooserView();
974 if (view_) {
975 view_->UpdateButtonStrip();
976 view_->UpdateOverlay();
979 // On the first successful response, compute the initial user state metric.
980 if (initial_user_state_ == AutofillMetrics::DIALOG_USER_STATE_UNKNOWN)
981 initial_user_state_ = GetInitialUserState();
984 void AutofillDialogControllerImpl::OnWalletFormFieldError(
985 const std::vector<wallet::FormFieldError>& form_field_errors) {
986 if (form_field_errors.empty())
987 return;
989 for (std::vector<wallet::FormFieldError>::const_iterator it =
990 form_field_errors.begin();
991 it != form_field_errors.end(); ++it) {
992 if (it->error_type() == wallet::FormFieldError::UNKNOWN_ERROR ||
993 it->GetAutofillType() == MAX_VALID_FIELD_TYPE ||
994 it->location() == wallet::FormFieldError::UNKNOWN_LOCATION) {
995 wallet_server_validation_recoverable_ = false;
996 break;
998 DialogSection section = SectionFromLocation(it->location());
999 wallet_errors_[section][it->GetAutofillType()] =
1000 std::make_pair(it->GetErrorMessage(),
1001 GetValueFromSection(section, it->GetAutofillType()));
1004 // Unrecoverable validation errors.
1005 if (!wallet_server_validation_recoverable_)
1006 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
1008 UpdateForErrors();
1011 void AutofillDialogControllerImpl::ConstructLegalDocumentsText() {
1012 legal_documents_text_.clear();
1013 legal_document_link_ranges_.clear();
1015 if (!wallet_items_)
1016 return;
1018 PrefService* local_state = g_browser_process->local_state();
1019 // List of users who have accepted location sharing for fraud protection
1020 // on this device.
1021 const base::ListValue* accepted =
1022 local_state->GetList(::prefs::kAutofillDialogWalletLocationAcceptance);
1023 bool has_accepted_location_sharing =
1024 accepted->Find(base::StringValue(
1025 account_chooser_model_->GetActiveWalletAccountName())) !=
1026 accepted->end();
1028 if (wallet_items_->legal_documents().empty()) {
1029 if (!has_accepted_location_sharing) {
1030 legal_documents_text_ = l10n_util::GetStringUTF16(
1031 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE);
1034 return;
1037 const std::vector<wallet::WalletItems::LegalDocument*>& documents =
1038 wallet_items_->legal_documents();
1039 // There should never be just one document because the privacy policy doc gets
1040 // tacked on the end of other documents.
1041 DCHECK_GE(documents.size(), 2U);
1043 std::vector<base::string16> link_names;
1044 for (size_t i = 0; i < documents.size(); ++i) {
1045 link_names.push_back(documents[i]->display_name());
1048 int resource_id = 0;
1049 switch (documents.size()) {
1050 case 2U:
1051 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_2;
1052 break;
1053 case 3U:
1054 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_3;
1055 break;
1056 case 4U:
1057 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_4;
1058 break;
1059 case 5U:
1060 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_5;
1061 break;
1062 case 6U:
1063 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_6;
1064 break;
1065 default:
1066 // We can only handle so many documents. For lack of a better way of
1067 // handling document overflow, just error out if there are too many.
1068 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
1069 return;
1072 std::vector<size_t> offsets;
1073 base::string16 text =
1074 l10n_util::GetStringFUTF16(resource_id, link_names,&offsets);
1076 // Tack on the location string if need be.
1077 size_t base_offset = 0;
1078 if (!has_accepted_location_sharing) {
1079 text = l10n_util::GetStringFUTF16(
1080 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE_WITH_LEGAL_DOCS,
1081 text,
1082 &base_offset);
1085 for (size_t i = 0; i < documents.size(); ++i) {
1086 size_t link_start = offsets[i] + base_offset;
1087 legal_document_link_ranges_.push_back(gfx::Range(
1088 link_start, link_start + documents[i]->display_name().size()));
1090 legal_documents_text_ = text;
1093 void AutofillDialogControllerImpl::ResetSectionInput(DialogSection section) {
1094 SetEditingExistingData(section, false);
1096 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1097 for (DetailInputs::iterator it = inputs->begin(); it != inputs->end(); ++it) {
1098 it->initial_value = common::GetHardcodedValueForType(it->type);
1102 void AutofillDialogControllerImpl::ShowEditUiIfBadSuggestion(
1103 DialogSection section) {
1104 // |CreateWrapper()| returns an empty wrapper if |IsEditingExistingData()|, so
1105 // get the wrapper before this potentially happens below.
1106 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1108 // If the chosen item in |model| yields an empty suggestion text, it is
1109 // invalid. In this case, show the edit UI and highlight invalid fields.
1110 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1111 base::string16 unused, unused2;
1112 if (IsASuggestionItemKey(model->GetItemKeyForCheckedItem()) &&
1113 !SuggestionTextForSection(section, &unused, &unused2)) {
1114 SetEditingExistingData(section, true);
1117 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1118 if (wrapper && IsEditingExistingData(section))
1119 wrapper->FillInputs(inputs);
1122 bool AutofillDialogControllerImpl::InputWasEdited(ServerFieldType type,
1123 const base::string16& value) {
1124 if (value.empty())
1125 return false;
1127 // If this is a combobox at the default value, don't preserve it.
1128 ui::ComboboxModel* model = ComboboxModelForAutofillType(type);
1129 if (model && model->GetItemAt(model->GetDefaultIndex()) == value)
1130 return false;
1132 return true;
1135 FieldValueMap AutofillDialogControllerImpl::TakeUserInputSnapshot() {
1136 FieldValueMap snapshot;
1137 if (!view_)
1138 return snapshot;
1140 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1141 DialogSection section = static_cast<DialogSection>(i);
1142 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1143 if (model->GetItemKeyForCheckedItem() != kAddNewItemKey)
1144 continue;
1146 FieldValueMap outputs;
1147 view_->GetUserInput(section, &outputs);
1148 // Remove fields that are empty, at their default values, or invalid.
1149 for (FieldValueMap::iterator it = outputs.begin(); it != outputs.end();
1150 ++it) {
1151 if (InputWasEdited(it->first, it->second) &&
1152 InputValidityMessage(section, it->first, it->second).empty()) {
1153 snapshot.insert(std::make_pair(it->first, it->second));
1158 return snapshot;
1161 void AutofillDialogControllerImpl::RestoreUserInputFromSnapshot(
1162 const FieldValueMap& snapshot) {
1163 if (snapshot.empty())
1164 return;
1166 FieldValueMap::const_iterator it = snapshot.find(ADDRESS_BILLING_COUNTRY);
1167 if (it != snapshot.end()) {
1168 billing_country_combobox_model_.SetDefaultCountry(
1169 AutofillCountry::GetCountryCode(
1170 it->second, g_browser_process->GetApplicationLocale()));
1173 FieldValueMap::const_iterator ship_it = snapshot.find(ADDRESS_HOME_COUNTRY);
1174 if (ship_it != snapshot.end()) {
1175 shipping_country_combobox_model_.SetDefaultCountry(
1176 AutofillCountry::GetCountryCode(
1177 ship_it->second, g_browser_process->GetApplicationLocale()));
1180 FieldMapWrapper wrapper(snapshot);
1181 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1182 DialogSection section = static_cast<DialogSection>(i);
1183 if (!SectionIsActive(section))
1184 continue;
1186 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1187 wrapper.FillInputs(inputs);
1189 for (size_t i = 0; i < inputs->size(); ++i) {
1190 if (InputWasEdited((*inputs)[i].type, (*inputs)[i].initial_value)) {
1191 SuggestionsMenuModelForSection(section)->SetCheckedItem(kAddNewItemKey);
1192 break;
1198 void AutofillDialogControllerImpl::UpdateSection(DialogSection section) {
1199 if (view_)
1200 view_->UpdateSection(section);
1203 void AutofillDialogControllerImpl::UpdateForErrors() {
1204 if (!view_)
1205 return;
1207 // Currently, the view should only need to be updated if there are
1208 // |wallet_errors_| or validating a suggestion that's based on existing data.
1209 bool should_update = !wallet_errors_.empty();
1210 if (!should_update) {
1211 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1212 if (IsEditingExistingData(static_cast<DialogSection>(i))) {
1213 should_update = true;
1214 break;
1219 if (should_update)
1220 view_->UpdateForErrors();
1223 gfx::Image AutofillDialogControllerImpl::GetGeneratedCardImage(
1224 const base::string16& card_number,
1225 const base::string16& name,
1226 const SkColor& gradient_top,
1227 const SkColor& gradient_bottom) {
1228 const int kCardWidthPx = 300;
1229 const int kCardHeightPx = 190;
1230 const gfx::Size size(kCardWidthPx, kCardHeightPx);
1231 ui::ScaleFactor scale_factor = ui::GetScaleFactorForNativeView(
1232 web_contents()->GetView()->GetNativeView());
1233 gfx::Canvas canvas(size, ui::GetImageScale(scale_factor), false);
1235 gfx::Rect display_rect(size);
1237 skia::RefPtr<SkShader> shader = gfx::CreateGradientShader(
1238 0, size.height(), gradient_top, gradient_bottom);
1239 SkPaint paint;
1240 paint.setShader(shader.get());
1241 canvas.DrawRoundRect(display_rect, 8, paint);
1243 display_rect.Inset(20, 0, 0, 0);
1244 gfx::Font font(l10n_util::GetStringUTF8(IDS_FIXED_FONT_FAMILY), 18);
1245 gfx::FontList font_list(font);
1246 gfx::ShadowValues shadows;
1247 shadows.push_back(gfx::ShadowValue(gfx::Point(0, 1), 1.0, SK_ColorBLACK));
1248 canvas.DrawStringRectWithShadows(
1249 card_number,
1250 font_list,
1251 SK_ColorWHITE,
1252 display_rect, 0, 0, shadows);
1254 base::string16 capitalized_name = base::i18n::ToUpper(name);
1255 display_rect.Inset(0, size.height() / 2, 0, 0);
1256 canvas.DrawStringRectWithShadows(
1257 capitalized_name,
1258 font_list,
1259 SK_ColorWHITE,
1260 display_rect, 0, 0, shadows);
1262 gfx::ImageSkia skia(canvas.ExtractImageRep());
1263 return gfx::Image(skia);
1266 void AutofillDialogControllerImpl::StartCardScramblingRefresher() {
1267 RefreshCardScramblingOverlay();
1268 card_scrambling_refresher_.Start(
1269 FROM_HERE,
1270 base::TimeDelta::FromMilliseconds(75),
1271 this,
1272 &AutofillDialogControllerImpl::RefreshCardScramblingOverlay);
1275 void AutofillDialogControllerImpl::RefreshCardScramblingOverlay() {
1276 scrambled_card_number_ = GenerateRandomCardNumber();
1277 PushOverlayUpdate();
1280 void AutofillDialogControllerImpl::PushOverlayUpdate() {
1281 if (view_) {
1282 ScopedViewUpdates updates(view_.get());
1283 view_->UpdateOverlay();
1287 const DetailInputs& AutofillDialogControllerImpl::RequestedFieldsForSection(
1288 DialogSection section) const {
1289 switch (section) {
1290 case SECTION_CC:
1291 return requested_cc_fields_;
1292 case SECTION_BILLING:
1293 return requested_billing_fields_;
1294 case SECTION_CC_BILLING:
1295 return requested_cc_billing_fields_;
1296 case SECTION_SHIPPING:
1297 return requested_shipping_fields_;
1300 NOTREACHED();
1301 return requested_billing_fields_;
1304 ui::ComboboxModel* AutofillDialogControllerImpl::ComboboxModelForAutofillType(
1305 ServerFieldType type) {
1306 switch (type) {
1307 case CREDIT_CARD_EXP_MONTH:
1308 return &cc_exp_month_combobox_model_;
1310 case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1311 return &cc_exp_year_combobox_model_;
1313 case ADDRESS_BILLING_COUNTRY:
1314 return &billing_country_combobox_model_;
1316 case ADDRESS_HOME_COUNTRY:
1317 return &shipping_country_combobox_model_;
1319 default:
1320 return NULL;
1324 ui::MenuModel* AutofillDialogControllerImpl::MenuModelForSection(
1325 DialogSection section) {
1326 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1327 // The shipping section menu is special. It will always show because there is
1328 // a choice between "Use billing" and "enter new".
1329 if (section == SECTION_SHIPPING)
1330 return model;
1332 // For other sections, only show a menu if there's at least one suggestion.
1333 for (int i = 0; i < model->GetItemCount(); ++i) {
1334 if (IsASuggestionItemKey(model->GetItemKeyAt(i)))
1335 return model;
1338 return NULL;
1341 ui::MenuModel* AutofillDialogControllerImpl::MenuModelForAccountChooser() {
1342 // If there were unrecoverable Wallet errors, or if there are choices other
1343 // than "Pay without the wallet", show the full menu.
1344 // TODO(estade): this can present a braindead menu (only 1 option) when
1345 // there's a wallet error.
1346 if (wallet_error_notification_ ||
1347 (SignedInState() == SIGNED_IN &&
1348 account_chooser_model_->HasAccountsToChoose() &&
1349 !ShouldShowSignInWebView())) {
1350 return account_chooser_model_.get();
1353 // Otherwise, there is no menu, just a sign in link.
1354 return NULL;
1357 gfx::Image AutofillDialogControllerImpl::AccountChooserImage() {
1358 if (!MenuModelForAccountChooser() && !ShouldShowSignInWebView()) {
1359 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1360 IDR_WALLET_ICON);
1363 return gfx::Image();
1366 gfx::Image AutofillDialogControllerImpl::ButtonStripImage() const {
1367 if (IsPayingWithWallet()) {
1368 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1369 IDR_WALLET_LOGO);
1372 return gfx::Image();
1375 base::string16 AutofillDialogControllerImpl::LabelForSection(
1376 DialogSection section) const {
1377 switch (section) {
1378 case SECTION_CC:
1379 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_CC);
1380 case SECTION_BILLING:
1381 case SECTION_CC_BILLING:
1382 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_BILLING);
1383 case SECTION_SHIPPING:
1384 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_SHIPPING);
1386 NOTREACHED();
1387 return base::string16();
1390 SuggestionState AutofillDialogControllerImpl::SuggestionStateForSection(
1391 DialogSection section) {
1392 base::string16 vertically_compact, horizontally_compact;
1393 bool show_suggestion = SuggestionTextForSection(section,
1394 &vertically_compact,
1395 &horizontally_compact);
1396 return SuggestionState(show_suggestion,
1397 vertically_compact,
1398 horizontally_compact,
1399 SuggestionIconForSection(section),
1400 ExtraSuggestionTextForSection(section),
1401 ExtraSuggestionIconForSection(section));
1404 bool AutofillDialogControllerImpl::SuggestionTextForSection(
1405 DialogSection section,
1406 base::string16* vertically_compact,
1407 base::string16* horizontally_compact) {
1408 base::string16 action_text = RequiredActionTextForSection(section);
1409 if (!action_text.empty()) {
1410 *vertically_compact = *horizontally_compact = action_text;
1411 return true;
1414 // When the user has clicked 'edit' or a suggestion is somehow invalid (e.g. a
1415 // user selects a credit card that has expired), don't show a suggestion (even
1416 // though there is a profile selected in the model).
1417 if (IsEditingExistingData(section))
1418 return false;
1420 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1421 std::string item_key = model->GetItemKeyForCheckedItem();
1422 if (item_key == kSameAsBillingKey) {
1423 *vertically_compact = *horizontally_compact = l10n_util::GetStringUTF16(
1424 IDS_AUTOFILL_DIALOG_USING_BILLING_FOR_SHIPPING);
1425 return true;
1428 if (!IsASuggestionItemKey(item_key))
1429 return false;
1431 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1432 return wrapper->GetDisplayText(vertically_compact, horizontally_compact);
1435 base::string16 AutofillDialogControllerImpl::RequiredActionTextForSection(
1436 DialogSection section) const {
1437 if (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV)) {
1438 const wallet::WalletItems::MaskedInstrument* current_instrument =
1439 wallet_items_->GetInstrumentById(active_instrument_id_);
1440 if (current_instrument)
1441 return current_instrument->TypeAndLastFourDigits();
1443 FieldValueMap output;
1444 view_->GetUserInput(section, &output);
1445 CreditCard card;
1446 GetBillingInfoFromOutputs(output, &card, NULL, NULL);
1447 return card.TypeAndLastFourDigits();
1450 return base::string16();
1453 base::string16 AutofillDialogControllerImpl::ExtraSuggestionTextForSection(
1454 DialogSection section) const {
1455 if (section == SECTION_CC ||
1456 (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV))) {
1457 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC);
1460 return base::string16();
1463 const wallet::WalletItems::MaskedInstrument* AutofillDialogControllerImpl::
1464 ActiveInstrument() const {
1465 if (!IsPayingWithWallet())
1466 return NULL;
1468 const SuggestionsMenuModel* model =
1469 SuggestionsMenuModelForSection(SECTION_CC_BILLING);
1470 const std::string item_key = model->GetItemKeyForCheckedItem();
1471 if (!IsASuggestionItemKey(item_key))
1472 return NULL;
1474 int index;
1475 if (!base::StringToInt(item_key, &index) || index < 0 ||
1476 static_cast<size_t>(index) >= wallet_items_->instruments().size()) {
1477 NOTREACHED();
1478 return NULL;
1481 return wallet_items_->instruments()[index];
1484 const wallet::Address* AutofillDialogControllerImpl::
1485 ActiveShippingAddress() const {
1486 if (!IsPayingWithWallet() || !IsShippingAddressRequired())
1487 return NULL;
1489 const SuggestionsMenuModel* model =
1490 SuggestionsMenuModelForSection(SECTION_SHIPPING);
1491 const std::string item_key = model->GetItemKeyForCheckedItem();
1492 if (!IsASuggestionItemKey(item_key))
1493 return NULL;
1495 int index;
1496 if (!base::StringToInt(item_key, &index) || index < 0 ||
1497 static_cast<size_t>(index) >= wallet_items_->addresses().size()) {
1498 NOTREACHED();
1499 return NULL;
1502 return wallet_items_->addresses()[index];
1505 scoped_ptr<DataModelWrapper> AutofillDialogControllerImpl::CreateWrapper(
1506 DialogSection section) {
1507 if (IsPayingWithWallet() && full_wallet_ &&
1508 full_wallet_->required_actions().empty()) {
1509 if (section == SECTION_CC_BILLING) {
1510 return scoped_ptr<DataModelWrapper>(
1511 new FullWalletBillingWrapper(full_wallet_.get()));
1513 if (section == SECTION_SHIPPING) {
1514 return scoped_ptr<DataModelWrapper>(
1515 new FullWalletShippingWrapper(full_wallet_.get()));
1519 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1520 std::string item_key = model->GetItemKeyForCheckedItem();
1521 if (!IsASuggestionItemKey(item_key) || IsManuallyEditingSection(section))
1522 return scoped_ptr<DataModelWrapper>();
1524 if (IsPayingWithWallet()) {
1525 if (section == SECTION_CC_BILLING) {
1526 return scoped_ptr<DataModelWrapper>(
1527 new WalletInstrumentWrapper(ActiveInstrument()));
1530 if (section == SECTION_SHIPPING) {
1531 return scoped_ptr<DataModelWrapper>(
1532 new WalletAddressWrapper(ActiveShippingAddress()));
1535 return scoped_ptr<DataModelWrapper>();
1538 if (section == SECTION_CC) {
1539 CreditCard* card = GetManager()->GetCreditCardByGUID(item_key);
1540 DCHECK(card);
1541 return scoped_ptr<DataModelWrapper>(new AutofillCreditCardWrapper(card));
1544 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key);
1545 DCHECK(profile);
1546 if (section == SECTION_SHIPPING) {
1547 return scoped_ptr<DataModelWrapper>(
1548 new AutofillShippingAddressWrapper(profile));
1550 DCHECK_EQ(SECTION_BILLING, section);
1551 return scoped_ptr<DataModelWrapper>(
1552 new AutofillProfileWrapper(profile));
1555 gfx::Image AutofillDialogControllerImpl::SuggestionIconForSection(
1556 DialogSection section) {
1557 scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1558 if (!model.get())
1559 return gfx::Image();
1561 return model->GetIcon();
1564 gfx::Image AutofillDialogControllerImpl::ExtraSuggestionIconForSection(
1565 DialogSection section) {
1566 if (section != SECTION_CC && section != SECTION_CC_BILLING)
1567 return gfx::Image();
1569 scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1570 if (!model.get())
1571 return gfx::Image();
1573 return CvcIconForCreditCardType(
1574 model->GetInfo(AutofillType(CREDIT_CARD_TYPE)));
1577 FieldIconMap AutofillDialogControllerImpl::IconsForFields(
1578 const FieldValueMap& user_inputs) const {
1579 FieldIconMap result;
1580 base::string16 credit_card_type;
1582 FieldValueMap::const_iterator credit_card_iter =
1583 user_inputs.find(CREDIT_CARD_NUMBER);
1584 if (credit_card_iter != user_inputs.end()) {
1585 const base::string16& number = credit_card_iter->second;
1586 const std::string type = CreditCard::GetCreditCardType(number);
1587 credit_card_type = CreditCard::TypeForDisplay(type);
1588 result[CREDIT_CARD_NUMBER] = CreditCardIconForType(type);
1591 if (!user_inputs.count(CREDIT_CARD_VERIFICATION_CODE))
1592 return result;
1594 result[CREDIT_CARD_VERIFICATION_CODE] =
1595 CvcIconForCreditCardType(credit_card_type);
1597 return result;
1600 bool AutofillDialogControllerImpl::FieldControlsIcons(
1601 ServerFieldType type) const {
1602 return type == CREDIT_CARD_NUMBER;
1605 base::string16 AutofillDialogControllerImpl::TooltipForField(
1606 ServerFieldType type) const {
1607 if (type == PHONE_HOME_WHOLE_NUMBER || type == PHONE_BILLING_WHOLE_NUMBER)
1608 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TOOLTIP_PHONE_NUMBER);
1610 return base::string16();
1613 bool AutofillDialogControllerImpl::InputIsEditable(
1614 const DetailInput& input,
1615 DialogSection section) {
1616 if (section != SECTION_CC_BILLING)
1617 return true;
1619 if (input.type == CREDIT_CARD_NUMBER)
1620 return !IsEditingExistingData(section);
1622 // For CVC, only require (allow) input if the user has edited some other
1623 // aspect of the card.
1624 if (input.type == CREDIT_CARD_VERIFICATION_CODE &&
1625 IsEditingExistingData(section)) {
1626 FieldValueMap output;
1627 view_->GetUserInput(section, &output);
1628 WalletInstrumentWrapper wrapper(ActiveInstrument());
1630 for (FieldValueMap::iterator iter = output.begin(); iter != output.end();
1631 ++iter) {
1632 if (iter->first == input.type)
1633 continue;
1635 AutofillType type(iter->first);
1636 if (type.group() == CREDIT_CARD &&
1637 iter->second != wrapper.GetInfo(type)) {
1638 return true;
1642 return false;
1645 return true;
1648 // TODO(groby): Add more tests.
1649 base::string16 AutofillDialogControllerImpl::InputValidityMessage(
1650 DialogSection section,
1651 ServerFieldType type,
1652 const base::string16& value) {
1653 // If the field is edited, clear any Wallet errors.
1654 if (IsPayingWithWallet()) {
1655 WalletValidationErrors::iterator it = wallet_errors_.find(section);
1656 if (it != wallet_errors_.end()) {
1657 TypeErrorInputMap::const_iterator iter = it->second.find(type);
1658 if (iter != it->second.end()) {
1659 if (iter->second.second == value)
1660 return iter->second.first;
1661 it->second.erase(type);
1666 switch (AutofillType(type).GetStorableType()) {
1667 case EMAIL_ADDRESS:
1668 if (!value.empty() && !IsValidEmailAddress(value)) {
1669 return l10n_util::GetStringUTF16(
1670 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_EMAIL_ADDRESS);
1672 break;
1674 case CREDIT_CARD_NUMBER: {
1675 if (!value.empty()) {
1676 base::string16 message = CreditCardNumberValidityMessage(value);
1677 if (!message.empty())
1678 return message;
1680 break;
1683 case CREDIT_CARD_EXP_MONTH:
1684 if (!InputWasEdited(CREDIT_CARD_EXP_MONTH, value)) {
1685 return l10n_util::GetStringUTF16(
1686 IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE);
1688 break;
1690 case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1691 if (!InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR, value)) {
1692 return l10n_util::GetStringUTF16(
1693 IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE);
1695 break;
1697 case CREDIT_CARD_VERIFICATION_CODE:
1698 if (!value.empty() && !autofill::IsValidCreditCardSecurityCode(value)) {
1699 return l10n_util::GetStringUTF16(
1700 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
1702 break;
1704 case ADDRESS_HOME_LINE1:
1705 break;
1707 case ADDRESS_HOME_LINE2:
1708 case ADDRESS_HOME_DEPENDENT_LOCALITY:
1709 case ADDRESS_HOME_SORTING_CODE:
1710 return base::string16(); // Optional until we have better validation.
1712 case ADDRESS_HOME_CITY:
1713 case ADDRESS_HOME_COUNTRY:
1714 break;
1716 case ADDRESS_HOME_STATE:
1717 if (!value.empty() && !autofill::IsValidState(value) &&
1718 CountryCodeForSection(section) == "US") {
1719 return l10n_util::GetStringUTF16(
1720 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_REGION);
1722 break;
1724 case ADDRESS_HOME_ZIP:
1725 if (!value.empty() && !autofill::IsValidZip(value) &&
1726 CountryCodeForSection(section) == "US") {
1727 return l10n_util::GetStringUTF16(
1728 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_ZIP_CODE);
1730 break;
1732 case NAME_FULL:
1733 // Wallet requires a first and last billing name.
1734 if (section == SECTION_CC_BILLING && !value.empty() &&
1735 !IsCardHolderNameValidForWallet(value)) {
1736 DCHECK(IsPayingWithWallet());
1737 return l10n_util::GetStringUTF16(
1738 IDS_AUTOFILL_DIALOG_VALIDATION_WALLET_REQUIRES_TWO_NAMES);
1740 break;
1742 case PHONE_HOME_WHOLE_NUMBER: // Used in shipping section.
1743 break;
1745 case PHONE_BILLING_WHOLE_NUMBER: // Used in billing section.
1746 break;
1748 default:
1749 NOTREACHED(); // Trying to validate unknown field.
1750 break;
1753 return value.empty() ?
1754 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE) :
1755 base::string16();
1758 // TODO(groby): Also add tests.
1759 ValidityMessages AutofillDialogControllerImpl::InputsAreValid(
1760 DialogSection section,
1761 const FieldValueMap& inputs) {
1762 ValidityMessages messages;
1763 FieldValueMap field_values;
1764 for (FieldValueMap::const_iterator iter = inputs.begin();
1765 iter != inputs.end(); ++iter) {
1766 const ServerFieldType type = iter->first;
1768 base::string16 text = InputValidityMessage(section, type, iter->second);
1770 // Skip empty/unchanged fields in edit mode. Ignore country as it always has
1771 // a value. If the individual field does not have validation errors, assume
1772 // it to be valid unless later proven otherwise.
1773 bool sure = InputWasEdited(type, iter->second) ||
1774 AutofillType(type).GetStorableType() == ADDRESS_HOME_COUNTRY;
1776 // Consider only individually valid fields for inter-field validation.
1777 if (text.empty()) {
1778 field_values[type] = iter->second;
1779 // If the field is valid but can be invalidated by inter-field validation,
1780 // assume it to be unsure.
1781 if (type == CREDIT_CARD_EXP_4_DIGIT_YEAR ||
1782 type == CREDIT_CARD_EXP_MONTH ||
1783 type == CREDIT_CARD_VERIFICATION_CODE ||
1784 type == PHONE_HOME_WHOLE_NUMBER ||
1785 type == PHONE_BILLING_WHOLE_NUMBER) {
1786 sure = false;
1789 messages.Set(type, ValidityMessage(text, sure));
1792 // Validate the date formed by month and year field. (Autofill dialog is
1793 // never supposed to have 2-digit years, so not checked).
1794 if (field_values.count(CREDIT_CARD_EXP_4_DIGIT_YEAR) &&
1795 field_values.count(CREDIT_CARD_EXP_MONTH) &&
1796 InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR,
1797 field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR]) &&
1798 InputWasEdited(CREDIT_CARD_EXP_MONTH,
1799 field_values[CREDIT_CARD_EXP_MONTH])) {
1800 ValidityMessage year_message(base::string16(), true);
1801 ValidityMessage month_message(base::string16(), true);
1802 if (!IsCreditCardExpirationValid(field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR],
1803 field_values[CREDIT_CARD_EXP_MONTH])) {
1804 // The dialog shows the same error message for the month and year fields.
1805 year_message.text = l10n_util::GetStringUTF16(
1806 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
1807 month_message.text = l10n_util::GetStringUTF16(
1808 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
1810 messages.Set(CREDIT_CARD_EXP_4_DIGIT_YEAR, year_message);
1811 messages.Set(CREDIT_CARD_EXP_MONTH, month_message);
1814 // If there is a credit card number and a CVC, validate them together.
1815 if (field_values.count(CREDIT_CARD_NUMBER) &&
1816 field_values.count(CREDIT_CARD_VERIFICATION_CODE)) {
1817 ValidityMessage ccv_message(base::string16(), true);
1818 if (!autofill::IsValidCreditCardSecurityCode(
1819 field_values[CREDIT_CARD_VERIFICATION_CODE],
1820 field_values[CREDIT_CARD_NUMBER])) {
1821 ccv_message.text = l10n_util::GetStringUTF16(
1822 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
1824 messages.Set(CREDIT_CARD_VERIFICATION_CODE, ccv_message);
1827 // Validate the shipping phone number against the country code of the address.
1828 if (field_values.count(ADDRESS_HOME_COUNTRY) &&
1829 field_values.count(PHONE_HOME_WHOLE_NUMBER)) {
1830 i18n::PhoneObject phone_object(
1831 field_values[PHONE_HOME_WHOLE_NUMBER],
1832 AutofillCountry::GetCountryCode(
1833 field_values[ADDRESS_HOME_COUNTRY],
1834 g_browser_process->GetApplicationLocale()));
1835 ValidityMessage phone_message(base::string16(), true);
1836 if (!phone_object.IsValidNumber()) {
1837 phone_message.text = l10n_util::GetStringUTF16(
1838 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER);
1840 messages.Set(PHONE_HOME_WHOLE_NUMBER, phone_message);
1843 // Validate the billing phone number against the country code of the address.
1844 if (field_values.count(ADDRESS_BILLING_COUNTRY) &&
1845 field_values.count(PHONE_BILLING_WHOLE_NUMBER)) {
1846 i18n::PhoneObject phone_object(
1847 field_values[PHONE_BILLING_WHOLE_NUMBER],
1848 AutofillCountry::GetCountryCode(
1849 field_values[ADDRESS_BILLING_COUNTRY],
1850 g_browser_process->GetApplicationLocale()));
1851 ValidityMessage phone_message(base::string16(), true);
1852 if (!phone_object.IsValidNumber()) {
1853 phone_message.text = l10n_util::GetStringUTF16(
1854 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER);
1856 messages.Set(PHONE_BILLING_WHOLE_NUMBER, phone_message);
1859 return messages;
1862 void AutofillDialogControllerImpl::UserEditedOrActivatedInput(
1863 DialogSection section,
1864 ServerFieldType type,
1865 gfx::NativeView parent_view,
1866 const gfx::Rect& content_bounds,
1867 const base::string16& field_contents,
1868 bool was_edit) {
1869 ScopedViewUpdates updates(view_.get());
1871 if (type == ADDRESS_BILLING_COUNTRY || type == ADDRESS_HOME_COUNTRY) {
1872 FieldValueMap snapshot = TakeUserInputSnapshot();
1873 snapshot[type] = field_contents;
1874 RestoreUserInputFromSnapshot(snapshot);
1875 const bool is_billing = type == ADDRESS_BILLING_COUNTRY;
1876 UpdateSection(is_billing ? ActiveBillingSection() : SECTION_SHIPPING);
1879 // The rest of this method applies only to textfields. If a combobox, bail.
1880 if (ComboboxModelForAutofillType(type))
1881 return;
1883 // If the field is edited down to empty, don't show a popup.
1884 if (was_edit && field_contents.empty()) {
1885 HidePopup();
1886 return;
1889 // If the user clicks while the popup is already showing, be sure to hide
1890 // it.
1891 if (!was_edit && popup_controller_.get()) {
1892 HidePopup();
1893 return;
1896 std::vector<base::string16> popup_values, popup_labels, popup_icons;
1897 if (common::IsCreditCardType(type)) {
1898 GetManager()->GetCreditCardSuggestions(AutofillType(type),
1899 field_contents,
1900 &popup_values,
1901 &popup_labels,
1902 &popup_icons,
1903 &popup_guids_);
1904 } else {
1905 std::vector<ServerFieldType> field_types;
1906 const DetailInputs& inputs = RequestedFieldsForSection(section);
1907 for (DetailInputs::const_iterator iter = inputs.begin();
1908 iter != inputs.end(); ++iter) {
1909 field_types.push_back(iter->type);
1911 GetManager()->GetProfileSuggestions(AutofillType(type),
1912 field_contents,
1913 false,
1914 field_types,
1915 &popup_values,
1916 &popup_labels,
1917 &popup_icons,
1918 &popup_guids_);
1921 if (popup_values.empty()) {
1922 HidePopup();
1923 return;
1926 // |popup_input_type_| must be set before calling |Show()|.
1927 popup_input_type_ = type;
1929 // TODO(estade): do we need separators and control rows like 'Clear
1930 // Form'?
1931 std::vector<int> popup_ids;
1932 for (size_t i = 0; i < popup_guids_.size(); ++i) {
1933 popup_ids.push_back(i);
1936 popup_controller_ = AutofillPopupControllerImpl::GetOrCreate(
1937 popup_controller_,
1938 weak_ptr_factory_.GetWeakPtr(),
1939 NULL,
1940 parent_view,
1941 content_bounds,
1942 base::i18n::IsRTL() ?
1943 base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT);
1944 popup_controller_->set_hide_on_outside_click(true);
1945 popup_controller_->Show(popup_values,
1946 popup_labels,
1947 popup_icons,
1948 popup_ids);
1951 void AutofillDialogControllerImpl::FocusMoved() {
1952 HidePopup();
1955 bool AutofillDialogControllerImpl::ShouldShowErrorBubble() const {
1956 return popup_input_type_ == UNKNOWN_TYPE;
1959 void AutofillDialogControllerImpl::ViewClosed() {
1960 GetManager()->RemoveObserver(this);
1962 // Called from here rather than in ~AutofillDialogControllerImpl as this
1963 // relies on virtual methods that change to their base class in the dtor.
1964 MaybeShowCreditCardBubble();
1966 delete this;
1969 std::vector<DialogNotification> AutofillDialogControllerImpl::
1970 CurrentNotifications() {
1971 std::vector<DialogNotification> notifications;
1973 // TODO(dbeam): figure out a way to dismiss this error after a while.
1974 if (wallet_error_notification_)
1975 notifications.push_back(*wallet_error_notification_);
1977 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
1978 notifications.push_back(DialogNotification(
1979 DialogNotification::REQUIRED_ACTION,
1980 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VERIFY_CVV)));
1983 if (!wallet_server_validation_recoverable_) {
1984 notifications.push_back(DialogNotification(
1985 DialogNotification::REQUIRED_ACTION,
1986 l10n_util::GetStringUTF16(
1987 IDS_AUTOFILL_DIALOG_FAILED_TO_SAVE_WALLET_DATA)));
1990 if (choose_another_instrument_or_address_) {
1991 notifications.push_back(DialogNotification(
1992 DialogNotification::REQUIRED_ACTION,
1993 l10n_util::GetStringUTF16(
1994 IDS_AUTOFILL_DIALOG_CHOOSE_DIFFERENT_WALLET_INSTRUMENT)));
1997 if (notifications.empty() && MenuModelForAccountChooser()) {
1998 base::string16 text = l10n_util::GetStringUTF16(
1999 IsManuallyEditingAnySection() ?
2000 IDS_AUTOFILL_DIALOG_SAVE_DETAILS_IN_WALLET :
2001 IDS_AUTOFILL_DIALOG_USE_WALLET);
2002 DialogNotification notification(
2003 DialogNotification::WALLET_USAGE_CONFIRMATION,
2004 text);
2005 notification.set_tooltip_text(
2006 l10n_util::GetStringUTF16(
2007 IDS_AUTOFILL_DIALOG_SAVE_IN_WALLET_TOOLTIP));
2008 notification.set_checked(IsPayingWithWallet());
2009 notifications.push_back(notification);
2012 if (IsPayingWithWallet() && !wallet::IsUsingProd()) {
2013 notifications.push_back(DialogNotification(
2014 DialogNotification::DEVELOPER_WARNING,
2015 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_NOT_PROD_WARNING)));
2018 if (!invoked_from_same_origin_) {
2019 notifications.push_back(DialogNotification(
2020 DialogNotification::SECURITY_WARNING,
2021 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_SITE_WARNING,
2022 base::UTF8ToUTF16(source_url_.host()))));
2025 return notifications;
2028 void AutofillDialogControllerImpl::LinkClicked(const GURL& url) {
2029 OpenTabWithUrl(url);
2032 void AutofillDialogControllerImpl::SignInLinkClicked() {
2033 ScopedViewUpdates updates(view_.get());
2035 if (SignedInState() == NOT_CHECKED) {
2036 handling_use_wallet_link_click_ = true;
2037 account_chooser_model_->SelectWalletAccount(0);
2038 FetchWalletCookie();
2039 } else if (signin_registrar_.IsEmpty()) {
2040 // Start sign in.
2041 waiting_for_explicit_sign_in_response_ = true;
2042 content::Source<content::NavigationController> source(view_->ShowSignIn());
2043 signin_registrar_.Add(
2044 this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, source);
2046 GetMetricLogger().LogDialogUiEvent(
2047 AutofillMetrics::DIALOG_UI_SIGNIN_SHOWN);
2048 } else {
2049 waiting_for_explicit_sign_in_response_ = false;
2050 HideSignIn();
2053 view_->UpdateAccountChooser();
2054 view_->UpdateButtonStrip();
2057 void AutofillDialogControllerImpl::NotificationCheckboxStateChanged(
2058 DialogNotification::Type type, bool checked) {
2059 if (type == DialogNotification::WALLET_USAGE_CONFIRMATION) {
2060 if (checked) {
2061 account_chooser_model_->SelectWalletAccount(
2062 GetWalletClient()->user_index());
2063 } else {
2064 account_chooser_model_->SelectUseAutofill();
2067 AccountChoiceChanged();
2071 void AutofillDialogControllerImpl::LegalDocumentLinkClicked(
2072 const gfx::Range& range) {
2073 for (size_t i = 0; i < legal_document_link_ranges_.size(); ++i) {
2074 if (legal_document_link_ranges_[i] == range) {
2075 OpenTabWithUrl(wallet_items_->legal_documents()[i]->url());
2076 return;
2080 NOTREACHED();
2083 bool AutofillDialogControllerImpl::OnCancel() {
2084 HidePopup();
2085 if (!is_submitting_)
2086 LogOnCancelMetrics();
2087 callback_.Run(NULL);
2088 return true;
2091 bool AutofillDialogControllerImpl::OnAccept() {
2092 ScopedViewUpdates updates(view_.get());
2093 choose_another_instrument_or_address_ = false;
2094 wallet_server_validation_recoverable_ = true;
2095 HidePopup();
2097 // This must come before SetIsSubmitting().
2098 if (IsPayingWithWallet()) {
2099 // In the VERIFY_CVV case, hold onto the previously submitted cardholder
2100 // name.
2101 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2102 submitted_cardholder_name_ =
2103 GetValueFromSection(SECTION_CC_BILLING, NAME_BILLING_FULL);
2105 // Snag the last four digits of the backing card now as it could be wiped
2106 // out if a CVC challenge happens.
2107 if (ActiveInstrument()) {
2108 backing_card_last_four_ = ActiveInstrument()->TypeAndLastFourDigits();
2109 } else {
2110 FieldValueMap output;
2111 view_->GetUserInput(SECTION_CC_BILLING, &output);
2112 CreditCard card;
2113 GetBillingInfoFromOutputs(output, &card, NULL, NULL);
2114 backing_card_last_four_ = card.TypeAndLastFourDigits();
2117 DCHECK(!submitted_cardholder_name_.empty());
2118 DCHECK(!backing_card_last_four_.empty());
2121 SetIsSubmitting(true);
2123 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2124 DCHECK(!active_instrument_id_.empty());
2125 full_wallet_.reset();
2126 GetWalletClient()->AuthenticateInstrument(
2127 active_instrument_id_,
2128 base::UTF16ToUTF8(view_->GetCvc()));
2129 view_->UpdateOverlay();
2130 } else if (IsPayingWithWallet()) {
2131 AcceptLegalTerms();
2132 } else {
2133 FinishSubmit();
2136 return false;
2139 Profile* AutofillDialogControllerImpl::profile() {
2140 return profile_;
2143 content::WebContents* AutofillDialogControllerImpl::GetWebContents() {
2144 return web_contents();
2147 ////////////////////////////////////////////////////////////////////////////////
2148 // AutofillPopupDelegate implementation.
2150 void AutofillDialogControllerImpl::OnPopupShown() {
2151 ScopedViewUpdates update(view_.get());
2152 view_->UpdateErrorBubble();
2154 GetMetricLogger().LogDialogPopupEvent(AutofillMetrics::DIALOG_POPUP_SHOWN);
2157 void AutofillDialogControllerImpl::OnPopupHidden() {}
2159 bool AutofillDialogControllerImpl::ShouldRepostEvent(
2160 const ui::MouseEvent& event) {
2161 DCHECK_NE(UNKNOWN_TYPE, popup_input_type_);
2162 // If the event would be reposted inside the input showing an Autofill popup,
2163 // just ignore.
2164 return !view_->HitTestInput(popup_input_type_, event.location());
2167 void AutofillDialogControllerImpl::DidSelectSuggestion(int identifier) {
2168 // TODO(estade): implement.
2171 void AutofillDialogControllerImpl::DidAcceptSuggestion(
2172 const base::string16& value,
2173 int identifier) {
2174 DCHECK_NE(UNKNOWN_TYPE, popup_input_type_);
2175 // Because |HidePopup()| can be called from |UpdateSection()|, remember the
2176 // type of the input for later here.
2177 const ServerFieldType popup_input_type = popup_input_type_;
2179 ScopedViewUpdates updates(view_.get());
2180 const PersonalDataManager::GUIDPair& pair = popup_guids_[identifier];
2182 scoped_ptr<DataModelWrapper> wrapper;
2183 if (common::IsCreditCardType(popup_input_type)) {
2184 wrapper.reset(new AutofillCreditCardWrapper(
2185 GetManager()->GetCreditCardByGUID(pair.first)));
2186 } else {
2187 wrapper.reset(new AutofillProfileWrapper(
2188 GetManager()->GetProfileByGUID(pair.first),
2189 AutofillType(popup_input_type),
2190 pair.second));
2193 if (i18ninput::Enabled()) {
2194 base::string16 billing_country =
2195 wrapper->GetInfo(AutofillType(ADDRESS_BILLING_COUNTRY));
2196 base::string16 shipping_country =
2197 wrapper->GetInfo(AutofillType(ADDRESS_HOME_COUNTRY));
2199 if (!billing_country.empty() || !shipping_country.empty()) {
2200 FieldValueMap snapshot = TakeUserInputSnapshot();
2201 if (!billing_country.empty())
2202 snapshot[ADDRESS_BILLING_COUNTRY] = billing_country;
2203 if (!shipping_country.empty())
2204 snapshot[ADDRESS_HOME_COUNTRY] = shipping_country;
2206 RestoreUserInputFromSnapshot(snapshot);
2208 if (!billing_country.empty())
2209 UpdateSection(ActiveBillingSection());
2210 if (!shipping_country.empty())
2211 UpdateSection(SECTION_SHIPPING);
2215 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2216 DialogSection section = static_cast<DialogSection>(i);
2217 if (!SectionIsActive(section))
2218 continue;
2220 wrapper->FillInputs(MutableRequestedFieldsForSection(section));
2221 view_->FillSection(section, popup_input_type);
2224 GetMetricLogger().LogDialogPopupEvent(
2225 AutofillMetrics::DIALOG_POPUP_FORM_FILLED);
2227 // TODO(estade): not sure why it's necessary to do this explicitly.
2228 HidePopup();
2231 void AutofillDialogControllerImpl::RemoveSuggestion(
2232 const base::string16& value,
2233 int identifier) {
2234 // TODO(estade): implement.
2237 void AutofillDialogControllerImpl::ClearPreviewedForm() {
2238 // TODO(estade): implement.
2241 ////////////////////////////////////////////////////////////////////////////////
2242 // content::NotificationObserver implementation.
2244 void AutofillDialogControllerImpl::Observe(
2245 int type,
2246 const content::NotificationSource& source,
2247 const content::NotificationDetails& details) {
2248 DCHECK_EQ(type, content::NOTIFICATION_NAV_ENTRY_COMMITTED);
2249 content::LoadCommittedDetails* load_details =
2250 content::Details<content::LoadCommittedDetails>(details).ptr();
2251 size_t user_index = 0;
2252 if (IsSignInContinueUrl(load_details->entry->GetVirtualURL(), &user_index)) {
2253 GetWalletClient()->SetUserIndex(user_index);
2254 FetchWalletCookie();
2256 // NOTE: |HideSignIn()| may delete the WebContents which doesn't expect to
2257 // be deleted while committing a nav entry. Just call |HideSignIn()| later.
2258 base::MessageLoop::current()->PostTask(FROM_HERE,
2259 base::Bind(&AutofillDialogControllerImpl::HideSignIn,
2260 base::Unretained(this)));
2264 ////////////////////////////////////////////////////////////////////////////////
2265 // SuggestionsMenuModelDelegate implementation.
2267 void AutofillDialogControllerImpl::SuggestionsMenuWillShow() {
2268 HidePopup();
2271 void AutofillDialogControllerImpl::SuggestionItemSelected(
2272 SuggestionsMenuModel* model,
2273 size_t index) {
2274 ScopedViewUpdates updates(view_.get());
2276 if (model->GetItemKeyAt(index) == kManageItemsKey) {
2277 GURL url;
2278 if (!IsPayingWithWallet()) {
2279 GURL settings_url(chrome::kChromeUISettingsURL);
2280 url = settings_url.Resolve(chrome::kAutofillSubPage);
2281 } else {
2282 // Reset |last_wallet_items_fetch_timestamp_| to ensure that the Wallet
2283 // data is refreshed as soon as the user switches back to this tab after
2284 // potentially editing his data.
2285 last_wallet_items_fetch_timestamp_ = base::TimeTicks();
2286 size_t user_index = GetWalletClient()->user_index();
2287 url = SectionForSuggestionsMenuModel(*model) == SECTION_SHIPPING ?
2288 wallet::GetManageAddressesUrl(user_index) :
2289 wallet::GetManageInstrumentsUrl(user_index);
2292 OpenTabWithUrl(url);
2293 return;
2296 model->SetCheckedIndex(index);
2297 DialogSection section = SectionForSuggestionsMenuModel(*model);
2299 if (i18ninput::Enabled()) {
2300 CountryComboboxModel* model = CountryComboboxModelForSection(section);
2301 if (model)
2302 model->ResetDefault();
2305 ResetSectionInput(section);
2306 ShowEditUiIfBadSuggestion(section);
2307 UpdateSection(section);
2308 view_->UpdateNotificationArea();
2309 UpdateForErrors();
2311 LogSuggestionItemSelectedMetric(*model);
2314 ////////////////////////////////////////////////////////////////////////////////
2315 // wallet::WalletClientDelegate implementation.
2317 const AutofillMetrics& AutofillDialogControllerImpl::GetMetricLogger() const {
2318 return metric_logger_;
2321 std::string AutofillDialogControllerImpl::GetRiskData() const {
2322 DCHECK(!risk_data_.empty());
2323 return risk_data_;
2326 std::string AutofillDialogControllerImpl::GetWalletCookieValue() const {
2327 return wallet_cookie_value_;
2330 bool AutofillDialogControllerImpl::IsShippingAddressRequired() const {
2331 return cares_about_shipping_;
2334 void AutofillDialogControllerImpl::OnDidAcceptLegalDocuments() {
2335 DCHECK(is_submitting_ && IsPayingWithWallet());
2336 has_accepted_legal_documents_ = true;
2337 LoadRiskFingerprintData();
2340 void AutofillDialogControllerImpl::OnDidAuthenticateInstrument(bool success) {
2341 DCHECK(is_submitting_ && IsPayingWithWallet());
2343 // TODO(dbeam): use the returned full wallet. http://crbug.com/224992
2344 if (success) {
2345 GetFullWallet();
2346 } else {
2347 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2348 SuggestionsUpdated();
2352 void AutofillDialogControllerImpl::OnDidGetFullWallet(
2353 scoped_ptr<wallet::FullWallet> full_wallet) {
2354 DCHECK(is_submitting_ && IsPayingWithWallet());
2355 ScopedViewUpdates updates(view_.get());
2357 full_wallet_ = full_wallet.Pass();
2359 if (full_wallet_->required_actions().empty()) {
2360 FinishSubmit();
2361 return;
2364 switch (full_wallet_->required_actions()[0]) {
2365 case wallet::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS:
2366 choose_another_instrument_or_address_ = true;
2367 SetIsSubmitting(false);
2368 GetWalletItems();
2369 break;
2371 case wallet::VERIFY_CVV:
2372 SuggestionsUpdated();
2373 break;
2375 default:
2376 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2377 return;
2380 view_->UpdateNotificationArea();
2381 view_->UpdateButtonStrip();
2382 view_->UpdateOverlay();
2385 void AutofillDialogControllerImpl::OnPassiveSigninSuccess() {
2386 FetchWalletCookie();
2389 void AutofillDialogControllerImpl::OnPassiveSigninFailure(
2390 const GoogleServiceAuthError& error) {
2391 signin_helper_.reset();
2392 passive_failed_ = true;
2394 if (handling_use_wallet_link_click_ ||
2395 GetWalletClient()->user_index() != 0) {
2396 // TODO(estade): When a secondary account is selected and fails passive
2397 // auth, we show a sign in page. Currently we show the generic add account
2398 // page, but we should instead show sign in for the selected account.
2399 // http://crbug.com/323327
2400 SignInLinkClicked();
2401 handling_use_wallet_link_click_ = false;
2404 OnWalletSigninError();
2407 void AutofillDialogControllerImpl::OnDidFetchWalletCookieValue(
2408 const std::string& cookie_value) {
2409 wallet_cookie_value_ = cookie_value;
2410 signin_helper_.reset();
2411 GetWalletItems();
2414 void AutofillDialogControllerImpl::OnDidGetWalletItems(
2415 scoped_ptr<wallet::WalletItems> wallet_items) {
2416 legal_documents_text_.clear();
2417 legal_document_link_ranges_.clear();
2418 has_accepted_legal_documents_ = false;
2420 wallet_items_ = wallet_items.Pass();
2422 if (wallet_items_ && !wallet_items_->ObfuscatedGaiaId().empty()) {
2423 // Making sure the user index is in sync shouldn't be necessary, but is an
2424 // extra precaution. But if there is no active account (such as in the
2425 // PASSIVE_AUTH case), stick with the old active account.
2426 GetWalletClient()->SetUserIndex(wallet_items_->active_account_index());
2428 std::vector<std::string> usernames;
2429 for (size_t i = 0; i < wallet_items_->gaia_accounts().size(); ++i) {
2430 usernames.push_back(wallet_items_->gaia_accounts()[i]->email_address());
2432 account_chooser_model_->SetWalletAccounts(
2433 usernames, wallet_items_->active_account_index());
2436 ConstructLegalDocumentsText();
2437 OnWalletOrSigninUpdate();
2440 void AutofillDialogControllerImpl::OnDidSaveToWallet(
2441 const std::string& instrument_id,
2442 const std::string& address_id,
2443 const std::vector<wallet::RequiredAction>& required_actions,
2444 const std::vector<wallet::FormFieldError>& form_field_errors) {
2445 DCHECK(is_submitting_ && IsPayingWithWallet());
2447 if (required_actions.empty()) {
2448 if (!address_id.empty())
2449 active_address_id_ = address_id;
2450 if (!instrument_id.empty())
2451 active_instrument_id_ = instrument_id;
2452 GetFullWallet();
2453 } else {
2454 OnWalletFormFieldError(form_field_errors);
2455 HandleSaveOrUpdateRequiredActions(required_actions);
2459 void AutofillDialogControllerImpl::OnWalletError(
2460 wallet::WalletClient::ErrorType error_type) {
2461 DisableWallet(error_type);
2464 ////////////////////////////////////////////////////////////////////////////////
2465 // PersonalDataManagerObserver implementation.
2467 void AutofillDialogControllerImpl::OnPersonalDataChanged() {
2468 if (is_submitting_)
2469 return;
2471 SuggestionsUpdated();
2474 ////////////////////////////////////////////////////////////////////////////////
2475 // AccountChooserModelDelegate implementation.
2477 void AutofillDialogControllerImpl::AccountChooserWillShow() {
2478 HidePopup();
2481 void AutofillDialogControllerImpl::AccountChoiceChanged() {
2482 ScopedViewUpdates updates(view_.get());
2483 wallet::WalletClient* client = GetWalletClient();
2485 if (is_submitting_)
2486 client->CancelRequest();
2488 SetIsSubmitting(false);
2490 size_t selected_user_index =
2491 account_chooser_model_->GetActiveWalletAccountIndex();
2492 if (account_chooser_model_->WalletIsSelected() &&
2493 client->user_index() != selected_user_index) {
2494 client->SetUserIndex(selected_user_index);
2495 // Clear |wallet_items_| so we don't try to restore the selected instrument
2496 // and address.
2497 wallet_items_.reset();
2498 GetWalletItems();
2499 } else {
2500 SuggestionsUpdated();
2501 UpdateAccountChooserView();
2505 void AutofillDialogControllerImpl::AddAccount() {
2506 SignInLinkClicked();
2509 void AutofillDialogControllerImpl::UpdateAccountChooserView() {
2510 if (view_) {
2511 ScopedViewUpdates updates(view_.get());
2512 view_->UpdateAccountChooser();
2513 view_->UpdateNotificationArea();
2517 ////////////////////////////////////////////////////////////////////////////////
2519 bool AutofillDialogControllerImpl::HandleKeyPressEventInInput(
2520 const content::NativeWebKeyboardEvent& event) {
2521 if (popup_controller_.get())
2522 return popup_controller_->HandleKeyPressEvent(event);
2524 return false;
2527 bool AutofillDialogControllerImpl::IsSubmitPausedOn(
2528 wallet::RequiredAction required_action) const {
2529 return full_wallet_ && full_wallet_->HasRequiredAction(required_action);
2532 void AutofillDialogControllerImpl::ShowNewCreditCardBubble(
2533 scoped_ptr<CreditCard> new_card,
2534 scoped_ptr<AutofillProfile> billing_profile) {
2535 #if !defined(OS_ANDROID)
2536 NewCreditCardBubbleController::Show(web_contents(),
2537 new_card.Pass(),
2538 billing_profile.Pass());
2539 #endif
2542 void AutofillDialogControllerImpl::SubmitButtonDelayBegin() {
2543 submit_button_delay_timer_.Start(
2544 FROM_HERE,
2545 base::TimeDelta::FromMilliseconds(kSubmitButtonDelayMs),
2546 this,
2547 &AutofillDialogControllerImpl::OnSubmitButtonDelayEnd);
2550 void AutofillDialogControllerImpl::SubmitButtonDelayEndForTesting() {
2551 DCHECK(submit_button_delay_timer_.IsRunning());
2552 submit_button_delay_timer_.user_task().Run();
2553 submit_button_delay_timer_.Stop();
2556 void AutofillDialogControllerImpl::
2557 ClearLastWalletItemsFetchTimestampForTesting() {
2558 last_wallet_items_fetch_timestamp_ = base::TimeTicks();
2561 AccountChooserModel* AutofillDialogControllerImpl::
2562 AccountChooserModelForTesting() {
2563 return account_chooser_model_.get();
2566 bool AutofillDialogControllerImpl::IsSignInContinueUrl(
2567 const GURL& url,
2568 size_t* user_index) const {
2569 return wallet::IsSignInContinueUrl(url, user_index);
2572 AutofillDialogControllerImpl::AutofillDialogControllerImpl(
2573 content::WebContents* contents,
2574 const FormData& form_structure,
2575 const GURL& source_url,
2576 const base::Callback<void(const FormStructure*)>& callback)
2577 : WebContentsObserver(contents),
2578 profile_(Profile::FromBrowserContext(contents->GetBrowserContext())),
2579 initial_user_state_(AutofillMetrics::DIALOG_USER_STATE_UNKNOWN),
2580 form_structure_(form_structure),
2581 invoked_from_same_origin_(true),
2582 source_url_(source_url),
2583 callback_(callback),
2584 wallet_client_(profile_->GetRequestContext(), this, source_url),
2585 wallet_items_requested_(false),
2586 handling_use_wallet_link_click_(false),
2587 passive_failed_(false),
2588 billing_country_combobox_model_(*GetManager()),
2589 shipping_country_combobox_model_(*GetManager()),
2590 suggested_cc_(this),
2591 suggested_billing_(this),
2592 suggested_cc_billing_(this),
2593 suggested_shipping_(this),
2594 cares_about_shipping_(true),
2595 popup_input_type_(UNKNOWN_TYPE),
2596 weak_ptr_factory_(this),
2597 waiting_for_explicit_sign_in_response_(false),
2598 has_accepted_legal_documents_(false),
2599 is_submitting_(false),
2600 choose_another_instrument_or_address_(false),
2601 wallet_server_validation_recoverable_(true),
2602 data_was_passed_back_(false),
2603 was_ui_latency_logged_(false),
2604 card_generated_animation_(2000, 60, this),
2605 observer_(this) {
2606 // TODO(estade): remove duplicates from |form_structure|?
2607 DCHECK(!callback_.is_null());
2610 AutofillDialogView* AutofillDialogControllerImpl::CreateView() {
2611 return AutofillDialogView::Create(this);
2614 PersonalDataManager* AutofillDialogControllerImpl::GetManager() const {
2615 return PersonalDataManagerFactory::GetForProfile(profile_);
2618 const wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient()
2619 const {
2620 return const_cast<AutofillDialogControllerImpl*>(this)->GetWalletClient();
2623 wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient() {
2624 return &wallet_client_;
2627 bool AutofillDialogControllerImpl::IsPayingWithWallet() const {
2628 return account_chooser_model_->WalletIsSelected() &&
2629 SignedInState() == SIGNED_IN;
2632 void AutofillDialogControllerImpl::LoadRiskFingerprintData() {
2633 risk_data_.clear();
2635 uint64 obfuscated_gaia_id = 0;
2636 bool success = base::StringToUint64(wallet_items_->ObfuscatedGaiaId(),
2637 &obfuscated_gaia_id);
2638 DCHECK(success);
2640 gfx::Rect window_bounds;
2641 window_bounds = GetBaseWindowForWebContents(web_contents())->GetBounds();
2643 PrefService* user_prefs = profile_->GetPrefs();
2644 std::string charset = user_prefs->GetString(::prefs::kDefaultCharset);
2645 std::string accept_languages =
2646 user_prefs->GetString(::prefs::kAcceptLanguages);
2647 base::Time install_time = base::Time::FromTimeT(
2648 g_browser_process->local_state()->GetInt64(::prefs::kInstallDate));
2650 risk::GetFingerprint(
2651 obfuscated_gaia_id, window_bounds, *web_contents(),
2652 chrome::VersionInfo().Version(), charset, accept_languages, install_time,
2653 g_browser_process->GetApplicationLocale(),
2654 base::Bind(&AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData,
2655 weak_ptr_factory_.GetWeakPtr()));
2658 void AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData(
2659 scoped_ptr<risk::Fingerprint> fingerprint) {
2660 DCHECK(AreLegalDocumentsCurrent());
2662 std::string proto_data;
2663 fingerprint->SerializeToString(&proto_data);
2664 base::Base64Encode(proto_data, &risk_data_);
2666 SubmitWithWallet();
2669 void AutofillDialogControllerImpl::OpenTabWithUrl(const GURL& url) {
2670 chrome::NavigateParams params(
2671 chrome::FindBrowserWithWebContents(web_contents()),
2672 url,
2673 content::PAGE_TRANSITION_LINK);
2674 params.disposition = NEW_FOREGROUND_TAB;
2675 chrome::Navigate(&params);
2678 DialogSection AutofillDialogControllerImpl::ActiveBillingSection() const {
2679 return IsPayingWithWallet() ? SECTION_CC_BILLING : SECTION_BILLING;
2682 bool AutofillDialogControllerImpl::IsEditingExistingData(
2683 DialogSection section) const {
2684 return section_editing_state_.count(section) > 0;
2687 bool AutofillDialogControllerImpl::IsManuallyEditingSection(
2688 DialogSection section) const {
2689 return IsEditingExistingData(section) ||
2690 SuggestionsMenuModelForSection(section)->
2691 GetItemKeyForCheckedItem() == kAddNewItemKey;
2694 void AutofillDialogControllerImpl::OnWalletSigninError() {
2695 account_chooser_model_->SetHadWalletSigninError();
2696 GetWalletClient()->CancelRequest();
2697 LogDialogLatencyToShow();
2700 void AutofillDialogControllerImpl::DisableWallet(
2701 wallet::WalletClient::ErrorType error_type) {
2702 signin_helper_.reset();
2703 wallet_items_.reset();
2704 wallet_errors_.clear();
2705 GetWalletClient()->CancelRequest();
2706 SetIsSubmitting(false);
2707 wallet_error_notification_ = GetWalletError(error_type);
2708 account_chooser_model_->SetHadWalletError();
2711 void AutofillDialogControllerImpl::SuggestionsUpdated() {
2712 ScopedViewUpdates updates(view_.get());
2714 const FieldValueMap snapshot = TakeUserInputSnapshot();
2716 suggested_cc_.Reset();
2717 suggested_billing_.Reset();
2718 suggested_cc_billing_.Reset();
2719 suggested_shipping_.Reset();
2720 HidePopup();
2722 suggested_shipping_.AddKeyedItem(
2723 kSameAsBillingKey,
2724 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_USE_BILLING_FOR_SHIPPING));
2726 if (IsPayingWithWallet()) {
2727 const std::vector<wallet::Address*>& addresses =
2728 wallet_items_->addresses();
2730 bool shipping_same_as_billing = profile_->GetPrefs()->GetBoolean(
2731 ::prefs::kAutofillDialogWalletShippingSameAsBilling);
2733 if (shipping_same_as_billing)
2734 suggested_shipping_.SetCheckedItem(kSameAsBillingKey);
2736 for (size_t i = 0; i < addresses.size(); ++i) {
2737 std::string key = base::IntToString(i);
2738 suggested_shipping_.AddKeyedItemWithMinorText(
2739 key,
2740 addresses[i]->DisplayName(),
2741 addresses[i]->DisplayNameDetail());
2743 // TODO(scr): Move this assignment outside the loop or comment why it
2744 // can't be there.
2745 const std::string default_shipping_address_id =
2746 GetIdToSelect(wallet_items_->default_address_id(),
2747 previous_default_shipping_address_id_,
2748 previously_selected_shipping_address_id_);
2750 if (!shipping_same_as_billing &&
2751 addresses[i]->object_id() == default_shipping_address_id) {
2752 suggested_shipping_.SetCheckedItem(key);
2756 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2757 const std::vector<wallet::WalletItems::MaskedInstrument*>& instruments =
2758 wallet_items_->instruments();
2759 std::string first_active_instrument_key;
2760 std::string default_instrument_key;
2761 for (size_t i = 0; i < instruments.size(); ++i) {
2762 bool allowed = IsInstrumentAllowed(*instruments[i]);
2763 gfx::Image icon = instruments[i]->CardIcon();
2764 if (!allowed && !icon.IsEmpty()) {
2765 // Create a grayed disabled icon.
2766 SkBitmap disabled_bitmap = SkBitmapOperations::CreateHSLShiftedBitmap(
2767 *icon.ToSkBitmap(), kGrayImageShift);
2768 icon = gfx::Image(
2769 gfx::ImageSkia::CreateFrom1xBitmap(disabled_bitmap));
2771 std::string key = base::IntToString(i);
2772 suggested_cc_billing_.AddKeyedItemWithMinorTextAndIcon(
2773 key,
2774 instruments[i]->DisplayName(),
2775 instruments[i]->DisplayNameDetail(),
2776 icon);
2777 suggested_cc_billing_.SetEnabled(key, allowed);
2779 if (allowed) {
2780 if (first_active_instrument_key.empty())
2781 first_active_instrument_key = key;
2783 const std::string default_instrument_id =
2784 GetIdToSelect(wallet_items_->default_instrument_id(),
2785 previous_default_instrument_id_,
2786 previously_selected_instrument_id_);
2787 if (instruments[i]->object_id() == default_instrument_id)
2788 default_instrument_key = key;
2792 suggested_cc_billing_.AddKeyedItem(
2793 kAddNewItemKey,
2794 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_DETAILS));
2795 if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
2796 suggested_cc_billing_.AddKeyedItemWithMinorText(
2797 kManageItemsKey,
2798 l10n_util::GetStringUTF16(
2799 IDS_AUTOFILL_DIALOG_MANAGE_BILLING_DETAILS),
2800 base::UTF8ToUTF16(wallet::GetManageInstrumentsUrl(0U).host()));
2803 // Determine which instrument item should be selected.
2804 if (!default_instrument_key.empty())
2805 suggested_cc_billing_.SetCheckedItem(default_instrument_key);
2806 else if (!first_active_instrument_key.empty())
2807 suggested_cc_billing_.SetCheckedItem(first_active_instrument_key);
2808 else
2809 suggested_cc_billing_.SetCheckedItem(kAddNewItemKey);
2811 } else {
2812 PersonalDataManager* manager = GetManager();
2813 const std::vector<CreditCard*>& cards = manager->GetCreditCards();
2814 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
2815 for (size_t i = 0; i < cards.size(); ++i) {
2816 if (!HasCompleteAndVerifiedData(*cards[i], requested_cc_fields_))
2817 continue;
2819 suggested_cc_.AddKeyedItemWithIcon(
2820 cards[i]->guid(),
2821 cards[i]->Label(),
2822 rb.GetImageNamed(CreditCard::IconResourceId(cards[i]->type())));
2825 const std::vector<AutofillProfile*>& profiles = manager->GetProfiles();
2826 std::vector<base::string16> labels;
2827 AutofillProfile::CreateDifferentiatingLabels(profiles, &labels);
2828 DCHECK_EQ(labels.size(), profiles.size());
2829 for (size_t i = 0; i < profiles.size(); ++i) {
2830 const AutofillProfile& profile = *profiles[i];
2831 if (!HasCompleteAndVerifiedData(profile, requested_shipping_fields_) ||
2832 HasInvalidAddress(*profiles[i])) {
2833 continue;
2836 // Don't add variants for addresses: name is part of credit card and we'll
2837 // just ignore email and phone number variants.
2838 suggested_shipping_.AddKeyedItem(profile.guid(), labels[i]);
2839 if (!profile.GetRawInfo(EMAIL_ADDRESS).empty() &&
2840 !profile.IsPresentButInvalid(EMAIL_ADDRESS)) {
2841 suggested_billing_.AddKeyedItem(profile.guid(), labels[i]);
2845 suggested_cc_.AddKeyedItem(
2846 kAddNewItemKey,
2847 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_CREDIT_CARD));
2848 suggested_cc_.AddKeyedItem(
2849 kManageItemsKey,
2850 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_CREDIT_CARD));
2851 suggested_billing_.AddKeyedItem(
2852 kAddNewItemKey,
2853 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_ADDRESS));
2854 suggested_billing_.AddKeyedItem(
2855 kManageItemsKey,
2856 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_BILLING_ADDRESS));
2859 suggested_shipping_.AddKeyedItem(
2860 kAddNewItemKey,
2861 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_SHIPPING_ADDRESS));
2862 if (!IsPayingWithWallet()) {
2863 suggested_shipping_.AddKeyedItem(
2864 kManageItemsKey,
2865 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS));
2866 } else if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
2867 suggested_shipping_.AddKeyedItemWithMinorText(
2868 kManageItemsKey,
2869 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS),
2870 base::UTF8ToUTF16(wallet::GetManageAddressesUrl(0U).host()));
2873 if (!IsPayingWithWallet()) {
2874 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2875 DialogSection section = static_cast<DialogSection>(i);
2876 if (!SectionIsActive(section))
2877 continue;
2879 // Set the starting choice for the menu. First set to the default in case
2880 // the GUID saved in prefs refers to a profile that no longer exists.
2881 std::string guid;
2882 GetDefaultAutofillChoice(section, &guid);
2883 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
2884 model->SetCheckedItem(guid);
2885 if (GetAutofillChoice(section, &guid))
2886 model->SetCheckedItem(guid);
2890 if (view_)
2891 view_->ModelChanged();
2893 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2894 ResetSectionInput(static_cast<DialogSection>(i));
2897 RestoreUserInputFromSnapshot(snapshot);
2899 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2900 DialogSection section = static_cast<DialogSection>(i);
2901 if (!SectionIsActive(section))
2902 continue;
2904 ShowEditUiIfBadSuggestion(section);
2905 UpdateSection(section);
2908 UpdateForErrors();
2911 void AutofillDialogControllerImpl::FillOutputForSectionWithComparator(
2912 DialogSection section,
2913 const InputFieldComparator& compare) {
2914 if (!SectionIsActive(section))
2915 return;
2917 DetailInputs inputs;
2918 std::string country_code = CountryCodeForSection(section);
2919 common::BuildInputsForSection(section, country_code, &inputs);
2921 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
2922 if (wrapper) {
2923 // Only fill in data that is associated with this section.
2924 wrapper->FillFormStructure(inputs, compare, &form_structure_);
2926 // CVC needs special-casing because the CreditCard class doesn't store or
2927 // handle them. This isn't necessary when filling the combined CC and
2928 // billing section as CVC comes from |full_wallet_| in this case.
2929 if (section == SECTION_CC)
2930 SetOutputForFieldsOfType(CREDIT_CARD_VERIFICATION_CODE, view_->GetCvc());
2932 // When filling from Wallet data, use the email address associated with the
2933 // account. There is no other email address stored as part of a Wallet
2934 // address.
2935 if (section == SECTION_CC_BILLING) {
2936 SetOutputForFieldsOfType(
2937 EMAIL_ADDRESS, account_chooser_model_->GetActiveWalletAccountName());
2939 } else {
2940 // The user manually input data. If using Autofill, save the info as new or
2941 // edited data. Always fill local data into |form_structure_|.
2942 FieldValueMap output;
2943 view_->GetUserInput(section, &output);
2945 if (section == SECTION_CC) {
2946 CreditCard card;
2947 card.set_origin(kAutofillDialogOrigin);
2948 FillFormGroupFromOutputs(output, &card);
2950 // The card holder name comes from the billing address section.
2951 card.SetRawInfo(CREDIT_CARD_NAME,
2952 GetValueFromSection(SECTION_BILLING, NAME_BILLING_FULL));
2954 if (ShouldSaveDetailsLocally()) {
2955 std::string guid = GetManager()->SaveImportedCreditCard(card);
2956 newly_saved_data_model_guids_[section] = guid;
2957 DCHECK(!profile()->IsOffTheRecord());
2958 newly_saved_card_.reset(new CreditCard(card));
2961 AutofillCreditCardWrapper card_wrapper(&card);
2962 card_wrapper.FillFormStructure(inputs, compare, &form_structure_);
2964 // Again, CVC needs special-casing. Fill it in directly from |output|.
2965 SetOutputForFieldsOfType(
2966 CREDIT_CARD_VERIFICATION_CODE,
2967 output[CREDIT_CARD_VERIFICATION_CODE]);
2968 } else {
2969 AutofillProfile profile;
2970 profile.set_origin(kAutofillDialogOrigin);
2971 FillFormGroupFromOutputs(output, &profile);
2973 if (ShouldSaveDetailsLocally()) {
2974 std::string guid = GetManager()->SaveImportedProfile(profile);
2975 newly_saved_data_model_guids_[section] = guid;
2978 AutofillProfileWrapper profile_wrapper(&profile);
2979 profile_wrapper.FillFormStructure(inputs, compare, &form_structure_);
2984 void AutofillDialogControllerImpl::FillOutputForSection(DialogSection section) {
2985 FillOutputForSectionWithComparator(
2986 section, base::Bind(common::DetailInputMatchesField, section));
2989 bool AutofillDialogControllerImpl::FormStructureCaresAboutSection(
2990 DialogSection section) const {
2991 // For now, only SECTION_SHIPPING may be omitted due to a site not asking for
2992 // any of the fields.
2993 if (section == SECTION_SHIPPING)
2994 return cares_about_shipping_;
2996 return true;
2999 void AutofillDialogControllerImpl::SetOutputForFieldsOfType(
3000 ServerFieldType type,
3001 const base::string16& output) {
3002 for (size_t i = 0; i < form_structure_.field_count(); ++i) {
3003 AutofillField* field = form_structure_.field(i);
3004 if (field->Type().GetStorableType() == type)
3005 field->value = output;
3009 base::string16 AutofillDialogControllerImpl::GetValueFromSection(
3010 DialogSection section,
3011 ServerFieldType type) {
3012 DCHECK(SectionIsActive(section));
3014 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3015 if (wrapper)
3016 return wrapper->GetInfo(AutofillType(type));
3018 FieldValueMap output;
3019 view_->GetUserInput(section, &output);
3020 return output[type];
3023 SuggestionsMenuModel* AutofillDialogControllerImpl::
3024 SuggestionsMenuModelForSection(DialogSection section) {
3025 switch (section) {
3026 case SECTION_CC:
3027 return &suggested_cc_;
3028 case SECTION_BILLING:
3029 return &suggested_billing_;
3030 case SECTION_SHIPPING:
3031 return &suggested_shipping_;
3032 case SECTION_CC_BILLING:
3033 return &suggested_cc_billing_;
3036 NOTREACHED();
3037 return NULL;
3040 const SuggestionsMenuModel* AutofillDialogControllerImpl::
3041 SuggestionsMenuModelForSection(DialogSection section) const {
3042 return const_cast<AutofillDialogControllerImpl*>(this)->
3043 SuggestionsMenuModelForSection(section);
3046 DialogSection AutofillDialogControllerImpl::SectionForSuggestionsMenuModel(
3047 const SuggestionsMenuModel& model) {
3048 if (&model == &suggested_cc_)
3049 return SECTION_CC;
3051 if (&model == &suggested_billing_)
3052 return SECTION_BILLING;
3054 if (&model == &suggested_cc_billing_)
3055 return SECTION_CC_BILLING;
3057 DCHECK_EQ(&model, &suggested_shipping_);
3058 return SECTION_SHIPPING;
3061 CountryComboboxModel* AutofillDialogControllerImpl::
3062 CountryComboboxModelForSection(DialogSection section) {
3063 switch (section) {
3064 case SECTION_CC:
3065 return NULL;
3066 case SECTION_BILLING:
3067 case SECTION_CC_BILLING:
3068 return &billing_country_combobox_model_;
3069 case SECTION_SHIPPING:
3070 return &shipping_country_combobox_model_;
3073 NOTREACHED();
3074 return NULL;
3077 DetailInputs* AutofillDialogControllerImpl::MutableRequestedFieldsForSection(
3078 DialogSection section) {
3079 return const_cast<DetailInputs*>(&RequestedFieldsForSection(section));
3082 void AutofillDialogControllerImpl::OnComboboxModelChanged(
3083 ui::ComboboxModel* model) {
3084 DCHECK(model == &billing_country_combobox_model_ ||
3085 model == &shipping_country_combobox_model_);
3087 const std::string country_code = AutofillCountry::GetCountryCode(
3088 model->GetItemAt(model->GetDefaultIndex()),
3089 g_browser_process->GetApplicationLocale());
3091 const bool is_billing = model == &billing_country_combobox_model_;
3092 DialogSection section = is_billing ? SECTION_BILLING : SECTION_SHIPPING;
3094 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
3095 inputs->clear();
3096 common::BuildInputsForSection(section, country_code, inputs);
3098 if (is_billing) {
3099 // Also rebuild inputs for the combined credit card + billing section.
3100 DetailInputs* inputs = MutableRequestedFieldsForSection(SECTION_CC_BILLING);
3101 inputs->clear();
3102 common::BuildInputsForSection(SECTION_CC_BILLING, country_code, inputs);
3106 std::string AutofillDialogControllerImpl::CountryCodeForSection(
3107 DialogSection section) {
3108 if (section == SECTION_CC)
3109 return std::string();
3111 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3112 if (wrapper) {
3113 ServerFieldType type = section == SECTION_SHIPPING ?
3114 ADDRESS_HOME_COUNTRY : ADDRESS_BILLING_COUNTRY;
3115 return AutofillCountry::GetCountryCode(
3116 wrapper->GetInfo(AutofillType(type)),
3117 g_browser_process->GetApplicationLocale());
3120 CountryComboboxModel* model = CountryComboboxModelForSection(section);
3121 return model->countries()[model->GetDefaultIndex()]->country_code();
3124 void AutofillDialogControllerImpl::HidePopup() {
3125 if (popup_controller_.get())
3126 popup_controller_->Hide();
3127 popup_input_type_ = UNKNOWN_TYPE;
3130 void AutofillDialogControllerImpl::SetEditingExistingData(
3131 DialogSection section, bool editing) {
3132 if (editing)
3133 section_editing_state_.insert(section);
3134 else
3135 section_editing_state_.erase(section);
3138 bool AutofillDialogControllerImpl::IsASuggestionItemKey(
3139 const std::string& key) const {
3140 return !key.empty() &&
3141 key != kAddNewItemKey &&
3142 key != kManageItemsKey &&
3143 key != kSameAsBillingKey;
3146 bool AutofillDialogControllerImpl::IsManuallyEditingAnySection() const {
3147 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
3148 if (IsManuallyEditingSection(static_cast<DialogSection>(section)))
3149 return true;
3151 return false;
3154 base::string16 AutofillDialogControllerImpl::CreditCardNumberValidityMessage(
3155 const base::string16& number) const {
3156 if (!number.empty() && !autofill::IsValidCreditCardNumber(number)) {
3157 return l10n_util::GetStringUTF16(
3158 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_NUMBER);
3161 base::string16 message;
3162 if (IsPayingWithWallet() && !wallet_items_->SupportsCard(number, &message))
3163 return message;
3165 // Card number is good and supported.
3166 return base::string16();
3169 bool AutofillDialogControllerImpl::AllSectionsAreValid() {
3170 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
3171 if (!SectionIsValid(static_cast<DialogSection>(section)))
3172 return false;
3174 return true;
3177 bool AutofillDialogControllerImpl::SectionIsValid(
3178 DialogSection section) {
3179 if (!IsManuallyEditingSection(section))
3180 return true;
3182 FieldValueMap detail_outputs;
3183 view_->GetUserInput(section, &detail_outputs);
3184 return !InputsAreValid(section, detail_outputs).HasSureErrors();
3187 bool AutofillDialogControllerImpl::IsCreditCardExpirationValid(
3188 const base::string16& year,
3189 const base::string16& month) const {
3190 // If the expiration is in the past as per the local clock, it's invalid.
3191 base::Time now = base::Time::Now();
3192 if (!autofill::IsValidCreditCardExpirationDate(year, month, now))
3193 return false;
3195 if (IsPayingWithWallet() && IsEditingExistingData(SECTION_CC_BILLING)) {
3196 const wallet::WalletItems::MaskedInstrument* instrument =
3197 ActiveInstrument();
3198 const std::string& locale = g_browser_process->GetApplicationLocale();
3199 int month_int;
3200 if (base::StringToInt(month, &month_int) &&
3201 instrument->status() ==
3202 wallet::WalletItems::MaskedInstrument::EXPIRED &&
3203 year ==
3204 instrument->GetInfo(
3205 AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), locale) &&
3206 month_int == instrument->expiration_month()) {
3207 // Otherwise, if the user is editing an instrument that's deemed expired
3208 // by the Online Wallet server, mark it invalid on selection.
3209 return false;
3213 return true;
3216 bool AutofillDialogControllerImpl::ShouldUseBillingForShipping() {
3217 return SectionIsActive(SECTION_SHIPPING) &&
3218 suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey;
3221 bool AutofillDialogControllerImpl::ShouldSaveDetailsLocally() {
3222 // It's possible that the user checked [X] Save details locally before
3223 // switching payment methods, so only ask the view whether to save details
3224 // locally if that checkbox is showing (currently if not paying with wallet).
3225 // Also, if the user isn't editing any sections, there's no data to save
3226 // locally.
3227 return ShouldOfferToSaveInChrome() && view_->SaveDetailsLocally();
3230 void AutofillDialogControllerImpl::SetIsSubmitting(bool submitting) {
3231 is_submitting_ = submitting;
3233 if (!submitting)
3234 full_wallet_.reset();
3236 if (view_) {
3237 ScopedViewUpdates updates(view_.get());
3238 view_->UpdateButtonStrip();
3239 view_->UpdateOverlay();
3240 view_->UpdateNotificationArea();
3244 bool AutofillDialogControllerImpl::AreLegalDocumentsCurrent() const {
3245 return has_accepted_legal_documents_ ||
3246 (wallet_items_ && wallet_items_->legal_documents().empty());
3249 void AutofillDialogControllerImpl::AcceptLegalTerms() {
3250 content::BrowserThread::PostTask(
3251 content::BrowserThread::IO, FROM_HERE,
3252 base::Bind(&UserDidOptIntoLocationServices));
3253 PrefService* local_state = g_browser_process->local_state();
3254 ListPrefUpdate accepted(
3255 local_state, ::prefs::kAutofillDialogWalletLocationAcceptance);
3256 accepted->AppendIfNotPresent(new base::StringValue(
3257 account_chooser_model_->GetActiveWalletAccountName()));
3259 if (AreLegalDocumentsCurrent()) {
3260 LoadRiskFingerprintData();
3261 } else {
3262 GetWalletClient()->AcceptLegalDocuments(
3263 wallet_items_->legal_documents(),
3264 wallet_items_->google_transaction_id());
3268 void AutofillDialogControllerImpl::SubmitWithWallet() {
3269 active_instrument_id_.clear();
3270 active_address_id_.clear();
3271 full_wallet_.reset();
3273 const wallet::WalletItems::MaskedInstrument* active_instrument =
3274 ActiveInstrument();
3275 if (!IsManuallyEditingSection(SECTION_CC_BILLING)) {
3276 active_instrument_id_ = active_instrument->object_id();
3277 DCHECK(!active_instrument_id_.empty());
3280 const wallet::Address* active_address = ActiveShippingAddress();
3281 if (!IsManuallyEditingSection(SECTION_SHIPPING) &&
3282 !ShouldUseBillingForShipping() &&
3283 IsShippingAddressRequired()) {
3284 active_address_id_ = active_address->object_id();
3285 DCHECK(!active_address_id_.empty());
3288 scoped_ptr<wallet::Instrument> inputted_instrument =
3289 CreateTransientInstrument();
3291 scoped_ptr<wallet::Address> inputted_address;
3292 if (active_address_id_.empty() && IsShippingAddressRequired()) {
3293 if (ShouldUseBillingForShipping()) {
3294 const wallet::Address& address = inputted_instrument ?
3295 *inputted_instrument->address() : active_instrument->address();
3296 // Try to find an exact matched shipping address and use it for shipping,
3297 // otherwise save it as a new shipping address. http://crbug.com/225442
3298 const wallet::Address* duplicated_address =
3299 FindDuplicateAddress(wallet_items_->addresses(), address);
3300 if (duplicated_address) {
3301 active_address_id_ = duplicated_address->object_id();
3302 DCHECK(!active_address_id_.empty());
3303 } else {
3304 inputted_address.reset(new wallet::Address(address));
3305 DCHECK(inputted_address->object_id().empty());
3307 } else {
3308 inputted_address = CreateTransientAddress();
3312 // If there's neither an address nor instrument to save, |GetFullWallet()|
3313 // is called when the risk fingerprint is loaded.
3314 if (!active_instrument_id_.empty() &&
3315 (!active_address_id_.empty() || !IsShippingAddressRequired())) {
3316 GetFullWallet();
3317 return;
3320 GetWalletClient()->SaveToWallet(
3321 inputted_instrument.Pass(),
3322 inputted_address.Pass(),
3323 IsEditingExistingData(SECTION_CC_BILLING) ? active_instrument : NULL,
3324 IsEditingExistingData(SECTION_SHIPPING) ? active_address : NULL);
3327 scoped_ptr<wallet::Instrument> AutofillDialogControllerImpl::
3328 CreateTransientInstrument() {
3329 if (!active_instrument_id_.empty())
3330 return scoped_ptr<wallet::Instrument>();
3332 FieldValueMap output;
3333 view_->GetUserInput(SECTION_CC_BILLING, &output);
3335 CreditCard card;
3336 AutofillProfile profile;
3337 base::string16 cvc;
3338 GetBillingInfoFromOutputs(output, &card, &cvc, &profile);
3340 return scoped_ptr<wallet::Instrument>(
3341 new wallet::Instrument(card, cvc, profile));
3344 scoped_ptr<wallet::Address>AutofillDialogControllerImpl::
3345 CreateTransientAddress() {
3346 // If not using billing for shipping, just scrape the view.
3347 FieldValueMap output;
3348 view_->GetUserInput(SECTION_SHIPPING, &output);
3350 AutofillProfile profile;
3351 FillFormGroupFromOutputs(output, &profile);
3353 return scoped_ptr<wallet::Address>(new wallet::Address(profile));
3356 void AutofillDialogControllerImpl::GetFullWallet() {
3357 DCHECK(is_submitting_);
3358 DCHECK(IsPayingWithWallet());
3359 DCHECK(wallet_items_);
3360 DCHECK(!active_instrument_id_.empty());
3361 DCHECK(!active_address_id_.empty() || !IsShippingAddressRequired());
3363 std::vector<wallet::WalletClient::RiskCapability> capabilities;
3364 capabilities.push_back(wallet::WalletClient::VERIFY_CVC);
3366 GetWalletClient()->GetFullWallet(wallet::WalletClient::FullWalletRequest(
3367 active_instrument_id_,
3368 active_address_id_,
3369 wallet_items_->google_transaction_id(),
3370 capabilities,
3371 wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)));
3374 void AutofillDialogControllerImpl::HandleSaveOrUpdateRequiredActions(
3375 const std::vector<wallet::RequiredAction>& required_actions) {
3376 DCHECK(!required_actions.empty());
3378 // TODO(ahutter): Investigate if we need to support more generic actions on
3379 // this call such as GAIA_AUTH. See crbug.com/243457.
3380 for (std::vector<wallet::RequiredAction>::const_iterator iter =
3381 required_actions.begin();
3382 iter != required_actions.end(); ++iter) {
3383 if (*iter != wallet::INVALID_FORM_FIELD) {
3384 // TODO(dbeam): handle this more gracefully.
3385 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
3388 SetIsSubmitting(false);
3391 void AutofillDialogControllerImpl::FinishSubmit() {
3392 if (IsPayingWithWallet()) {
3393 ScopedViewUpdates updates(view_.get());
3394 view_->UpdateOverlay();
3396 card_generated_animation_.Start();
3397 return;
3399 DoFinishSubmit();
3402 void AutofillDialogControllerImpl::AnimationProgressed(
3403 const gfx::Animation* animation) {
3404 DCHECK_EQ(animation, &card_generated_animation_);
3405 PushOverlayUpdate();
3408 void AutofillDialogControllerImpl::AnimationEnded(
3409 const gfx::Animation* animation) {
3410 DCHECK_EQ(animation, &card_generated_animation_);
3411 DoFinishSubmit();
3414 void AutofillDialogControllerImpl::DoFinishSubmit() {
3415 FillOutputForSection(SECTION_CC);
3416 FillOutputForSection(SECTION_BILLING);
3417 FillOutputForSection(SECTION_CC_BILLING);
3419 if (ShouldUseBillingForShipping()) {
3420 FillOutputForSectionWithComparator(
3421 SECTION_BILLING,
3422 base::Bind(DetailInputMatchesShippingField));
3423 FillOutputForSectionWithComparator(
3424 SECTION_CC,
3425 base::Bind(DetailInputMatchesShippingField));
3426 FillOutputForSectionWithComparator(
3427 SECTION_CC_BILLING,
3428 base::Bind(DetailInputMatchesShippingField));
3429 } else {
3430 FillOutputForSection(SECTION_SHIPPING);
3433 if (IsPayingWithWallet()) {
3434 if (SectionIsActive(SECTION_SHIPPING)) {
3435 profile_->GetPrefs()->SetBoolean(
3436 ::prefs::kAutofillDialogWalletShippingSameAsBilling,
3437 suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey);
3439 } else {
3440 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3441 DialogSection section = static_cast<DialogSection>(i);
3442 if (!SectionIsActive(section))
3443 continue;
3445 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3446 std::string item_key = model->GetItemKeyForCheckedItem();
3447 if (IsASuggestionItemKey(item_key) || item_key == kSameAsBillingKey) {
3448 PersistAutofillChoice(section, item_key);
3449 } else if (item_key == kAddNewItemKey && ShouldSaveDetailsLocally()) {
3450 DCHECK(newly_saved_data_model_guids_.count(section));
3451 PersistAutofillChoice(section, newly_saved_data_model_guids_[section]);
3455 profile_->GetPrefs()->SetBoolean(::prefs::kAutofillDialogSaveData,
3456 view_->SaveDetailsLocally());
3459 // On a successful submit, if the user manually selected "pay without wallet",
3460 // stop trying to pay with Wallet on future runs of the dialog. On the other
3461 // hand, if there was an error that prevented the user from having the choice
3462 // of using Wallet, leave the pref alone.
3463 if (!wallet_error_notification_ &&
3464 account_chooser_model_->HasAccountsToChoose()) {
3465 profile_->GetPrefs()->SetBoolean(
3466 ::prefs::kAutofillDialogPayWithoutWallet,
3467 !account_chooser_model_->WalletIsSelected());
3470 LogOnFinishSubmitMetrics();
3472 // Callback should be called as late as possible.
3473 callback_.Run(&form_structure_);
3474 data_was_passed_back_ = true;
3476 // This might delete us.
3477 Hide();
3480 void AutofillDialogControllerImpl::PersistAutofillChoice(
3481 DialogSection section,
3482 const std::string& guid) {
3483 DCHECK(!IsPayingWithWallet());
3484 scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
3485 value->SetString(kGuidPrefKey, guid);
3487 DictionaryPrefUpdate updater(profile()->GetPrefs(),
3488 ::prefs::kAutofillDialogAutofillDefault);
3489 base::DictionaryValue* autofill_choice = updater.Get();
3490 autofill_choice->Set(SectionToPrefString(section), value.release());
3493 void AutofillDialogControllerImpl::GetDefaultAutofillChoice(
3494 DialogSection section,
3495 std::string* guid) {
3496 DCHECK(!IsPayingWithWallet());
3497 // The default choice is the first thing in the menu that is a suggestion
3498 // item.
3499 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3500 for (int i = 0; i < model->GetItemCount(); ++i) {
3501 if (IsASuggestionItemKey(model->GetItemKeyAt(i))) {
3502 *guid = model->GetItemKeyAt(i);
3503 break;
3508 bool AutofillDialogControllerImpl::GetAutofillChoice(DialogSection section,
3509 std::string* guid) {
3510 DCHECK(!IsPayingWithWallet());
3511 const base::DictionaryValue* choices = profile()->GetPrefs()->GetDictionary(
3512 ::prefs::kAutofillDialogAutofillDefault);
3513 if (!choices)
3514 return false;
3516 const base::DictionaryValue* choice = NULL;
3517 if (!choices->GetDictionary(SectionToPrefString(section), &choice))
3518 return false;
3520 choice->GetString(kGuidPrefKey, guid);
3521 return true;
3524 void AutofillDialogControllerImpl::LogOnFinishSubmitMetrics() {
3525 GetMetricLogger().LogDialogUiDuration(
3526 base::Time::Now() - dialog_shown_timestamp_,
3527 AutofillMetrics::DIALOG_ACCEPTED);
3529 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_ACCEPTED);
3531 AutofillMetrics::DialogDismissalState dismissal_state;
3532 if (!IsManuallyEditingAnySection())
3533 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_EXISTING_DATA;
3534 else if (IsPayingWithWallet())
3535 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_WALLET;
3536 else if (ShouldSaveDetailsLocally())
3537 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_AUTOFILL;
3538 else
3539 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_NO_SAVE;
3541 GetMetricLogger().LogDialogDismissalState(dismissal_state);
3544 void AutofillDialogControllerImpl::LogOnCancelMetrics() {
3545 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_CANCELED);
3547 AutofillMetrics::DialogDismissalState dismissal_state;
3548 if (ShouldShowSignInWebView())
3549 dismissal_state = AutofillMetrics::DIALOG_CANCELED_DURING_SIGNIN;
3550 else if (!IsManuallyEditingAnySection())
3551 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_EDITS;
3552 else if (AllSectionsAreValid())
3553 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_INVALID_FIELDS;
3554 else
3555 dismissal_state = AutofillMetrics::DIALOG_CANCELED_WITH_INVALID_FIELDS;
3557 GetMetricLogger().LogDialogDismissalState(dismissal_state);
3559 GetMetricLogger().LogDialogUiDuration(
3560 base::Time::Now() - dialog_shown_timestamp_,
3561 AutofillMetrics::DIALOG_CANCELED);
3564 void AutofillDialogControllerImpl::LogSuggestionItemSelectedMetric(
3565 const SuggestionsMenuModel& model) {
3566 DialogSection section = SectionForSuggestionsMenuModel(model);
3568 AutofillMetrics::DialogUiEvent dialog_ui_event;
3569 if (model.GetItemKeyForCheckedItem() == kAddNewItemKey) {
3570 // Selected to add a new item.
3571 dialog_ui_event = common::DialogSectionToUiItemAddedEvent(section);
3572 } else if (IsASuggestionItemKey(model.GetItemKeyForCheckedItem())) {
3573 // Selected an existing item.
3574 dialog_ui_event = common::DialogSectionToUiSelectionChangedEvent(section);
3575 } else {
3576 // TODO(estade): add logging for "Manage items" or "Use billing for
3577 // shipping"?
3578 return;
3581 GetMetricLogger().LogDialogUiEvent(dialog_ui_event);
3584 void AutofillDialogControllerImpl::LogDialogLatencyToShow() {
3585 if (was_ui_latency_logged_)
3586 return;
3588 GetMetricLogger().LogDialogLatencyToShow(
3589 base::Time::Now() - dialog_shown_timestamp_);
3590 was_ui_latency_logged_ = true;
3593 AutofillMetrics::DialogInitialUserStateMetric
3594 AutofillDialogControllerImpl::GetInitialUserState() const {
3595 // Consider a user to be an Autofill user if the user has any credit cards
3596 // or addresses saved. Check that the item count is greater than 2 because
3597 // an "empty" menu still has the "add new" menu item and "manage" menu item.
3598 const bool has_autofill_profiles =
3599 suggested_cc_.GetItemCount() > 2 ||
3600 suggested_billing_.GetItemCount() > 2;
3602 if (SignedInState() != SIGNED_IN) {
3603 // Not signed in.
3604 return has_autofill_profiles ?
3605 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_HAS_AUTOFILL :
3606 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_NO_AUTOFILL;
3609 // Signed in.
3610 if (wallet_items_->instruments().empty()) {
3611 // No Wallet items.
3612 return has_autofill_profiles ?
3613 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_HAS_AUTOFILL :
3614 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_NO_AUTOFILL;
3617 // Has Wallet items.
3618 return has_autofill_profiles ?
3619 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_HAS_AUTOFILL :
3620 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_NO_AUTOFILL;
3623 void AutofillDialogControllerImpl::MaybeShowCreditCardBubble() {
3624 if (!data_was_passed_back_)
3625 return;
3627 if (newly_saved_card_) {
3628 scoped_ptr<AutofillProfile> billing_profile;
3629 if (IsManuallyEditingSection(SECTION_BILLING)) {
3630 // Scrape the view as the user's entering or updating information.
3631 FieldValueMap outputs;
3632 view_->GetUserInput(SECTION_BILLING, &outputs);
3633 billing_profile.reset(new AutofillProfile);
3634 FillFormGroupFromOutputs(outputs, billing_profile.get());
3635 } else {
3636 // Just snag the currently suggested profile.
3637 std::string item_key = SuggestionsMenuModelForSection(SECTION_BILLING)->
3638 GetItemKeyForCheckedItem();
3639 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key);
3640 billing_profile.reset(new AutofillProfile(*profile));
3643 ShowNewCreditCardBubble(newly_saved_card_.Pass(),
3644 billing_profile.Pass());
3645 return;
3648 if (!full_wallet_ || !full_wallet_->billing_address())
3649 return;
3651 #if !defined(OS_ANDROID)
3652 GeneratedCreditCardBubbleController::Show(
3653 web_contents(),
3654 full_wallet_->TypeAndLastFourDigits(),
3655 backing_card_last_four_);
3656 #endif
3659 void AutofillDialogControllerImpl::OnSubmitButtonDelayEnd() {
3660 if (!view_)
3661 return;
3662 ScopedViewUpdates updates(view_.get());
3663 view_->UpdateButtonStrip();
3666 void AutofillDialogControllerImpl::FetchWalletCookie() {
3667 net::URLRequestContextGetter* request_context = profile_->GetRequestContext();
3668 signin_helper_.reset(new wallet::WalletSigninHelper(this, request_context));
3669 signin_helper_->StartWalletCookieValueFetch();
3672 } // namespace autofill