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