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