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