Upstream version 10.38.208.0
[platform/framework/web/crosswalk.git] / src / components / autofill / core / browser / autofill_manager.cc
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "components/autofill/core/browser/autofill_manager.h"
6
7 #include <stddef.h>
8
9 #include <limits>
10 #include <map>
11 #include <set>
12 #include <utility>
13
14 #include "base/bind.h"
15 #include "base/command_line.h"
16 #include "base/guid.h"
17 #include "base/logging.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/threading/sequenced_worker_pool.h"
23 #include "components/autofill/core/browser/autocomplete_history_manager.h"
24 #include "components/autofill/core/browser/autofill_client.h"
25 #include "components/autofill/core/browser/autofill_data_model.h"
26 #include "components/autofill/core/browser/autofill_external_delegate.h"
27 #include "components/autofill/core/browser/autofill_field.h"
28 #include "components/autofill/core/browser/autofill_manager_test_delegate.h"
29 #include "components/autofill/core/browser/autofill_metrics.h"
30 #include "components/autofill/core/browser/autofill_profile.h"
31 #include "components/autofill/core/browser/autofill_type.h"
32 #include "components/autofill/core/browser/credit_card.h"
33 #include "components/autofill/core/browser/form_structure.h"
34 #include "components/autofill/core/browser/personal_data_manager.h"
35 #include "components/autofill/core/browser/phone_number.h"
36 #include "components/autofill/core/browser/phone_number_i18n.h"
37 #include "components/autofill/core/browser/popup_item_ids.h"
38 #include "components/autofill/core/common/autofill_data_validation.h"
39 #include "components/autofill/core/common/autofill_pref_names.h"
40 #include "components/autofill/core/common/autofill_switches.h"
41 #include "components/autofill/core/common/form_data.h"
42 #include "components/autofill/core/common/form_data_predictions.h"
43 #include "components/autofill/core/common/form_field_data.h"
44 #include "components/autofill/core/common/password_form_fill_data.h"
45 #include "components/pref_registry/pref_registry_syncable.h"
46 #include "grit/components_strings.h"
47 #include "ui/base/l10n/l10n_util.h"
48 #include "ui/gfx/rect.h"
49 #include "url/gurl.h"
50
51 namespace autofill {
52
53 typedef PersonalDataManager::GUIDPair GUIDPair;
54
55 using base::TimeTicks;
56
57 namespace {
58
59 // We only send a fraction of the forms to upload server.
60 // The rate for positive/negative matches potentially could be different.
61 const double kAutofillPositiveUploadRateDefaultValue = 0.20;
62 const double kAutofillNegativeUploadRateDefaultValue = 0.20;
63
64 const size_t kMaxRecentFormSignaturesToRemember = 3;
65
66 // Set a conservative upper bound on the number of forms we are willing to
67 // cache, simply to prevent unbounded memory consumption.
68 const size_t kMaxFormCacheSize = 100;
69
70 // Removes duplicate suggestions whilst preserving their original order.
71 void RemoveDuplicateSuggestions(std::vector<base::string16>* values,
72                                 std::vector<base::string16>* labels,
73                                 std::vector<base::string16>* icons,
74                                 std::vector<int>* unique_ids) {
75   DCHECK_EQ(values->size(), labels->size());
76   DCHECK_EQ(values->size(), icons->size());
77   DCHECK_EQ(values->size(), unique_ids->size());
78
79   std::set<std::pair<base::string16, base::string16> > seen_suggestions;
80   std::vector<base::string16> values_copy;
81   std::vector<base::string16> labels_copy;
82   std::vector<base::string16> icons_copy;
83   std::vector<int> unique_ids_copy;
84
85   for (size_t i = 0; i < values->size(); ++i) {
86     const std::pair<base::string16, base::string16> suggestion(
87         (*values)[i], (*labels)[i]);
88     if (seen_suggestions.insert(suggestion).second) {
89       values_copy.push_back((*values)[i]);
90       labels_copy.push_back((*labels)[i]);
91       icons_copy.push_back((*icons)[i]);
92       unique_ids_copy.push_back((*unique_ids)[i]);
93     }
94   }
95
96   values->swap(values_copy);
97   labels->swap(labels_copy);
98   icons->swap(icons_copy);
99   unique_ids->swap(unique_ids_copy);
100 }
101
102 // Precondition: |form_structure| and |form| should correspond to the same
103 // logical form.  Returns true if any field in the given |section| within |form|
104 // is auto-filled.
105 bool SectionIsAutofilled(const FormStructure& form_structure,
106                          const FormData& form,
107                          const std::string& section) {
108   DCHECK_EQ(form_structure.field_count(), form.fields.size());
109   for (size_t i = 0; i < form_structure.field_count(); ++i) {
110     if (form_structure.field(i)->section() == section &&
111         form.fields[i].is_autofilled) {
112       return true;
113     }
114   }
115
116   return false;
117 }
118
119 bool FormIsHTTPS(const FormStructure& form) {
120   // TODO(blundell): Change this to use a constant once crbug.com/306258 is
121   // fixed.
122   return form.source_url().SchemeIs("https");
123 }
124
125 // Uses the existing personal data in |profiles| and |credit_cards| to determine
126 // possible field types for the |submitted_form|.  This is potentially
127 // expensive -- on the order of 50ms even for a small set of |stored_data|.
128 // Hence, it should not run on the UI thread -- to avoid locking up the UI --
129 // nor on the IO thread -- to avoid blocking IPC calls.
130 void DeterminePossibleFieldTypesForUpload(
131     const std::vector<AutofillProfile>& profiles,
132     const std::vector<CreditCard>& credit_cards,
133     const std::string& app_locale,
134     FormStructure* submitted_form) {
135   // For each field in the |submitted_form|, extract the value.  Then for each
136   // profile or credit card, identify any stored types that match the value.
137   for (size_t i = 0; i < submitted_form->field_count(); ++i) {
138     AutofillField* field = submitted_form->field(i);
139     ServerFieldTypeSet matching_types;
140
141     base::string16 value;
142     base::TrimWhitespace(field->value, base::TRIM_ALL, &value);
143     for (std::vector<AutofillProfile>::const_iterator it = profiles.begin();
144          it != profiles.end(); ++it) {
145       it->GetMatchingTypes(value, app_locale, &matching_types);
146     }
147     for (std::vector<CreditCard>::const_iterator it = credit_cards.begin();
148          it != credit_cards.end(); ++it) {
149       it->GetMatchingTypes(value, app_locale, &matching_types);
150     }
151
152     if (matching_types.empty())
153       matching_types.insert(UNKNOWN_TYPE);
154
155     field->set_possible_types(matching_types);
156   }
157 }
158
159 }  // namespace
160
161 AutofillManager::AutofillManager(
162     AutofillDriver* driver,
163     AutofillClient* client,
164     const std::string& app_locale,
165     AutofillDownloadManagerState enable_download_manager)
166     : driver_(driver),
167       client_(client),
168       app_locale_(app_locale),
169       personal_data_(client->GetPersonalDataManager()),
170       autocomplete_history_manager_(
171           new AutocompleteHistoryManager(driver, client)),
172       metric_logger_(new AutofillMetrics),
173       has_logged_autofill_enabled_(false),
174       has_logged_address_suggestions_count_(false),
175       did_show_suggestions_(false),
176       user_did_type_(false),
177       user_did_autofill_(false),
178       user_did_edit_autofilled_field_(false),
179       external_delegate_(NULL),
180       test_delegate_(NULL),
181       weak_ptr_factory_(this) {
182   if (enable_download_manager == ENABLE_AUTOFILL_DOWNLOAD_MANAGER) {
183     download_manager_.reset(
184         new AutofillDownloadManager(driver, client_->GetPrefs(), this));
185   }
186 }
187
188 AutofillManager::~AutofillManager() {}
189
190 // static
191 void AutofillManager::RegisterProfilePrefs(
192     user_prefs::PrefRegistrySyncable* registry) {
193   registry->RegisterBooleanPref(
194       prefs::kAutofillEnabled,
195       true,
196       user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
197 #if defined(OS_MACOSX)
198   registry->RegisterBooleanPref(
199       prefs::kAutofillAuxiliaryProfilesEnabled,
200       true,
201       user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
202 #else  // defined(OS_MACOSX)
203   registry->RegisterBooleanPref(
204       prefs::kAutofillAuxiliaryProfilesEnabled,
205       false,
206       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
207 #endif  // defined(OS_MACOSX)
208 #if defined(OS_MACOSX)
209   registry->RegisterBooleanPref(
210       prefs::kAutofillMacAddressBookQueried,
211       false,
212       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
213 #endif  // defined(OS_MACOSX)
214   registry->RegisterDoublePref(
215       prefs::kAutofillPositiveUploadRate,
216       kAutofillPositiveUploadRateDefaultValue,
217       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
218   registry->RegisterDoublePref(
219       prefs::kAutofillNegativeUploadRate,
220       kAutofillNegativeUploadRateDefaultValue,
221       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
222
223 #if defined(OS_MACOSX) && !defined(OS_IOS)
224   registry->RegisterBooleanPref(
225       prefs::kAutofillUseMacAddressBook,
226       false,
227       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
228 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
229 }
230
231 #if defined(OS_MACOSX) && !defined(OS_IOS)
232 void AutofillManager::MigrateUserPrefs(PrefService* prefs) {
233   const PrefService::Preference* pref =
234       prefs->FindPreference(prefs::kAutofillUseMacAddressBook);
235
236   // If the pref is not its default value, then the migration has already been
237   // performed.
238   if (!pref->IsDefaultValue())
239     return;
240
241   // Whether Chrome has already tried to access the user's Address Book.
242   const PrefService::Preference* pref_accessed =
243       prefs->FindPreference(prefs::kAutofillMacAddressBookQueried);
244   // Whether the user wants to use the Address Book to populate Autofill.
245   const PrefService::Preference* pref_enabled =
246       prefs->FindPreference(prefs::kAutofillAuxiliaryProfilesEnabled);
247
248   if (pref_accessed->IsDefaultValue() && pref_enabled->IsDefaultValue()) {
249     // This is likely a new user. Reset the default value to prevent the
250     // migration from happening again.
251     prefs->SetBoolean(prefs::kAutofillUseMacAddressBook,
252                       prefs->GetBoolean(prefs::kAutofillUseMacAddressBook));
253     return;
254   }
255
256   bool accessed;
257   bool enabled;
258   bool success = pref_accessed->GetValue()->GetAsBoolean(&accessed);
259   DCHECK(success);
260   success = pref_enabled->GetValue()->GetAsBoolean(&enabled);
261   DCHECK(success);
262
263   prefs->SetBoolean(prefs::kAutofillUseMacAddressBook, accessed && enabled);
264 }
265 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
266
267 void AutofillManager::SetExternalDelegate(AutofillExternalDelegate* delegate) {
268   // TODO(jrg): consider passing delegate into the ctor.  That won't
269   // work if the delegate has a pointer to the AutofillManager, but
270   // future directions may not need such a pointer.
271   external_delegate_ = delegate;
272   autocomplete_history_manager_->SetExternalDelegate(delegate);
273 }
274
275 void AutofillManager::ShowAutofillSettings() {
276   client_->ShowAutofillSettings();
277 }
278
279 #if defined(OS_MACOSX) && !defined(OS_IOS)
280 bool AutofillManager::ShouldShowAccessAddressBookSuggestion(
281     const FormData& form,
282     const FormFieldData& field) {
283   if (!personal_data_)
284     return false;
285   FormStructure* form_structure = NULL;
286   AutofillField* autofill_field = NULL;
287   if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
288     return false;
289
290   return personal_data_->ShouldShowAccessAddressBookSuggestion(
291       autofill_field->Type());
292 }
293
294 bool AutofillManager::AccessAddressBook() {
295   if (!personal_data_)
296     return false;
297   return personal_data_->AccessAddressBook();
298 }
299 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
300
301 bool AutofillManager::OnFormSubmitted(const FormData& form,
302                                       const TimeTicks& timestamp) {
303   if (!IsValidFormData(form))
304     return false;
305
306   // Let Autocomplete know as well.
307   autocomplete_history_manager_->OnFormSubmitted(form);
308
309   // Grab a copy of the form data.
310   scoped_ptr<FormStructure> submitted_form(new FormStructure(form));
311
312   if (!ShouldUploadForm(*submitted_form))
313     return false;
314
315   // Don't save data that was submitted through JavaScript.
316   if (!form.user_submitted)
317     return false;
318
319   // Ignore forms not present in our cache.  These are typically forms with
320   // wonky JavaScript that also makes them not auto-fillable.
321   FormStructure* cached_submitted_form;
322   if (!FindCachedForm(form, &cached_submitted_form))
323     return false;
324
325   submitted_form->UpdateFromCache(*cached_submitted_form);
326   if (submitted_form->IsAutofillable())
327     ImportFormData(*submitted_form);
328
329   // Only upload server statistics and UMA metrics if at least some local data
330   // is available to use as a baseline.
331   const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles();
332   const std::vector<CreditCard*>& credit_cards =
333       personal_data_->GetCreditCards();
334   if (!profiles.empty() || !credit_cards.empty()) {
335     // Copy the profile and credit card data, so that it can be accessed on a
336     // separate thread.
337     std::vector<AutofillProfile> copied_profiles;
338     copied_profiles.reserve(profiles.size());
339     for (std::vector<AutofillProfile*>::const_iterator it = profiles.begin();
340          it != profiles.end(); ++it) {
341       copied_profiles.push_back(**it);
342     }
343
344     std::vector<CreditCard> copied_credit_cards;
345     copied_credit_cards.reserve(credit_cards.size());
346     for (std::vector<CreditCard*>::const_iterator it = credit_cards.begin();
347          it != credit_cards.end(); ++it) {
348       copied_credit_cards.push_back(**it);
349     }
350
351     // Note that ownership of |submitted_form| is passed to the second task,
352     // using |base::Owned|.
353     FormStructure* raw_submitted_form = submitted_form.get();
354     driver_->GetBlockingPool()->PostTaskAndReply(
355         FROM_HERE,
356         base::Bind(&DeterminePossibleFieldTypesForUpload,
357                    copied_profiles,
358                    copied_credit_cards,
359                    app_locale_,
360                    raw_submitted_form),
361         base::Bind(&AutofillManager::UploadFormDataAsyncCallback,
362                    weak_ptr_factory_.GetWeakPtr(),
363                    base::Owned(submitted_form.release()),
364                    forms_loaded_timestamps_[form],
365                    initial_interaction_timestamp_,
366                    timestamp));
367   }
368
369   return true;
370 }
371
372 void AutofillManager::OnFormsSeen(const std::vector<FormData>& forms,
373                                   const TimeTicks& timestamp) {
374   if (!IsValidFormDataVector(forms))
375     return;
376
377   if (!driver_->RendererIsAvailable())
378     return;
379
380   bool enabled = IsAutofillEnabled();
381   if (!has_logged_autofill_enabled_) {
382     metric_logger_->LogIsAutofillEnabledAtPageLoad(enabled);
383     has_logged_autofill_enabled_ = true;
384   }
385
386   if (!enabled)
387     return;
388
389   for (size_t i = 0; i < forms.size(); ++i) {
390     forms_loaded_timestamps_[forms[i]] = timestamp;
391   }
392
393   ParseForms(forms);
394 }
395
396 void AutofillManager::OnTextFieldDidChange(const FormData& form,
397                                            const FormFieldData& field,
398                                            const TimeTicks& timestamp) {
399   if (!IsValidFormData(form) || !IsValidFormFieldData(field))
400     return;
401
402   FormStructure* form_structure = NULL;
403   AutofillField* autofill_field = NULL;
404   if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
405     return;
406
407   if (!user_did_type_) {
408     user_did_type_ = true;
409     metric_logger_->LogUserHappinessMetric(AutofillMetrics::USER_DID_TYPE);
410   }
411
412   if (autofill_field->is_autofilled) {
413     autofill_field->is_autofilled = false;
414     metric_logger_->LogUserHappinessMetric(
415         AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD);
416
417     if (!user_did_edit_autofilled_field_) {
418       user_did_edit_autofilled_field_ = true;
419       metric_logger_->LogUserHappinessMetric(
420           AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD_ONCE);
421     }
422   }
423
424   UpdateInitialInteractionTimestamp(timestamp);
425 }
426
427 void AutofillManager::OnQueryFormFieldAutofill(int query_id,
428                                                const FormData& form,
429                                                const FormFieldData& field,
430                                                const gfx::RectF& bounding_box,
431                                                bool display_warning) {
432   if (!IsValidFormData(form) || !IsValidFormFieldData(field))
433     return;
434
435   std::vector<base::string16> values;
436   std::vector<base::string16> labels;
437   std::vector<base::string16> icons;
438   std::vector<int> unique_ids;
439
440   external_delegate_->OnQuery(query_id,
441                               form,
442                               field,
443                               bounding_box,
444                               display_warning);
445   FormStructure* form_structure = NULL;
446   AutofillField* autofill_field = NULL;
447   if (RefreshDataModels() &&
448       driver_->RendererIsAvailable() &&
449       GetCachedFormAndField(form, field, &form_structure, &autofill_field) &&
450       // Don't send suggestions for forms that aren't auto-fillable.
451       form_structure->IsAutofillable()) {
452     AutofillType type = autofill_field->Type();
453     bool is_filling_credit_card = (type.group() == CREDIT_CARD);
454     if (is_filling_credit_card) {
455       GetCreditCardSuggestions(
456           field, type, &values, &labels, &icons, &unique_ids);
457     } else {
458       GetProfileSuggestions(
459           form_structure, field, type, &values, &labels, &icons, &unique_ids);
460     }
461
462     DCHECK_EQ(values.size(), labels.size());
463     DCHECK_EQ(values.size(), icons.size());
464     DCHECK_EQ(values.size(), unique_ids.size());
465
466     if (!values.empty()) {
467       // Don't provide Autofill suggestions when Autofill is disabled, and don't
468       // provide credit card suggestions for non-HTTPS pages. However, provide a
469       // warning to the user in these cases.
470       int warning = 0;
471       if (!form_structure->IsAutofillable())
472         warning = IDS_AUTOFILL_WARNING_FORM_DISABLED;
473       else if (is_filling_credit_card && !FormIsHTTPS(*form_structure))
474         warning = IDS_AUTOFILL_WARNING_INSECURE_CONNECTION;
475       if (warning) {
476         values.assign(1, l10n_util::GetStringUTF16(warning));
477         labels.assign(1, base::string16());
478         icons.assign(1, base::string16());
479         unique_ids.assign(1, POPUP_ITEM_ID_WARNING_MESSAGE);
480       } else {
481         bool section_is_autofilled =
482             SectionIsAutofilled(*form_structure, form,
483                                 autofill_field->section());
484         if (section_is_autofilled) {
485           // If the relevant section is auto-filled and the renderer is querying
486           // for suggestions, then the user is editing the value of a field.
487           // In this case, mimic autocomplete: don't display labels or icons,
488           // as that information is redundant.
489           labels.assign(labels.size(), base::string16());
490           icons.assign(icons.size(), base::string16());
491         }
492
493         // When filling credit card suggestions, the values and labels are
494         // typically obfuscated, which makes detecting duplicates hard.  Since
495         // duplicates only tend to be a problem when filling address forms
496         // anyway, only don't de-dup credit card suggestions.
497         if (!is_filling_credit_card)
498           RemoveDuplicateSuggestions(&values, &labels, &icons, &unique_ids);
499
500         // The first time we show suggestions on this page, log the number of
501         // suggestions shown.
502         if (!has_logged_address_suggestions_count_ && !section_is_autofilled) {
503           metric_logger_->LogAddressSuggestionsCount(values.size());
504           has_logged_address_suggestions_count_ = true;
505         }
506       }
507     }
508   }
509
510   // Add the results from AutoComplete.  They come back asynchronously, so we
511   // hand off what we generated and they will send the results back to the
512   // renderer.
513   autocomplete_history_manager_->OnGetAutocompleteSuggestions(
514       query_id, field.name, field.value, field.form_control_type, values,
515       labels, icons, unique_ids);
516 }
517
518 void AutofillManager::FillOrPreviewForm(
519     AutofillDriver::RendererFormDataAction action,
520     int query_id,
521     const FormData& form,
522     const FormFieldData& field,
523     int unique_id) {
524   if (!IsValidFormData(form) || !IsValidFormFieldData(field))
525     return;
526
527   const AutofillDataModel* data_model = NULL;
528   size_t variant = 0;
529   FormStructure* form_structure = NULL;
530   AutofillField* autofill_field = NULL;
531   bool is_credit_card = false;
532   // NOTE: RefreshDataModels may invalidate |data_model| because it causes the
533   // PersonalDataManager to reload Mac address book entries. Thus it must come
534   // before GetProfileOrCreditCard.
535   if (!RefreshDataModels() ||
536       !driver_->RendererIsAvailable() ||
537       !GetProfileOrCreditCard(
538           unique_id, &data_model, &variant, &is_credit_card) ||
539       !GetCachedFormAndField(form, field, &form_structure, &autofill_field))
540     return;
541
542   DCHECK(form_structure);
543   DCHECK(autofill_field);
544
545   FormData result = form;
546
547   base::string16 profile_full_name;
548   std::string profile_language_code;
549   if (!is_credit_card) {
550     profile_full_name = data_model->GetInfo(
551         AutofillType(NAME_FULL), app_locale_);
552     profile_language_code =
553         static_cast<const AutofillProfile*>(data_model)->language_code();
554   }
555
556   // If the relevant section is auto-filled, we should fill |field| but not the
557   // rest of the form.
558   if (SectionIsAutofilled(*form_structure, form, autofill_field->section())) {
559     for (std::vector<FormFieldData>::iterator iter = result.fields.begin();
560          iter != result.fields.end(); ++iter) {
561       if ((*iter) == field) {
562         base::string16 value = data_model->GetInfoForVariant(
563             autofill_field->Type(), variant, app_locale_);
564         if (AutofillField::FillFormField(*autofill_field,
565                                          value,
566                                          profile_language_code,
567                                          app_locale_,
568                                          &(*iter))) {
569           // Mark the cached field as autofilled, so that we can detect when a
570           // user edits an autofilled field (for metrics).
571           autofill_field->is_autofilled = true;
572
573           // Mark the field as autofilled when a non-empty value is assigned to
574           // it. This allows the renderer to distinguish autofilled fields from
575           // fields with non-empty values, such as select-one fields.
576           iter->is_autofilled = true;
577
578           if (!is_credit_card && !value.empty())
579             client_->DidFillOrPreviewField(value, profile_full_name);
580         }
581         break;
582       }
583     }
584
585     driver_->SendFormDataToRenderer(query_id, action, result);
586     return;
587   }
588
589   // Cache the field type for the field from which the user initiated autofill.
590   FieldTypeGroup initiating_group_type = autofill_field->Type().group();
591   DCHECK_EQ(form_structure->field_count(), form.fields.size());
592   for (size_t i = 0; i < form_structure->field_count(); ++i) {
593     if (form_structure->field(i)->section() != autofill_field->section())
594       continue;
595
596     DCHECK_EQ(*form_structure->field(i), result.fields[i]);
597
598     const AutofillField* cached_field = form_structure->field(i);
599     FieldTypeGroup field_group_type = cached_field->Type().group();
600     if (field_group_type != NO_GROUP) {
601       // If the field being filled is either
602       //   (a) the field that the user initiated the fill from, or
603       //   (b) part of the same logical unit, e.g. name or phone number,
604       // then take the multi-profile "variant" into account.
605       // Otherwise fill with the default (zeroth) variant.
606       size_t use_variant = 0;
607       if (result.fields[i] == field ||
608           field_group_type == initiating_group_type) {
609         use_variant = variant;
610       }
611       base::string16 value = data_model->GetInfoForVariant(
612           cached_field->Type(), use_variant, app_locale_);
613
614       // Must match ForEachMatchingFormField() in form_autofill_util.cc.
615       // Only notify autofilling of empty fields and the field that initiated
616       // the filling (note that "select-one" controls may not be empty but will
617       // still be autofilled).
618       bool should_notify =
619           !is_credit_card &&
620           !value.empty() &&
621           (result.fields[i] == field ||
622            result.fields[i].form_control_type == "select-one" ||
623            result.fields[i].value.empty());
624       if (AutofillField::FillFormField(*cached_field,
625                                        value,
626                                        profile_language_code,
627                                        app_locale_,
628                                        &result.fields[i])) {
629         // Mark the cached field as autofilled, so that we can detect when a
630         // user edits an autofilled field (for metrics).
631         form_structure->field(i)->is_autofilled = true;
632
633         // Mark the field as autofilled when a non-empty value is assigned to
634         // it. This allows the renderer to distinguish autofilled fields from
635         // fields with non-empty values, such as select-one fields.
636         result.fields[i].is_autofilled = true;
637
638         if (should_notify)
639           client_->DidFillOrPreviewField(value, profile_full_name);
640       }
641     }
642   }
643
644   autofilled_form_signatures_.push_front(form_structure->FormSignature());
645   // Only remember the last few forms that we've seen, both to avoid false
646   // positives and to avoid wasting memory.
647   if (autofilled_form_signatures_.size() > kMaxRecentFormSignaturesToRemember)
648     autofilled_form_signatures_.pop_back();
649
650   driver_->SendFormDataToRenderer(query_id, action, result);
651 }
652
653 void AutofillManager::OnDidPreviewAutofillFormData() {
654   if (test_delegate_)
655     test_delegate_->DidPreviewFormData();
656 }
657
658 void AutofillManager::OnDidFillAutofillFormData(const TimeTicks& timestamp) {
659   if (test_delegate_)
660     test_delegate_->DidFillFormData();
661
662   metric_logger_->LogUserHappinessMetric(AutofillMetrics::USER_DID_AUTOFILL);
663   if (!user_did_autofill_) {
664     user_did_autofill_ = true;
665     metric_logger_->LogUserHappinessMetric(
666         AutofillMetrics::USER_DID_AUTOFILL_ONCE);
667   }
668
669   UpdateInitialInteractionTimestamp(timestamp);
670 }
671
672 void AutofillManager::DidShowSuggestions(bool is_new_popup) {
673   if (test_delegate_)
674     test_delegate_->DidShowSuggestions();
675
676   if (is_new_popup) {
677     metric_logger_->LogUserHappinessMetric(AutofillMetrics::SUGGESTIONS_SHOWN);
678
679     if (!did_show_suggestions_) {
680       did_show_suggestions_ = true;
681       metric_logger_->LogUserHappinessMetric(
682           AutofillMetrics::SUGGESTIONS_SHOWN_ONCE);
683     }
684   }
685 }
686
687 void AutofillManager::OnHidePopup() {
688   if (!IsAutofillEnabled())
689     return;
690
691   client_->HideAutofillPopup();
692 }
693
694 void AutofillManager::RemoveAutofillProfileOrCreditCard(int unique_id) {
695   const AutofillDataModel* data_model = NULL;
696   size_t variant = 0;
697   bool unused_is_credit_card = false;
698   if (!GetProfileOrCreditCard(
699           unique_id, &data_model, &variant, &unused_is_credit_card)) {
700     NOTREACHED();
701     return;
702   }
703
704   // TODO(csharp): If we are dealing with a variant only the variant should
705   // be deleted, instead of doing nothing.
706   // http://crbug.com/124211
707   if (variant != 0)
708     return;
709
710   personal_data_->RemoveByGUID(data_model->guid());
711 }
712
713 void AutofillManager::RemoveAutocompleteEntry(const base::string16& name,
714                                               const base::string16& value) {
715   autocomplete_history_manager_->OnRemoveAutocompleteEntry(name, value);
716 }
717
718 const std::vector<FormStructure*>& AutofillManager::GetFormStructures() {
719   return form_structures_.get();
720 }
721
722 void AutofillManager::SetTestDelegate(AutofillManagerTestDelegate* delegate) {
723   test_delegate_ = delegate;
724 }
725
726 void AutofillManager::OnSetDataList(const std::vector<base::string16>& values,
727                                     const std::vector<base::string16>& labels) {
728   if (!IsValidString16Vector(values) ||
729       !IsValidString16Vector(labels) ||
730       values.size() != labels.size())
731     return;
732
733   external_delegate_->SetCurrentDataListValues(values, labels);
734 }
735
736 void AutofillManager::OnLoadedServerPredictions(
737     const std::string& response_xml) {
738   // Parse and store the server predictions.
739   FormStructure::ParseQueryResponse(response_xml,
740                                     form_structures_.get(),
741                                     *metric_logger_);
742
743   // Forward form structures to the password generation manager to detect
744   // account creation forms.
745   client_->DetectAccountCreationForms(form_structures_.get());
746
747   // If the corresponding flag is set, annotate forms with the predicted types.
748   driver_->SendAutofillTypePredictionsToRenderer(form_structures_.get());
749 }
750
751 void AutofillManager::OnDidEndTextFieldEditing() {
752   external_delegate_->DidEndTextFieldEditing();
753 }
754
755 bool AutofillManager::IsAutofillEnabled() const {
756   return client_->GetPrefs()->GetBoolean(prefs::kAutofillEnabled);
757 }
758
759 void AutofillManager::ImportFormData(const FormStructure& submitted_form) {
760   scoped_ptr<CreditCard> imported_credit_card;
761   if (!personal_data_->ImportFormData(submitted_form, &imported_credit_card))
762     return;
763
764   // If credit card information was submitted, we need to confirm whether to
765   // save it.
766   if (imported_credit_card) {
767     client_->ConfirmSaveCreditCard(
768         *metric_logger_,
769         base::Bind(
770             base::IgnoreResult(&PersonalDataManager::SaveImportedCreditCard),
771             base::Unretained(personal_data_),
772             *imported_credit_card));
773   }
774 }
775
776 // Note that |submitted_form| is passed as a pointer rather than as a reference
777 // so that we can get memory management right across threads.  Note also that we
778 // explicitly pass in all the time stamps of interest, as the cached ones might
779 // get reset before this method executes.
780 void AutofillManager::UploadFormDataAsyncCallback(
781     const FormStructure* submitted_form,
782     const TimeTicks& load_time,
783     const TimeTicks& interaction_time,
784     const TimeTicks& submission_time) {
785   submitted_form->LogQualityMetrics(*metric_logger_,
786                                     load_time,
787                                     interaction_time,
788                                     submission_time);
789
790   if (submitted_form->ShouldBeCrowdsourced())
791     UploadFormData(*submitted_form);
792 }
793
794 void AutofillManager::UploadFormData(const FormStructure& submitted_form) {
795   if (!download_manager_)
796     return;
797
798   // Check if the form is among the forms that were recently auto-filled.
799   bool was_autofilled = false;
800   std::string form_signature = submitted_form.FormSignature();
801   for (std::list<std::string>::const_iterator it =
802            autofilled_form_signatures_.begin();
803        it != autofilled_form_signatures_.end() && !was_autofilled;
804        ++it) {
805     if (*it == form_signature)
806       was_autofilled = true;
807   }
808
809   ServerFieldTypeSet non_empty_types;
810   personal_data_->GetNonEmptyTypes(&non_empty_types);
811
812   download_manager_->StartUploadRequest(submitted_form, was_autofilled,
813                                         non_empty_types);
814 }
815
816 bool AutofillManager::UploadPasswordForm(
817     const FormData& form,
818     const ServerFieldType& password_type) {
819   FormStructure form_structure(form);
820
821   if (!ShouldUploadForm(form_structure))
822     return false;
823
824   if (!form_structure.ShouldBeCrowdsourced())
825     return false;
826
827   // Find the first password field to label. We don't try to label anything
828   // else.
829   bool found_password_field = false;
830   for (size_t i = 0; i < form_structure.field_count(); ++i) {
831     AutofillField* field = form_structure.field(i);
832
833     ServerFieldTypeSet types;
834     if (!found_password_field && field->form_control_type == "password") {
835       types.insert(password_type);
836       found_password_field = true;
837     } else {
838       types.insert(UNKNOWN_TYPE);
839     }
840     field->set_possible_types(types);
841   }
842   DCHECK(found_password_field);
843
844   // Only one field type should be present.
845   ServerFieldTypeSet available_field_types;
846   available_field_types.insert(password_type);
847
848   // Force uploading as these events are relatively rare and we want to make
849   // sure to receive them. It also makes testing easier if these requests
850   // always pass.
851   form_structure.set_upload_required(UPLOAD_REQUIRED);
852
853   if (!download_manager_)
854     return false;
855
856   return download_manager_->StartUploadRequest(form_structure,
857                                                false /* was_autofilled */,
858                                                available_field_types);
859 }
860
861 void AutofillManager::Reset() {
862   form_structures_.clear();
863   has_logged_autofill_enabled_ = false;
864   has_logged_address_suggestions_count_ = false;
865   did_show_suggestions_ = false;
866   user_did_type_ = false;
867   user_did_autofill_ = false;
868   user_did_edit_autofilled_field_ = false;
869   forms_loaded_timestamps_.clear();
870   initial_interaction_timestamp_ = TimeTicks();
871   external_delegate_->Reset();
872 }
873
874 AutofillManager::AutofillManager(AutofillDriver* driver,
875                                  AutofillClient* client,
876                                  PersonalDataManager* personal_data)
877     : driver_(driver),
878       client_(client),
879       app_locale_("en-US"),
880       personal_data_(personal_data),
881       autocomplete_history_manager_(
882           new AutocompleteHistoryManager(driver, client)),
883       metric_logger_(new AutofillMetrics),
884       has_logged_autofill_enabled_(false),
885       has_logged_address_suggestions_count_(false),
886       did_show_suggestions_(false),
887       user_did_type_(false),
888       user_did_autofill_(false),
889       user_did_edit_autofilled_field_(false),
890       external_delegate_(NULL),
891       test_delegate_(NULL),
892       weak_ptr_factory_(this) {
893   DCHECK(driver_);
894   DCHECK(client_);
895 }
896
897 void AutofillManager::set_metric_logger(const AutofillMetrics* metric_logger) {
898   metric_logger_.reset(metric_logger);
899 }
900
901 bool AutofillManager::RefreshDataModels() const {
902   if (!IsAutofillEnabled())
903     return false;
904
905   // No autofill data to return if the profiles are empty.
906   if (personal_data_->GetProfiles().empty() &&
907       personal_data_->GetCreditCards().empty()) {
908     return false;
909   }
910
911   return true;
912 }
913
914 bool AutofillManager::GetProfileOrCreditCard(
915     int unique_id,
916     const AutofillDataModel** data_model,
917     size_t* variant,
918     bool* is_credit_card) const {
919   // Unpack the |unique_id| into component parts.
920   GUIDPair credit_card_guid;
921   GUIDPair profile_guid;
922   UnpackGUIDs(unique_id, &credit_card_guid, &profile_guid);
923   DCHECK(!base::IsValidGUID(credit_card_guid.first) ||
924          !base::IsValidGUID(profile_guid.first));
925   *is_credit_card = false;
926
927   // Find the profile that matches the |profile_guid|, if one is specified.
928   // Otherwise find the credit card that matches the |credit_card_guid|,
929   // if specified.
930   if (base::IsValidGUID(profile_guid.first)) {
931     *data_model = personal_data_->GetProfileByGUID(profile_guid.first);
932     *variant = profile_guid.second;
933   } else if (base::IsValidGUID(credit_card_guid.first)) {
934     *data_model = personal_data_->GetCreditCardByGUID(credit_card_guid.first);
935     *variant = credit_card_guid.second;
936     *is_credit_card = true;
937   }
938
939   return !!*data_model;
940 }
941
942 bool AutofillManager::FindCachedForm(const FormData& form,
943                                      FormStructure** form_structure) const {
944   // Find the FormStructure that corresponds to |form|.
945   // Scan backward through the cached |form_structures_|, as updated versions of
946   // forms are added to the back of the list, whereas original versions of these
947   // forms might appear toward the beginning of the list.  The communication
948   // protocol with the crowdsourcing server does not permit us to discard the
949   // original versions of the forms.
950   *form_structure = NULL;
951   for (std::vector<FormStructure*>::const_reverse_iterator iter =
952            form_structures_.rbegin();
953        iter != form_structures_.rend(); ++iter) {
954     if (**iter == form) {
955       *form_structure = *iter;
956
957       // The same form might be cached with multiple field counts: in some
958       // cases, non-autofillable fields are filtered out, whereas in other cases
959       // they are not.  To avoid thrashing the cache, keep scanning until we
960       // find a cached version with the same number of fields, if there is one.
961       if ((*iter)->field_count() == form.fields.size())
962         break;
963     }
964   }
965
966   if (!(*form_structure))
967     return false;
968
969   return true;
970 }
971
972 bool AutofillManager::GetCachedFormAndField(const FormData& form,
973                                             const FormFieldData& field,
974                                             FormStructure** form_structure,
975                                             AutofillField** autofill_field) {
976   // Find the FormStructure that corresponds to |form|.
977   // If we do not have this form in our cache but it is parseable, we'll add it
978   // in the call to |UpdateCachedForm()|.
979   if (!FindCachedForm(form, form_structure) &&
980       !FormStructure(form).ShouldBeParsed()) {
981     return false;
982   }
983
984   // Update the cached form to reflect any dynamic changes to the form data, if
985   // necessary.
986   if (!UpdateCachedForm(form, *form_structure, form_structure))
987     return false;
988
989   // No data to return if there are no auto-fillable fields.
990   if (!(*form_structure)->autofill_count())
991     return false;
992
993   // Find the AutofillField that corresponds to |field|.
994   *autofill_field = NULL;
995   for (std::vector<AutofillField*>::const_iterator iter =
996            (*form_structure)->begin();
997        iter != (*form_structure)->end(); ++iter) {
998     if ((**iter) == field) {
999       *autofill_field = *iter;
1000       break;
1001     }
1002   }
1003
1004   // Even though we always update the cache, the field might not exist if the
1005   // website disables autocomplete while the user is interacting with the form.
1006   // See http://crbug.com/160476
1007   return *autofill_field != NULL;
1008 }
1009
1010 bool AutofillManager::UpdateCachedForm(const FormData& live_form,
1011                                        const FormStructure* cached_form,
1012                                        FormStructure** updated_form) {
1013   bool needs_update =
1014       (!cached_form ||
1015        live_form.fields.size() != cached_form->field_count());
1016   for (size_t i = 0; !needs_update && i < cached_form->field_count(); ++i) {
1017     needs_update = *cached_form->field(i) != live_form.fields[i];
1018   }
1019
1020   if (!needs_update)
1021     return true;
1022
1023   if (form_structures_.size() >= kMaxFormCacheSize)
1024     return false;
1025
1026   // Add the new or updated form to our cache.
1027   form_structures_.push_back(new FormStructure(live_form));
1028   *updated_form = *form_structures_.rbegin();
1029   (*updated_form)->DetermineHeuristicTypes(*metric_logger_);
1030
1031   // If we have cached data, propagate it to the updated form.
1032   if (cached_form) {
1033     std::map<base::string16, const AutofillField*> cached_fields;
1034     for (size_t i = 0; i < cached_form->field_count(); ++i) {
1035       const AutofillField* field = cached_form->field(i);
1036       cached_fields[field->unique_name()] = field;
1037     }
1038
1039     for (size_t i = 0; i < (*updated_form)->field_count(); ++i) {
1040       AutofillField* field = (*updated_form)->field(i);
1041       std::map<base::string16, const AutofillField*>::iterator cached_field =
1042           cached_fields.find(field->unique_name());
1043       if (cached_field != cached_fields.end()) {
1044         field->set_server_type(cached_field->second->server_type());
1045         field->is_autofilled = cached_field->second->is_autofilled;
1046       }
1047     }
1048
1049     // Note: We _must not_ remove the original version of the cached form from
1050     // the list of |form_structures_|.  Otherwise, we break parsing of the
1051     // crowdsourcing server's response to our query.
1052   }
1053
1054   // Annotate the updated form with its predicted types.
1055   std::vector<FormStructure*> forms(1, *updated_form);
1056   driver_->SendAutofillTypePredictionsToRenderer(forms);
1057
1058   return true;
1059 }
1060
1061 void AutofillManager::GetProfileSuggestions(
1062     FormStructure* form,
1063     const FormFieldData& field,
1064     const AutofillType& type,
1065     std::vector<base::string16>* values,
1066     std::vector<base::string16>* labels,
1067     std::vector<base::string16>* icons,
1068     std::vector<int>* unique_ids) const {
1069   std::vector<ServerFieldType> field_types(form->field_count());
1070   for (size_t i = 0; i < form->field_count(); ++i) {
1071     field_types.push_back(form->field(i)->Type().GetStorableType());
1072   }
1073   std::vector<GUIDPair> guid_pairs;
1074
1075   personal_data_->GetProfileSuggestions(
1076       type, field.value, field.is_autofilled, field_types,
1077       base::Callback<bool(const AutofillProfile&)>(),
1078       values, labels, icons, &guid_pairs);
1079
1080   for (size_t i = 0; i < guid_pairs.size(); ++i) {
1081     unique_ids->push_back(PackGUIDs(GUIDPair(std::string(), 0),
1082                                     guid_pairs[i]));
1083   }
1084 }
1085
1086 void AutofillManager::GetCreditCardSuggestions(
1087     const FormFieldData& field,
1088     const AutofillType& type,
1089     std::vector<base::string16>* values,
1090     std::vector<base::string16>* labels,
1091     std::vector<base::string16>* icons,
1092     std::vector<int>* unique_ids) const {
1093   std::vector<GUIDPair> guid_pairs;
1094   personal_data_->GetCreditCardSuggestions(
1095       type, field.value, values, labels, icons, &guid_pairs);
1096
1097   for (size_t i = 0; i < guid_pairs.size(); ++i) {
1098     unique_ids->push_back(PackGUIDs(guid_pairs[i], GUIDPair(std::string(), 0)));
1099   }
1100 }
1101
1102 void AutofillManager::ParseForms(const std::vector<FormData>& forms) {
1103   std::vector<FormStructure*> non_queryable_forms;
1104   for (std::vector<FormData>::const_iterator iter = forms.begin();
1105        iter != forms.end(); ++iter) {
1106     scoped_ptr<FormStructure> form_structure(new FormStructure(*iter));
1107     if (!form_structure->ShouldBeParsed())
1108       continue;
1109
1110     form_structure->DetermineHeuristicTypes(*metric_logger_);
1111
1112     // Set aside forms with method GET or author-specified types, so that they
1113     // are not included in the query to the server.
1114     if (form_structure->ShouldBeCrowdsourced())
1115       form_structures_.push_back(form_structure.release());
1116     else
1117       non_queryable_forms.push_back(form_structure.release());
1118   }
1119
1120   if (!form_structures_.empty() && download_manager_) {
1121     // Query the server if we have at least one of the forms were parsed.
1122     download_manager_->StartQueryRequest(form_structures_.get(),
1123                                         *metric_logger_);
1124   }
1125
1126   for (std::vector<FormStructure*>::const_iterator iter =
1127            non_queryable_forms.begin();
1128        iter != non_queryable_forms.end(); ++iter) {
1129     form_structures_.push_back(*iter);
1130   }
1131
1132   if (!form_structures_.empty())
1133     metric_logger_->LogUserHappinessMetric(AutofillMetrics::FORMS_LOADED);
1134
1135   // For the |non_queryable_forms|, we have all the field type info we're ever
1136   // going to get about them.  For the other forms, we'll wait until we get a
1137   // response from the server.
1138   driver_->SendAutofillTypePredictionsToRenderer(non_queryable_forms);
1139 }
1140
1141 int AutofillManager::GUIDToID(const GUIDPair& guid) const {
1142   if (!base::IsValidGUID(guid.first))
1143     return 0;
1144
1145   std::map<GUIDPair, int>::const_iterator iter = guid_id_map_.find(guid);
1146   if (iter == guid_id_map_.end()) {
1147     int id = guid_id_map_.size() + 1;
1148     guid_id_map_[guid] = id;
1149     id_guid_map_[id] = guid;
1150     return id;
1151   } else {
1152     return iter->second;
1153   }
1154 }
1155
1156 const GUIDPair AutofillManager::IDToGUID(int id) const {
1157   if (id == 0)
1158     return GUIDPair(std::string(), 0);
1159
1160   std::map<int, GUIDPair>::const_iterator iter = id_guid_map_.find(id);
1161   if (iter == id_guid_map_.end()) {
1162     NOTREACHED();
1163     return GUIDPair(std::string(), 0);
1164   }
1165
1166   return iter->second;
1167 }
1168
1169 // When sending IDs (across processes) to the renderer we pack credit card and
1170 // profile IDs into a single integer.  Credit card IDs are sent in the high
1171 // word and profile IDs are sent in the low word.
1172 int AutofillManager::PackGUIDs(const GUIDPair& cc_guid,
1173                                const GUIDPair& profile_guid) const {
1174   int cc_id = GUIDToID(cc_guid);
1175   int profile_id = GUIDToID(profile_guid);
1176
1177   DCHECK(cc_id <= std::numeric_limits<unsigned short>::max());
1178   DCHECK(profile_id <= std::numeric_limits<unsigned short>::max());
1179
1180   return cc_id << std::numeric_limits<unsigned short>::digits | profile_id;
1181 }
1182
1183 // When receiving IDs (across processes) from the renderer we unpack credit card
1184 // and profile IDs from a single integer.  Credit card IDs are stored in the
1185 // high word and profile IDs are stored in the low word.
1186 void AutofillManager::UnpackGUIDs(int id,
1187                                   GUIDPair* cc_guid,
1188                                   GUIDPair* profile_guid) const {
1189   int cc_id = id >> std::numeric_limits<unsigned short>::digits &
1190       std::numeric_limits<unsigned short>::max();
1191   int profile_id = id & std::numeric_limits<unsigned short>::max();
1192
1193   *cc_guid = IDToGUID(cc_id);
1194   *profile_guid = IDToGUID(profile_id);
1195 }
1196
1197 void AutofillManager::UpdateInitialInteractionTimestamp(
1198     const TimeTicks& interaction_timestamp) {
1199   if (initial_interaction_timestamp_.is_null() ||
1200       interaction_timestamp < initial_interaction_timestamp_) {
1201     initial_interaction_timestamp_ = interaction_timestamp;
1202   }
1203 }
1204
1205 bool AutofillManager::ShouldUploadForm(const FormStructure& form) {
1206   if (!IsAutofillEnabled())
1207     return false;
1208
1209   if (driver_->IsOffTheRecord())
1210     return false;
1211
1212   // Disregard forms that we wouldn't ever autofill in the first place.
1213   if (!form.ShouldBeParsed())
1214     return false;
1215
1216   return true;
1217 }
1218
1219 }  // namespace autofill