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.
5 #include "components/autofill/core/browser/autofill_manager.h"
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"
53 typedef PersonalDataManager::GUIDPair GUIDPair;
55 using base::TimeTicks;
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;
64 const size_t kMaxRecentFormSignaturesToRemember = 3;
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;
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());
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;
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]);
96 values->swap(values_copy);
97 labels->swap(labels_copy);
98 icons->swap(icons_copy);
99 unique_ids->swap(unique_ids_copy);
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|
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) {
119 bool FormIsHTTPS(const FormStructure& form) {
120 // TODO(blundell): Change this to use a constant once crbug.com/306258 is
122 return form.source_url().SchemeIs("https");
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;
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);
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);
152 if (matching_types.empty())
153 matching_types.insert(UNKNOWN_TYPE);
155 field->set_possible_types(matching_types);
161 AutofillManager::AutofillManager(
162 AutofillDriver* driver,
163 AutofillClient* client,
164 const std::string& app_locale,
165 AutofillDownloadManagerState enable_download_manager)
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));
188 AutofillManager::~AutofillManager() {}
191 void AutofillManager::RegisterProfilePrefs(
192 user_prefs::PrefRegistrySyncable* registry) {
193 registry->RegisterBooleanPref(
194 prefs::kAutofillEnabled,
196 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
197 #if defined(OS_MACOSX)
198 registry->RegisterBooleanPref(
199 prefs::kAutofillAuxiliaryProfilesEnabled,
201 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
202 #else // defined(OS_MACOSX)
203 registry->RegisterBooleanPref(
204 prefs::kAutofillAuxiliaryProfilesEnabled,
206 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
207 #endif // defined(OS_MACOSX)
208 #if defined(OS_MACOSX)
209 registry->RegisterBooleanPref(
210 prefs::kAutofillMacAddressBookQueried,
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);
223 #if defined(OS_MACOSX) && !defined(OS_IOS)
224 registry->RegisterBooleanPref(
225 prefs::kAutofillUseMacAddressBook,
227 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
228 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
231 #if defined(OS_MACOSX) && !defined(OS_IOS)
232 void AutofillManager::MigrateUserPrefs(PrefService* prefs) {
233 const PrefService::Preference* pref =
234 prefs->FindPreference(prefs::kAutofillUseMacAddressBook);
236 // If the pref is not its default value, then the migration has already been
238 if (!pref->IsDefaultValue())
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);
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));
258 bool success = pref_accessed->GetValue()->GetAsBoolean(&accessed);
260 success = pref_enabled->GetValue()->GetAsBoolean(&enabled);
263 prefs->SetBoolean(prefs::kAutofillUseMacAddressBook, accessed && enabled);
265 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
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);
275 void AutofillManager::ShowAutofillSettings() {
276 client_->ShowAutofillSettings();
279 #if defined(OS_MACOSX) && !defined(OS_IOS)
280 bool AutofillManager::ShouldShowAccessAddressBookSuggestion(
281 const FormData& form,
282 const FormFieldData& field) {
285 FormStructure* form_structure = NULL;
286 AutofillField* autofill_field = NULL;
287 if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
290 return personal_data_->ShouldShowAccessAddressBookSuggestion(
291 autofill_field->Type());
294 bool AutofillManager::AccessAddressBook() {
297 return personal_data_->AccessAddressBook();
299 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
301 bool AutofillManager::OnFormSubmitted(const FormData& form,
302 const TimeTicks& timestamp) {
303 if (!IsValidFormData(form))
306 // Let Autocomplete know as well.
307 autocomplete_history_manager_->OnFormSubmitted(form);
309 // Grab a copy of the form data.
310 scoped_ptr<FormStructure> submitted_form(new FormStructure(form));
312 if (!ShouldUploadForm(*submitted_form))
315 // Don't save data that was submitted through JavaScript.
316 if (!form.user_submitted)
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))
325 submitted_form->UpdateFromCache(*cached_submitted_form);
326 if (submitted_form->IsAutofillable())
327 ImportFormData(*submitted_form);
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
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);
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);
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(
356 base::Bind(&DeterminePossibleFieldTypesForUpload,
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_,
372 void AutofillManager::OnFormsSeen(const std::vector<FormData>& forms,
373 const TimeTicks& timestamp) {
374 if (!IsValidFormDataVector(forms))
377 if (!driver_->RendererIsAvailable())
380 bool enabled = IsAutofillEnabled();
381 if (!has_logged_autofill_enabled_) {
382 metric_logger_->LogIsAutofillEnabledAtPageLoad(enabled);
383 has_logged_autofill_enabled_ = true;
389 for (size_t i = 0; i < forms.size(); ++i) {
390 forms_loaded_timestamps_[forms[i]] = timestamp;
396 void AutofillManager::OnTextFieldDidChange(const FormData& form,
397 const FormFieldData& field,
398 const TimeTicks& timestamp) {
399 if (!IsValidFormData(form) || !IsValidFormFieldData(field))
402 FormStructure* form_structure = NULL;
403 AutofillField* autofill_field = NULL;
404 if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
407 if (!user_did_type_) {
408 user_did_type_ = true;
409 metric_logger_->LogUserHappinessMetric(AutofillMetrics::USER_DID_TYPE);
412 if (autofill_field->is_autofilled) {
413 autofill_field->is_autofilled = false;
414 metric_logger_->LogUserHappinessMetric(
415 AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD);
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);
424 UpdateInitialInteractionTimestamp(timestamp);
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))
435 std::vector<base::string16> values;
436 std::vector<base::string16> labels;
437 std::vector<base::string16> icons;
438 std::vector<int> unique_ids;
440 external_delegate_->OnQuery(query_id,
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);
458 GetProfileSuggestions(
459 form_structure, field, type, &values, &labels, &icons, &unique_ids);
462 DCHECK_EQ(values.size(), labels.size());
463 DCHECK_EQ(values.size(), icons.size());
464 DCHECK_EQ(values.size(), unique_ids.size());
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.
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;
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);
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());
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);
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;
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
513 autocomplete_history_manager_->OnGetAutocompleteSuggestions(
514 query_id, field.name, field.value, field.form_control_type, values,
515 labels, icons, unique_ids);
518 void AutofillManager::FillOrPreviewForm(
519 AutofillDriver::RendererFormDataAction action,
521 const FormData& form,
522 const FormFieldData& field,
524 if (!IsValidFormData(form) || !IsValidFormFieldData(field))
527 const AutofillDataModel* data_model = NULL;
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))
542 DCHECK(form_structure);
543 DCHECK(autofill_field);
545 FormData result = form;
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();
556 // If the relevant section is auto-filled, we should fill |field| but not the
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,
566 profile_language_code,
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;
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;
578 if (!is_credit_card && !value.empty())
579 client_->DidFillOrPreviewField(value, profile_full_name);
585 driver_->SendFormDataToRenderer(query_id, action, result);
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())
596 DCHECK_EQ(*form_structure->field(i), result.fields[i]);
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;
611 base::string16 value = data_model->GetInfoForVariant(
612 cached_field->Type(), use_variant, app_locale_);
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).
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,
626 profile_language_code,
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;
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;
639 client_->DidFillOrPreviewField(value, profile_full_name);
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();
650 driver_->SendFormDataToRenderer(query_id, action, result);
653 void AutofillManager::OnDidPreviewAutofillFormData() {
655 test_delegate_->DidPreviewFormData();
658 void AutofillManager::OnDidFillAutofillFormData(const TimeTicks& timestamp) {
660 test_delegate_->DidFillFormData();
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);
669 UpdateInitialInteractionTimestamp(timestamp);
672 void AutofillManager::DidShowSuggestions(bool is_new_popup) {
674 test_delegate_->DidShowSuggestions();
677 metric_logger_->LogUserHappinessMetric(AutofillMetrics::SUGGESTIONS_SHOWN);
679 if (!did_show_suggestions_) {
680 did_show_suggestions_ = true;
681 metric_logger_->LogUserHappinessMetric(
682 AutofillMetrics::SUGGESTIONS_SHOWN_ONCE);
687 void AutofillManager::OnHidePopup() {
688 if (!IsAutofillEnabled())
691 client_->HideAutofillPopup();
694 void AutofillManager::RemoveAutofillProfileOrCreditCard(int unique_id) {
695 const AutofillDataModel* data_model = NULL;
697 bool unused_is_credit_card = false;
698 if (!GetProfileOrCreditCard(
699 unique_id, &data_model, &variant, &unused_is_credit_card)) {
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
710 personal_data_->RemoveByGUID(data_model->guid());
713 void AutofillManager::RemoveAutocompleteEntry(const base::string16& name,
714 const base::string16& value) {
715 autocomplete_history_manager_->OnRemoveAutocompleteEntry(name, value);
718 const std::vector<FormStructure*>& AutofillManager::GetFormStructures() {
719 return form_structures_.get();
722 void AutofillManager::SetTestDelegate(AutofillManagerTestDelegate* delegate) {
723 test_delegate_ = delegate;
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())
733 external_delegate_->SetCurrentDataListValues(values, labels);
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(),
743 // Forward form structures to the password generation manager to detect
744 // account creation forms.
745 client_->DetectAccountCreationForms(form_structures_.get());
747 // If the corresponding flag is set, annotate forms with the predicted types.
748 driver_->SendAutofillTypePredictionsToRenderer(form_structures_.get());
751 void AutofillManager::OnDidEndTextFieldEditing() {
752 external_delegate_->DidEndTextFieldEditing();
755 bool AutofillManager::IsAutofillEnabled() const {
756 return client_->GetPrefs()->GetBoolean(prefs::kAutofillEnabled);
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))
764 // If credit card information was submitted, we need to confirm whether to
766 if (imported_credit_card) {
767 client_->ConfirmSaveCreditCard(
770 base::IgnoreResult(&PersonalDataManager::SaveImportedCreditCard),
771 base::Unretained(personal_data_),
772 *imported_credit_card));
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_,
790 if (submitted_form->ShouldBeCrowdsourced())
791 UploadFormData(*submitted_form);
794 void AutofillManager::UploadFormData(const FormStructure& submitted_form) {
795 if (!download_manager_)
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;
805 if (*it == form_signature)
806 was_autofilled = true;
809 ServerFieldTypeSet non_empty_types;
810 personal_data_->GetNonEmptyTypes(&non_empty_types);
812 download_manager_->StartUploadRequest(submitted_form, was_autofilled,
816 bool AutofillManager::UploadPasswordForm(
817 const FormData& form,
818 const ServerFieldType& password_type) {
819 FormStructure form_structure(form);
821 if (!ShouldUploadForm(form_structure))
824 if (!form_structure.ShouldBeCrowdsourced())
827 // Find the first password field to label. We don't try to label anything
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);
833 ServerFieldTypeSet types;
834 if (!found_password_field && field->form_control_type == "password") {
835 types.insert(password_type);
836 found_password_field = true;
838 types.insert(UNKNOWN_TYPE);
840 field->set_possible_types(types);
842 DCHECK(found_password_field);
844 // Only one field type should be present.
845 ServerFieldTypeSet available_field_types;
846 available_field_types.insert(password_type);
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
851 form_structure.set_upload_required(UPLOAD_REQUIRED);
853 if (!download_manager_)
856 return download_manager_->StartUploadRequest(form_structure,
857 false /* was_autofilled */,
858 available_field_types);
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();
874 AutofillManager::AutofillManager(AutofillDriver* driver,
875 AutofillClient* client,
876 PersonalDataManager* personal_data)
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) {
897 void AutofillManager::set_metric_logger(const AutofillMetrics* metric_logger) {
898 metric_logger_.reset(metric_logger);
901 bool AutofillManager::RefreshDataModels() const {
902 if (!IsAutofillEnabled())
905 // No autofill data to return if the profiles are empty.
906 if (personal_data_->GetProfiles().empty() &&
907 personal_data_->GetCreditCards().empty()) {
914 bool AutofillManager::GetProfileOrCreditCard(
916 const AutofillDataModel** data_model,
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;
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|,
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;
939 return !!*data_model;
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;
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())
966 if (!(*form_structure))
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()) {
984 // Update the cached form to reflect any dynamic changes to the form data, if
986 if (!UpdateCachedForm(form, *form_structure, form_structure))
989 // No data to return if there are no auto-fillable fields.
990 if (!(*form_structure)->autofill_count())
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;
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;
1010 bool AutofillManager::UpdateCachedForm(const FormData& live_form,
1011 const FormStructure* cached_form,
1012 FormStructure** updated_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];
1023 if (form_structures_.size() >= kMaxFormCacheSize)
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_);
1031 // If we have cached data, propagate it to the updated 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;
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;
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.
1054 // Annotate the updated form with its predicted types.
1055 std::vector<FormStructure*> forms(1, *updated_form);
1056 driver_->SendAutofillTypePredictionsToRenderer(forms);
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());
1073 std::vector<GUIDPair> guid_pairs;
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);
1080 for (size_t i = 0; i < guid_pairs.size(); ++i) {
1081 unique_ids->push_back(PackGUIDs(GUIDPair(std::string(), 0),
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);
1097 for (size_t i = 0; i < guid_pairs.size(); ++i) {
1098 unique_ids->push_back(PackGUIDs(guid_pairs[i], GUIDPair(std::string(), 0)));
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())
1110 form_structure->DetermineHeuristicTypes(*metric_logger_);
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());
1117 non_queryable_forms.push_back(form_structure.release());
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(),
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);
1132 if (!form_structures_.empty())
1133 metric_logger_->LogUserHappinessMetric(AutofillMetrics::FORMS_LOADED);
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);
1141 int AutofillManager::GUIDToID(const GUIDPair& guid) const {
1142 if (!base::IsValidGUID(guid.first))
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;
1152 return iter->second;
1156 const GUIDPair AutofillManager::IDToGUID(int id) const {
1158 return GUIDPair(std::string(), 0);
1160 std::map<int, GUIDPair>::const_iterator iter = id_guid_map_.find(id);
1161 if (iter == id_guid_map_.end()) {
1163 return GUIDPair(std::string(), 0);
1166 return iter->second;
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);
1177 DCHECK(cc_id <= std::numeric_limits<unsigned short>::max());
1178 DCHECK(profile_id <= std::numeric_limits<unsigned short>::max());
1180 return cc_id << std::numeric_limits<unsigned short>::digits | profile_id;
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,
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();
1193 *cc_guid = IDToGUID(cc_id);
1194 *profile_guid = IDToGUID(profile_id);
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;
1205 bool AutofillManager::ShouldUploadForm(const FormStructure& form) {
1206 if (!IsAutofillEnabled())
1209 if (driver_->IsOffTheRecord())
1212 // Disregard forms that we wouldn't ever autofill in the first place.
1213 if (!form.ShouldBeParsed())
1219 } // namespace autofill