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