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