autofill_dialog_controller_impl.cc revision 3240926e260ce088908e02ac07a6cf7b0c0cbf44
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/native_app_window.h"
12#include "apps/shell_window.h"
13#include "base/base64.h"
14#include "base/bind.h"
15#include "base/i18n/rtl.h"
16#include "base/logging.h"
17#include "base/prefs/pref_service.h"
18#include "base/strings/string_number_conversions.h"
19#include "base/strings/string_split.h"
20#include "base/strings/string_util.h"
21#include "base/strings/utf_string_conversions.h"
22#include "base/time/time.h"
23#include "chrome/browser/autofill/personal_data_manager_factory.h"
24#include "chrome/browser/browser_process.h"
25#include "chrome/browser/extensions/shell_window_registry.h"
26#include "chrome/browser/prefs/scoped_user_pref_update.h"
27#include "chrome/browser/profiles/profile.h"
28#include "chrome/browser/ui/autofill/autofill_credit_card_bubble_controller.h"
29#include "chrome/browser/ui/autofill/autofill_dialog_view.h"
30#include "chrome/browser/ui/autofill/data_model_wrapper.h"
31#include "chrome/browser/ui/browser.h"
32#include "chrome/browser/ui/browser_finder.h"
33#include "chrome/browser/ui/browser_navigator.h"
34#include "chrome/browser/ui/browser_window.h"
35#include "chrome/common/chrome_version_info.h"
36#include "chrome/common/pref_names.h"
37#include "chrome/common/render_messages.h"
38#include "chrome/common/url_constants.h"
39#include "components/autofill/content/browser/risk/fingerprint.h"
40#include "components/autofill/content/browser/risk/proto/fingerprint.pb.h"
41#include "components/autofill/content/browser/wallet/form_field_error.h"
42#include "components/autofill/content/browser/wallet/full_wallet.h"
43#include "components/autofill/content/browser/wallet/instrument.h"
44#include "components/autofill/content/browser/wallet/wallet_address.h"
45#include "components/autofill/content/browser/wallet/wallet_items.h"
46#include "components/autofill/content/browser/wallet/wallet_service_url.h"
47#include "components/autofill/content/browser/wallet/wallet_signin_helper.h"
48#include "components/autofill/core/browser/autofill_country.h"
49#include "components/autofill/core/browser/autofill_data_model.h"
50#include "components/autofill/core/browser/autofill_manager.h"
51#include "components/autofill/core/browser/autofill_type.h"
52#include "components/autofill/core/browser/personal_data_manager.h"
53#include "components/autofill/core/browser/phone_number_i18n.h"
54#include "components/autofill/core/browser/validation.h"
55#include "components/autofill/core/common/form_data.h"
56#include "components/user_prefs/pref_registry_syncable.h"
57#include "content/public/browser/browser_thread.h"
58#include "content/public/browser/geolocation_provider.h"
59#include "content/public/browser/navigation_controller.h"
60#include "content/public/browser/navigation_details.h"
61#include "content/public/browser/navigation_entry.h"
62#include "content/public/browser/notification_service.h"
63#include "content/public/browser/notification_types.h"
64#include "content/public/browser/render_view_host.h"
65#include "content/public/browser/web_contents.h"
66#include "content/public/browser/web_contents_view.h"
67#include "content/public/common/url_constants.h"
68#include "grit/chromium_strings.h"
69#include "grit/component_strings.h"
70#include "grit/generated_resources.h"
71#include "grit/theme_resources.h"
72#include "grit/webkit_resources.h"
73#include "net/cert/cert_status_flags.h"
74#include "ui/base/base_window.h"
75#include "ui/base/l10n/l10n_util.h"
76#include "ui/base/models/combobox_model.h"
77#include "ui/base/resource/resource_bundle.h"
78#include "ui/gfx/canvas.h"
79#include "ui/gfx/color_utils.h"
80#include "ui/gfx/skbitmap_operations.h"
81
82namespace autofill {
83
84namespace {
85
86const char kAddNewItemKey[] = "add-new-item";
87const char kManageItemsKey[] = "manage-items";
88const char kSameAsBillingKey[] = "same-as-billing";
89
90// Keys for the kAutofillDialogAutofillDefault pref dictionary (do not change
91// these values).
92const char kGuidPrefKey[] = "guid";
93const char kVariantPrefKey[] = "variant";
94
95// This string is stored along with saved addresses and credit cards in the
96// WebDB, and hence should not be modified, so that it remains consistent over
97// time.
98const char kAutofillDialogOrigin[] = "Chrome Autofill dialog";
99
100// HSL shift to gray out an image.
101const color_utils::HSL kGrayImageShift = {-1, 0, 0.8};
102
103// Limit Wallet items refresh rate to at most once per minute.
104const int kWalletItemsRefreshRateSeconds = 60;
105
106// Returns true if |card_type| is supported by Wallet.
107bool IsWalletSupportedCard(const std::string& card_type) {
108  return card_type == autofill::kVisaCard ||
109         card_type == autofill::kMasterCard ||
110         card_type == autofill::kDiscoverCard;
111}
112
113// Returns true if |input| should be shown when |field_type| has been requested.
114bool InputTypeMatchesFieldType(const DetailInput& input,
115                               const AutofillType& field_type) {
116  // If any credit card expiration info is asked for, show both month and year
117  // inputs.
118  if (field_type.server_type() == CREDIT_CARD_EXP_4_DIGIT_YEAR ||
119      field_type.server_type() == CREDIT_CARD_EXP_2_DIGIT_YEAR ||
120      field_type.server_type() == CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR ||
121      field_type.server_type() == CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR ||
122      field_type.server_type() == CREDIT_CARD_EXP_MONTH) {
123    return input.type == CREDIT_CARD_EXP_4_DIGIT_YEAR ||
124           input.type == CREDIT_CARD_EXP_MONTH;
125  }
126
127  if (field_type.server_type() == CREDIT_CARD_TYPE)
128    return input.type == CREDIT_CARD_NUMBER;
129
130  return input.type == field_type.server_type();
131}
132
133// Returns true if |input| in the given |section| should be used for a
134// site-requested |field|.
135bool DetailInputMatchesField(DialogSection section,
136                             const DetailInput& input,
137                             const AutofillField& field) {
138  AutofillType field_type = field.Type();
139
140  // The credit card name is filled from the billing section's data.
141  if (field_type.server_type() == CREDIT_CARD_NAME &&
142      (section == SECTION_BILLING || section == SECTION_CC_BILLING)) {
143    return input.type == NAME_BILLING_FULL;
144  }
145
146  return InputTypeMatchesFieldType(input, field_type);
147}
148
149bool IsCreditCardType(ServerFieldType type) {
150  return AutofillType(type).group() == CREDIT_CARD;
151}
152
153// Returns true if |input| should be used to fill a site-requested |field| which
154// is notated with a "shipping" tag, for use when the user has decided to use
155// the billing address as the shipping address.
156bool DetailInputMatchesShippingField(const DetailInput& input,
157                                     const AutofillField& field) {
158  // Equivalent billing field type is used to support UseBillingAsShipping
159  // usecase.
160  ServerFieldType field_type =
161      AutofillType::GetEquivalentBillingFieldType(field.Type().server_type());
162
163  return InputTypeMatchesFieldType(input, AutofillType(field_type));
164}
165
166// Constructs |inputs| from template data.
167void BuildInputs(const DetailInput* input_template,
168                 size_t template_size,
169                 DetailInputs* inputs) {
170  for (size_t i = 0; i < template_size; ++i) {
171    const DetailInput* input = &input_template[i];
172    inputs->push_back(*input);
173  }
174}
175
176// Initializes |form_group| from user-entered data.
177void FillFormGroupFromOutputs(const DetailOutputMap& detail_outputs,
178                              FormGroup* form_group) {
179  for (DetailOutputMap::const_iterator iter = detail_outputs.begin();
180       iter != detail_outputs.end(); ++iter) {
181    ServerFieldType type = iter->first->type;
182    if (!iter->second.empty()) {
183      if (type == ADDRESS_HOME_COUNTRY || type == ADDRESS_BILLING_COUNTRY) {
184        form_group->SetInfo(AutofillType(type),
185                            iter->second,
186                            g_browser_process->GetApplicationLocale());
187      } else {
188        form_group->SetRawInfo(type, iter->second);
189      }
190    }
191  }
192}
193
194// Get billing info from |output| and put it into |card|, |cvc|, and |profile|.
195// These outparams are required because |card|/|profile| accept different types
196// of raw info, and CreditCard doesn't save CVCs.
197void GetBillingInfoFromOutputs(const DetailOutputMap& output,
198                               CreditCard* card,
199                               string16* cvc,
200                               AutofillProfile* profile) {
201  for (DetailOutputMap::const_iterator it = output.begin();
202       it != output.end(); ++it) {
203    string16 trimmed;
204    TrimWhitespace(it->second, TRIM_ALL, &trimmed);
205
206    // Special case CVC as CreditCard just swallows it.
207    if (it->first->type == CREDIT_CARD_VERIFICATION_CODE) {
208      if (cvc)
209        cvc->assign(trimmed);
210    } else if (it->first->type == ADDRESS_HOME_COUNTRY ||
211               it->first->type == ADDRESS_BILLING_COUNTRY) {
212      if (profile) {
213        profile->SetInfo(AutofillType(it->first->type),
214                         trimmed,
215                         g_browser_process->GetApplicationLocale());
216      }
217    } else {
218      // Copy the credit card name to |profile| in addition to |card| as
219      // wallet::Instrument requires a recipient name for its billing address.
220      if (card && it->first->type == NAME_FULL)
221        card->SetRawInfo(CREDIT_CARD_NAME, trimmed);
222
223      if (IsCreditCardType(it->first->type)) {
224        if (card)
225          card->SetRawInfo(it->first->type, trimmed);
226      } else if (profile) {
227        profile->SetRawInfo(it->first->type, trimmed);
228      }
229    }
230  }
231}
232
233// Returns the containing window for the given |web_contents|. The containing
234// window might be a browser window for a Chrome tab, or it might be a shell
235// window for a platform app.
236ui::BaseWindow* GetBaseWindowForWebContents(
237    const content::WebContents* web_contents) {
238  Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
239  if (browser)
240    return browser->window();
241
242  gfx::NativeWindow native_window =
243      web_contents->GetView()->GetTopLevelNativeWindow();
244  apps::ShellWindow* shell_window =
245      extensions::ShellWindowRegistry::
246          GetShellWindowForNativeWindowAnyProfile(native_window);
247  return shell_window->GetBaseWindow();
248}
249
250// Extracts the string value of a field with |type| from |output|. This is
251// useful when you only need the value of 1 input from a section of view inputs.
252string16 GetValueForType(const DetailOutputMap& output,
253                         ServerFieldType type) {
254  for (DetailOutputMap::const_iterator it = output.begin();
255       it != output.end(); ++it) {
256    if (it->first->type == type)
257      return it->second;
258  }
259  NOTREACHED();
260  return string16();
261}
262
263// Returns a string descriptor for a DialogSection, for use with prefs (do not
264// change these values).
265std::string SectionToPrefString(DialogSection section) {
266  switch (section) {
267    case SECTION_CC:
268      return "cc";
269
270    case SECTION_BILLING:
271      return "billing";
272
273    case SECTION_CC_BILLING:
274      // The SECTION_CC_BILLING section isn't active when using Autofill.
275      NOTREACHED();
276      return std::string();
277
278    case SECTION_SHIPPING:
279      return "shipping";
280
281    case SECTION_EMAIL:
282      return "email";
283  }
284
285  NOTREACHED();
286  return std::string();
287}
288
289// Check if a given MaskedInstrument is allowed for the purchase.
290bool IsInstrumentAllowed(
291    const wallet::WalletItems::MaskedInstrument& instrument) {
292  switch (instrument.status()) {
293    case wallet::WalletItems::MaskedInstrument::VALID:
294    case wallet::WalletItems::MaskedInstrument::PENDING:
295    case wallet::WalletItems::MaskedInstrument::EXPIRED:
296    case wallet::WalletItems::MaskedInstrument::BILLING_INCOMPLETE:
297      return true;
298    default:
299      return false;
300  }
301}
302
303// Signals that the user has opted in to geolocation services.  Factored out
304// into a separate method because all interaction with the geolocation provider
305// needs to happen on the IO thread, which is not the thread
306// AutofillDialogViewDelegate lives on.
307void UserDidOptIntoLocationServices() {
308  content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
309}
310
311// Returns whether |data_model| is complete, i.e. can fill out all the
312// |requested_fields|, and verified, i.e. not just automatically aggregated.
313// Incomplete or unverifed data will not be displayed in the dropdown menu.
314bool HasCompleteAndVerifiedData(const AutofillDataModel& data_model,
315                                const DetailInputs& requested_fields) {
316  if (!data_model.IsVerified())
317    return false;
318
319  for (size_t i = 0; i < requested_fields.size(); ++i) {
320    ServerFieldType type = requested_fields[i].type;
321    if (type != ADDRESS_HOME_LINE2 &&
322        type != CREDIT_CARD_VERIFICATION_CODE &&
323        data_model.GetRawInfo(type).empty()) {
324      return false;
325    }
326  }
327
328  return true;
329}
330
331// Returns true if |profile| has an invalid address, i.e. an invalid state, zip
332// code, or phone number. Otherwise returns false. Profiles with invalid
333// addresses are not suggested in the dropdown menu for billing and shipping
334// addresses.
335bool HasInvalidAddress(const AutofillProfile& profile) {
336  return profile.IsPresentButInvalid(ADDRESS_HOME_STATE) ||
337         profile.IsPresentButInvalid(ADDRESS_HOME_ZIP) ||
338         profile.IsPresentButInvalid(PHONE_HOME_WHOLE_NUMBER);
339}
340
341// Loops through |addresses_| comparing to |address| ignoring ID. If a match
342// is not found, NULL is returned.
343const wallet::Address* FindDuplicateAddress(
344    const std::vector<wallet::Address*>& addresses,
345    const wallet::Address& address) {
346  for (size_t i = 0; i < addresses.size(); ++i) {
347    if (addresses[i]->EqualsIgnoreID(address))
348      return addresses[i];
349  }
350  return NULL;
351}
352
353bool IsCardHolderNameValidForWallet(const string16& name) {
354  base::string16 whitespace_collapsed_name = CollapseWhitespace(name, true);
355  std::vector<base::string16> split_name;
356  base::SplitString(whitespace_collapsed_name, ' ', &split_name);
357  return split_name.size() >= 2;
358}
359
360DialogSection SectionFromLocation(wallet::FormFieldError::Location location) {
361  switch (location) {
362    case wallet::FormFieldError::PAYMENT_INSTRUMENT:
363    case wallet::FormFieldError::LEGAL_ADDRESS:
364      return SECTION_CC_BILLING;
365
366    case wallet::FormFieldError::SHIPPING_ADDRESS:
367      return SECTION_SHIPPING;
368
369    case wallet::FormFieldError::UNKNOWN_LOCATION:
370      NOTREACHED();
371      return SECTION_MAX;
372  }
373
374  NOTREACHED();
375  return SECTION_MAX;
376}
377
378base::string16 WalletErrorMessage(wallet::WalletClient::ErrorType error_type) {
379  switch (error_type) {
380    case wallet::WalletClient::BUYER_ACCOUNT_ERROR:
381      return l10n_util::GetStringUTF16(IDS_AUTOFILL_WALLET_BUYER_ACCOUNT_ERROR);
382
383    case wallet::WalletClient::BAD_REQUEST:
384      return l10n_util::GetStringFUTF16(
385          IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR,
386          ASCIIToUTF16("71"));
387
388    case wallet::WalletClient::INVALID_PARAMS:
389      return l10n_util::GetStringFUTF16(
390          IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR,
391          ASCIIToUTF16("42"));
392
393    case wallet::WalletClient::UNSUPPORTED_API_VERSION:
394      return l10n_util::GetStringFUTF16(
395          IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR,
396          ASCIIToUTF16("43"));
397
398    case wallet::WalletClient::SERVICE_UNAVAILABLE:
399      return l10n_util::GetStringUTF16(
400          IDS_AUTOFILL_WALLET_SERVICE_UNAVAILABLE_ERROR);
401
402    case wallet::WalletClient::INTERNAL_ERROR:
403      return l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_UNKNOWN_ERROR,
404                                        ASCIIToUTF16("62"));
405
406    case wallet::WalletClient::MALFORMED_RESPONSE:
407      return l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_UNKNOWN_ERROR,
408                                        ASCIIToUTF16("72"));
409
410    case wallet::WalletClient::NETWORK_ERROR:
411      return l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_UNKNOWN_ERROR,
412                                        ASCIIToUTF16("73"));
413
414    case wallet::WalletClient::UNKNOWN_ERROR:
415      return l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_UNKNOWN_ERROR,
416                                        ASCIIToUTF16("74"));
417  }
418
419  NOTREACHED();
420  return base::string16();
421}
422
423gfx::Image GetGeneratedCardImage(const string16& card_number) {
424  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
425  const gfx::ImageSkia* card =
426      rb.GetImageSkiaNamed(IDR_AUTOFILL_GENERATED_CARD);
427  gfx::Canvas canvas(card->size(), ui::SCALE_FACTOR_100P, false);
428  canvas.DrawImageInt(*card, 0, 0);
429
430#if !defined(OS_ANDROID)
431  gfx::Rect display_rect(gfx::Point(), card->size());
432  display_rect.Inset(14, 0, 14, 0);
433  // TODO(estade): fallback font for systems that don't have Helvetica?
434  gfx::Font helvetica("Helvetica", 14);
435  gfx::ShadowValues shadows;
436  shadows.push_back(gfx::ShadowValue(gfx::Point(0, 1),
437                    0.0,
438                    SkColorSetARGB(85, 0, 0, 0)));
439  canvas.DrawStringWithShadows(
440      card_number,
441      helvetica,
442      SK_ColorWHITE,
443      display_rect, 0, 0, shadows);
444#endif
445
446  gfx::ImageSkia skia(canvas.ExtractImageRep());
447  return gfx::Image(skia);
448}
449
450}  // namespace
451
452AutofillDialogViewDelegate::~AutofillDialogViewDelegate() {}
453
454AutofillDialogControllerImpl::~AutofillDialogControllerImpl() {
455  if (popup_controller_)
456    popup_controller_->Hide();
457
458  GetMetricLogger().LogDialogInitialUserState(
459      GetDialogType(), initial_user_state_);
460
461  if (deemphasized_render_view_) {
462    web_contents()->GetRenderViewHost()->Send(
463        new ChromeViewMsg_SetVisuallyDeemphasized(
464            web_contents()->GetRenderViewHost()->GetRoutingID(), false));
465  }
466}
467
468#if !defined(OS_ANDROID)
469// static
470base::WeakPtr<AutofillDialogControllerImpl>
471    AutofillDialogControllerImpl::Create(
472    content::WebContents* contents,
473    const FormData& form_structure,
474    const GURL& source_url,
475    const DialogType dialog_type,
476    const base::Callback<void(const FormStructure*,
477                              const std::string&)>& callback) {
478  // AutofillDialogControllerImpl owns itself.
479  AutofillDialogControllerImpl* autofill_dialog_controller =
480      new AutofillDialogControllerImpl(contents,
481                                       form_structure,
482                                       source_url,
483                                       dialog_type,
484                                       callback);
485  return autofill_dialog_controller->weak_ptr_factory_.GetWeakPtr();
486}
487#endif  // !defined(OS_ANDROID)
488
489// static
490void AutofillDialogControllerImpl::RegisterProfilePrefs(
491    user_prefs::PrefRegistrySyncable* registry) {
492  registry->RegisterIntegerPref(
493      ::prefs::kAutofillDialogShowCount,
494      0,
495      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
496  registry->RegisterBooleanPref(
497      ::prefs::kAutofillDialogHasPaidWithWallet,
498      false,
499      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
500  registry->RegisterBooleanPref(
501      ::prefs::kAutofillDialogPayWithoutWallet,
502      false,
503      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
504  registry->RegisterDictionaryPref(
505      ::prefs::kAutofillDialogAutofillDefault,
506      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
507}
508
509void AutofillDialogControllerImpl::Show() {
510  dialog_shown_timestamp_ = base::Time::Now();
511
512  content::NavigationEntry* entry = contents_->GetController().GetActiveEntry();
513  const GURL& active_url = entry ? entry->GetURL() : contents_->GetURL();
514  invoked_from_same_origin_ = active_url.GetOrigin() == source_url_.GetOrigin();
515
516  // Log any relevant UI metrics and security exceptions.
517  GetMetricLogger().LogDialogUiEvent(
518      GetDialogType(), AutofillMetrics::DIALOG_UI_SHOWN);
519
520  GetMetricLogger().LogDialogSecurityMetric(
521      GetDialogType(), AutofillMetrics::SECURITY_METRIC_DIALOG_SHOWN);
522
523  if (RequestingCreditCardInfo() && !TransmissionWillBeSecure()) {
524    GetMetricLogger().LogDialogSecurityMetric(
525        GetDialogType(),
526        AutofillMetrics::SECURITY_METRIC_CREDIT_CARD_OVER_HTTP);
527  }
528
529  if (!invoked_from_same_origin_) {
530    GetMetricLogger().LogDialogSecurityMetric(
531        GetDialogType(),
532        AutofillMetrics::SECURITY_METRIC_CROSS_ORIGIN_FRAME);
533  }
534
535  // Determine what field types should be included in the dialog.
536  bool has_types = false;
537  bool has_sections = false;
538  form_structure_.ParseFieldTypesFromAutocompleteAttributes(
539      FormStructure::PARSE_FOR_AUTOFILL_DIALOG, &has_types, &has_sections);
540
541  // Fail if the author didn't specify autocomplete types.
542  if (!has_types) {
543    callback_.Run(NULL, std::string());
544    delete this;
545    return;
546  }
547
548  const DetailInput kEmailInputs[] = {
549    { 1, EMAIL_ADDRESS, IDS_AUTOFILL_DIALOG_PLACEHOLDER_EMAIL },
550  };
551
552  const DetailInput kCCInputs[] = {
553    { 2, CREDIT_CARD_NUMBER, IDS_AUTOFILL_DIALOG_PLACEHOLDER_CARD_NUMBER },
554    { 3, CREDIT_CARD_EXP_MONTH },
555    { 3, CREDIT_CARD_EXP_4_DIGIT_YEAR },
556    { 3, CREDIT_CARD_VERIFICATION_CODE, IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC,
557      1.5 },
558  };
559
560  const DetailInput kBillingInputs[] = {
561    { 4, NAME_BILLING_FULL, IDS_AUTOFILL_DIALOG_PLACEHOLDER_CARDHOLDER_NAME },
562    { 5, ADDRESS_BILLING_LINE1,
563      IDS_AUTOFILL_DIALOG_PLACEHOLDER_ADDRESS_LINE_1 },
564    { 6, ADDRESS_BILLING_LINE2,
565      IDS_AUTOFILL_DIALOG_PLACEHOLDER_ADDRESS_LINE_2 },
566    { 7, ADDRESS_BILLING_CITY,
567      IDS_AUTOFILL_DIALOG_PLACEHOLDER_LOCALITY },
568    // TODO(estade): state placeholder should depend on locale.
569    { 8, ADDRESS_BILLING_STATE, IDS_AUTOFILL_FIELD_LABEL_STATE },
570    { 8, ADDRESS_BILLING_ZIP,
571      IDS_AUTOFILL_DIALOG_PLACEHOLDER_POSTAL_CODE },
572    // We don't allow the user to change the country: http://crbug.com/247518
573    { -1, ADDRESS_BILLING_COUNTRY, 0 },
574    { 10, PHONE_BILLING_WHOLE_NUMBER,
575      IDS_AUTOFILL_DIALOG_PLACEHOLDER_PHONE_NUMBER },
576  };
577
578  const DetailInput kShippingInputs[] = {
579    { 11, NAME_FULL, IDS_AUTOFILL_DIALOG_PLACEHOLDER_ADDRESSEE_NAME },
580    { 12, ADDRESS_HOME_LINE1, IDS_AUTOFILL_DIALOG_PLACEHOLDER_ADDRESS_LINE_1 },
581    { 13, ADDRESS_HOME_LINE2, IDS_AUTOFILL_DIALOG_PLACEHOLDER_ADDRESS_LINE_2 },
582    { 14, ADDRESS_HOME_CITY, IDS_AUTOFILL_DIALOG_PLACEHOLDER_LOCALITY },
583    { 15, ADDRESS_HOME_STATE, IDS_AUTOFILL_FIELD_LABEL_STATE },
584    { 15, ADDRESS_HOME_ZIP, IDS_AUTOFILL_DIALOG_PLACEHOLDER_POSTAL_CODE },
585    { -1, ADDRESS_HOME_COUNTRY, 0 },
586    { 17, PHONE_HOME_WHOLE_NUMBER,
587      IDS_AUTOFILL_DIALOG_PLACEHOLDER_PHONE_NUMBER },
588  };
589
590  BuildInputs(kEmailInputs,
591              arraysize(kEmailInputs),
592              &requested_email_fields_);
593
594  BuildInputs(kCCInputs,
595              arraysize(kCCInputs),
596              &requested_cc_fields_);
597
598  BuildInputs(kBillingInputs,
599              arraysize(kBillingInputs),
600              &requested_billing_fields_);
601
602  BuildInputs(kCCInputs,
603              arraysize(kCCInputs),
604              &requested_cc_billing_fields_);
605  BuildInputs(kBillingInputs,
606              arraysize(kBillingInputs),
607              &requested_cc_billing_fields_);
608
609  BuildInputs(kShippingInputs,
610              arraysize(kShippingInputs),
611              &requested_shipping_fields_);
612
613  // Test whether we need to show the shipping section. If filling that section
614  // would be a no-op, don't show it.
615  const DetailInputs& inputs = RequestedFieldsForSection(SECTION_SHIPPING);
616  EmptyDataModelWrapper empty_wrapper;
617  cares_about_shipping_ = empty_wrapper.FillFormStructure(
618      inputs,
619      base::Bind(DetailInputMatchesField, SECTION_SHIPPING),
620      &form_structure_);
621
622  SuggestionsUpdated();
623
624  int show_count =
625      profile_->GetPrefs()->GetInteger(::prefs::kAutofillDialogShowCount);
626  profile_->GetPrefs()->SetInteger(::prefs::kAutofillDialogShowCount,
627                                   show_count + 1);
628
629  // TODO(estade): don't show the dialog if the site didn't specify the right
630  // fields. First we must figure out what the "right" fields are.
631  view_.reset(CreateView());
632  view_->Show();
633  GetManager()->AddObserver(this);
634
635  // Try to see if the user is already signed-in. If signed-in, fetch the user's
636  // Wallet data. Otherwise, see if the user could be signed in passively.
637  // TODO(aruslan): UMA metrics for sign-in.
638  signin_helper_.reset(new wallet::WalletSigninHelper(
639      this, profile_->GetRequestContext()));
640  signin_helper_->StartWalletCookieValueFetch();
641
642  if (!account_chooser_model_.WalletIsSelected())
643    LogDialogLatencyToShow();
644}
645
646void AutofillDialogControllerImpl::Hide() {
647  if (view_)
648    view_->Hide();
649}
650
651void AutofillDialogControllerImpl::TabActivated() {
652  // If the user switched away from this tab and then switched back, reload the
653  // Wallet items, in case they've changed.
654  int seconds_elapsed_since_last_refresh =
655      (base::TimeTicks::Now() - last_wallet_items_fetch_timestamp_).InSeconds();
656  if (IsPayingWithWallet() && wallet_items_ &&
657      seconds_elapsed_since_last_refresh >= kWalletItemsRefreshRateSeconds) {
658    GetWalletItems();
659  }
660}
661
662void AutofillDialogControllerImpl::OnAutocheckoutError() {
663  DCHECK_EQ(AUTOCHECKOUT_IN_PROGRESS, autocheckout_state_);
664  GetMetricLogger().LogAutocheckoutDuration(
665      base::Time::Now() - autocheckout_started_timestamp_,
666      AutofillMetrics::AUTOCHECKOUT_FAILED);
667  SetAutocheckoutState(AUTOCHECKOUT_ERROR);
668  autocheckout_started_timestamp_ = base::Time();
669}
670
671void AutofillDialogControllerImpl::OnAutocheckoutSuccess() {
672  DCHECK_EQ(AUTOCHECKOUT_IN_PROGRESS, autocheckout_state_);
673  GetMetricLogger().LogAutocheckoutDuration(
674      base::Time::Now() - autocheckout_started_timestamp_,
675      AutofillMetrics::AUTOCHECKOUT_SUCCEEDED);
676  SetAutocheckoutState(AUTOCHECKOUT_SUCCESS);
677  autocheckout_started_timestamp_ = base::Time();
678}
679
680
681TestableAutofillDialogView* AutofillDialogControllerImpl::GetTestableView() {
682  return view_ ? view_->GetTestableView() : NULL;
683}
684
685void AutofillDialogControllerImpl::AddAutocheckoutStep(
686    AutocheckoutStepType step_type) {
687  for (size_t i = 0; i < steps_.size(); ++i) {
688    if (steps_[i].type() == step_type)
689      return;
690  }
691  steps_.push_back(
692      DialogAutocheckoutStep(step_type, AUTOCHECKOUT_STEP_UNSTARTED));
693}
694
695void AutofillDialogControllerImpl::UpdateAutocheckoutStep(
696    AutocheckoutStepType step_type,
697    AutocheckoutStepStatus step_status) {
698  int total_steps = 0;
699  int completed_steps = 0;
700  for (size_t i = 0; i < steps_.size(); ++i) {
701    ++total_steps;
702    if (steps_[i].status() == AUTOCHECKOUT_STEP_COMPLETED)
703      ++completed_steps;
704    if (steps_[i].type() == step_type && steps_[i].status() != step_status)
705      steps_[i] = DialogAutocheckoutStep(step_type, step_status);
706  }
707  if (view_) {
708    view_->UpdateAutocheckoutStepsArea();
709    view_->UpdateProgressBar(1.0 * completed_steps / total_steps);
710  }
711}
712
713std::vector<DialogAutocheckoutStep>
714    AutofillDialogControllerImpl::CurrentAutocheckoutSteps() const {
715  if (autocheckout_state_ != AUTOCHECKOUT_NOT_STARTED)
716    return steps_;
717
718  std::vector<DialogAutocheckoutStep> empty_steps;
719  return empty_steps;
720}
721
722////////////////////////////////////////////////////////////////////////////////
723// AutofillDialogViewDelegate implementation.
724
725string16 AutofillDialogControllerImpl::DialogTitle() const {
726  return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TITLE);
727}
728
729string16 AutofillDialogControllerImpl::EditSuggestionText() const {
730  return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_EDIT);
731}
732
733string16 AutofillDialogControllerImpl::CancelButtonText() const {
734  return l10n_util::GetStringUTF16(IDS_CANCEL);
735}
736
737string16 AutofillDialogControllerImpl::ConfirmButtonText() const {
738  if (autocheckout_state_ == AUTOCHECKOUT_ERROR)
739    return l10n_util::GetStringUTF16(IDS_OK);
740  if (autocheckout_state_ == AUTOCHECKOUT_SUCCESS)
741    return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_CONTINUE_BUTTON);
742
743  return l10n_util::GetStringUTF16(IsSubmitPausedOn(wallet::VERIFY_CVV) ?
744      IDS_AUTOFILL_DIALOG_VERIFY_BUTTON : IDS_AUTOFILL_DIALOG_SUBMIT_BUTTON);
745}
746
747string16 AutofillDialogControllerImpl::SaveLocallyText() const {
748  return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_CHECKBOX);
749}
750
751string16 AutofillDialogControllerImpl::LegalDocumentsText() {
752  if (!IsPayingWithWallet() || autocheckout_state_ != AUTOCHECKOUT_NOT_STARTED)
753    return string16();
754
755  EnsureLegalDocumentsText();
756  return legal_documents_text_;
757}
758
759DialogSignedInState AutofillDialogControllerImpl::SignedInState() const {
760  if (account_chooser_model_.HadWalletError())
761    return SIGN_IN_DISABLED;
762
763  if (signin_helper_ || !wallet_items_)
764    return REQUIRES_RESPONSE;
765
766  if (wallet_items_->HasRequiredAction(wallet::GAIA_AUTH))
767    return REQUIRES_SIGN_IN;
768
769  if (wallet_items_->HasRequiredAction(wallet::PASSIVE_GAIA_AUTH))
770    return REQUIRES_PASSIVE_SIGN_IN;
771
772  return SIGNED_IN;
773}
774
775bool AutofillDialogControllerImpl::ShouldShowSpinner() const {
776  return account_chooser_model_.WalletIsSelected() &&
777         SignedInState() == REQUIRES_RESPONSE;
778}
779
780string16 AutofillDialogControllerImpl::AccountChooserText() const {
781  // TODO(aruslan): this should be l10n "Not using Google Wallet".
782  if (!account_chooser_model_.WalletIsSelected())
783    return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PAY_WITHOUT_WALLET);
784
785  if (SignedInState() == SIGNED_IN)
786    return account_chooser_model_.active_wallet_account_name();
787
788  // In this case, the account chooser should be showing the signin link.
789  return string16();
790}
791
792string16 AutofillDialogControllerImpl::SignInLinkText() const {
793  return l10n_util::GetStringUTF16(
794      signin_registrar_.IsEmpty() ? IDS_AUTOFILL_DIALOG_SIGN_IN :
795                                    IDS_AUTOFILL_DIALOG_PAY_WITHOUT_WALLET);
796}
797
798bool AutofillDialogControllerImpl::ShouldOfferToSaveInChrome() const {
799  return !IsPayingWithWallet() &&
800      !profile_->IsOffTheRecord() &&
801      IsManuallyEditingAnySection() &&
802      ShouldShowDetailArea();
803}
804
805int AutofillDialogControllerImpl::GetDialogButtons() const {
806  if (autocheckout_state_ == AUTOCHECKOUT_IN_PROGRESS)
807    return ui::DIALOG_BUTTON_CANCEL;
808  if (autocheckout_state_ == AUTOCHECKOUT_NOT_STARTED)
809    return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
810  return ui::DIALOG_BUTTON_OK;
811}
812
813bool AutofillDialogControllerImpl::IsDialogButtonEnabled(
814    ui::DialogButton button) const {
815  if (button == ui::DIALOG_BUTTON_OK) {
816    if (IsSubmitPausedOn(wallet::VERIFY_CVV))
817      return true;
818
819    if (ShouldShowSpinner())
820      return false;
821
822    if (is_submitting_) {
823      return autocheckout_state_ == AUTOCHECKOUT_SUCCESS ||
824             autocheckout_state_ == AUTOCHECKOUT_ERROR;
825    }
826
827    return true;
828  }
829
830  DCHECK_EQ(ui::DIALOG_BUTTON_CANCEL, button);
831  return !is_submitting_ || IsSubmitPausedOn(wallet::VERIFY_CVV);
832}
833
834DialogOverlayState AutofillDialogControllerImpl::GetDialogOverlay() const {
835  bool show_wallet_interstitial = IsPayingWithWallet() && is_submitting_ &&
836      !IsSubmitPausedOn(wallet::VERIFY_CVV) &&
837      GetDialogType() == DIALOG_TYPE_REQUEST_AUTOCOMPLETE;
838  if (!show_wallet_interstitial)
839    return DialogOverlayState();
840
841  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
842  DialogOverlayState state;
843
844  state.strings.push_back(DialogOverlayString());
845  DialogOverlayString& string = state.strings.back();
846#if !defined(OS_ANDROID)
847  // gfx::Font isn't implemented on Android; DeriveFont() causes a null deref.
848  string.font = rb.GetFont(ui::ResourceBundle::BaseFont).DeriveFont(4);
849#endif
850
851  // First-run, post-submit, Wallet expository page.
852  if (full_wallet_ && full_wallet_->required_actions().empty()) {
853    string16 cc_number =
854        full_wallet_->GetInfo(AutofillType(CREDIT_CARD_NUMBER));
855    DCHECK_EQ(16U, cc_number.size());
856    state.image = GetGeneratedCardImage(
857        ASCIIToUTF16("xxxx xxxx xxxx ") +
858        cc_number.substr(cc_number.size() - 4));
859    string.text = l10n_util::GetStringUTF16(
860        IDS_AUTOFILL_DIALOG_CARD_GENERATION_DONE);
861    string.text_color = SK_ColorBLACK;
862    string.alignment = gfx::ALIGN_CENTER;
863
864    state.strings.push_back(DialogOverlayString());
865    DialogOverlayString& subtext = state.strings.back();
866    subtext.font = rb.GetFont(ui::ResourceBundle::BaseFont);
867    subtext.text_color = SkColorSetRGB(102, 102, 102);
868    subtext.text = l10n_util::GetStringUTF16(
869        IDS_AUTOFILL_DIALOG_CARD_GENERATION_EXPLANATION);
870    subtext.alignment = gfx::ALIGN_CENTER;
871
872    state.button_text = l10n_util::GetStringUTF16(
873        IDS_AUTOFILL_DIALOG_CARD_GENERATION_OK_BUTTON);
874  } else {
875    // TODO(estade): fix this (animation?).
876    state.image =
877        GetGeneratedCardImage(ASCIIToUTF16("xxxx xxxx xx..."));
878
879    // "Submitting" waiting page.
880    string.text = l10n_util::GetStringUTF16(
881        IDS_AUTOFILL_DIALOG_CARD_GENERATION_IN_PROGRESS);
882    string.text_color = SK_ColorBLACK;
883    string.alignment = gfx::ALIGN_CENTER;
884  }
885
886  return state;
887}
888
889const std::vector<ui::Range>& AutofillDialogControllerImpl::
890    LegalDocumentLinks() {
891  EnsureLegalDocumentsText();
892  return legal_document_link_ranges_;
893}
894
895bool AutofillDialogControllerImpl::SectionIsActive(DialogSection section)
896    const {
897  if (IsSubmitPausedOn(wallet::VERIFY_CVV))
898    return section == SECTION_CC_BILLING;
899
900  if (!FormStructureCaresAboutSection(section))
901    return false;
902
903  if (IsPayingWithWallet())
904    return section == SECTION_CC_BILLING || section == SECTION_SHIPPING;
905
906  return section != SECTION_CC_BILLING;
907}
908
909bool AutofillDialogControllerImpl::HasCompleteWallet() const {
910  return wallet_items_.get() != NULL &&
911         !wallet_items_->instruments().empty() &&
912         !wallet_items_->addresses().empty();
913}
914
915bool AutofillDialogControllerImpl::IsSubmitPausedOn(
916    wallet::RequiredAction required_action) const {
917  return full_wallet_ && full_wallet_->HasRequiredAction(required_action);
918}
919
920void AutofillDialogControllerImpl::GetWalletItems() {
921  DCHECK(previously_selected_instrument_id_.empty());
922  DCHECK(previously_selected_shipping_address_id_.empty());
923
924  if (wallet_items_) {
925    if (ActiveInstrument())
926      previously_selected_instrument_id_ = ActiveInstrument()->object_id();
927
928    const wallet::Address* address = ActiveShippingAddress();
929    if (address)
930      previously_selected_shipping_address_id_ = address->object_id();
931  }
932
933  last_wallet_items_fetch_timestamp_ = base::TimeTicks::Now();
934  wallet_items_.reset();
935
936  // The "Loading..." page should be showing now, which should cause the
937  // account chooser to hide.
938  view_->UpdateAccountChooser();
939  GetWalletClient()->GetWalletItems(source_url_);
940}
941
942void AutofillDialogControllerImpl::HideSignIn() {
943  signin_registrar_.RemoveAll();
944  view_->HideSignIn();
945  view_->UpdateAccountChooser();
946}
947
948void AutofillDialogControllerImpl::SignedInStateUpdated() {
949  switch (SignedInState()) {
950    case SIGNED_IN:
951      // Start fetching the user name if we don't know it yet.
952      if (account_chooser_model_.active_wallet_account_name().empty()) {
953        signin_helper_.reset(new wallet::WalletSigninHelper(
954            this, profile_->GetRequestContext()));
955        signin_helper_->StartUserNameFetch();
956      } else {
957        LogDialogLatencyToShow();
958      }
959      break;
960
961    case REQUIRES_SIGN_IN:
962    case SIGN_IN_DISABLED:
963      // Switch to the local account and refresh the dialog.
964      OnWalletSigninError();
965      break;
966
967    case REQUIRES_PASSIVE_SIGN_IN:
968      // Attempt to passively sign in the user.
969      DCHECK(!signin_helper_);
970      account_chooser_model_.ClearActiveWalletAccountName();
971      signin_helper_.reset(new wallet::WalletSigninHelper(
972          this,
973          profile_->GetRequestContext()));
974      signin_helper_->StartPassiveSignin();
975      break;
976
977    case REQUIRES_RESPONSE:
978      break;
979  }
980}
981
982void AutofillDialogControllerImpl::OnWalletOrSigninUpdate() {
983  SignedInStateUpdated();
984  SuggestionsUpdated();
985  UpdateAccountChooserView();
986
987  if (view_)
988    view_->UpdateButtonStrip();
989
990  // On the first successful response, compute the initial user state metric.
991  if (initial_user_state_ == AutofillMetrics::DIALOG_USER_STATE_UNKNOWN)
992    initial_user_state_ = GetInitialUserState();
993}
994
995void AutofillDialogControllerImpl::OnWalletFormFieldError(
996    const std::vector<wallet::FormFieldError>& form_field_errors) {
997  if (form_field_errors.empty())
998    return;
999
1000  for (std::vector<wallet::FormFieldError>::const_iterator it =
1001           form_field_errors.begin();
1002       it != form_field_errors.end(); ++it) {
1003    if (it->error_type() == wallet::FormFieldError::UNKNOWN_ERROR ||
1004        it->GetAutofillType() == MAX_VALID_FIELD_TYPE ||
1005        it->location() == wallet::FormFieldError::UNKNOWN_LOCATION) {
1006      wallet_server_validation_recoverable_ = false;
1007      break;
1008    }
1009    DialogSection section = SectionFromLocation(it->location());
1010    wallet_errors_[section][it->GetAutofillType()] =
1011        std::make_pair(it->GetErrorMessage(),
1012                       GetValueFromSection(section, it->GetAutofillType()));
1013  }
1014
1015  // Unrecoverable validation errors.
1016  if (!wallet_server_validation_recoverable_)
1017    DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
1018
1019  UpdateForErrors();
1020}
1021
1022void AutofillDialogControllerImpl::EnsureLegalDocumentsText() {
1023  if (!wallet_items_ || wallet_items_->legal_documents().empty())
1024    return;
1025
1026  // The text has already been constructed, no need to recompute.
1027  if (!legal_documents_text_.empty())
1028    return;
1029
1030  const std::vector<wallet::WalletItems::LegalDocument*>& documents =
1031      wallet_items_->legal_documents();
1032  DCHECK_LE(documents.size(), 3U);
1033  DCHECK_GE(documents.size(), 2U);
1034  const bool new_user = wallet_items_->HasRequiredAction(wallet::SETUP_WALLET);
1035
1036  const string16 privacy_policy_display_name =
1037      l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PRIVACY_POLICY_LINK);
1038  string16 text;
1039  if (documents.size() == 2U) {
1040    text = l10n_util::GetStringFUTF16(
1041        new_user ? IDS_AUTOFILL_DIALOG_LEGAL_LINKS_NEW_2 :
1042                   IDS_AUTOFILL_DIALOG_LEGAL_LINKS_UPDATED_2,
1043        documents[0]->display_name(),
1044        documents[1]->display_name());
1045  } else {
1046    text = l10n_util::GetStringFUTF16(
1047        new_user ? IDS_AUTOFILL_DIALOG_LEGAL_LINKS_NEW_3 :
1048                   IDS_AUTOFILL_DIALOG_LEGAL_LINKS_UPDATED_3,
1049        documents[0]->display_name(),
1050        documents[1]->display_name(),
1051        documents[2]->display_name());
1052  }
1053
1054  legal_document_link_ranges_.clear();
1055  for (size_t i = 0; i < documents.size(); ++i) {
1056    size_t link_start = text.find(documents[i]->display_name());
1057    legal_document_link_ranges_.push_back(ui::Range(
1058        link_start, link_start + documents[i]->display_name().size()));
1059  }
1060  legal_documents_text_ = text;
1061}
1062
1063void AutofillDialogControllerImpl::ResetSectionInput(DialogSection section) {
1064  SetEditingExistingData(section, false);
1065
1066  DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1067  for (DetailInputs::iterator it = inputs->begin(); it != inputs->end(); ++it) {
1068    it->initial_value.clear();
1069  }
1070}
1071
1072void AutofillDialogControllerImpl::ShowEditUiIfBadSuggestion(
1073    DialogSection section) {
1074  // |CreateWrapper()| returns an empty wrapper if |IsEditingExistingData()|, so
1075  // get the wrapper before this potentially happens below.
1076  scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1077
1078  // If the chosen item in |model| yields an empty suggestion text, it is
1079  // invalid. In this case, show the edit UI and highlight invalid fields.
1080  SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1081  if (IsASuggestionItemKey(model->GetItemKeyForCheckedItem()) &&
1082      SuggestionTextForSection(section).empty()) {
1083    SetEditingExistingData(section, true);
1084  }
1085
1086  DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1087  if (wrapper && IsEditingExistingData(section))
1088    wrapper->FillInputs(inputs);
1089
1090  for (DetailInputs::iterator it = inputs->begin(); it != inputs->end(); ++it) {
1091    it->editable = InputIsEditable(*it, section);
1092  }
1093}
1094
1095bool AutofillDialogControllerImpl::InputWasEdited(const DetailInput& input,
1096                                                  const base::string16& value) {
1097  if (value.empty())
1098    return false;
1099
1100  // If this is a combobox at the default value, don't preserve.
1101  ui::ComboboxModel* model = ComboboxModelForAutofillType(input.type);
1102  if (model && model->GetItemAt(model->GetDefaultIndex()) == value)
1103    return false;
1104
1105  return true;
1106}
1107
1108DetailOutputMap AutofillDialogControllerImpl::TakeUserInputSnapshot() {
1109  DetailOutputMap snapshot;
1110  if (!view_)
1111    return snapshot;
1112
1113  for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1114    DialogSection section = static_cast<DialogSection>(i);
1115    SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1116    if (model->GetItemKeyForCheckedItem() != kAddNewItemKey)
1117      continue;
1118
1119    DetailOutputMap outputs;
1120    view_->GetUserInput(section, &outputs);
1121    // Remove fields that are empty, at their default values, or invalid.
1122    for (DetailOutputMap::iterator it = outputs.begin(); it != outputs.end();
1123         ++it) {
1124      if (InputWasEdited(*it->first, it->second) &&
1125          InputValidityMessage(section, it->first->type, it->second).empty()) {
1126        snapshot.insert(std::make_pair(it->first, it->second));
1127      }
1128    }
1129  }
1130
1131  return snapshot;
1132}
1133
1134void AutofillDialogControllerImpl::RestoreUserInputFromSnapshot(
1135    const DetailOutputMap& snapshot) {
1136  if (snapshot.empty())
1137    return;
1138
1139  DetailOutputWrapper wrapper(snapshot);
1140  for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1141    DialogSection section = static_cast<DialogSection>(i);
1142    if (!SectionIsActive(section))
1143      continue;
1144
1145    DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1146    wrapper.FillInputs(inputs);
1147
1148    for (size_t i = 0; i < inputs->size(); ++i) {
1149      if (InputWasEdited((*inputs)[i], (*inputs)[i].initial_value)) {
1150        SuggestionsMenuModelForSection(section)->SetCheckedItem(kAddNewItemKey);
1151        break;
1152      }
1153    }
1154  }
1155}
1156
1157void AutofillDialogControllerImpl::UpdateSection(DialogSection section) {
1158  if (view_)
1159    view_->UpdateSection(section);
1160}
1161
1162void AutofillDialogControllerImpl::UpdateForErrors() {
1163  if (!view_)
1164    return;
1165
1166  // Currently, the view should only need to be updated if there are
1167  // |wallet_errors_| or validating a suggestion that's based on existing data.
1168  bool should_update = !wallet_errors_.empty();
1169  if (!should_update) {
1170    for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1171      if (IsEditingExistingData(static_cast<DialogSection>(i))) {
1172        should_update = true;
1173        break;
1174      }
1175    }
1176  }
1177
1178  if (should_update)
1179    view_->UpdateForErrors();
1180}
1181
1182const DetailInputs& AutofillDialogControllerImpl::RequestedFieldsForSection(
1183    DialogSection section) const {
1184  switch (section) {
1185    case SECTION_EMAIL:
1186      return requested_email_fields_;
1187    case SECTION_CC:
1188      return requested_cc_fields_;
1189    case SECTION_BILLING:
1190      return requested_billing_fields_;
1191    case SECTION_CC_BILLING:
1192      return requested_cc_billing_fields_;
1193    case SECTION_SHIPPING:
1194      return requested_shipping_fields_;
1195  }
1196
1197  NOTREACHED();
1198  return requested_billing_fields_;
1199}
1200
1201ui::ComboboxModel* AutofillDialogControllerImpl::ComboboxModelForAutofillType(
1202    ServerFieldType type) {
1203  switch (AutofillType::GetEquivalentFieldType(type)) {
1204    case CREDIT_CARD_EXP_MONTH:
1205      return &cc_exp_month_combobox_model_;
1206
1207    case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1208      return &cc_exp_year_combobox_model_;
1209
1210    case ADDRESS_HOME_COUNTRY:
1211      return &country_combobox_model_;
1212
1213    default:
1214      return NULL;
1215  }
1216}
1217
1218ui::MenuModel* AutofillDialogControllerImpl::MenuModelForSection(
1219    DialogSection section) {
1220  SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1221  // The shipping section menu is special. It will always show because there is
1222  // a choice between "Use billing" and "enter new".
1223  if (section == SECTION_SHIPPING)
1224    return model;
1225
1226  // For other sections, only show a menu if there's at least one suggestion.
1227  for (int i = 0; i < model->GetItemCount(); ++i) {
1228    if (IsASuggestionItemKey(model->GetItemKeyAt(i)))
1229      return model;
1230  }
1231
1232  return NULL;
1233}
1234
1235ui::MenuModel* AutofillDialogControllerImpl::MenuModelForAccountChooser() {
1236  // If there were unrecoverable Wallet errors, or if there are choices other
1237  // than "Pay without the wallet", show the full menu.
1238  if (account_chooser_model_.HadWalletError() ||
1239      account_chooser_model_.HasAccountsToChoose()) {
1240    return &account_chooser_model_;
1241  }
1242
1243  // Otherwise, there is no menu, just a sign in link.
1244  return NULL;
1245}
1246
1247gfx::Image AutofillDialogControllerImpl::AccountChooserImage() {
1248  if (!MenuModelForAccountChooser()) {
1249    if (signin_registrar_.IsEmpty()) {
1250      return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1251          IDR_WALLET_ICON);
1252    }
1253
1254    return gfx::Image();
1255  }
1256
1257  gfx::Image icon;
1258  account_chooser_model_.GetIconAt(
1259      account_chooser_model_.GetIndexOfCommandId(
1260          account_chooser_model_.checked_item()),
1261      &icon);
1262  return icon;
1263}
1264
1265bool AutofillDialogControllerImpl::ShouldShowDetailArea() const {
1266  // Hide the detail area when Autocheckout is running or there was an error (as
1267  // there's nothing they can do after an error but cancel).
1268  return autocheckout_state_ == AUTOCHECKOUT_NOT_STARTED;
1269}
1270
1271bool AutofillDialogControllerImpl::ShouldShowProgressBar() const {
1272  // Show the progress bar while Autocheckout is running but hide it on errors,
1273  // as there's no use leaving it up if the flow has failed.
1274  return autocheckout_state_ == AUTOCHECKOUT_IN_PROGRESS;
1275}
1276
1277gfx::Image AutofillDialogControllerImpl::ButtonStripImage() const {
1278  if (ShouldShowDetailArea() && IsPayingWithWallet()) {
1279    return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1280        IDR_WALLET_LOGO);
1281  }
1282
1283  return gfx::Image();
1284}
1285
1286string16 AutofillDialogControllerImpl::LabelForSection(DialogSection section)
1287    const {
1288  switch (section) {
1289    case SECTION_EMAIL:
1290      return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_EMAIL);
1291    case SECTION_CC:
1292      return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_CC);
1293    case SECTION_BILLING:
1294    case SECTION_CC_BILLING:
1295      return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_BILLING);
1296    case SECTION_SHIPPING:
1297      return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_SHIPPING);
1298    default:
1299      NOTREACHED();
1300      return string16();
1301  }
1302}
1303
1304SuggestionState AutofillDialogControllerImpl::SuggestionStateForSection(
1305    DialogSection section) {
1306  return SuggestionState(SuggestionTextForSection(section),
1307                         SuggestionTextStyleForSection(section),
1308                         SuggestionIconForSection(section),
1309                         ExtraSuggestionTextForSection(section),
1310                         ExtraSuggestionIconForSection(section));
1311}
1312
1313string16 AutofillDialogControllerImpl::SuggestionTextForSection(
1314    DialogSection section) {
1315  string16 action_text = RequiredActionTextForSection(section);
1316  if (!action_text.empty())
1317    return action_text;
1318
1319  // When the user has clicked 'edit' or a suggestion is somehow invalid (e.g. a
1320  // user selects a credit card that has expired), don't show a suggestion (even
1321  // though there is a profile selected in the model).
1322  if (IsEditingExistingData(section))
1323    return string16();
1324
1325  SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1326  std::string item_key = model->GetItemKeyForCheckedItem();
1327  if (item_key == kSameAsBillingKey) {
1328    return l10n_util::GetStringUTF16(
1329        IDS_AUTOFILL_DIALOG_USING_BILLING_FOR_SHIPPING);
1330  }
1331
1332  if (!IsASuggestionItemKey(item_key))
1333    return string16();
1334
1335  if (section == SECTION_EMAIL)
1336    return model->GetLabelAt(model->checked_item());
1337
1338  scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1339  return wrapper->GetDisplayText();
1340}
1341
1342gfx::Font::FontStyle
1343    AutofillDialogControllerImpl::SuggestionTextStyleForSection(
1344        DialogSection section) const {
1345  const SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1346  if (model->GetItemKeyForCheckedItem() == kSameAsBillingKey)
1347    return gfx::Font::ITALIC;
1348
1349  return gfx::Font::NORMAL;
1350}
1351
1352string16 AutofillDialogControllerImpl::RequiredActionTextForSection(
1353    DialogSection section) const {
1354  if (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV)) {
1355    const wallet::WalletItems::MaskedInstrument* current_instrument =
1356        wallet_items_->GetInstrumentById(active_instrument_id_);
1357    if (current_instrument)
1358      return current_instrument->TypeAndLastFourDigits();
1359
1360    DetailOutputMap output;
1361    view_->GetUserInput(section, &output);
1362    CreditCard card;
1363    GetBillingInfoFromOutputs(output, &card, NULL, NULL);
1364    return card.TypeAndLastFourDigits();
1365  }
1366
1367  return string16();
1368}
1369
1370string16 AutofillDialogControllerImpl::ExtraSuggestionTextForSection(
1371    DialogSection section) const {
1372  if (section == SECTION_CC ||
1373      (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV))) {
1374    return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC);
1375  }
1376
1377  return string16();
1378}
1379
1380const wallet::WalletItems::MaskedInstrument* AutofillDialogControllerImpl::
1381    ActiveInstrument() const {
1382  if (!IsPayingWithWallet())
1383    return NULL;
1384
1385  const SuggestionsMenuModel* model =
1386      SuggestionsMenuModelForSection(SECTION_CC_BILLING);
1387  const std::string item_key = model->GetItemKeyForCheckedItem();
1388  if (!IsASuggestionItemKey(item_key))
1389    return NULL;
1390
1391  int index;
1392  if (!base::StringToInt(item_key, &index) || index < 0 ||
1393      static_cast<size_t>(index) >= wallet_items_->instruments().size()) {
1394    NOTREACHED();
1395    return NULL;
1396  }
1397
1398  return wallet_items_->instruments()[index];
1399}
1400
1401const wallet::Address* AutofillDialogControllerImpl::
1402    ActiveShippingAddress() const {
1403  if (!IsPayingWithWallet() || !IsShippingAddressRequired())
1404    return NULL;
1405
1406  const SuggestionsMenuModel* model =
1407      SuggestionsMenuModelForSection(SECTION_SHIPPING);
1408  const std::string item_key = model->GetItemKeyForCheckedItem();
1409  if (!IsASuggestionItemKey(item_key))
1410    return NULL;
1411
1412  int index;
1413  if (!base::StringToInt(item_key, &index) || index < 0 ||
1414      static_cast<size_t>(index) >= wallet_items_->addresses().size()) {
1415    NOTREACHED();
1416    return NULL;
1417  }
1418
1419  return wallet_items_->addresses()[index];
1420}
1421
1422scoped_ptr<DataModelWrapper> AutofillDialogControllerImpl::CreateWrapper(
1423    DialogSection section) {
1424  if (IsPayingWithWallet() && full_wallet_ &&
1425      full_wallet_->required_actions().empty()) {
1426    if (section == SECTION_CC_BILLING) {
1427      return scoped_ptr<DataModelWrapper>(
1428          new FullWalletBillingWrapper(full_wallet_.get()));
1429    }
1430    if (section == SECTION_SHIPPING) {
1431      return scoped_ptr<DataModelWrapper>(
1432          new FullWalletShippingWrapper(full_wallet_.get()));
1433    }
1434  }
1435
1436  SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1437  std::string item_key = model->GetItemKeyForCheckedItem();
1438  if (!IsASuggestionItemKey(item_key) || IsManuallyEditingSection(section))
1439    return scoped_ptr<DataModelWrapper>();
1440
1441  if (IsPayingWithWallet()) {
1442    if (section == SECTION_CC_BILLING) {
1443      return scoped_ptr<DataModelWrapper>(
1444          new WalletInstrumentWrapper(ActiveInstrument()));
1445    }
1446
1447    if (section == SECTION_SHIPPING) {
1448      return scoped_ptr<DataModelWrapper>(
1449          new WalletAddressWrapper(ActiveShippingAddress()));
1450    }
1451
1452    return scoped_ptr<DataModelWrapper>();
1453  }
1454
1455  if (section == SECTION_CC) {
1456    CreditCard* card = GetManager()->GetCreditCardByGUID(item_key);
1457    DCHECK(card);
1458    return scoped_ptr<DataModelWrapper>(new AutofillCreditCardWrapper(card));
1459  }
1460
1461  AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key);
1462  DCHECK(profile);
1463  size_t variant = GetSelectedVariantForModel(*model);
1464  return scoped_ptr<DataModelWrapper>(
1465      new AutofillProfileWrapper(profile, variant));
1466}
1467
1468gfx::Image AutofillDialogControllerImpl::SuggestionIconForSection(
1469    DialogSection section) {
1470  scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1471  if (!model.get())
1472    return gfx::Image();
1473
1474  return model->GetIcon();
1475}
1476
1477gfx::Image AutofillDialogControllerImpl::ExtraSuggestionIconForSection(
1478    DialogSection section) const {
1479  if (section == SECTION_CC || section == SECTION_CC_BILLING)
1480    return IconForField(CREDIT_CARD_VERIFICATION_CODE, string16());
1481
1482  return gfx::Image();
1483}
1484
1485void AutofillDialogControllerImpl::EditClickedForSection(
1486    DialogSection section) {
1487  scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1488  SetEditingExistingData(section, true);
1489
1490  DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1491  for (DetailInputs::iterator it = inputs->begin(); it != inputs->end(); ++it) {
1492    it->editable = InputIsEditable(*it, section);
1493  }
1494  model->FillInputs(inputs);
1495
1496  UpdateSection(section);
1497
1498  GetMetricLogger().LogDialogUiEvent(
1499      GetDialogType(), DialogSectionToUiEditEvent(section));
1500}
1501
1502void AutofillDialogControllerImpl::EditCancelledForSection(
1503    DialogSection section) {
1504  ResetSectionInput(section);
1505  UpdateSection(section);
1506}
1507
1508gfx::Image AutofillDialogControllerImpl::IconForField(
1509    ServerFieldType type, const string16& user_input) const {
1510  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1511  if (type == CREDIT_CARD_VERIFICATION_CODE)
1512    return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT);
1513
1514  // For the credit card, we show a few grayscale images, and possibly one
1515  // color image if |user_input| is a valid card number.
1516  if (type == CREDIT_CARD_NUMBER) {
1517    const int card_idrs[] = {
1518      IDR_AUTOFILL_CC_VISA,
1519      IDR_AUTOFILL_CC_MASTERCARD,
1520      IDR_AUTOFILL_CC_AMEX,
1521      IDR_AUTOFILL_CC_DISCOVER
1522    };
1523    const int number_of_cards = arraysize(card_idrs);
1524    // The number of pixels between card icons.
1525    const int kCardPadding = 2;
1526
1527    gfx::ImageSkia some_card = *rb.GetImageSkiaNamed(card_idrs[0]);
1528    const int card_width = some_card.width();
1529    gfx::Canvas canvas(
1530        gfx::Size((card_width + kCardPadding) * number_of_cards - kCardPadding,
1531                  some_card.height()),
1532        ui::SCALE_FACTOR_100P,
1533        false);
1534
1535    const int input_card_idr = CreditCard::IconResourceId(
1536        CreditCard::GetCreditCardType(user_input));
1537    for (int i = 0; i < number_of_cards; ++i) {
1538      int idr = card_idrs[i];
1539      gfx::ImageSkia card_image = *rb.GetImageSkiaNamed(idr);
1540      if (input_card_idr != idr) {
1541        SkBitmap disabled_bitmap =
1542            SkBitmapOperations::CreateHSLShiftedBitmap(*card_image.bitmap(),
1543                                                       kGrayImageShift);
1544        card_image = gfx::ImageSkia::CreateFrom1xBitmap(disabled_bitmap);
1545      }
1546
1547      canvas.DrawImageInt(card_image, i * (card_width + kCardPadding), 0);
1548    }
1549
1550    gfx::ImageSkia skia(canvas.ExtractImageRep());
1551    return gfx::Image(skia);
1552  }
1553
1554  return gfx::Image();
1555}
1556
1557// TODO(estade): Replace all the error messages here with more helpful and
1558// translateable ones. TODO(groby): Also add tests.
1559string16 AutofillDialogControllerImpl::InputValidityMessage(
1560    DialogSection section,
1561    ServerFieldType type,
1562    const string16& value) {
1563  // If the field is edited, clear any Wallet errors.
1564  if (IsPayingWithWallet()) {
1565    WalletValidationErrors::iterator it = wallet_errors_.find(section);
1566    if (it != wallet_errors_.end()) {
1567      TypeErrorInputMap::const_iterator iter = it->second.find(type);
1568      if (iter != it->second.end()) {
1569        if (iter->second.second == value)
1570          return iter->second.first;
1571        it->second.erase(type);
1572      }
1573    }
1574  }
1575
1576  switch (AutofillType::GetEquivalentFieldType(type)) {
1577    case EMAIL_ADDRESS:
1578      if (!value.empty() && !IsValidEmailAddress(value)) {
1579        return l10n_util::GetStringUTF16(
1580            IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_EMAIL_ADDRESS);
1581      }
1582      break;
1583
1584    case CREDIT_CARD_NUMBER: {
1585      if (!value.empty()) {
1586        base::string16 message = CreditCardNumberValidityMessage(value);
1587        if (!message.empty())
1588          return message;
1589      }
1590      break;
1591    }
1592
1593    case CREDIT_CARD_EXP_MONTH:
1594    case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1595      break;
1596
1597    case CREDIT_CARD_VERIFICATION_CODE:
1598      if (!value.empty() && !autofill::IsValidCreditCardSecurityCode(value)) {
1599        return l10n_util::GetStringUTF16(
1600            IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
1601      }
1602      break;
1603
1604    case ADDRESS_HOME_LINE1:
1605      break;
1606
1607    case ADDRESS_HOME_LINE2:
1608      return base::string16();  // Line 2 is optional - always valid.
1609
1610    case ADDRESS_HOME_CITY:
1611    case ADDRESS_HOME_COUNTRY:
1612      break;
1613
1614    case ADDRESS_HOME_STATE:
1615      if (!value.empty() && !autofill::IsValidState(value)) {
1616        return l10n_util::GetStringUTF16(
1617            IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_REGION);
1618      }
1619      break;
1620
1621    case ADDRESS_HOME_ZIP:
1622      if (!value.empty() && !autofill::IsValidZip(value)) {
1623        return l10n_util::GetStringUTF16(
1624            IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_ZIP_CODE);
1625      }
1626      break;
1627
1628    case NAME_FULL:
1629      // Wallet requires a first and last billing name.
1630      if (section == SECTION_CC_BILLING && !value.empty() &&
1631          !IsCardHolderNameValidForWallet(value)) {
1632        DCHECK(IsPayingWithWallet());
1633        return l10n_util::GetStringUTF16(
1634            IDS_AUTOFILL_DIALOG_VALIDATION_WALLET_REQUIRES_TWO_NAMES);
1635      }
1636      break;
1637
1638    case PHONE_HOME_WHOLE_NUMBER:  // Used in shipping section.
1639      break;
1640
1641    case PHONE_BILLING_WHOLE_NUMBER:  // Used in billing section.
1642      break;
1643
1644    default:
1645      NOTREACHED();  // Trying to validate unknown field.
1646      break;
1647  }
1648
1649  return value.empty() ?
1650      l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE) :
1651      base::string16();
1652}
1653
1654// TODO(estade): Replace all the error messages here with more helpful and
1655// translateable ones. TODO(groby): Also add tests.
1656ValidityData AutofillDialogControllerImpl::InputsAreValid(
1657    DialogSection section,
1658    const DetailOutputMap& inputs,
1659    ValidationType validation_type) {
1660  ValidityData invalid_messages;
1661  std::map<ServerFieldType, string16> field_values;
1662  for (DetailOutputMap::const_iterator iter = inputs.begin();
1663       iter != inputs.end(); ++iter) {
1664    // Skip empty fields in edit mode.
1665    if (validation_type == VALIDATE_EDIT && iter->second.empty())
1666      continue;
1667
1668    const ServerFieldType type = iter->first->type;
1669    string16 message = InputValidityMessage(section, type, iter->second);
1670    if (!message.empty())
1671      invalid_messages[type] = message;
1672    else
1673      field_values[type] = iter->second;
1674  }
1675
1676  // Validate the date formed by month and year field. (Autofill dialog is
1677  // never supposed to have 2-digit years, so not checked).
1678  if (field_values.count(CREDIT_CARD_EXP_4_DIGIT_YEAR) &&
1679      field_values.count(CREDIT_CARD_EXP_MONTH) &&
1680      !IsCreditCardExpirationValid(field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR],
1681                                   field_values[CREDIT_CARD_EXP_MONTH])) {
1682    // The dialog shows the same error message for the month and year fields.
1683    invalid_messages[CREDIT_CARD_EXP_4_DIGIT_YEAR] = l10n_util::GetStringUTF16(
1684        IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
1685    invalid_messages[CREDIT_CARD_EXP_MONTH] = l10n_util::GetStringUTF16(
1686        IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
1687  }
1688
1689  // If there is a credit card number and a CVC, validate them together.
1690  if (field_values.count(CREDIT_CARD_NUMBER) &&
1691      field_values.count(CREDIT_CARD_VERIFICATION_CODE) &&
1692      !invalid_messages.count(CREDIT_CARD_NUMBER) &&
1693      !autofill::IsValidCreditCardSecurityCode(
1694          field_values[CREDIT_CARD_VERIFICATION_CODE],
1695          field_values[CREDIT_CARD_NUMBER])) {
1696    invalid_messages[CREDIT_CARD_VERIFICATION_CODE] =
1697        l10n_util::GetStringUTF16(
1698            IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
1699  }
1700
1701  // Validate the shipping phone number against the country code of the address.
1702  if (field_values.count(ADDRESS_HOME_COUNTRY) &&
1703      field_values.count(PHONE_HOME_WHOLE_NUMBER)) {
1704    i18n::PhoneObject phone_object(
1705        field_values[PHONE_HOME_WHOLE_NUMBER],
1706        AutofillCountry::GetCountryCode(
1707            field_values[ADDRESS_HOME_COUNTRY],
1708            g_browser_process->GetApplicationLocale()));
1709    if (!phone_object.IsValidNumber()) {
1710      invalid_messages[PHONE_HOME_WHOLE_NUMBER] = l10n_util::GetStringUTF16(
1711          IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER);
1712    }
1713  }
1714
1715  // Validate the billing phone number against the country code of the address.
1716  if (field_values.count(ADDRESS_BILLING_COUNTRY) &&
1717      field_values.count(PHONE_BILLING_WHOLE_NUMBER)) {
1718    i18n::PhoneObject phone_object(
1719        field_values[PHONE_BILLING_WHOLE_NUMBER],
1720        AutofillCountry::GetCountryCode(
1721            field_values[ADDRESS_BILLING_COUNTRY],
1722            g_browser_process->GetApplicationLocale()));
1723    if (!phone_object.IsValidNumber()) {
1724      invalid_messages[PHONE_BILLING_WHOLE_NUMBER] = l10n_util::GetStringUTF16(
1725          IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER);
1726    }
1727  }
1728
1729  return invalid_messages;
1730}
1731
1732void AutofillDialogControllerImpl::UserEditedOrActivatedInput(
1733    DialogSection section,
1734    const DetailInput* input,
1735    gfx::NativeView parent_view,
1736    const gfx::Rect& content_bounds,
1737    const string16& field_contents,
1738    bool was_edit) {
1739  // If the field is edited down to empty, don't show a popup.
1740  if (was_edit && field_contents.empty()) {
1741    HidePopup();
1742    return;
1743  }
1744
1745  // If the user clicks while the popup is already showing, be sure to hide
1746  // it.
1747  if (!was_edit && popup_controller_.get()) {
1748    HidePopup();
1749    return;
1750  }
1751
1752  std::vector<string16> popup_values, popup_labels, popup_icons;
1753  if (IsCreditCardType(input->type)) {
1754    GetManager()->GetCreditCardSuggestions(AutofillType(input->type),
1755                                           field_contents,
1756                                           &popup_values,
1757                                           &popup_labels,
1758                                           &popup_icons,
1759                                           &popup_guids_);
1760  } else {
1761    std::vector<ServerFieldType> field_types;
1762    field_types.push_back(EMAIL_ADDRESS);
1763    for (DetailInputs::const_iterator iter = requested_shipping_fields_.begin();
1764         iter != requested_shipping_fields_.end(); ++iter) {
1765      field_types.push_back(iter->type);
1766    }
1767    GetManager()->GetProfileSuggestions(AutofillType(input->type),
1768                                        field_contents,
1769                                        false,
1770                                        field_types,
1771                                        &popup_values,
1772                                        &popup_labels,
1773                                        &popup_icons,
1774                                        &popup_guids_);
1775  }
1776
1777  if (popup_values.empty()) {
1778    HidePopup();
1779    return;
1780  }
1781
1782  // TODO(estade): do we need separators and control rows like 'Clear
1783  // Form'?
1784  std::vector<int> popup_ids;
1785  for (size_t i = 0; i < popup_guids_.size(); ++i) {
1786    popup_ids.push_back(i);
1787  }
1788
1789  popup_controller_ = AutofillPopupControllerImpl::GetOrCreate(
1790      popup_controller_,
1791      weak_ptr_factory_.GetWeakPtr(),
1792      parent_view,
1793      content_bounds,
1794      base::i18n::IsRTL() ?
1795          base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT);
1796  popup_controller_->Show(popup_values,
1797                          popup_labels,
1798                          popup_icons,
1799                          popup_ids);
1800  input_showing_popup_ = input;
1801}
1802
1803void AutofillDialogControllerImpl::FocusMoved() {
1804  HidePopup();
1805}
1806
1807gfx::Image AutofillDialogControllerImpl::SplashPageImage() const {
1808  // Only show the splash page the first few times the dialog is opened.
1809  int show_count =
1810      profile_->GetPrefs()->GetInteger(::prefs::kAutofillDialogShowCount);
1811  if (show_count <= 4) {
1812    return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1813        IDR_PRODUCT_LOGO_NAME_48);
1814  }
1815
1816  return gfx::Image();
1817}
1818
1819void AutofillDialogControllerImpl::ViewClosed() {
1820  GetManager()->RemoveObserver(this);
1821
1822  // TODO(ahutter): Once a user can cancel Autocheckout mid-flow, log that
1823  // metric here.
1824
1825  // Called from here rather than in ~AutofillDialogControllerImpl as this
1826  // relies on virtual methods that change to their base class in the dtor.
1827  MaybeShowCreditCardBubble();
1828
1829  delete this;
1830}
1831
1832std::vector<DialogNotification> AutofillDialogControllerImpl::
1833    CurrentNotifications() {
1834  std::vector<DialogNotification> notifications;
1835
1836  if (IsPayingWithWallet() && !wallet::IsUsingProd()) {
1837    notifications.push_back(DialogNotification(
1838        DialogNotification::DEVELOPER_WARNING,
1839        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_NOT_PROD_WARNING)));
1840  }
1841
1842  if (RequestingCreditCardInfo() && !TransmissionWillBeSecure()) {
1843    notifications.push_back(DialogNotification(
1844        DialogNotification::SECURITY_WARNING,
1845        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECURITY_WARNING)));
1846  }
1847
1848  if (!invoked_from_same_origin_) {
1849    notifications.push_back(DialogNotification(
1850        DialogNotification::SECURITY_WARNING,
1851        l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_SITE_WARNING,
1852                                   UTF8ToUTF16(source_url_.host()))));
1853  }
1854
1855  if (account_chooser_model_.HadWalletError()) {
1856    // TODO(dbeam): figure out a way to dismiss this error after a while.
1857    notifications.push_back(DialogNotification(
1858        DialogNotification::WALLET_ERROR,
1859        l10n_util::GetStringFUTF16(
1860            IDS_AUTOFILL_DIALOG_COMPLETE_WITHOUT_WALLET,
1861            account_chooser_model_.wallet_error_message())));
1862  }
1863
1864  if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
1865    notifications.push_back(DialogNotification(
1866        DialogNotification::REQUIRED_ACTION,
1867        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VERIFY_CVV)));
1868  }
1869
1870  if (autocheckout_state_ == AUTOCHECKOUT_ERROR) {
1871    notifications.push_back(DialogNotification(
1872        DialogNotification::AUTOCHECKOUT_ERROR,
1873        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_AUTOCHECKOUT_ERROR)));
1874  }
1875
1876  if (autocheckout_state_ == AUTOCHECKOUT_SUCCESS) {
1877    notifications.push_back(DialogNotification(
1878        DialogNotification::AUTOCHECKOUT_SUCCESS,
1879        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_AUTOCHECKOUT_SUCCESS)));
1880  }
1881
1882  if (!wallet_server_validation_recoverable_) {
1883    notifications.push_back(DialogNotification(
1884        DialogNotification::REQUIRED_ACTION,
1885        l10n_util::GetStringUTF16(
1886            IDS_AUTOFILL_DIALOG_FAILED_TO_SAVE_WALLET_DATA)));
1887  }
1888
1889  if (choose_another_instrument_or_address_) {
1890    notifications.push_back(DialogNotification(
1891        DialogNotification::REQUIRED_ACTION,
1892        l10n_util::GetStringUTF16(
1893            IDS_AUTOFILL_DIALOG_CHOOSE_DIFFERENT_WALLET_INSTRUMENT)));
1894  }
1895
1896  if (should_show_wallet_promo_ && ShouldShowDetailArea() &&
1897      notifications.empty()) {
1898    if (IsPayingWithWallet() && HasCompleteWallet()) {
1899      notifications.push_back(DialogNotification(
1900          DialogNotification::EXPLANATORY_MESSAGE,
1901          l10n_util::GetStringUTF16(
1902              IDS_AUTOFILL_DIALOG_DETAILS_FROM_WALLET)));
1903    } else if ((IsPayingWithWallet() && !HasCompleteWallet()) ||
1904               has_shown_wallet_usage_confirmation_) {
1905      DialogNotification notification(
1906          DialogNotification::WALLET_USAGE_CONFIRMATION,
1907          l10n_util::GetStringUTF16(
1908              IDS_AUTOFILL_DIALOG_SAVE_DETAILS_IN_WALLET));
1909      notification.set_tooltip_text(
1910          l10n_util::GetStringUTF16(
1911              IDS_AUTOFILL_DIALOG_SAVE_IN_WALLET_TOOLTIP));
1912      notification.set_checked(account_chooser_model_.WalletIsSelected());
1913      notification.set_interactive(!is_submitting_);
1914      notifications.push_back(notification);
1915      has_shown_wallet_usage_confirmation_ = true;
1916    }
1917  }
1918
1919  return notifications;
1920}
1921
1922void AutofillDialogControllerImpl::SignInLinkClicked() {
1923  if (signin_registrar_.IsEmpty()) {
1924    // Start sign in.
1925    DCHECK(!IsPayingWithWallet());
1926
1927    content::Source<content::NavigationController> source(view_->ShowSignIn());
1928    signin_registrar_.Add(
1929        this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, source);
1930    view_->UpdateAccountChooser();
1931
1932    GetMetricLogger().LogDialogUiEvent(
1933        GetDialogType(), AutofillMetrics::DIALOG_UI_SIGNIN_SHOWN);
1934  } else {
1935    HideSignIn();
1936  }
1937}
1938
1939void AutofillDialogControllerImpl::NotificationCheckboxStateChanged(
1940    DialogNotification::Type type, bool checked) {
1941  if (type == DialogNotification::WALLET_USAGE_CONFIRMATION) {
1942    if (checked)
1943      account_chooser_model_.SelectActiveWalletAccount();
1944    else
1945      account_chooser_model_.SelectUseAutofill();
1946  }
1947}
1948
1949void AutofillDialogControllerImpl::LegalDocumentLinkClicked(
1950    const ui::Range& range) {
1951  for (size_t i = 0; i < legal_document_link_ranges_.size(); ++i) {
1952    if (legal_document_link_ranges_[i] == range) {
1953      OpenTabWithUrl(wallet_items_->legal_documents()[i]->url());
1954      return;
1955    }
1956  }
1957
1958  NOTREACHED();
1959}
1960
1961void AutofillDialogControllerImpl::OverlayButtonPressed() {
1962  DCHECK(is_submitting_);
1963  DCHECK(full_wallet_);
1964  profile_->GetPrefs()->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet,
1965                                   true);
1966  FinishSubmit();
1967}
1968
1969bool AutofillDialogControllerImpl::OnCancel() {
1970  HidePopup();
1971  if (autocheckout_state_ == AUTOCHECKOUT_NOT_STARTED && !is_submitting_)
1972    LogOnCancelMetrics();
1973  if (autocheckout_state_ == AUTOCHECKOUT_IN_PROGRESS) {
1974    GetMetricLogger().LogAutocheckoutDuration(
1975        base::Time::Now() - autocheckout_started_timestamp_,
1976        AutofillMetrics::AUTOCHECKOUT_CANCELLED);
1977  }
1978  callback_.Run(NULL, std::string());
1979  return true;
1980}
1981
1982bool AutofillDialogControllerImpl::OnAccept() {
1983  // If autocheckout has already started, the only thing left to do is to
1984  // close the dialog.
1985  if (autocheckout_state_ != AUTOCHECKOUT_NOT_STARTED)
1986    return true;
1987
1988  choose_another_instrument_or_address_ = false;
1989  wallet_server_validation_recoverable_ = true;
1990  HidePopup();
1991  if (IsPayingWithWallet()) {
1992    bool has_proxy_card_step = false;
1993    for (size_t i = 0; i < steps_.size(); ++i) {
1994      if (steps_[i].type() == AUTOCHECKOUT_STEP_PROXY_CARD) {
1995        has_proxy_card_step = true;
1996        break;
1997      }
1998    }
1999    if (!has_proxy_card_step) {
2000      steps_.insert(steps_.begin(),
2001                    DialogAutocheckoutStep(AUTOCHECKOUT_STEP_PROXY_CARD,
2002                                           AUTOCHECKOUT_STEP_UNSTARTED));
2003    }
2004  }
2005
2006  if (GetDialogType() == DIALOG_TYPE_AUTOCHECKOUT)
2007    DeemphasizeRenderView();
2008
2009  SetIsSubmitting(true);
2010  if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2011    DCHECK(!active_instrument_id_.empty());
2012    GetWalletClient()->AuthenticateInstrument(
2013        active_instrument_id_,
2014        UTF16ToUTF8(view_->GetCvc()));
2015  } else if (IsPayingWithWallet()) {
2016    // TODO(dbeam): disallow interacting with the dialog while submitting.
2017    // http://crbug.com/230932
2018    AcceptLegalDocuments();
2019  } else {
2020    FinishSubmit();
2021  }
2022
2023  return false;
2024}
2025
2026Profile* AutofillDialogControllerImpl::profile() {
2027  return profile_;
2028}
2029
2030content::WebContents* AutofillDialogControllerImpl::web_contents() {
2031  return contents_;
2032}
2033
2034////////////////////////////////////////////////////////////////////////////////
2035// AutofillPopupDelegate implementation.
2036
2037void AutofillDialogControllerImpl::OnPopupShown(
2038    content::KeyboardListener* listener) {
2039  GetMetricLogger().LogDialogPopupEvent(
2040      GetDialogType(), AutofillMetrics::DIALOG_POPUP_SHOWN);
2041}
2042
2043void AutofillDialogControllerImpl::OnPopupHidden(
2044    content::KeyboardListener* listener) {}
2045
2046void AutofillDialogControllerImpl::DidSelectSuggestion(int identifier) {
2047  // TODO(estade): implement.
2048}
2049
2050void AutofillDialogControllerImpl::DidAcceptSuggestion(const string16& value,
2051                                                       int identifier) {
2052  const PersonalDataManager::GUIDPair& pair = popup_guids_[identifier];
2053
2054  scoped_ptr<DataModelWrapper> wrapper;
2055  if (IsCreditCardType(input_showing_popup_->type)) {
2056    wrapper.reset(new AutofillCreditCardWrapper(
2057        GetManager()->GetCreditCardByGUID(pair.first)));
2058  } else {
2059    wrapper.reset(new AutofillProfileWrapper(
2060        GetManager()->GetProfileByGUID(pair.first), pair.second));
2061  }
2062
2063  for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2064    DialogSection section = static_cast<DialogSection>(i);
2065    wrapper->FillInputs(MutableRequestedFieldsForSection(section));
2066    view_->FillSection(section, *input_showing_popup_);
2067  }
2068
2069  GetMetricLogger().LogDialogPopupEvent(
2070      GetDialogType(), AutofillMetrics::DIALOG_POPUP_FORM_FILLED);
2071
2072  // TODO(estade): not sure why it's necessary to do this explicitly.
2073  HidePopup();
2074}
2075
2076void AutofillDialogControllerImpl::RemoveSuggestion(const string16& value,
2077                                                    int identifier) {
2078  // TODO(estade): implement.
2079}
2080
2081void AutofillDialogControllerImpl::ClearPreviewedForm() {
2082  // TODO(estade): implement.
2083}
2084
2085////////////////////////////////////////////////////////////////////////////////
2086// content::NotificationObserver implementation.
2087
2088void AutofillDialogControllerImpl::Observe(
2089    int type,
2090    const content::NotificationSource& source,
2091    const content::NotificationDetails& details) {
2092  DCHECK_EQ(type, content::NOTIFICATION_NAV_ENTRY_COMMITTED);
2093  content::LoadCommittedDetails* load_details =
2094      content::Details<content::LoadCommittedDetails>(details).ptr();
2095  if (wallet::IsSignInContinueUrl(load_details->entry->GetVirtualURL())) {
2096    should_show_wallet_promo_ = false;
2097    account_chooser_model_.SelectActiveWalletAccount();
2098    signin_helper_.reset(new wallet::WalletSigninHelper(
2099        this, profile_->GetRequestContext()));
2100    signin_helper_->StartWalletCookieValueFetch();
2101    HideSignIn();
2102  }
2103}
2104
2105////////////////////////////////////////////////////////////////////////////////
2106// SuggestionsMenuModelDelegate implementation.
2107
2108void AutofillDialogControllerImpl::SuggestionItemSelected(
2109    SuggestionsMenuModel* model,
2110    size_t index) {
2111  if (model->GetItemKeyAt(index) == kManageItemsKey) {
2112    GURL url;
2113    if (!IsPayingWithWallet()) {
2114      GURL settings_url(chrome::kChromeUISettingsURL);
2115      url = settings_url.Resolve(chrome::kAutofillSubPage);
2116    } else {
2117      // Reset |last_wallet_items_fetch_timestamp_| to ensure that the Wallet
2118      // data is refreshed as soon as the user switches back to this tab after
2119      // potentially editing his data.
2120      last_wallet_items_fetch_timestamp_ = base::TimeTicks();
2121      url = SectionForSuggestionsMenuModel(*model) == SECTION_SHIPPING ?
2122          wallet::GetManageAddressesUrl() : wallet::GetManageInstrumentsUrl();
2123    }
2124
2125    OpenTabWithUrl(url);
2126    return;
2127  }
2128
2129  model->SetCheckedIndex(index);
2130  DialogSection section = SectionForSuggestionsMenuModel(*model);
2131  ResetSectionInput(section);
2132  ShowEditUiIfBadSuggestion(section);
2133  UpdateSection(section);
2134  UpdateForErrors();
2135
2136  LogSuggestionItemSelectedMetric(*model);
2137}
2138
2139////////////////////////////////////////////////////////////////////////////////
2140// wallet::WalletClientDelegate implementation.
2141
2142const AutofillMetrics& AutofillDialogControllerImpl::GetMetricLogger() const {
2143  return metric_logger_;
2144}
2145
2146DialogType AutofillDialogControllerImpl::GetDialogType() const {
2147  return dialog_type_;
2148}
2149
2150std::string AutofillDialogControllerImpl::GetRiskData() const {
2151  DCHECK(!risk_data_.empty());
2152  return risk_data_;
2153}
2154
2155std::string AutofillDialogControllerImpl::GetWalletCookieValue() const {
2156  return wallet_cookie_value_;
2157}
2158
2159bool AutofillDialogControllerImpl::IsShippingAddressRequired() const {
2160  return cares_about_shipping_;
2161}
2162
2163void AutofillDialogControllerImpl::OnDidAcceptLegalDocuments() {
2164  DCHECK(is_submitting_ && IsPayingWithWallet());
2165  has_accepted_legal_documents_ = true;
2166  LoadRiskFingerprintData();
2167}
2168
2169void AutofillDialogControllerImpl::OnDidAuthenticateInstrument(bool success) {
2170  DCHECK(is_submitting_ && IsPayingWithWallet());
2171
2172  // TODO(dbeam): use the returned full wallet. b/8332329
2173  if (success) {
2174    GetFullWallet();
2175  } else {
2176    DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2177    SuggestionsUpdated();
2178  }
2179}
2180
2181void AutofillDialogControllerImpl::OnDidGetFullWallet(
2182    scoped_ptr<wallet::FullWallet> full_wallet) {
2183  DCHECK(is_submitting_ && IsPayingWithWallet());
2184
2185  full_wallet_ = full_wallet.Pass();
2186
2187  if (full_wallet_->required_actions().empty()) {
2188    UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_PROXY_CARD,
2189                           AUTOCHECKOUT_STEP_COMPLETED);
2190    FinishSubmit();
2191    return;
2192  }
2193
2194  SetAutocheckoutState(AUTOCHECKOUT_NOT_STARTED);
2195
2196  switch (full_wallet_->required_actions()[0]) {
2197    case wallet::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS:
2198      choose_another_instrument_or_address_ = true;
2199      SetIsSubmitting(false);
2200      GetWalletItems();
2201      view_->UpdateNotificationArea();
2202      view_->UpdateButtonStrip();
2203      break;
2204
2205    case wallet::VERIFY_CVV:
2206      SuggestionsUpdated();
2207      break;
2208
2209    default:
2210      DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2211      break;
2212  }
2213}
2214
2215void AutofillDialogControllerImpl::OnPassiveSigninSuccess(
2216    const std::string& username) {
2217  const string16 username16 = UTF8ToUTF16(username);
2218  signin_helper_->StartWalletCookieValueFetch();
2219  account_chooser_model_.SetActiveWalletAccountName(username16);
2220}
2221
2222void AutofillDialogControllerImpl::OnUserNameFetchSuccess(
2223    const std::string& username) {
2224  const string16 username16 = UTF8ToUTF16(username);
2225  signin_helper_.reset();
2226  account_chooser_model_.SetActiveWalletAccountName(username16);
2227  OnWalletOrSigninUpdate();
2228}
2229
2230void AutofillDialogControllerImpl::OnPassiveSigninFailure(
2231    const GoogleServiceAuthError& error) {
2232  // TODO(aruslan): report an error.
2233  LOG(ERROR) << "failed to passively sign in: " << error.ToString();
2234  OnWalletSigninError();
2235}
2236
2237void AutofillDialogControllerImpl::OnUserNameFetchFailure(
2238    const GoogleServiceAuthError& error) {
2239  // TODO(aruslan): report an error.
2240  LOG(ERROR) << "failed to fetch the user account name: " << error.ToString();
2241  OnWalletSigninError();
2242}
2243
2244void AutofillDialogControllerImpl::OnDidFetchWalletCookieValue(
2245    const std::string& cookie_value) {
2246  wallet_cookie_value_ = cookie_value;
2247  signin_helper_.reset();
2248  GetWalletItems();
2249}
2250
2251void AutofillDialogControllerImpl::OnDidGetWalletItems(
2252    scoped_ptr<wallet::WalletItems> wallet_items) {
2253  legal_documents_text_.clear();
2254  legal_document_link_ranges_.clear();
2255  has_accepted_legal_documents_ = false;
2256
2257  wallet_items_ = wallet_items.Pass();
2258  OnWalletOrSigninUpdate();
2259}
2260
2261void AutofillDialogControllerImpl::OnDidSaveToWallet(
2262    const std::string& instrument_id,
2263    const std::string& address_id,
2264    const std::vector<wallet::RequiredAction>& required_actions,
2265    const std::vector<wallet::FormFieldError>& form_field_errors) {
2266  DCHECK(is_submitting_ && IsPayingWithWallet());
2267
2268  if (required_actions.empty()) {
2269    if (!address_id.empty())
2270      active_address_id_ = address_id;
2271    if (!instrument_id.empty())
2272      active_instrument_id_ = instrument_id;
2273    GetFullWallet();
2274  } else {
2275    OnWalletFormFieldError(form_field_errors);
2276    HandleSaveOrUpdateRequiredActions(required_actions);
2277  }
2278}
2279
2280void AutofillDialogControllerImpl::OnWalletError(
2281    wallet::WalletClient::ErrorType error_type) {
2282  DisableWallet(error_type);
2283}
2284
2285////////////////////////////////////////////////////////////////////////////////
2286// PersonalDataManagerObserver implementation.
2287
2288void AutofillDialogControllerImpl::OnPersonalDataChanged() {
2289  if (is_submitting_)
2290    return;
2291
2292  SuggestionsUpdated();
2293}
2294
2295////////////////////////////////////////////////////////////////////////////////
2296// AccountChooserModelDelegate implementation.
2297
2298void AutofillDialogControllerImpl::AccountChoiceChanged() {
2299  if (is_submitting_)
2300    GetWalletClient()->CancelRequests();
2301
2302  SetIsSubmitting(false);
2303
2304  SuggestionsUpdated();
2305  UpdateAccountChooserView();
2306}
2307
2308void AutofillDialogControllerImpl::UpdateAccountChooserView() {
2309  if (view_) {
2310    view_->UpdateAccountChooser();
2311    view_->UpdateNotificationArea();
2312  }
2313}
2314
2315////////////////////////////////////////////////////////////////////////////////
2316
2317bool AutofillDialogControllerImpl::HandleKeyPressEventInInput(
2318    const content::NativeWebKeyboardEvent& event) {
2319  if (popup_controller_.get())
2320    return popup_controller_->HandleKeyPressEvent(event);
2321
2322  return false;
2323}
2324
2325bool AutofillDialogControllerImpl::RequestingCreditCardInfo() const {
2326  DCHECK_GT(form_structure_.field_count(), 0U);
2327
2328  for (size_t i = 0; i < form_structure_.field_count(); ++i) {
2329    if (IsCreditCardType(form_structure_.field(i)->Type().server_type()))
2330      return true;
2331  }
2332
2333  return false;
2334}
2335
2336bool AutofillDialogControllerImpl::TransmissionWillBeSecure() const {
2337  return source_url_.SchemeIs(chrome::kHttpsScheme);
2338}
2339
2340AutofillDialogControllerImpl::AutofillDialogControllerImpl(
2341    content::WebContents* contents,
2342    const FormData& form_structure,
2343    const GURL& source_url,
2344    const DialogType dialog_type,
2345    const base::Callback<void(const FormStructure*,
2346                              const std::string&)>& callback)
2347    : profile_(Profile::FromBrowserContext(contents->GetBrowserContext())),
2348      contents_(contents),
2349      initial_user_state_(AutofillMetrics::DIALOG_USER_STATE_UNKNOWN),
2350      dialog_type_(dialog_type),
2351      form_structure_(form_structure, std::string()),
2352      invoked_from_same_origin_(true),
2353      source_url_(source_url),
2354      callback_(callback),
2355      account_chooser_model_(this, profile_->GetPrefs(), metric_logger_,
2356                             dialog_type),
2357      wallet_client_(profile_->GetRequestContext(), this),
2358      suggested_email_(this),
2359      suggested_cc_(this),
2360      suggested_billing_(this),
2361      suggested_cc_billing_(this),
2362      suggested_shipping_(this),
2363      cares_about_shipping_(true),
2364      input_showing_popup_(NULL),
2365      weak_ptr_factory_(this),
2366      should_show_wallet_promo_(!profile_->GetPrefs()->GetBoolean(
2367          ::prefs::kAutofillDialogHasPaidWithWallet)),
2368      has_shown_wallet_usage_confirmation_(false),
2369      has_accepted_legal_documents_(false),
2370      is_submitting_(false),
2371      choose_another_instrument_or_address_(false),
2372      wallet_server_validation_recoverable_(true),
2373      data_was_passed_back_(false),
2374      autocheckout_state_(AUTOCHECKOUT_NOT_STARTED),
2375      was_ui_latency_logged_(false),
2376      deemphasized_render_view_(false) {
2377  // TODO(estade): remove duplicates from |form_structure|?
2378  DCHECK(!callback_.is_null());
2379}
2380
2381AutofillDialogView* AutofillDialogControllerImpl::CreateView() {
2382  return AutofillDialogView::Create(this);
2383}
2384
2385PersonalDataManager* AutofillDialogControllerImpl::GetManager() {
2386  return PersonalDataManagerFactory::GetForProfile(profile_);
2387}
2388
2389wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient() {
2390  return &wallet_client_;
2391}
2392
2393bool AutofillDialogControllerImpl::IsPayingWithWallet() const {
2394  return account_chooser_model_.WalletIsSelected() &&
2395         SignedInState() == SIGNED_IN;
2396}
2397
2398void AutofillDialogControllerImpl::LoadRiskFingerprintData() {
2399  risk_data_.clear();
2400
2401  uint64 obfuscated_gaia_id = 0;
2402  bool success = base::StringToUint64(wallet_items_->obfuscated_gaia_id(),
2403                                      &obfuscated_gaia_id);
2404  DCHECK(success);
2405
2406  gfx::Rect window_bounds;
2407#if !defined(OS_ANDROID)
2408  window_bounds = GetBaseWindowForWebContents(web_contents())->GetBounds();
2409#endif
2410
2411  PrefService* user_prefs = profile_->GetPrefs();
2412  std::string charset = user_prefs->GetString(::prefs::kDefaultCharset);
2413  std::string accept_languages =
2414      user_prefs->GetString(::prefs::kAcceptLanguages);
2415  base::Time install_time = base::Time::FromTimeT(
2416      g_browser_process->local_state()->GetInt64(::prefs::kInstallDate));
2417
2418  risk::GetFingerprint(
2419      obfuscated_gaia_id, window_bounds, *web_contents(),
2420      chrome::VersionInfo().Version(), charset, accept_languages, install_time,
2421      dialog_type_, g_browser_process->GetApplicationLocale(),
2422      base::Bind(&AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData,
2423                 weak_ptr_factory_.GetWeakPtr()));
2424}
2425
2426void AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData(
2427    scoped_ptr<risk::Fingerprint> fingerprint) {
2428  DCHECK(AreLegalDocumentsCurrent());
2429
2430  std::string proto_data;
2431  fingerprint->SerializeToString(&proto_data);
2432  bool success = base::Base64Encode(proto_data, &risk_data_);
2433  DCHECK(success);
2434
2435  SubmitWithWallet();
2436}
2437
2438void AutofillDialogControllerImpl::OpenTabWithUrl(const GURL& url) {
2439#if !defined(OS_ANDROID)
2440  chrome::NavigateParams params(
2441      chrome::FindBrowserWithWebContents(web_contents()),
2442      url,
2443      content::PAGE_TRANSITION_AUTO_BOOKMARK);
2444  params.disposition = NEW_FOREGROUND_TAB;
2445  chrome::Navigate(&params);
2446#endif
2447}
2448
2449bool AutofillDialogControllerImpl::IsEditingExistingData(
2450    DialogSection section) const {
2451  return section_editing_state_.count(section) > 0;
2452}
2453
2454bool AutofillDialogControllerImpl::IsManuallyEditingSection(
2455    DialogSection section) const {
2456  return IsEditingExistingData(section) ||
2457         SuggestionsMenuModelForSection(section)->
2458             GetItemKeyForCheckedItem() == kAddNewItemKey;
2459}
2460
2461void AutofillDialogControllerImpl::OnWalletSigninError() {
2462  signin_helper_.reset();
2463  account_chooser_model_.SetHadWalletSigninError();
2464  GetWalletClient()->CancelRequests();
2465  LogDialogLatencyToShow();
2466}
2467
2468void AutofillDialogControllerImpl::DisableWallet(
2469    wallet::WalletClient::ErrorType error_type) {
2470  signin_helper_.reset();
2471  wallet_items_.reset();
2472  wallet_errors_.clear();
2473  GetWalletClient()->CancelRequests();
2474  SetAutocheckoutState(AUTOCHECKOUT_NOT_STARTED);
2475  for (std::vector<DialogAutocheckoutStep>::iterator it = steps_.begin();
2476      it != steps_.end(); ++it) {
2477    if (it->type() == AUTOCHECKOUT_STEP_PROXY_CARD) {
2478      steps_.erase(it);
2479      break;
2480    }
2481  }
2482  SetIsSubmitting(false);
2483  account_chooser_model_.SetHadWalletError(WalletErrorMessage(error_type));
2484}
2485
2486void AutofillDialogControllerImpl::SuggestionsUpdated() {
2487  const DetailOutputMap snapshot = TakeUserInputSnapshot();
2488
2489  suggested_email_.Reset();
2490  suggested_cc_.Reset();
2491  suggested_billing_.Reset();
2492  suggested_cc_billing_.Reset();
2493  suggested_shipping_.Reset();
2494  HidePopup();
2495
2496  suggested_shipping_.AddKeyedItem(
2497      kSameAsBillingKey,
2498      l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_USE_BILLING_FOR_SHIPPING));
2499
2500  if (IsPayingWithWallet()) {
2501    if (!account_chooser_model_.active_wallet_account_name().empty()) {
2502      suggested_email_.AddKeyedItem(
2503          base::IntToString(0),
2504          account_chooser_model_.active_wallet_account_name());
2505    }
2506
2507    const std::vector<wallet::Address*>& addresses =
2508        wallet_items_->addresses();
2509    for (size_t i = 0; i < addresses.size(); ++i) {
2510      std::string key = base::IntToString(i);
2511      suggested_shipping_.AddKeyedItemWithSublabel(
2512          key,
2513          addresses[i]->DisplayName(),
2514          addresses[i]->DisplayNameDetail());
2515
2516      const std::string default_shipping_address_id =
2517          !previously_selected_shipping_address_id_.empty() ?
2518              previously_selected_shipping_address_id_ :
2519              wallet_items_->default_address_id();
2520      if (addresses[i]->object_id() == default_shipping_address_id)
2521        suggested_shipping_.SetCheckedItem(key);
2522    }
2523    previously_selected_shipping_address_id_.clear();
2524
2525    if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2526      const std::vector<wallet::WalletItems::MaskedInstrument*>& instruments =
2527          wallet_items_->instruments();
2528      std::string first_active_instrument_key;
2529      std::string default_instrument_key;
2530      for (size_t i = 0; i < instruments.size(); ++i) {
2531        bool allowed = IsInstrumentAllowed(*instruments[i]);
2532        gfx::Image icon = instruments[i]->CardIcon();
2533        if (!allowed && !icon.IsEmpty()) {
2534          // Create a grayed disabled icon.
2535          SkBitmap disabled_bitmap = SkBitmapOperations::CreateHSLShiftedBitmap(
2536              *icon.ToSkBitmap(), kGrayImageShift);
2537          icon = gfx::Image(
2538              gfx::ImageSkia::CreateFrom1xBitmap(disabled_bitmap));
2539        }
2540        std::string key = base::IntToString(i);
2541        suggested_cc_billing_.AddKeyedItemWithSublabelAndIcon(
2542            key,
2543            instruments[i]->DisplayName(),
2544            instruments[i]->DisplayNameDetail(),
2545            icon);
2546        suggested_cc_billing_.SetEnabled(key, allowed);
2547
2548        if (allowed) {
2549          if (first_active_instrument_key.empty())
2550            first_active_instrument_key = key;
2551
2552          const std::string default_instrument_id =
2553              !previously_selected_instrument_id_.empty() ?
2554                  previously_selected_instrument_id_ :
2555                  wallet_items_->default_instrument_id();
2556          if (instruments[i]->object_id() == default_instrument_id)
2557            default_instrument_key = key;
2558        }
2559      }
2560      previously_selected_instrument_id_.clear();
2561
2562      // TODO(estade): this should have a URL sublabel.
2563      suggested_cc_billing_.AddKeyedItem(
2564          kAddNewItemKey,
2565          l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_DETAILS));
2566      if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
2567        suggested_cc_billing_.AddKeyedItemWithSublabel(
2568            kManageItemsKey,
2569            l10n_util::GetStringUTF16(
2570                IDS_AUTOFILL_DIALOG_MANAGE_BILLING_DETAILS),
2571                UTF8ToUTF16(wallet::GetManageInstrumentsUrl().host()));
2572      }
2573
2574      // Determine which instrument item should be selected.
2575      if (!default_instrument_key.empty())
2576        suggested_cc_billing_.SetCheckedItem(default_instrument_key);
2577      else if (!first_active_instrument_key.empty())
2578        suggested_cc_billing_.SetCheckedItem(first_active_instrument_key);
2579      else
2580        suggested_cc_billing_.SetCheckedItem(kAddNewItemKey);
2581    }
2582  } else {
2583    PersonalDataManager* manager = GetManager();
2584    const std::vector<CreditCard*>& cards = manager->GetCreditCards();
2585    ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
2586    for (size_t i = 0; i < cards.size(); ++i) {
2587      if (!HasCompleteAndVerifiedData(*cards[i], requested_cc_fields_))
2588        continue;
2589
2590      suggested_cc_.AddKeyedItemWithIcon(
2591          cards[i]->guid(),
2592          cards[i]->Label(),
2593          rb.GetImageNamed(CreditCard::IconResourceId(cards[i]->type())));
2594    }
2595
2596    const std::vector<AutofillProfile*>& profiles = manager->GetProfiles();
2597    const std::string app_locale = g_browser_process->GetApplicationLocale();
2598    for (size_t i = 0; i < profiles.size(); ++i) {
2599      if (!HasCompleteAndVerifiedData(*profiles[i],
2600                                      requested_shipping_fields_) ||
2601          HasInvalidAddress(*profiles[i])) {
2602        continue;
2603      }
2604
2605      // Add all email addresses.
2606      std::vector<string16> values;
2607      profiles[i]->GetMultiInfo(
2608          AutofillType(EMAIL_ADDRESS), app_locale, &values);
2609      for (size_t j = 0; j < values.size(); ++j) {
2610        if (IsValidEmailAddress(values[j]))
2611          suggested_email_.AddKeyedItem(profiles[i]->guid(), values[j]);
2612      }
2613
2614      // Don't add variants for addresses: the email variants are handled above,
2615      // name is part of credit card and we'll just ignore phone number
2616      // variants.
2617      suggested_billing_.AddKeyedItem(profiles[i]->guid(),
2618                                      profiles[i]->Label());
2619      suggested_shipping_.AddKeyedItem(profiles[i]->guid(),
2620                                       profiles[i]->Label());
2621    }
2622
2623    suggested_cc_.AddKeyedItem(
2624        kAddNewItemKey,
2625        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_CREDIT_CARD));
2626    suggested_cc_.AddKeyedItem(
2627        kManageItemsKey,
2628        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_CREDIT_CARD));
2629    suggested_billing_.AddKeyedItem(
2630        kAddNewItemKey,
2631        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_ADDRESS));
2632    suggested_billing_.AddKeyedItem(
2633        kManageItemsKey,
2634        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_BILLING_ADDRESS));
2635  }
2636
2637  suggested_email_.AddKeyedItem(
2638      kAddNewItemKey,
2639      l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_EMAIL_ADDRESS));
2640  if (!IsPayingWithWallet()) {
2641    suggested_email_.AddKeyedItem(
2642        kManageItemsKey,
2643        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_EMAIL_ADDRESS));
2644  }
2645
2646  suggested_shipping_.AddKeyedItem(
2647      kAddNewItemKey,
2648      l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_SHIPPING_ADDRESS));
2649  if (!IsPayingWithWallet()) {
2650    suggested_shipping_.AddKeyedItem(
2651        kManageItemsKey,
2652        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS));
2653  } else if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
2654    suggested_shipping_.AddKeyedItemWithSublabel(
2655        kManageItemsKey,
2656        l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS),
2657        UTF8ToUTF16(wallet::GetManageAddressesUrl().host()));
2658  }
2659
2660  if (!IsPayingWithWallet()) {
2661    for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2662      DialogSection section = static_cast<DialogSection>(i);
2663      if (!SectionIsActive(section))
2664        continue;
2665
2666      // Set the starting choice for the menu. First set to the default in case
2667      // the GUID saved in prefs refers to a profile that no longer exists.
2668      std::string guid;
2669      int variant;
2670      GetDefaultAutofillChoice(section, &guid, &variant);
2671      SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
2672      model->SetCheckedItemNthWithKey(guid, variant + 1);
2673      if (GetAutofillChoice(section, &guid, &variant))
2674        model->SetCheckedItemNthWithKey(guid, variant + 1);
2675    }
2676  }
2677
2678  if (view_)
2679    view_->ModelChanged();
2680
2681  for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2682    ResetSectionInput(static_cast<DialogSection>(i));
2683  }
2684
2685  RestoreUserInputFromSnapshot(snapshot);
2686
2687  for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2688    DialogSection section = static_cast<DialogSection>(i);
2689    ShowEditUiIfBadSuggestion(section);
2690    UpdateSection(section);
2691  }
2692
2693  UpdateForErrors();
2694}
2695
2696void AutofillDialogControllerImpl::FillOutputForSectionWithComparator(
2697    DialogSection section,
2698    const InputFieldComparator& compare) {
2699  const DetailInputs& inputs = RequestedFieldsForSection(section);
2700
2701  // Email is hidden while using Wallet, special case it.
2702  if (section == SECTION_EMAIL && IsPayingWithWallet()) {
2703    AutofillProfile profile;
2704    profile.SetRawInfo(EMAIL_ADDRESS,
2705                       account_chooser_model_.active_wallet_account_name());
2706    AutofillProfileWrapper profile_wrapper(&profile, 0);
2707    profile_wrapper.FillFormStructure(inputs, compare, &form_structure_);
2708    return;
2709  }
2710
2711  if (!SectionIsActive(section))
2712    return;
2713
2714  scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
2715  if (wrapper) {
2716    // Only fill in data that is associated with this section.
2717    const DetailInputs& inputs = RequestedFieldsForSection(section);
2718    wrapper->FillFormStructure(inputs, compare, &form_structure_);
2719
2720    // CVC needs special-casing because the CreditCard class doesn't store or
2721    // handle them. This isn't necessary when filling the combined CC and
2722    // billing section as CVC comes from |full_wallet_| in this case.
2723    if (section == SECTION_CC)
2724      SetCvcResult(view_->GetCvc());
2725  } else {
2726    // The user manually input data. If using Autofill, save the info as new or
2727    // edited data. Always fill local data into |form_structure_|.
2728    DetailOutputMap output;
2729    view_->GetUserInput(section, &output);
2730
2731    if (section == SECTION_CC) {
2732      CreditCard card;
2733      card.set_origin(kAutofillDialogOrigin);
2734      FillFormGroupFromOutputs(output, &card);
2735
2736      // The card holder name comes from the billing address section.
2737      card.SetRawInfo(CREDIT_CARD_NAME,
2738                      GetValueFromSection(SECTION_BILLING, NAME_FULL));
2739
2740      if (ShouldSaveDetailsLocally()) {
2741        GetManager()->SaveImportedCreditCard(card);
2742        DCHECK(!profile()->IsOffTheRecord());
2743        newly_saved_card_.reset(new CreditCard(card));
2744      }
2745
2746      AutofillCreditCardWrapper card_wrapper(&card);
2747      card_wrapper.FillFormStructure(inputs, compare, &form_structure_);
2748
2749      // Again, CVC needs special-casing. Fill it in directly from |output|.
2750      SetCvcResult(GetValueForType(output, CREDIT_CARD_VERIFICATION_CODE));
2751    } else {
2752      AutofillProfile profile;
2753      profile.set_origin(kAutofillDialogOrigin);
2754      FillFormGroupFromOutputs(output, &profile);
2755
2756      // For billing, the email address comes from the separate email section.
2757      if (section == SECTION_BILLING) {
2758        profile.SetRawInfo(EMAIL_ADDRESS,
2759                           GetValueFromSection(SECTION_EMAIL, EMAIL_ADDRESS));
2760      }
2761
2762      if (ShouldSaveDetailsLocally())
2763        SaveProfileGleanedFromSection(profile, section);
2764
2765      AutofillProfileWrapper profile_wrapper(&profile, 0);
2766      profile_wrapper.FillFormStructure(inputs, compare, &form_structure_);
2767    }
2768  }
2769}
2770
2771void AutofillDialogControllerImpl::FillOutputForSection(DialogSection section) {
2772  FillOutputForSectionWithComparator(
2773      section, base::Bind(DetailInputMatchesField, section));
2774}
2775
2776bool AutofillDialogControllerImpl::FormStructureCaresAboutSection(
2777    DialogSection section) const {
2778  // For now, only SECTION_SHIPPING may be omitted due to a site not asking for
2779  // any of the fields.
2780  if (section == SECTION_SHIPPING)
2781    return cares_about_shipping_;
2782
2783  return true;
2784}
2785
2786void AutofillDialogControllerImpl::SetCvcResult(const string16& cvc) {
2787  for (size_t i = 0; i < form_structure_.field_count(); ++i) {
2788    AutofillField* field = form_structure_.field(i);
2789    if (field->Type().server_type() == CREDIT_CARD_VERIFICATION_CODE) {
2790      field->value = cvc;
2791      break;
2792    }
2793  }
2794}
2795
2796string16 AutofillDialogControllerImpl::GetValueFromSection(
2797    DialogSection section,
2798    ServerFieldType type) {
2799  DCHECK(SectionIsActive(section));
2800
2801  scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
2802  if (wrapper)
2803    return wrapper->GetInfo(AutofillType(type));
2804
2805  DetailOutputMap output;
2806  view_->GetUserInput(section, &output);
2807  for (DetailOutputMap::iterator iter = output.begin(); iter != output.end();
2808       ++iter) {
2809    if (iter->first->type == type)
2810      return iter->second;
2811  }
2812
2813  return string16();
2814}
2815
2816void AutofillDialogControllerImpl::SaveProfileGleanedFromSection(
2817    const AutofillProfile& profile,
2818    DialogSection section) {
2819  if (section == SECTION_EMAIL) {
2820    // Save the email address to the existing (suggested) billing profile. If
2821    // there is no existing profile, the newly created one will pick up this
2822    // email, so in that case do nothing.
2823    scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(SECTION_BILLING);
2824    if (wrapper) {
2825      std::string item_key = SuggestionsMenuModelForSection(SECTION_BILLING)->
2826          GetItemKeyForCheckedItem();
2827      AutofillProfile* billing_profile =
2828          GetManager()->GetProfileByGUID(item_key);
2829      billing_profile->OverwriteWithOrAddTo(
2830          profile,
2831          g_browser_process->GetApplicationLocale());
2832    }
2833  } else {
2834    GetManager()->SaveImportedProfile(profile);
2835  }
2836}
2837
2838SuggestionsMenuModel* AutofillDialogControllerImpl::
2839    SuggestionsMenuModelForSection(DialogSection section) {
2840  switch (section) {
2841    case SECTION_EMAIL:
2842      return &suggested_email_;
2843    case SECTION_CC:
2844      return &suggested_cc_;
2845    case SECTION_BILLING:
2846      return &suggested_billing_;
2847    case SECTION_SHIPPING:
2848      return &suggested_shipping_;
2849    case SECTION_CC_BILLING:
2850      return &suggested_cc_billing_;
2851  }
2852
2853  NOTREACHED();
2854  return NULL;
2855}
2856
2857const SuggestionsMenuModel* AutofillDialogControllerImpl::
2858    SuggestionsMenuModelForSection(DialogSection section) const {
2859  return const_cast<AutofillDialogControllerImpl*>(this)->
2860      SuggestionsMenuModelForSection(section);
2861}
2862
2863DialogSection AutofillDialogControllerImpl::SectionForSuggestionsMenuModel(
2864    const SuggestionsMenuModel& model) {
2865  if (&model == &suggested_email_)
2866    return SECTION_EMAIL;
2867
2868  if (&model == &suggested_cc_)
2869    return SECTION_CC;
2870
2871  if (&model == &suggested_billing_)
2872    return SECTION_BILLING;
2873
2874  if (&model == &suggested_cc_billing_)
2875    return SECTION_CC_BILLING;
2876
2877  DCHECK_EQ(&model, &suggested_shipping_);
2878  return SECTION_SHIPPING;
2879}
2880
2881DetailInputs* AutofillDialogControllerImpl::MutableRequestedFieldsForSection(
2882    DialogSection section) {
2883  return const_cast<DetailInputs*>(&RequestedFieldsForSection(section));
2884}
2885
2886void AutofillDialogControllerImpl::HidePopup() {
2887  if (popup_controller_.get())
2888    popup_controller_->Hide();
2889  input_showing_popup_ = NULL;
2890}
2891
2892void AutofillDialogControllerImpl::SetEditingExistingData(
2893    DialogSection section, bool editing) {
2894  if (editing)
2895    section_editing_state_.insert(section);
2896  else
2897    section_editing_state_.erase(section);
2898}
2899
2900bool AutofillDialogControllerImpl::IsASuggestionItemKey(
2901    const std::string& key) const {
2902  return !key.empty() &&
2903      key != kAddNewItemKey &&
2904      key != kManageItemsKey &&
2905      key != kSameAsBillingKey;
2906}
2907
2908bool AutofillDialogControllerImpl::IsManuallyEditingAnySection() const {
2909  for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
2910    if (IsManuallyEditingSection(static_cast<DialogSection>(section)))
2911      return true;
2912  }
2913  return false;
2914}
2915
2916base::string16 AutofillDialogControllerImpl::CreditCardNumberValidityMessage(
2917    const base::string16& number) const {
2918  if (!number.empty() && !autofill::IsValidCreditCardNumber(number)) {
2919    return l10n_util::GetStringUTF16(
2920        IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_NUMBER);
2921  }
2922
2923  // Wallet only accepts MasterCard, Visa and Discover. No AMEX.
2924  if (IsPayingWithWallet() &&
2925      !IsWalletSupportedCard(CreditCard::GetCreditCardType(number))) {
2926    return l10n_util::GetStringUTF16(
2927        IDS_AUTOFILL_DIALOG_VALIDATION_CREDIT_CARD_NOT_SUPPORTED_BY_WALLET);
2928  }
2929
2930  // Card number is good and supported.
2931  return base::string16();
2932}
2933
2934bool AutofillDialogControllerImpl::InputIsEditable(
2935    const DetailInput& input,
2936    DialogSection section) const {
2937  if (input.type != CREDIT_CARD_NUMBER || !IsPayingWithWallet())
2938    return true;
2939
2940  if (IsEditingExistingData(section))
2941    return false;
2942
2943  return true;
2944}
2945
2946bool AutofillDialogControllerImpl::AllSectionsAreValid() {
2947  for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
2948    if (!SectionIsValid(static_cast<DialogSection>(section)))
2949      return false;
2950  }
2951  return true;
2952}
2953
2954bool AutofillDialogControllerImpl::SectionIsValid(
2955    DialogSection section) {
2956  if (!IsManuallyEditingSection(section))
2957    return true;
2958
2959  DetailOutputMap detail_outputs;
2960  view_->GetUserInput(section, &detail_outputs);
2961  return InputsAreValid(section, detail_outputs, VALIDATE_EDIT).empty();
2962}
2963
2964bool AutofillDialogControllerImpl::IsCreditCardExpirationValid(
2965    const base::string16& year,
2966    const base::string16& month) const {
2967  // If the expiration is in the past as per the local clock, it's invalid.
2968  base::Time now = base::Time::Now();
2969  if (!autofill::IsValidCreditCardExpirationDate(year, month, now))
2970    return false;
2971
2972  if (IsPayingWithWallet() && IsEditingExistingData(SECTION_CC_BILLING)) {
2973    const wallet::WalletItems::MaskedInstrument* instrument =
2974        ActiveInstrument();
2975    const std::string& locale = g_browser_process->GetApplicationLocale();
2976    int month_int;
2977    if (base::StringToInt(month, &month_int) &&
2978        instrument->status() ==
2979            wallet::WalletItems::MaskedInstrument::EXPIRED &&
2980        year ==
2981            instrument->GetInfo(
2982                AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), locale) &&
2983        month_int == instrument->expiration_month()) {
2984      // Otherwise, if the user is editing an instrument that's deemed expired
2985      // by the Online Wallet server, mark it invalid on selection.
2986      return false;
2987    }
2988  }
2989
2990  return true;
2991}
2992
2993bool AutofillDialogControllerImpl::ShouldUseBillingForShipping() {
2994  return SectionIsActive(SECTION_SHIPPING) &&
2995      suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey;
2996}
2997
2998bool AutofillDialogControllerImpl::ShouldSaveDetailsLocally() {
2999  // It's possible that the user checked [X] Save details locally before
3000  // switching payment methods, so only ask the view whether to save details
3001  // locally if that checkbox is showing (currently if not paying with wallet).
3002  // Also, if the user isn't editing any sections, there's no data to save
3003  // locally.
3004  return ShouldOfferToSaveInChrome() && view_->SaveDetailsLocally();
3005}
3006
3007void AutofillDialogControllerImpl::SetIsSubmitting(bool submitting) {
3008  is_submitting_ = submitting;
3009
3010  if (!submitting)
3011    full_wallet_.reset();
3012
3013  if (view_) {
3014    view_->UpdateButtonStrip();
3015    view_->UpdateNotificationArea();
3016  }
3017}
3018
3019bool AutofillDialogControllerImpl::AreLegalDocumentsCurrent() const {
3020  return has_accepted_legal_documents_ ||
3021      (wallet_items_ && wallet_items_->legal_documents().empty());
3022}
3023
3024void AutofillDialogControllerImpl::AcceptLegalDocuments() {
3025  content::BrowserThread::PostTask(
3026      content::BrowserThread::IO, FROM_HERE,
3027      base::Bind(&UserDidOptIntoLocationServices));
3028
3029  GetWalletClient()->AcceptLegalDocuments(
3030      wallet_items_->legal_documents(),
3031      wallet_items_->google_transaction_id(),
3032      source_url_);
3033
3034  if (AreLegalDocumentsCurrent())
3035    LoadRiskFingerprintData();
3036}
3037
3038void AutofillDialogControllerImpl::SubmitWithWallet() {
3039  active_instrument_id_.clear();
3040  active_address_id_.clear();
3041  full_wallet_.reset();
3042
3043  const wallet::WalletItems::MaskedInstrument* active_instrument =
3044      ActiveInstrument();
3045  if (!IsManuallyEditingSection(SECTION_CC_BILLING)) {
3046    active_instrument_id_ = active_instrument->object_id();
3047    DCHECK(!active_instrument_id_.empty());
3048  }
3049
3050  const wallet::Address* active_address = ActiveShippingAddress();
3051  if (!IsManuallyEditingSection(SECTION_SHIPPING) &&
3052      !ShouldUseBillingForShipping() &&
3053      IsShippingAddressRequired()) {
3054    active_address_id_ = active_address->object_id();
3055    DCHECK(!active_address_id_.empty());
3056  }
3057
3058  if (GetDialogType() == DIALOG_TYPE_AUTOCHECKOUT) {
3059    DCHECK_EQ(AUTOCHECKOUT_NOT_STARTED, autocheckout_state_);
3060    SetAutocheckoutState(AUTOCHECKOUT_IN_PROGRESS);
3061  }
3062
3063  scoped_ptr<wallet::Instrument> inputted_instrument =
3064      CreateTransientInstrument();
3065  if (inputted_instrument && IsEditingExistingData(SECTION_CC_BILLING)) {
3066    inputted_instrument->set_object_id(active_instrument->object_id());
3067    DCHECK(!inputted_instrument->object_id().empty());
3068  }
3069
3070  scoped_ptr<wallet::Address> inputted_address;
3071  if (active_address_id_.empty() && IsShippingAddressRequired()) {
3072    if (ShouldUseBillingForShipping()) {
3073      const wallet::Address& address = inputted_instrument ?
3074          *inputted_instrument->address() : active_instrument->address();
3075      // Try to find an exact matched shipping address and use it for shipping,
3076      // otherwise save it as a new shipping address. http://crbug.com/225442
3077      const wallet::Address* duplicated_address =
3078          FindDuplicateAddress(wallet_items_->addresses(), address);
3079      if (duplicated_address) {
3080        active_address_id_ = duplicated_address->object_id();
3081        DCHECK(!active_address_id_.empty());
3082      } else {
3083        inputted_address.reset(new wallet::Address(address));
3084        DCHECK(inputted_address->object_id().empty());
3085      }
3086    } else {
3087      inputted_address = CreateTransientAddress();
3088      if (IsEditingExistingData(SECTION_SHIPPING)) {
3089        inputted_address->set_object_id(active_address->object_id());
3090        DCHECK(!inputted_address->object_id().empty());
3091      }
3092    }
3093  }
3094
3095  // If there's neither an address nor instrument to save, |GetFullWallet()|
3096  // is called when the risk fingerprint is loaded.
3097  if (!active_instrument_id_.empty() &&
3098      (!active_address_id_.empty() || !IsShippingAddressRequired())) {
3099    GetFullWallet();
3100    return;
3101  }
3102
3103  GetWalletClient()->SaveToWallet(inputted_instrument.Pass(),
3104                                  inputted_address.Pass(),
3105                                  source_url_);
3106}
3107
3108scoped_ptr<wallet::Instrument> AutofillDialogControllerImpl::
3109    CreateTransientInstrument() {
3110  if (!active_instrument_id_.empty())
3111    return scoped_ptr<wallet::Instrument>();
3112
3113  DetailOutputMap output;
3114  view_->GetUserInput(SECTION_CC_BILLING, &output);
3115
3116  CreditCard card;
3117  AutofillProfile profile;
3118  string16 cvc;
3119  GetBillingInfoFromOutputs(output, &card, &cvc, &profile);
3120
3121  return scoped_ptr<wallet::Instrument>(
3122      new wallet::Instrument(card, cvc, profile));
3123}
3124
3125scoped_ptr<wallet::Address>AutofillDialogControllerImpl::
3126    CreateTransientAddress() {
3127  // If not using billing for shipping, just scrape the view.
3128  DetailOutputMap output;
3129  view_->GetUserInput(SECTION_SHIPPING, &output);
3130
3131  AutofillProfile profile;
3132  FillFormGroupFromOutputs(output, &profile);
3133
3134  return scoped_ptr<wallet::Address>(new wallet::Address(profile));
3135}
3136
3137void AutofillDialogControllerImpl::GetFullWallet() {
3138  DCHECK(is_submitting_);
3139  DCHECK(IsPayingWithWallet());
3140  DCHECK(wallet_items_);
3141  DCHECK(!active_instrument_id_.empty());
3142  DCHECK(!active_address_id_.empty() || !IsShippingAddressRequired());
3143
3144  std::vector<wallet::WalletClient::RiskCapability> capabilities;
3145  capabilities.push_back(wallet::WalletClient::VERIFY_CVC);
3146
3147  UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_PROXY_CARD,
3148                         AUTOCHECKOUT_STEP_STARTED);
3149
3150  GetWalletClient()->GetFullWallet(wallet::WalletClient::FullWalletRequest(
3151      active_instrument_id_,
3152      active_address_id_,
3153      source_url_,
3154      wallet_items_->google_transaction_id(),
3155      capabilities));
3156}
3157
3158void AutofillDialogControllerImpl::HandleSaveOrUpdateRequiredActions(
3159    const std::vector<wallet::RequiredAction>& required_actions) {
3160  DCHECK(!required_actions.empty());
3161
3162  // TODO(ahutter): Invesitigate if we need to support more generic actions on
3163  // this call such as GAIA_AUTH. See crbug.com/243457.
3164  for (std::vector<wallet::RequiredAction>::const_iterator iter =
3165           required_actions.begin();
3166       iter != required_actions.end(); ++iter) {
3167    if (*iter != wallet::INVALID_FORM_FIELD) {
3168      // TODO(dbeam): handle this more gracefully.
3169      DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
3170    }
3171  }
3172  SetAutocheckoutState(AUTOCHECKOUT_NOT_STARTED);
3173  SetIsSubmitting(false);
3174}
3175
3176void AutofillDialogControllerImpl::FinishSubmit() {
3177  if (IsPayingWithWallet() &&
3178      !profile_->GetPrefs()->GetBoolean(
3179          ::prefs::kAutofillDialogHasPaidWithWallet)) {
3180    if (GetDialogType() == DIALOG_TYPE_REQUEST_AUTOCOMPLETE) {
3181      // To get past this point, the view must call back OverlayButtonPressed.
3182#if defined(TOOLKIT_VIEWS)
3183      view_->UpdateButtonStrip();
3184#else
3185      // TODO(estade): implement overlays on other platforms.
3186      OverlayButtonPressed();
3187#endif
3188      return;
3189    } else {
3190      profile_->GetPrefs()->SetBoolean(
3191        ::prefs::kAutofillDialogHasPaidWithWallet, true);
3192    }
3193  }
3194
3195  FillOutputForSection(SECTION_EMAIL);
3196  FillOutputForSection(SECTION_CC);
3197  FillOutputForSection(SECTION_BILLING);
3198  FillOutputForSection(SECTION_CC_BILLING);
3199
3200  if (ShouldUseBillingForShipping()) {
3201    FillOutputForSectionWithComparator(
3202        SECTION_BILLING,
3203        base::Bind(DetailInputMatchesShippingField));
3204    FillOutputForSectionWithComparator(
3205        SECTION_CC,
3206        base::Bind(DetailInputMatchesShippingField));
3207    FillOutputForSectionWithComparator(
3208        SECTION_CC_BILLING,
3209        base::Bind(DetailInputMatchesShippingField));
3210  } else {
3211    FillOutputForSection(SECTION_SHIPPING);
3212  }
3213
3214  if (!IsPayingWithWallet()) {
3215    for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3216      DialogSection section = static_cast<DialogSection>(i);
3217      if (!SectionIsActive(section))
3218        continue;
3219
3220      SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3221      std::string item_key = model->GetItemKeyForCheckedItem();
3222      if (IsASuggestionItemKey(item_key) || item_key == kSameAsBillingKey) {
3223        int variant = GetSelectedVariantForModel(*model);
3224        PersistAutofillChoice(section, item_key, variant);
3225      }
3226    }
3227  }
3228
3229  // On a successful submit, if the user manually selected "pay without wallet",
3230  // stop trying to pay with Wallet on future runs of the dialog. On the other
3231  // hand, if there was an error that prevented the user from having the choice
3232  // of using Wallet, leave the pref alone.
3233  if (!account_chooser_model_.HadWalletError() &&
3234      account_chooser_model_.HasAccountsToChoose()) {
3235    profile_->GetPrefs()->SetBoolean(
3236        ::prefs::kAutofillDialogPayWithoutWallet,
3237        !account_chooser_model_.WalletIsSelected());
3238  }
3239
3240  if (GetDialogType() == DIALOG_TYPE_AUTOCHECKOUT) {
3241    // Stop observing PersonalDataManager to avoid the dialog redrawing while
3242    // in an Autocheckout flow.
3243    GetManager()->RemoveObserver(this);
3244    autocheckout_started_timestamp_ = base::Time::Now();
3245    SetAutocheckoutState(AUTOCHECKOUT_IN_PROGRESS);
3246  }
3247
3248  LogOnFinishSubmitMetrics();
3249
3250  // Callback should be called as late as possible.
3251  callback_.Run(&form_structure_, !wallet_items_ ? std::string() :
3252      wallet_items_->google_transaction_id());
3253  data_was_passed_back_ = true;
3254
3255  // This might delete us.
3256  if (GetDialogType() == DIALOG_TYPE_REQUEST_AUTOCOMPLETE)
3257    Hide();
3258}
3259
3260void AutofillDialogControllerImpl::PersistAutofillChoice(
3261    DialogSection section,
3262    const std::string& guid,
3263    int variant) {
3264  DCHECK(!IsPayingWithWallet());
3265  scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
3266  value->SetString(kGuidPrefKey, guid);
3267  value->SetInteger(kVariantPrefKey, variant);
3268
3269  DictionaryPrefUpdate updater(profile()->GetPrefs(),
3270                               ::prefs::kAutofillDialogAutofillDefault);
3271  base::DictionaryValue* autofill_choice = updater.Get();
3272  autofill_choice->Set(SectionToPrefString(section), value.release());
3273}
3274
3275void AutofillDialogControllerImpl::GetDefaultAutofillChoice(
3276    DialogSection section,
3277    std::string* guid,
3278    int* variant) {
3279  DCHECK(!IsPayingWithWallet());
3280  // The default choice is the first thing in the menu that is a suggestion
3281  // item.
3282  *variant = 0;
3283  SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3284  for (int i = 0; i < model->GetItemCount(); ++i) {
3285    if (IsASuggestionItemKey(model->GetItemKeyAt(i))) {
3286      *guid = model->GetItemKeyAt(i);
3287      break;
3288    }
3289  }
3290}
3291
3292bool AutofillDialogControllerImpl::GetAutofillChoice(DialogSection section,
3293                                                     std::string* guid,
3294                                                     int* variant) {
3295  DCHECK(!IsPayingWithWallet());
3296  const base::DictionaryValue* choices = profile()->GetPrefs()->GetDictionary(
3297      ::prefs::kAutofillDialogAutofillDefault);
3298  if (!choices)
3299    return false;
3300
3301  const base::DictionaryValue* choice = NULL;
3302  if (!choices->GetDictionary(SectionToPrefString(section), &choice))
3303    return false;
3304
3305  choice->GetString(kGuidPrefKey, guid);
3306  choice->GetInteger(kVariantPrefKey, variant);
3307  return true;
3308}
3309
3310size_t AutofillDialogControllerImpl::GetSelectedVariantForModel(
3311    const SuggestionsMenuModel& model) {
3312  size_t variant = 0;
3313  // Calculate the variant by looking at how many items come from the same
3314  // data model.
3315  for (int i = model.checked_item() - 1; i >= 0; --i) {
3316    if (model.GetItemKeyAt(i) == model.GetItemKeyForCheckedItem())
3317      variant++;
3318    else
3319      break;
3320  }
3321  return variant;
3322}
3323
3324void AutofillDialogControllerImpl::LogOnFinishSubmitMetrics() {
3325  GetMetricLogger().LogDialogUiDuration(
3326      base::Time::Now() - dialog_shown_timestamp_,
3327      GetDialogType(),
3328      AutofillMetrics::DIALOG_ACCEPTED);
3329
3330  GetMetricLogger().LogDialogUiEvent(
3331      GetDialogType(), AutofillMetrics::DIALOG_UI_ACCEPTED);
3332
3333  AutofillMetrics::DialogDismissalState dismissal_state;
3334  if (!IsManuallyEditingAnySection())
3335    dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_EXISTING_DATA;
3336  else if (IsPayingWithWallet())
3337    dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_WALLET;
3338  else if (ShouldSaveDetailsLocally())
3339    dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_AUTOFILL;
3340  else
3341    dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_NO_SAVE;
3342
3343  GetMetricLogger().LogDialogDismissalState(GetDialogType(), dismissal_state);
3344}
3345
3346void AutofillDialogControllerImpl::LogOnCancelMetrics() {
3347  GetMetricLogger().LogDialogUiEvent(
3348      GetDialogType(), AutofillMetrics::DIALOG_UI_CANCELED);
3349
3350  AutofillMetrics::DialogDismissalState dismissal_state;
3351  if (!signin_registrar_.IsEmpty())
3352    dismissal_state = AutofillMetrics::DIALOG_CANCELED_DURING_SIGNIN;
3353  else if (!IsManuallyEditingAnySection())
3354    dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_EDITS;
3355  else if (AllSectionsAreValid())
3356    dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_INVALID_FIELDS;
3357  else
3358    dismissal_state = AutofillMetrics::DIALOG_CANCELED_WITH_INVALID_FIELDS;
3359
3360  GetMetricLogger().LogDialogDismissalState(GetDialogType(), dismissal_state);
3361
3362  GetMetricLogger().LogDialogUiDuration(
3363      base::Time::Now() - dialog_shown_timestamp_,
3364      GetDialogType(),
3365      AutofillMetrics::DIALOG_CANCELED);
3366}
3367
3368void AutofillDialogControllerImpl::LogSuggestionItemSelectedMetric(
3369    const SuggestionsMenuModel& model) {
3370  DialogSection section = SectionForSuggestionsMenuModel(model);
3371
3372  AutofillMetrics::DialogUiEvent dialog_ui_event;
3373  if (model.GetItemKeyForCheckedItem() == kAddNewItemKey) {
3374    // Selected to add a new item.
3375    dialog_ui_event = DialogSectionToUiItemAddedEvent(section);
3376  } else if (IsASuggestionItemKey(model.GetItemKeyForCheckedItem())) {
3377    // Selected an existing item.
3378    dialog_ui_event = DialogSectionToUiSelectionChangedEvent(section);
3379  } else {
3380    // TODO(estade): add logging for "Manage items" or "Use billing for
3381    // shipping"?
3382    return;
3383  }
3384
3385  GetMetricLogger().LogDialogUiEvent(GetDialogType(), dialog_ui_event);
3386}
3387
3388void AutofillDialogControllerImpl::LogDialogLatencyToShow() {
3389  if (was_ui_latency_logged_)
3390    return;
3391
3392  GetMetricLogger().LogDialogLatencyToShow(
3393      GetDialogType(),
3394      base::Time::Now() - dialog_shown_timestamp_);
3395  was_ui_latency_logged_ = true;
3396}
3397
3398void AutofillDialogControllerImpl::SetAutocheckoutState(
3399    AutocheckoutState autocheckout_state) {
3400  if (autocheckout_state_ == autocheckout_state)
3401    return;
3402
3403  autocheckout_state_ = autocheckout_state;
3404  if (view_) {
3405    view_->UpdateDetailArea();
3406    view_->UpdateButtonStrip();
3407    view_->UpdateAutocheckoutStepsArea();
3408    view_->UpdateNotificationArea();
3409  }
3410}
3411
3412void AutofillDialogControllerImpl::DeemphasizeRenderView() {
3413  web_contents()->GetRenderViewHost()->Send(
3414      new ChromeViewMsg_SetVisuallyDeemphasized(
3415          web_contents()->GetRenderViewHost()->GetRoutingID(), true));
3416  deemphasized_render_view_ = true;
3417}
3418
3419AutofillMetrics::DialogInitialUserStateMetric
3420    AutofillDialogControllerImpl::GetInitialUserState() const {
3421  // Consider a user to be an Autofill user if the user has any credit cards
3422  // or addresses saved. Check that the item count is greater than 2 because
3423  // an "empty" menu still has the "add new" menu item and "manage" menu item.
3424  const bool has_autofill_profiles =
3425      suggested_cc_.GetItemCount() > 2 ||
3426      suggested_billing_.GetItemCount() > 2;
3427
3428  if (SignedInState() != SIGNED_IN) {
3429    // Not signed in.
3430    return has_autofill_profiles ?
3431        AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_HAS_AUTOFILL :
3432        AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_NO_AUTOFILL;
3433  }
3434
3435  // Signed in.
3436  if (wallet_items_->instruments().empty()) {
3437    // No Wallet items.
3438    return has_autofill_profiles ?
3439        AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_HAS_AUTOFILL :
3440        AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_NO_AUTOFILL;
3441  }
3442
3443  // Has Wallet items.
3444  return has_autofill_profiles ?
3445      AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_HAS_AUTOFILL :
3446      AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_NO_AUTOFILL;
3447}
3448
3449void AutofillDialogControllerImpl::MaybeShowCreditCardBubble() {
3450  if (!data_was_passed_back_)
3451    return;
3452
3453  if (newly_saved_card_) {
3454    AutofillCreditCardBubbleController::ShowNewCardSavedBubble(
3455        web_contents(), newly_saved_card_->TypeAndLastFourDigits());
3456    return;
3457  }
3458
3459  if (!full_wallet_ || !full_wallet_->billing_address())
3460    return;
3461
3462  // Don't show GeneratedCardBubble if Autocheckout failed.
3463  if (GetDialogType() == DIALOG_TYPE_AUTOCHECKOUT &&
3464      autocheckout_state_ != AUTOCHECKOUT_SUCCESS) {
3465    return;
3466  }
3467
3468  base::string16 backing_last_four;
3469  if (ActiveInstrument()) {
3470    backing_last_four = ActiveInstrument()->TypeAndLastFourDigits();
3471  } else {
3472    DetailOutputMap output;
3473    view_->GetUserInput(SECTION_CC_BILLING, &output);
3474    CreditCard card;
3475    GetBillingInfoFromOutputs(output, &card, NULL, NULL);
3476    backing_last_four = card.TypeAndLastFourDigits();
3477  }
3478  AutofillCreditCardBubbleController::ShowGeneratedCardUI(
3479      web_contents(), backing_last_four, full_wallet_->TypeAndLastFourDigits());
3480}
3481
3482}  // namespace autofill
3483