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