[Media Router] Add integration tests and e2e tests for media router and presentation...
[chromium-blink-merge.git] / components / autofill / core / browser / autofill_manager.cc
blob756b1b1c3f18001b814001cd7cafd6463d79ea06
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"
7 #include <stddef.h>
9 #include <limits>
10 #include <map>
11 #include <set>
12 #include <utility>
14 #include "base/bind.h"
15 #include "base/command_line.h"
16 #include "base/guid.h"
17 #include "base/logging.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram_macros.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/strings/string16.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/threading/sequenced_worker_pool.h"
26 #include "components/autofill/core/browser/autocomplete_history_manager.h"
27 #include "components/autofill/core/browser/autofill_client.h"
28 #include "components/autofill/core/browser/autofill_data_model.h"
29 #include "components/autofill/core/browser/autofill_experiments.h"
30 #include "components/autofill/core/browser/autofill_external_delegate.h"
31 #include "components/autofill/core/browser/autofill_field.h"
32 #include "components/autofill/core/browser/autofill_manager_test_delegate.h"
33 #include "components/autofill/core/browser/autofill_metrics.h"
34 #include "components/autofill/core/browser/autofill_profile.h"
35 #include "components/autofill/core/browser/autofill_type.h"
36 #include "components/autofill/core/browser/credit_card.h"
37 #include "components/autofill/core/browser/field_types.h"
38 #include "components/autofill/core/browser/form_structure.h"
39 #include "components/autofill/core/browser/personal_data_manager.h"
40 #include "components/autofill/core/browser/phone_number.h"
41 #include "components/autofill/core/browser/phone_number_i18n.h"
42 #include "components/autofill/core/browser/popup_item_ids.h"
43 #include "components/autofill/core/common/autofill_data_validation.h"
44 #include "components/autofill/core/common/autofill_pref_names.h"
45 #include "components/autofill/core/common/autofill_switches.h"
46 #include "components/autofill/core/common/form_data.h"
47 #include "components/autofill/core/common/form_data_predictions.h"
48 #include "components/autofill/core/common/form_field_data.h"
49 #include "components/autofill/core/common/password_form_fill_data.h"
50 #include "components/pref_registry/pref_registry_syncable.h"
51 #include "grit/components_strings.h"
52 #include "ui/base/l10n/l10n_util.h"
53 #include "ui/gfx/geometry/rect.h"
54 #include "url/gurl.h"
56 namespace autofill {
58 using base::TimeTicks;
60 namespace {
62 // We only send a fraction of the forms to upload server.
63 // The rate for positive/negative matches potentially could be different.
64 const double kAutofillPositiveUploadRateDefaultValue = 0.20;
65 const double kAutofillNegativeUploadRateDefaultValue = 0.20;
67 const size_t kMaxRecentFormSignaturesToRemember = 3;
69 // Set a conservative upper bound on the number of forms we are willing to
70 // cache, simply to prevent unbounded memory consumption.
71 const size_t kMaxFormCacheSize = 100;
73 // Precondition: |form_structure| and |form| should correspond to the same
74 // logical form. Returns true if any field in the given |section| within |form|
75 // is auto-filled.
76 bool SectionIsAutofilled(const FormStructure& form_structure,
77 const FormData& form,
78 const std::string& section) {
79 DCHECK_EQ(form_structure.field_count(), form.fields.size());
80 for (size_t i = 0; i < form_structure.field_count(); ++i) {
81 if (form_structure.field(i)->section() == section &&
82 form.fields[i].is_autofilled) {
83 return true;
87 return false;
90 bool FormIsHTTPS(const FormStructure& form) {
91 return form.source_url().SchemeIs(url::kHttpsScheme);
94 // Uses the existing personal data in |profiles| and |credit_cards| to determine
95 // possible field types for the |submitted_form|. This is potentially
96 // expensive -- on the order of 50ms even for a small set of |stored_data|.
97 // Hence, it should not run on the UI thread -- to avoid locking up the UI --
98 // nor on the IO thread -- to avoid blocking IPC calls.
99 void DeterminePossibleFieldTypesForUpload(
100 const std::vector<AutofillProfile>& profiles,
101 const std::vector<CreditCard>& credit_cards,
102 const std::string& app_locale,
103 FormStructure* submitted_form) {
104 // For each field in the |submitted_form|, extract the value. Then for each
105 // profile or credit card, identify any stored types that match the value.
106 for (size_t i = 0; i < submitted_form->field_count(); ++i) {
107 AutofillField* field = submitted_form->field(i);
108 ServerFieldTypeSet matching_types;
110 base::string16 value;
111 base::TrimWhitespace(field->value, base::TRIM_ALL, &value);
112 for (std::vector<AutofillProfile>::const_iterator it = profiles.begin();
113 it != profiles.end(); ++it) {
114 it->GetMatchingTypes(value, app_locale, &matching_types);
116 for (std::vector<CreditCard>::const_iterator it = credit_cards.begin();
117 it != credit_cards.end(); ++it) {
118 it->GetMatchingTypes(value, app_locale, &matching_types);
121 if (matching_types.empty())
122 matching_types.insert(UNKNOWN_TYPE);
124 field->set_possible_types(matching_types);
128 } // namespace
130 AutofillManager::AutofillManager(
131 AutofillDriver* driver,
132 AutofillClient* client,
133 const std::string& app_locale,
134 AutofillDownloadManagerState enable_download_manager)
135 : driver_(driver),
136 client_(client),
137 real_pan_client_(driver->GetURLRequestContext(), this),
138 app_locale_(app_locale),
139 personal_data_(client->GetPersonalDataManager()),
140 autocomplete_history_manager_(
141 new AutocompleteHistoryManager(driver, client)),
142 address_form_event_logger_(
143 new AutofillMetrics::FormEventLogger(false /* is_for_credit_card */)),
144 credit_card_form_event_logger_(
145 new AutofillMetrics::FormEventLogger(true /* is_for_credit_card */)),
146 has_logged_autofill_enabled_(false),
147 has_logged_address_suggestions_count_(false),
148 did_show_suggestions_(false),
149 user_did_type_(false),
150 user_did_autofill_(false),
151 user_did_edit_autofilled_field_(false),
152 external_delegate_(NULL),
153 test_delegate_(NULL),
154 weak_ptr_factory_(this) {
155 if (enable_download_manager == ENABLE_AUTOFILL_DOWNLOAD_MANAGER) {
156 download_manager_.reset(
157 new AutofillDownloadManager(driver, client_->GetPrefs(), this));
161 AutofillManager::~AutofillManager() {}
163 // static
164 void AutofillManager::RegisterProfilePrefs(
165 user_prefs::PrefRegistrySyncable* registry) {
166 registry->RegisterBooleanPref(
167 prefs::kAutofillEnabled,
168 true,
169 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
170 registry->RegisterBooleanPref(prefs::kAutofillWalletSyncExperimentEnabled,
171 false);
172 // TODO(estade): Should this be syncable?
173 registry->RegisterBooleanPref(
174 prefs::kAutofillWalletImportEnabled,
175 true,
176 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
177 // This choice is made on a per-device basis, so it's not syncable.
178 registry->RegisterBooleanPref(
179 prefs::kAutofillWalletImportStorageCheckboxState, true);
180 #if defined(OS_MACOSX)
181 registry->RegisterBooleanPref(
182 prefs::kAutofillAuxiliaryProfilesEnabled,
183 true,
184 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
185 #else // defined(OS_MACOSX)
186 registry->RegisterBooleanPref(prefs::kAutofillAuxiliaryProfilesEnabled,
187 false);
188 #endif // defined(OS_MACOSX)
189 #if defined(OS_MACOSX)
190 registry->RegisterBooleanPref(prefs::kAutofillMacAddressBookQueried, false);
191 #endif // defined(OS_MACOSX)
192 registry->RegisterDoublePref(prefs::kAutofillPositiveUploadRate,
193 kAutofillPositiveUploadRateDefaultValue);
194 registry->RegisterDoublePref(prefs::kAutofillNegativeUploadRate,
195 kAutofillNegativeUploadRateDefaultValue);
197 #if defined(OS_MACOSX) && !defined(OS_IOS)
198 registry->RegisterBooleanPref(prefs::kAutofillUseMacAddressBook, false);
199 registry->RegisterIntegerPref(prefs::kAutofillMacAddressBookShowedCount, 0);
200 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
203 #if defined(OS_MACOSX) && !defined(OS_IOS)
204 void AutofillManager::MigrateUserPrefs(PrefService* prefs) {
205 const PrefService::Preference* pref =
206 prefs->FindPreference(prefs::kAutofillUseMacAddressBook);
208 // If the pref is not its default value, then the migration has already been
209 // performed.
210 if (!pref->IsDefaultValue())
211 return;
213 // Whether Chrome has already tried to access the user's Address Book.
214 const PrefService::Preference* pref_accessed =
215 prefs->FindPreference(prefs::kAutofillMacAddressBookQueried);
216 // Whether the user wants to use the Address Book to populate Autofill.
217 const PrefService::Preference* pref_enabled =
218 prefs->FindPreference(prefs::kAutofillAuxiliaryProfilesEnabled);
220 if (pref_accessed->IsDefaultValue() && pref_enabled->IsDefaultValue()) {
221 // This is likely a new user. Reset the default value to prevent the
222 // migration from happening again.
223 prefs->SetBoolean(prefs::kAutofillUseMacAddressBook,
224 prefs->GetBoolean(prefs::kAutofillUseMacAddressBook));
225 return;
228 bool accessed;
229 bool enabled;
230 bool success = pref_accessed->GetValue()->GetAsBoolean(&accessed);
231 DCHECK(success);
232 success = pref_enabled->GetValue()->GetAsBoolean(&enabled);
233 DCHECK(success);
235 prefs->SetBoolean(prefs::kAutofillUseMacAddressBook, accessed && enabled);
237 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
239 void AutofillManager::SetExternalDelegate(AutofillExternalDelegate* delegate) {
240 // TODO(jrg): consider passing delegate into the ctor. That won't
241 // work if the delegate has a pointer to the AutofillManager, but
242 // future directions may not need such a pointer.
243 external_delegate_ = delegate;
244 autocomplete_history_manager_->SetExternalDelegate(delegate);
247 void AutofillManager::ShowAutofillSettings() {
248 client_->ShowAutofillSettings();
251 #if defined(OS_MACOSX) && !defined(OS_IOS)
252 bool AutofillManager::ShouldShowAccessAddressBookSuggestion(
253 const FormData& form,
254 const FormFieldData& field) {
255 AutofillField* autofill_field = GetAutofillField(form, field);
256 return autofill_field &&
257 personal_data_->ShouldShowAccessAddressBookSuggestion(
258 autofill_field->Type());
261 bool AutofillManager::AccessAddressBook() {
262 if (!personal_data_)
263 return false;
264 return personal_data_->AccessAddressBook();
267 void AutofillManager::ShowedAccessAddressBookPrompt() {
268 if (!personal_data_)
269 return;
270 return personal_data_->ShowedAccessAddressBookPrompt();
273 int AutofillManager::AccessAddressBookPromptCount() {
274 if (!personal_data_)
275 return 0;
276 return personal_data_->AccessAddressBookPromptCount();
278 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
280 bool AutofillManager::ShouldShowScanCreditCard(const FormData& form,
281 const FormFieldData& field) {
282 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
283 autofill::switches::kEnableCreditCardScan) &&
284 (base::FieldTrialList::FindFullName("CreditCardScan") != "Enabled" ||
285 base::CommandLine::ForCurrentProcess()->HasSwitch(
286 autofill::switches::kDisableCreditCardScan))) {
287 return false;
290 if (!client_->HasCreditCardScanFeature())
291 return false;
293 AutofillField* autofill_field = GetAutofillField(form, field);
294 if (!autofill_field ||
295 autofill_field->Type().GetStorableType() != CREDIT_CARD_NUMBER) {
296 return false;
299 static const int kShowScanCreditCardMaxValueLength = 6;
300 return field.value.size() <= kShowScanCreditCardMaxValueLength &&
301 base::ContainsOnlyChars(CreditCard::StripSeparators(field.value),
302 base::ASCIIToUTF16("0123456789"));
305 bool AutofillManager::OnWillSubmitForm(const FormData& form,
306 const TimeTicks& timestamp) {
307 if (!IsValidFormData(form))
308 return false;
310 scoped_ptr<FormStructure> submitted_form = ValidateSubmittedForm(form);
311 if (!submitted_form)
312 return false;
314 address_form_event_logger_->OnWillSubmitForm();
315 credit_card_form_event_logger_->OnWillSubmitForm();
317 // Only upload server statistics and UMA metrics if at least some local data
318 // is available to use as a baseline.
319 const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles();
320 if (submitted_form->IsAutofillable()) {
321 AutofillMetrics::LogNumberOfProfilesAtAutofillableFormSubmission(
322 personal_data_->GetProfiles().size());
324 const std::vector<CreditCard*>& credit_cards =
325 personal_data_->GetCreditCards();
326 if (!profiles.empty() || !credit_cards.empty()) {
327 // Copy the profile and credit card data, so that it can be accessed on a
328 // separate thread.
329 std::vector<AutofillProfile> copied_profiles;
330 copied_profiles.reserve(profiles.size());
331 for (std::vector<AutofillProfile*>::const_iterator it = profiles.begin();
332 it != profiles.end(); ++it) {
333 copied_profiles.push_back(**it);
336 std::vector<CreditCard> copied_credit_cards;
337 copied_credit_cards.reserve(credit_cards.size());
338 for (std::vector<CreditCard*>::const_iterator it = credit_cards.begin();
339 it != credit_cards.end(); ++it) {
340 copied_credit_cards.push_back(**it);
343 // Note that ownership of |submitted_form| is passed to the second task,
344 // using |base::Owned|.
345 FormStructure* raw_submitted_form = submitted_form.get();
346 driver_->GetBlockingPool()->PostTaskAndReply(
347 FROM_HERE,
348 base::Bind(&DeterminePossibleFieldTypesForUpload,
349 copied_profiles,
350 copied_credit_cards,
351 app_locale_,
352 raw_submitted_form),
353 base::Bind(&AutofillManager::UploadFormDataAsyncCallback,
354 weak_ptr_factory_.GetWeakPtr(),
355 base::Owned(submitted_form.release()),
356 forms_loaded_timestamps_[form],
357 initial_interaction_timestamp_,
358 timestamp));
361 return true;
364 bool AutofillManager::OnFormSubmitted(const FormData& form) {
365 if (!IsValidFormData(form))
366 return false;
368 // We will always give Autocomplete a chance to save the data.
369 scoped_ptr<FormStructure> submitted_form = ValidateSubmittedForm(form);
370 if (!submitted_form) {
371 autocomplete_history_manager_->OnFormSubmitted(form);
372 return false;
375 // However, if Autofill has recognized a field as CVC, that shouldn't be
376 // saved.
377 FormData form_for_autocomplete = submitted_form->ToFormData();
378 form_for_autocomplete.user_submitted = form.user_submitted;
379 for (size_t i = 0; i < submitted_form->field_count(); ++i) {
380 if (submitted_form->field(i)->Type().GetStorableType() ==
381 CREDIT_CARD_VERIFICATION_CODE) {
382 form_for_autocomplete.fields[i].should_autocomplete = false;
385 autocomplete_history_manager_->OnFormSubmitted(form_for_autocomplete);
387 address_form_event_logger_->OnFormSubmitted();
388 credit_card_form_event_logger_->OnFormSubmitted();
390 // Update Personal Data with the form's submitted data.
391 if (submitted_form->IsAutofillable())
392 ImportFormData(*submitted_form);
394 recently_unmasked_cards_.clear();
396 return true;
399 void AutofillManager::OnFormsSeen(const std::vector<FormData>& forms,
400 const TimeTicks& timestamp) {
401 if (!IsValidFormDataVector(forms))
402 return;
404 if (!driver_->RendererIsAvailable())
405 return;
407 bool enabled = IsAutofillEnabled();
408 if (!has_logged_autofill_enabled_) {
409 AutofillMetrics::LogIsAutofillEnabledAtPageLoad(enabled);
410 has_logged_autofill_enabled_ = true;
413 if (!enabled)
414 return;
416 for (size_t i = 0; i < forms.size(); ++i) {
417 forms_loaded_timestamps_[forms[i]] = timestamp;
420 ParseForms(forms);
423 void AutofillManager::OnTextFieldDidChange(const FormData& form,
424 const FormFieldData& field,
425 const TimeTicks& timestamp) {
426 if (!IsValidFormData(form) || !IsValidFormFieldData(field))
427 return;
429 FormStructure* form_structure = NULL;
430 AutofillField* autofill_field = NULL;
431 if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
432 return;
434 if (!user_did_type_) {
435 user_did_type_ = true;
436 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::USER_DID_TYPE);
439 if (autofill_field->is_autofilled) {
440 autofill_field->is_autofilled = false;
441 AutofillMetrics::LogUserHappinessMetric(
442 AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD);
444 if (!user_did_edit_autofilled_field_) {
445 user_did_edit_autofilled_field_ = true;
446 AutofillMetrics::LogUserHappinessMetric(
447 AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD_ONCE);
451 UpdateInitialInteractionTimestamp(timestamp);
454 void AutofillManager::OnQueryFormFieldAutofill(int query_id,
455 const FormData& form,
456 const FormFieldData& field,
457 const gfx::RectF& bounding_box) {
458 if (!IsValidFormData(form) || !IsValidFormFieldData(field))
459 return;
461 std::vector<Suggestion> suggestions;
463 external_delegate_->OnQuery(query_id, form, field, bounding_box);
465 // Need to refresh models before using the form_event_loggers.
466 bool is_autofill_possible = RefreshDataModels();
468 FormStructure* form_structure = NULL;
469 AutofillField* autofill_field = NULL;
470 bool got_autofillable_form =
471 GetCachedFormAndField(form, field, &form_structure, &autofill_field) &&
472 // Don't send suggestions or track forms that aren't auto-fillable.
473 form_structure->IsAutofillable();
475 // Logging interactions of forms that are autofillable.
476 if (got_autofillable_form) {
477 if (autofill_field->Type().group() == CREDIT_CARD)
478 credit_card_form_event_logger_->OnDidInteractWithAutofillableForm();
479 else
480 address_form_event_logger_->OnDidInteractWithAutofillableForm();
483 if (is_autofill_possible &&
484 driver_->RendererIsAvailable() &&
485 got_autofillable_form) {
486 AutofillType type = autofill_field->Type();
487 bool is_filling_credit_card = (type.group() == CREDIT_CARD);
488 if (is_filling_credit_card) {
489 suggestions = GetCreditCardSuggestions(field, type);
490 } else {
491 suggestions =
492 GetProfileSuggestions(*form_structure, field, *autofill_field);
494 if (!suggestions.empty()) {
495 // Don't provide credit card suggestions for non-HTTPS pages. However,
496 // do provide a warning to the user.
497 if (is_filling_credit_card && !FormIsHTTPS(*form_structure)) {
498 Suggestion warning_suggestion(l10n_util::GetStringUTF16(
499 IDS_AUTOFILL_WARNING_INSECURE_CONNECTION));
500 warning_suggestion.frontend_id = POPUP_ITEM_ID_WARNING_MESSAGE;
501 suggestions.assign(1, warning_suggestion);
502 } else {
503 bool section_is_autofilled =
504 SectionIsAutofilled(*form_structure, form,
505 autofill_field->section());
506 if (section_is_autofilled) {
507 // If the relevant section is auto-filled and the renderer is querying
508 // for suggestions, then the user is editing the value of a field.
509 // In this case, mimic autocomplete: don't display labels or icons,
510 // as that information is redundant.
511 for (size_t i = 0; i < suggestions.size(); i++) {
512 suggestions[i].label = base::string16();
513 suggestions[i].icon = base::string16();
517 // The first time we show suggestions on this page, log the number of
518 // suggestions available.
519 // TODO(mathp): Differentiate between number of suggestions available
520 // (current metric) and number shown to the user.
521 if (!has_logged_address_suggestions_count_ && !section_is_autofilled) {
522 AutofillMetrics::LogAddressSuggestionsCount(suggestions.size());
523 has_logged_address_suggestions_count_ = true;
529 if (field.should_autocomplete) {
530 // Add the results from AutoComplete. They come back asynchronously, so we
531 // hand off what we generated and they will send the results back to the
532 // renderer.
533 autocomplete_history_manager_->OnGetAutocompleteSuggestions(
534 query_id, field.name, field.value, field.form_control_type,
535 suggestions);
536 } else {
537 // Autocomplete is disabled for this field; only pass back Autofill
538 // suggestions.
539 autocomplete_history_manager_->CancelPendingQuery();
540 external_delegate_->OnSuggestionsReturned(
541 query_id, suggestions);
545 bool AutofillManager::WillFillCreditCardNumber(const FormData& form,
546 const FormFieldData& field) {
547 FormStructure* form_structure = nullptr;
548 AutofillField* autofill_field = nullptr;
549 if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
550 return false;
552 if (autofill_field->Type().GetStorableType() == CREDIT_CARD_NUMBER)
553 return true;
555 #if defined(OS_IOS)
556 // On iOS, we only fill out one field at a time. So we only need to check the
557 // current field.
558 return false;
559 #endif
561 // If the relevant section is already autofilled, the new fill operation will
562 // only fill |autofill_field|.
563 if (SectionIsAutofilled(*form_structure, form, autofill_field->section()))
564 return false;
566 DCHECK_EQ(form_structure->field_count(), form.fields.size());
567 for (size_t i = 0; i < form_structure->field_count(); ++i) {
568 if (form_structure->field(i)->section() == autofill_field->section() &&
569 form_structure->field(i)->Type().GetStorableType() ==
570 CREDIT_CARD_NUMBER &&
571 form.fields[i].value.empty()) {
572 return true;
576 return false;
579 void AutofillManager::FillOrPreviewCreditCardForm(
580 AutofillDriver::RendererFormDataAction action,
581 int query_id,
582 const FormData& form,
583 const FormFieldData& field,
584 const CreditCard& credit_card) {
585 if (action == AutofillDriver::FORM_DATA_ACTION_FILL) {
586 if (credit_card.record_type() == CreditCard::MASKED_SERVER_CARD &&
587 WillFillCreditCardNumber(form, field)) {
588 unmasking_card_ = credit_card;
589 unmasking_query_id_ = query_id;
590 unmasking_form_ = form;
591 unmasking_field_ = field;
592 real_pan_client_.Prepare();
593 client()->ShowUnmaskPrompt(unmasking_card_,
594 weak_ptr_factory_.GetWeakPtr());
595 credit_card_form_event_logger_->OnDidSelectMaskedServerCardSuggestion();
596 return;
598 credit_card_form_event_logger_->OnDidFillSuggestion(credit_card);
601 FillOrPreviewDataModelForm(action, query_id, form, field, credit_card,
602 true /* is_credit_card */);
605 void AutofillManager::FillOrPreviewProfileForm(
606 AutofillDriver::RendererFormDataAction action,
607 int query_id,
608 const FormData& form,
609 const FormFieldData& field,
610 const AutofillProfile& profile) {
611 if (action == AutofillDriver::FORM_DATA_ACTION_FILL)
612 address_form_event_logger_->OnDidFillSuggestion(profile);
614 FillOrPreviewDataModelForm(action, query_id, form, field, profile,
615 false /* is_credit_card */);
618 void AutofillManager::FillOrPreviewForm(
619 AutofillDriver::RendererFormDataAction action,
620 int query_id,
621 const FormData& form,
622 const FormFieldData& field,
623 int unique_id) {
624 #if defined(OS_MACOSX) && !defined(OS_IOS)
625 EmitIsFromAddressBookMetric(unique_id);
626 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
628 if (!IsValidFormData(form) || !IsValidFormFieldData(field))
629 return;
631 // NOTE: RefreshDataModels may invalidate |data_model| because it causes the
632 // PersonalDataManager to reload Mac address book entries. Thus it must come
633 // before GetProfile or GetCreditCard.
634 if (!RefreshDataModels() || !driver_->RendererIsAvailable())
635 return;
637 const CreditCard* credit_card = nullptr;
638 const AutofillProfile* profile = nullptr;
639 if (GetCreditCard(unique_id, &credit_card))
640 FillOrPreviewCreditCardForm(action, query_id, form, field, *credit_card);
641 else if (GetProfile(unique_id, &profile))
642 FillOrPreviewProfileForm(action, query_id, form, field, *profile);
645 void AutofillManager::FillCreditCardForm(int query_id,
646 const FormData& form,
647 const FormFieldData& field,
648 const CreditCard& credit_card) {
649 if (!IsValidFormData(form) || !IsValidFormFieldData(field) ||
650 !driver_->RendererIsAvailable()) {
651 return;
654 FillOrPreviewDataModelForm(AutofillDriver::FORM_DATA_ACTION_FILL, query_id,
655 form, field, credit_card, true);
658 void AutofillManager::OnDidPreviewAutofillFormData() {
659 if (test_delegate_)
660 test_delegate_->DidPreviewFormData();
663 void AutofillManager::OnDidFillAutofillFormData(const TimeTicks& timestamp) {
664 if (test_delegate_)
665 test_delegate_->DidFillFormData();
667 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::USER_DID_AUTOFILL);
668 if (!user_did_autofill_) {
669 user_did_autofill_ = true;
670 AutofillMetrics::LogUserHappinessMetric(
671 AutofillMetrics::USER_DID_AUTOFILL_ONCE);
674 UpdateInitialInteractionTimestamp(timestamp);
677 void AutofillManager::DidShowSuggestions(bool is_new_popup,
678 const FormData& form,
679 const FormFieldData& field) {
680 if (test_delegate_)
681 test_delegate_->DidShowSuggestions();
682 FormStructure* form_structure = NULL;
683 AutofillField* autofill_field = NULL;
684 if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
685 return;
687 if (is_new_popup) {
688 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::SUGGESTIONS_SHOWN);
690 if (!did_show_suggestions_) {
691 did_show_suggestions_ = true;
692 AutofillMetrics::LogUserHappinessMetric(
693 AutofillMetrics::SUGGESTIONS_SHOWN_ONCE);
696 if (autofill_field->Type().group() == CREDIT_CARD)
697 credit_card_form_event_logger_->OnDidShowSuggestions();
698 else
699 address_form_event_logger_->OnDidShowSuggestions();
703 void AutofillManager::OnHidePopup() {
704 if (!IsAutofillEnabled())
705 return;
707 autocomplete_history_manager_->CancelPendingQuery();
708 client_->HideAutofillPopup();
711 bool AutofillManager::GetDeletionConfirmationText(const base::string16& value,
712 int identifier,
713 base::string16* title,
714 base::string16* body) {
715 if (identifier == POPUP_ITEM_ID_AUTOCOMPLETE_ENTRY) {
716 if (title)
717 title->assign(value);
718 if (body) {
719 body->assign(l10n_util::GetStringUTF16(
720 IDS_AUTOFILL_DELETE_AUTOCOMPLETE_SUGGESTION_CONFIRMATION_BODY));
723 return true;
726 if (identifier < 0)
727 return false;
729 const CreditCard* credit_card = nullptr;
730 const AutofillProfile* profile = nullptr;
731 if (GetCreditCard(identifier, &credit_card)) {
732 if (credit_card->record_type() != CreditCard::LOCAL_CARD)
733 return false;
735 if (title)
736 title->assign(credit_card->TypeAndLastFourDigits());
737 if (body) {
738 body->assign(l10n_util::GetStringUTF16(
739 IDS_AUTOFILL_DELETE_CREDIT_CARD_SUGGESTION_CONFIRMATION_BODY));
742 return true;
743 } else if (GetProfile(identifier, &profile)) {
744 if (profile->record_type() != AutofillProfile::LOCAL_PROFILE)
745 return false;
747 if (title) {
748 base::string16 street_address = profile->GetRawInfo(ADDRESS_HOME_CITY);
749 if (!street_address.empty())
750 title->swap(street_address);
751 else
752 title->assign(value);
754 if (body) {
755 body->assign(l10n_util::GetStringUTF16(
756 IDS_AUTOFILL_DELETE_PROFILE_SUGGESTION_CONFIRMATION_BODY));
759 return true;
762 NOTREACHED();
763 return false;
766 bool AutofillManager::RemoveAutofillProfileOrCreditCard(int unique_id) {
767 std::string guid;
768 const CreditCard* credit_card = nullptr;
769 const AutofillProfile* profile = nullptr;
770 if (GetCreditCard(unique_id, &credit_card)) {
771 if (credit_card->record_type() != CreditCard::LOCAL_CARD)
772 return false;
774 guid = credit_card->guid();
775 } else if (GetProfile(unique_id, &profile)) {
776 if (profile->record_type() != AutofillProfile::LOCAL_PROFILE)
777 return false;
779 guid = profile->guid();
780 } else {
781 NOTREACHED();
782 return false;
785 personal_data_->RemoveByGUID(guid);
786 return true;
789 void AutofillManager::RemoveAutocompleteEntry(const base::string16& name,
790 const base::string16& value) {
791 autocomplete_history_manager_->OnRemoveAutocompleteEntry(name, value);
794 bool AutofillManager::IsShowingUnmaskPrompt() {
795 return unmasking_card_.Compare(CreditCard()) != 0;
798 const std::vector<FormStructure*>& AutofillManager::GetFormStructures() {
799 return form_structures_.get();
802 void AutofillManager::SetTestDelegate(AutofillManagerTestDelegate* delegate) {
803 test_delegate_ = delegate;
806 void AutofillManager::OnSetDataList(const std::vector<base::string16>& values,
807 const std::vector<base::string16>& labels) {
808 if (!IsValidString16Vector(values) ||
809 !IsValidString16Vector(labels) ||
810 values.size() != labels.size())
811 return;
813 external_delegate_->SetCurrentDataListValues(values, labels);
816 void AutofillManager::OnLoadedServerPredictions(
817 const std::string& response_xml) {
818 // Parse and store the server predictions.
819 FormStructure::ParseQueryResponse(response_xml, form_structures_.get(),
820 client_->GetRapporService());
822 // Forward form structures to the password generation manager to detect
823 // account creation forms.
824 driver_->PropagateAutofillPredictions(form_structures_.get());
826 // If the corresponding flag is set, annotate forms with the predicted types.
827 driver_->SendAutofillTypePredictionsToRenderer(form_structures_.get());
830 void AutofillManager::OnUnmaskResponse(const UnmaskResponse& response) {
831 unmask_response_ = response;
832 real_pan_request_timestamp_ = base::Time::Now();
833 real_pan_client_.UnmaskCard(unmasking_card_, response);
836 void AutofillManager::OnUnmaskPromptClosed() {
837 real_pan_client_.CancelRequest();
838 driver_->RendererShouldClearPreviewedForm();
839 unmasking_card_ = CreditCard();
840 unmask_response_ = UnmaskResponse();
843 IdentityProvider* AutofillManager::GetIdentityProvider() {
844 return client()->GetIdentityProvider();
847 void AutofillManager::OnDidGetRealPan(AutofillClient::GetRealPanResult result,
848 const std::string& real_pan) {
849 AutofillMetrics::LogRealPanDuration(
850 base::Time::Now() - real_pan_request_timestamp_, result);
851 if (!real_pan.empty()) {
852 DCHECK_EQ(AutofillClient::SUCCESS, result);
853 credit_card_form_event_logger_->OnDidFillSuggestion(unmasking_card_);
854 recently_unmasked_cards_.push_back(unmasking_card_);
855 unmasking_card_.set_record_type(CreditCard::FULL_SERVER_CARD);
856 unmasking_card_.SetNumber(base::UTF8ToUTF16(real_pan));
857 if (unmask_response_.should_store_pan)
858 personal_data_->UpdateServerCreditCard(unmasking_card_);
860 FillCreditCardForm(unmasking_query_id_, unmasking_form_, unmasking_field_,
861 unmasking_card_);
864 client()->OnUnmaskVerificationResult(result);
867 void AutofillManager::OnDidEndTextFieldEditing() {
868 external_delegate_->DidEndTextFieldEditing();
871 bool AutofillManager::IsAutofillEnabled() const {
872 return ::autofill::IsAutofillEnabled(client_->GetPrefs());
875 void AutofillManager::ImportFormData(const FormStructure& submitted_form) {
876 scoped_ptr<CreditCard> imported_credit_card;
877 if (!personal_data_->ImportFormData(submitted_form, &imported_credit_card))
878 return;
880 // If credit card information was submitted, we need to confirm whether to
881 // save it.
882 if (imported_credit_card) {
883 // Don't offer to save any cards that were recently unmasked.
884 if (recently_unmasked_cards_.end() !=
885 std::find_if(
886 recently_unmasked_cards_.begin(), recently_unmasked_cards_.end(),
887 [&imported_credit_card](const CreditCard& unmasked) -> bool {
888 return unmasked.TypeAndLastFourDigits() ==
889 imported_credit_card->TypeAndLastFourDigits();
890 })) {
891 return;
893 client_->ConfirmSaveCreditCard(
894 base::Bind(
895 base::IgnoreResult(&PersonalDataManager::SaveImportedCreditCard),
896 base::Unretained(personal_data_),
897 *imported_credit_card));
901 // Note that |submitted_form| is passed as a pointer rather than as a reference
902 // so that we can get memory management right across threads. Note also that we
903 // explicitly pass in all the time stamps of interest, as the cached ones might
904 // get reset before this method executes.
905 void AutofillManager::UploadFormDataAsyncCallback(
906 const FormStructure* submitted_form,
907 const TimeTicks& load_time,
908 const TimeTicks& interaction_time,
909 const TimeTicks& submission_time) {
910 submitted_form->LogQualityMetrics(load_time, interaction_time,
911 submission_time,
912 client_->GetRapporService());
914 if (submitted_form->ShouldBeCrowdsourced())
915 UploadFormData(*submitted_form);
918 void AutofillManager::UploadFormData(const FormStructure& submitted_form) {
919 if (!download_manager_)
920 return;
922 // Check if the form is among the forms that were recently auto-filled.
923 bool was_autofilled = false;
924 std::string form_signature = submitted_form.FormSignature();
925 for (std::list<std::string>::const_iterator it =
926 autofilled_form_signatures_.begin();
927 it != autofilled_form_signatures_.end() && !was_autofilled;
928 ++it) {
929 if (*it == form_signature)
930 was_autofilled = true;
933 ServerFieldTypeSet non_empty_types;
934 personal_data_->GetNonEmptyTypes(&non_empty_types);
936 download_manager_->StartUploadRequest(submitted_form, was_autofilled,
937 non_empty_types);
940 bool AutofillManager::UploadPasswordForm(
941 const FormData& form,
942 const ServerFieldType& password_type) {
943 FormStructure form_structure(form);
945 if (!ShouldUploadForm(form_structure))
946 return false;
948 if (!form_structure.ShouldBeCrowdsourced())
949 return false;
951 // Find the first password field to label. We don't try to label anything
952 // else.
953 bool found_password_field = false;
954 for (size_t i = 0; i < form_structure.field_count(); ++i) {
955 AutofillField* field = form_structure.field(i);
957 ServerFieldTypeSet types;
958 if (!found_password_field && field->form_control_type == "password") {
959 types.insert(password_type);
960 found_password_field = true;
961 } else {
962 types.insert(UNKNOWN_TYPE);
964 field->set_possible_types(types);
966 DCHECK(found_password_field);
968 // Only one field type should be present.
969 ServerFieldTypeSet available_field_types;
970 available_field_types.insert(password_type);
972 // Force uploading as these events are relatively rare and we want to make
973 // sure to receive them. It also makes testing easier if these requests
974 // always pass.
975 form_structure.set_upload_required(UPLOAD_REQUIRED);
977 if (!download_manager_)
978 return false;
980 return download_manager_->StartUploadRequest(form_structure,
981 false /* was_autofilled */,
982 available_field_types);
985 void AutofillManager::Reset() {
986 form_structures_.clear();
987 address_form_event_logger_.reset(
988 new AutofillMetrics::FormEventLogger(false /* is_for_credit_card */));
989 credit_card_form_event_logger_.reset(
990 new AutofillMetrics::FormEventLogger(true /* is_for_credit_card */));
991 has_logged_autofill_enabled_ = false;
992 has_logged_address_suggestions_count_ = false;
993 did_show_suggestions_ = false;
994 user_did_type_ = false;
995 user_did_autofill_ = false;
996 user_did_edit_autofilled_field_ = false;
997 unmasking_card_ = CreditCard();
998 unmasking_query_id_ = -1;
999 unmasking_form_ = FormData();
1000 unmasking_field_ = FormFieldData();
1001 forms_loaded_timestamps_.clear();
1002 initial_interaction_timestamp_ = TimeTicks();
1003 external_delegate_->Reset();
1006 AutofillManager::AutofillManager(AutofillDriver* driver,
1007 AutofillClient* client,
1008 PersonalDataManager* personal_data)
1009 : driver_(driver),
1010 client_(client),
1011 real_pan_client_(driver->GetURLRequestContext(), this),
1012 app_locale_("en-US"),
1013 personal_data_(personal_data),
1014 autocomplete_history_manager_(
1015 new AutocompleteHistoryManager(driver, client)),
1016 address_form_event_logger_(
1017 new AutofillMetrics::FormEventLogger(false /* is_for_credit_card */)),
1018 credit_card_form_event_logger_(
1019 new AutofillMetrics::FormEventLogger(true /* is_for_credit_card */)),
1020 has_logged_autofill_enabled_(false),
1021 has_logged_address_suggestions_count_(false),
1022 did_show_suggestions_(false),
1023 user_did_type_(false),
1024 user_did_autofill_(false),
1025 user_did_edit_autofilled_field_(false),
1026 unmasking_query_id_(-1),
1027 external_delegate_(NULL),
1028 test_delegate_(NULL),
1029 weak_ptr_factory_(this) {
1030 DCHECK(driver_);
1031 DCHECK(client_);
1034 bool AutofillManager::RefreshDataModels() {
1035 if (!IsAutofillEnabled())
1036 return false;
1038 // No autofill data to return if the profiles are empty.
1039 const std::vector<AutofillProfile*>& profiles =
1040 personal_data_->GetProfiles();
1041 const std::vector<CreditCard*>& credit_cards =
1042 personal_data_->GetCreditCards();
1044 // Updating the FormEventLoggers for addresses and credit cards.
1046 bool is_server_data_available = false;
1047 bool is_local_data_available = false;
1048 for (CreditCard* credit_card : credit_cards) {
1049 if (credit_card->record_type() == CreditCard::LOCAL_CARD)
1050 is_local_data_available = true;
1051 else
1052 is_server_data_available = true;
1054 credit_card_form_event_logger_->set_is_server_data_available(
1055 is_server_data_available);
1056 credit_card_form_event_logger_->set_is_local_data_available(
1057 is_local_data_available);
1060 bool is_server_data_available = false;
1061 bool is_local_data_available = false;
1062 for (AutofillProfile* profile : profiles) {
1063 if (profile->record_type() == AutofillProfile::LOCAL_PROFILE)
1064 is_local_data_available = true;
1065 else if (profile->record_type() == AutofillProfile::SERVER_PROFILE)
1066 is_server_data_available = true;
1068 address_form_event_logger_->set_is_server_data_available(
1069 is_server_data_available);
1070 address_form_event_logger_->set_is_local_data_available(
1071 is_local_data_available);
1074 if (profiles.empty() && credit_cards.empty())
1075 return false;
1077 return true;
1080 bool AutofillManager::IsCreditCard(int unique_id) {
1081 // Unpack the |unique_id| into component parts.
1082 std::string credit_card_id;
1083 std::string profile_id;
1084 SplitFrontendID(unique_id, &credit_card_id, &profile_id);
1085 DCHECK(!base::IsValidGUID(credit_card_id) || !base::IsValidGUID(profile_id));
1086 return base::IsValidGUID(credit_card_id);
1089 bool AutofillManager::GetProfile(int unique_id,
1090 const AutofillProfile** profile) {
1091 // Unpack the |unique_id| into component parts.
1092 std::string credit_card_id;
1093 std::string profile_id;
1094 SplitFrontendID(unique_id, &credit_card_id, &profile_id);
1095 *profile = NULL;
1096 if (base::IsValidGUID(profile_id))
1097 *profile = personal_data_->GetProfileByGUID(profile_id);
1098 return !!*profile;
1101 bool AutofillManager::GetCreditCard(int unique_id,
1102 const CreditCard** credit_card) {
1103 // Unpack the |unique_id| into component parts.
1104 std::string credit_card_id;
1105 std::string profile_id;
1106 SplitFrontendID(unique_id, &credit_card_id, &profile_id);
1107 *credit_card = NULL;
1108 if (base::IsValidGUID(credit_card_id))
1109 *credit_card = personal_data_->GetCreditCardByGUID(credit_card_id);
1110 return !!*credit_card;
1113 void AutofillManager::FillOrPreviewDataModelForm(
1114 AutofillDriver::RendererFormDataAction action,
1115 int query_id,
1116 const FormData& form,
1117 const FormFieldData& field,
1118 const AutofillDataModel& data_model,
1119 bool is_credit_card) {
1120 FormStructure* form_structure = NULL;
1121 AutofillField* autofill_field = NULL;
1122 if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
1123 return;
1125 DCHECK(form_structure);
1126 DCHECK(autofill_field);
1128 FormData result = form;
1130 base::string16 profile_full_name;
1131 std::string profile_language_code;
1132 if (!is_credit_card) {
1133 profile_full_name = data_model.GetInfo(
1134 AutofillType(NAME_FULL), app_locale_);
1135 profile_language_code =
1136 static_cast<const AutofillProfile*>(&data_model)->language_code();
1139 // If the relevant section is auto-filled, we should fill |field| but not the
1140 // rest of the form.
1141 if (SectionIsAutofilled(*form_structure, form, autofill_field->section())) {
1142 for (std::vector<FormFieldData>::iterator iter = result.fields.begin();
1143 iter != result.fields.end(); ++iter) {
1144 if (iter->SameFieldAs(field)) {
1145 base::string16 value =
1146 data_model.GetInfo(autofill_field->Type(), app_locale_);
1147 if (AutofillField::FillFormField(*autofill_field,
1148 value,
1149 profile_language_code,
1150 app_locale_,
1151 &(*iter))) {
1152 // Mark the cached field as autofilled, so that we can detect when a
1153 // user edits an autofilled field (for metrics).
1154 autofill_field->is_autofilled = true;
1156 // Mark the field as autofilled when a non-empty value is assigned to
1157 // it. This allows the renderer to distinguish autofilled fields from
1158 // fields with non-empty values, such as select-one fields.
1159 iter->is_autofilled = true;
1161 if (!is_credit_card && !value.empty())
1162 client_->DidFillOrPreviewField(value, profile_full_name);
1164 break;
1168 // Note that this may invalidate |data_model|, particularly if it is a Mac
1169 // address book entry.
1170 if (action == AutofillDriver::FORM_DATA_ACTION_FILL)
1171 personal_data_->RecordUseOf(data_model);
1173 driver_->SendFormDataToRenderer(query_id, action, result);
1174 return;
1177 DCHECK_EQ(form_structure->field_count(), form.fields.size());
1178 for (size_t i = 0; i < form_structure->field_count(); ++i) {
1179 if (form_structure->field(i)->section() != autofill_field->section())
1180 continue;
1182 DCHECK(form_structure->field(i)->SameFieldAs(result.fields[i]));
1184 const AutofillField* cached_field = form_structure->field(i);
1185 FieldTypeGroup field_group_type = cached_field->Type().group();
1187 if (field_group_type == NO_GROUP)
1188 continue;
1190 base::string16 value =
1191 data_model.GetInfo(cached_field->Type(), app_locale_);
1192 if (is_credit_card &&
1193 cached_field->Type().GetStorableType() ==
1194 CREDIT_CARD_VERIFICATION_CODE) {
1195 // If this is |unmasking_card_|, |unmask_response_.cvc| should be
1196 // non-empty and vice versa.
1197 value = unmask_response_.cvc;
1198 DCHECK_EQ(&unmasking_card_ == &data_model, !value.empty());
1201 // Must match ForEachMatchingFormField() in form_autofill_util.cc.
1202 // Only notify autofilling of empty fields and the field that initiated
1203 // the filling (note that "select-one" controls may not be empty but will
1204 // still be autofilled).
1205 bool should_notify =
1206 !is_credit_card &&
1207 !value.empty() &&
1208 (result.fields[i].SameFieldAs(field) ||
1209 result.fields[i].form_control_type == "select-one" ||
1210 result.fields[i].value.empty());
1211 if (AutofillField::FillFormField(*cached_field,
1212 value,
1213 profile_language_code,
1214 app_locale_,
1215 &result.fields[i])) {
1216 // Mark the cached field as autofilled, so that we can detect when a
1217 // user edits an autofilled field (for metrics).
1218 form_structure->field(i)->is_autofilled = true;
1220 // Mark the field as autofilled when a non-empty value is assigned to
1221 // it. This allows the renderer to distinguish autofilled fields from
1222 // fields with non-empty values, such as select-one fields.
1223 result.fields[i].is_autofilled = true;
1225 if (should_notify)
1226 client_->DidFillOrPreviewField(value, profile_full_name);
1230 autofilled_form_signatures_.push_front(form_structure->FormSignature());
1231 // Only remember the last few forms that we've seen, both to avoid false
1232 // positives and to avoid wasting memory.
1233 if (autofilled_form_signatures_.size() > kMaxRecentFormSignaturesToRemember)
1234 autofilled_form_signatures_.pop_back();
1236 // Note that this may invalidate |data_model|, particularly if it is a Mac
1237 // address book entry.
1238 if (action == AutofillDriver::FORM_DATA_ACTION_FILL)
1239 personal_data_->RecordUseOf(data_model);
1241 driver_->SendFormDataToRenderer(query_id, action, result);
1244 scoped_ptr<FormStructure> AutofillManager::ValidateSubmittedForm(
1245 const FormData& form) {
1246 scoped_ptr<FormStructure> submitted_form(new FormStructure(form));
1247 if (!ShouldUploadForm(*submitted_form))
1248 return scoped_ptr<FormStructure>();
1250 // Ignore forms not present in our cache. These are typically forms with
1251 // wonky JavaScript that also makes them not auto-fillable.
1252 FormStructure* cached_submitted_form;
1253 if (!FindCachedForm(form, &cached_submitted_form))
1254 return scoped_ptr<FormStructure>();
1256 submitted_form->UpdateFromCache(*cached_submitted_form);
1257 return submitted_form.Pass();
1260 bool AutofillManager::FindCachedForm(const FormData& form,
1261 FormStructure** form_structure) const {
1262 // Find the FormStructure that corresponds to |form|.
1263 // Scan backward through the cached |form_structures_|, as updated versions of
1264 // forms are added to the back of the list, whereas original versions of these
1265 // forms might appear toward the beginning of the list. The communication
1266 // protocol with the crowdsourcing server does not permit us to discard the
1267 // original versions of the forms.
1268 *form_structure = NULL;
1269 for (std::vector<FormStructure*>::const_reverse_iterator iter =
1270 form_structures_.rbegin();
1271 iter != form_structures_.rend(); ++iter) {
1272 if (**iter == form) {
1273 *form_structure = *iter;
1275 // The same form might be cached with multiple field counts: in some
1276 // cases, non-autofillable fields are filtered out, whereas in other cases
1277 // they are not. To avoid thrashing the cache, keep scanning until we
1278 // find a cached version with the same number of fields, if there is one.
1279 if ((*iter)->field_count() == form.fields.size())
1280 break;
1284 if (!(*form_structure))
1285 return false;
1287 return true;
1290 bool AutofillManager::GetCachedFormAndField(const FormData& form,
1291 const FormFieldData& field,
1292 FormStructure** form_structure,
1293 AutofillField** autofill_field) {
1294 // Find the FormStructure that corresponds to |form|.
1295 // If we do not have this form in our cache but it is parseable, we'll add it
1296 // in the call to |UpdateCachedForm()|.
1297 if (!FindCachedForm(form, form_structure) &&
1298 !FormStructure(form).ShouldBeParsed()) {
1299 return false;
1302 // Update the cached form to reflect any dynamic changes to the form data, if
1303 // necessary.
1304 if (!UpdateCachedForm(form, *form_structure, form_structure))
1305 return false;
1307 // No data to return if there are no auto-fillable fields.
1308 if (!(*form_structure)->autofill_count())
1309 return false;
1311 // Find the AutofillField that corresponds to |field|.
1312 *autofill_field = NULL;
1313 for (AutofillField* current : **form_structure) {
1314 if (current->SameFieldAs(field)) {
1315 *autofill_field = current;
1316 break;
1320 // Even though we always update the cache, the field might not exist if the
1321 // website disables autocomplete while the user is interacting with the form.
1322 // See http://crbug.com/160476
1323 return *autofill_field != NULL;
1326 AutofillField* AutofillManager::GetAutofillField(const FormData& form,
1327 const FormFieldData& field) {
1328 if (!personal_data_)
1329 return NULL;
1331 FormStructure* form_structure = NULL;
1332 AutofillField* autofill_field = NULL;
1333 if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
1334 return NULL;
1336 if (!form_structure->IsAutofillable())
1337 return NULL;
1339 return autofill_field;
1342 bool AutofillManager::UpdateCachedForm(const FormData& live_form,
1343 const FormStructure* cached_form,
1344 FormStructure** updated_form) {
1345 bool needs_update =
1346 (!cached_form ||
1347 live_form.fields.size() != cached_form->field_count());
1348 for (size_t i = 0; !needs_update && i < cached_form->field_count(); ++i)
1349 needs_update = !cached_form->field(i)->SameFieldAs(live_form.fields[i]);
1351 if (!needs_update)
1352 return true;
1354 if (form_structures_.size() >= kMaxFormCacheSize)
1355 return false;
1357 // Add the new or updated form to our cache.
1358 form_structures_.push_back(new FormStructure(live_form));
1359 *updated_form = *form_structures_.rbegin();
1360 (*updated_form)->DetermineHeuristicTypes();
1362 // If we have cached data, propagate it to the updated form.
1363 if (cached_form) {
1364 std::map<base::string16, const AutofillField*> cached_fields;
1365 for (size_t i = 0; i < cached_form->field_count(); ++i) {
1366 const AutofillField* field = cached_form->field(i);
1367 cached_fields[field->unique_name()] = field;
1370 for (size_t i = 0; i < (*updated_form)->field_count(); ++i) {
1371 AutofillField* field = (*updated_form)->field(i);
1372 std::map<base::string16, const AutofillField*>::iterator cached_field =
1373 cached_fields.find(field->unique_name());
1374 if (cached_field != cached_fields.end()) {
1375 field->set_server_type(cached_field->second->server_type());
1376 field->is_autofilled = cached_field->second->is_autofilled;
1380 // Note: We _must not_ remove the original version of the cached form from
1381 // the list of |form_structures_|. Otherwise, we break parsing of the
1382 // crowdsourcing server's response to our query.
1385 // Annotate the updated form with its predicted types.
1386 std::vector<FormStructure*> forms(1, *updated_form);
1387 driver_->SendAutofillTypePredictionsToRenderer(forms);
1389 return true;
1392 std::vector<Suggestion> AutofillManager::GetProfileSuggestions(
1393 const FormStructure& form,
1394 const FormFieldData& field,
1395 const AutofillField& autofill_field) const {
1396 std::vector<ServerFieldType> field_types(form.field_count());
1397 for (size_t i = 0; i < form.field_count(); ++i) {
1398 field_types.push_back(form.field(i)->Type().GetStorableType());
1401 std::vector<Suggestion> suggestions = personal_data_->GetProfileSuggestions(
1402 autofill_field.Type(), field.value, field.is_autofilled, field_types);
1404 // Adjust phone number to display in prefix/suffix case.
1405 if (autofill_field.Type().GetStorableType() == PHONE_HOME_NUMBER) {
1406 for (size_t i = 0; i < suggestions.size(); ++i) {
1407 suggestions[i].value = AutofillField::GetPhoneNumberValue(
1408 autofill_field, suggestions[i].value, field);
1412 for (size_t i = 0; i < suggestions.size(); ++i) {
1413 suggestions[i].frontend_id =
1414 MakeFrontendID(std::string(), suggestions[i].backend_id);
1416 return suggestions;
1419 std::vector<Suggestion> AutofillManager::GetCreditCardSuggestions(
1420 const FormFieldData& field,
1421 const AutofillType& type) const {
1422 std::vector<Suggestion> suggestions =
1423 personal_data_->GetCreditCardSuggestions(type, field.value);
1424 for (size_t i = 0; i < suggestions.size(); i++) {
1425 suggestions[i].frontend_id =
1426 MakeFrontendID(suggestions[i].backend_id, std::string());
1428 return suggestions;
1431 void AutofillManager::ParseForms(const std::vector<FormData>& forms) {
1432 std::vector<FormStructure*> non_queryable_forms;
1433 for (std::vector<FormData>::const_iterator iter = forms.begin();
1434 iter != forms.end(); ++iter) {
1435 scoped_ptr<FormStructure> form_structure(new FormStructure(*iter));
1437 if (!form_structure->ShouldBeParsed()) {
1438 if (form_structure->has_password_field()) {
1439 AutofillMetrics::LogPasswordFormQueryVolume(
1440 AutofillMetrics::NEW_PASSWORD_QUERY);
1442 continue;
1445 form_structure->DetermineHeuristicTypes();
1447 if (form_structure->ShouldBeCrowdsourced()) {
1448 AutofillMetrics::LogPasswordFormQueryVolume(
1449 AutofillMetrics::CURRENT_QUERY);
1450 form_structures_.push_back(form_structure.release());
1451 } else
1452 non_queryable_forms.push_back(form_structure.release());
1455 if (!form_structures_.empty() && download_manager_) {
1456 // Query the server if at least one of the forms was parsed.
1457 download_manager_->StartQueryRequest(form_structures_.get());
1460 for (std::vector<FormStructure*>::const_iterator iter =
1461 non_queryable_forms.begin();
1462 iter != non_queryable_forms.end(); ++iter) {
1463 form_structures_.push_back(*iter);
1466 if (!form_structures_.empty())
1467 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::FORMS_LOADED);
1469 // For the |non_queryable_forms|, we have all the field type info we're ever
1470 // going to get about them. For the other forms, we'll wait until we get a
1471 // response from the server.
1472 driver_->SendAutofillTypePredictionsToRenderer(non_queryable_forms);
1475 int AutofillManager::BackendIDToInt(const std::string& backend_id) const {
1476 if (!base::IsValidGUID(backend_id))
1477 return 0;
1479 const auto found = backend_to_int_map_.find(backend_id);
1480 if (found == backend_to_int_map_.end()) {
1481 // Unknown one, make a new entry.
1482 int int_id = backend_to_int_map_.size() + 1;
1483 backend_to_int_map_[backend_id] = int_id;
1484 int_to_backend_map_[int_id] = backend_id;
1485 return int_id;
1487 return found->second;
1490 std::string AutofillManager::IntToBackendID(int int_id) const {
1491 if (int_id == 0)
1492 return std::string();
1494 const auto found = int_to_backend_map_.find(int_id);
1495 if (found == int_to_backend_map_.end()) {
1496 NOTREACHED();
1497 return std::string();
1499 return found->second;
1502 // When sending IDs (across processes) to the renderer we pack credit card and
1503 // profile IDs into a single integer. Credit card IDs are sent in the high
1504 // word and profile IDs are sent in the low word.
1505 int AutofillManager::MakeFrontendID(
1506 const std::string& cc_backend_id,
1507 const std::string& profile_backend_id) const {
1508 int cc_int_id = BackendIDToInt(cc_backend_id);
1509 int profile_int_id = BackendIDToInt(profile_backend_id);
1511 // Should fit in signed 16-bit integers. We use 16-bits each when combining
1512 // below, and negative frontend IDs have special meaning so we can never use
1513 // the high bit.
1514 DCHECK(cc_int_id <= std::numeric_limits<int16_t>::max());
1515 DCHECK(profile_int_id <= std::numeric_limits<int16_t>::max());
1517 // Put CC in the high half of the bits.
1518 return (cc_int_id << std::numeric_limits<uint16_t>::digits) | profile_int_id;
1521 // When receiving IDs (across processes) from the renderer we unpack credit card
1522 // and profile IDs from a single integer. Credit card IDs are stored in the
1523 // high word and profile IDs are stored in the low word.
1524 void AutofillManager::SplitFrontendID(int frontend_id,
1525 std::string* cc_backend_id,
1526 std::string* profile_backend_id) const {
1527 int cc_int_id = (frontend_id >> std::numeric_limits<uint16_t>::digits) &
1528 std::numeric_limits<uint16_t>::max();
1529 int profile_int_id = frontend_id & std::numeric_limits<uint16_t>::max();
1531 *cc_backend_id = IntToBackendID(cc_int_id);
1532 *profile_backend_id = IntToBackendID(profile_int_id);
1535 void AutofillManager::UpdateInitialInteractionTimestamp(
1536 const TimeTicks& interaction_timestamp) {
1537 if (initial_interaction_timestamp_.is_null() ||
1538 interaction_timestamp < initial_interaction_timestamp_) {
1539 initial_interaction_timestamp_ = interaction_timestamp;
1543 bool AutofillManager::ShouldUploadForm(const FormStructure& form) {
1544 if (!IsAutofillEnabled())
1545 return false;
1547 if (driver_->IsOffTheRecord())
1548 return false;
1550 // Disregard forms that we wouldn't ever autofill in the first place.
1551 if (!form.ShouldBeParsed())
1552 return false;
1554 return true;
1557 #if defined(OS_MACOSX) && !defined(OS_IOS)
1558 void AutofillManager::EmitIsFromAddressBookMetric(int unique_id) {
1559 const AutofillProfile* profile = nullptr;
1560 bool result = GetProfile(unique_id, &profile);
1561 if (!result)
1562 return;
1564 bool is_from_address_book =
1565 profile->record_type() == AutofillProfile::AUXILIARY_PROFILE;
1566 UMA_HISTOGRAM_BOOLEAN(
1567 "Autofill.MacAddressBook.AcceptedSuggestionIsFromAddressBook",
1568 is_from_address_book);
1570 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
1572 } // namespace autofill