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