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