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