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