ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / components / autofill / core / browser / autofill_manager.h
blob5f8b67bff145c037d6f6249c9854fe57edf0822d
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 #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
6 #define COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
8 #include <list>
9 #include <map>
10 #include <string>
11 #include <vector>
13 #include "base/basictypes.h"
14 #include "base/callback_forward.h"
15 #include "base/compiler_specific.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/strings/string16.h"
21 #include "base/time/time.h"
22 #include "components/autofill/core/browser/autocomplete_history_manager.h"
23 #include "components/autofill/core/browser/autofill_client.h"
24 #include "components/autofill/core/browser/autofill_download_manager.h"
25 #include "components/autofill/core/browser/autofill_driver.h"
26 #include "components/autofill/core/browser/autofill_metrics.h"
27 #include "components/autofill/core/browser/card_unmask_delegate.h"
28 #include "components/autofill/core/browser/form_structure.h"
29 #include "components/autofill/core/browser/personal_data_manager.h"
30 #include "components/autofill/core/browser/wallet/real_pan_wallet_client.h"
31 #include "components/autofill/core/common/form_data.h"
33 namespace gfx {
34 class Rect;
35 class RectF;
38 namespace user_prefs {
39 class PrefRegistrySyncable;
42 namespace autofill {
44 class AutofillDataModel;
45 class AutofillDownloadManager;
46 class AutofillExternalDelegate;
47 class AutofillField;
48 class AutofillClient;
49 class AutofillManagerTestDelegate;
50 class AutofillProfile;
51 class AutofillType;
52 class CreditCard;
53 class FormStructureBrowserTest;
55 struct FormData;
56 struct FormFieldData;
58 // Manages saving and restoring the user's personal information entered into web
59 // forms. One per frame; owned by the AutofillDriver.
60 class AutofillManager : public AutofillDownloadManager::Observer,
61 public CardUnmaskDelegate,
62 public wallet::RealPanWalletClient::Delegate {
63 public:
64 enum AutofillDownloadManagerState {
65 ENABLE_AUTOFILL_DOWNLOAD_MANAGER,
66 DISABLE_AUTOFILL_DOWNLOAD_MANAGER,
69 // Registers our Enable/Disable Autofill pref.
70 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
72 #if defined(OS_MACOSX) && !defined(OS_IOS)
73 static void MigrateUserPrefs(PrefService* prefs);
74 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
76 AutofillManager(AutofillDriver* driver,
77 AutofillClient* client,
78 const std::string& app_locale,
79 AutofillDownloadManagerState enable_download_manager);
80 ~AutofillManager() override;
82 // Sets an external delegate.
83 void SetExternalDelegate(AutofillExternalDelegate* delegate);
85 void ShowAutofillSettings();
87 #if defined(OS_MACOSX) && !defined(OS_IOS)
88 // Whether the |field| should show an entry to prompt the user to give Chrome
89 // access to the user's address book.
90 bool ShouldShowAccessAddressBookSuggestion(const FormData& form,
91 const FormFieldData& field);
93 // If Chrome has not prompted for access to the user's address book, the
94 // method prompts the user for permission and blocks the process. Otherwise,
95 // this method has no effect. The return value reflects whether the user was
96 // prompted with a modal dialog.
97 bool AccessAddressBook();
99 // The access Address Book prompt was shown for a form.
100 void ShowedAccessAddressBookPrompt();
102 // The number of times that the access address book prompt was shown.
103 int AccessAddressBookPromptCount();
104 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
106 // Whether the |field| should show an entry to scan a credit card.
107 virtual bool ShouldShowScanCreditCard(const FormData& form,
108 const FormFieldData& field);
110 // Called from our external delegate so they cannot be private.
111 virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action,
112 int query_id,
113 const FormData& form,
114 const FormFieldData& field,
115 int unique_id);
116 virtual void FillCreditCardForm(int query_id,
117 const FormData& form,
118 const FormFieldData& field,
119 const CreditCard& credit_card);
120 void DidShowSuggestions(bool is_new_popup,
121 const FormData& form,
122 const FormFieldData& field);
123 void OnDidFillAutofillFormData(const base::TimeTicks& timestamp);
124 void OnDidPreviewAutofillFormData();
126 // Remove the credit card or Autofill profile that matches |unique_id|
127 // from the database.
128 void RemoveAutofillProfileOrCreditCard(int unique_id);
130 // Remove the specified Autocomplete entry.
131 void RemoveAutocompleteEntry(const base::string16& name,
132 const base::string16& value);
134 // Returns true when the Wallet card unmask prompt is being displayed.
135 bool IsShowingUnmaskPrompt();
137 // Returns the present form structures seen by Autofill manager.
138 const std::vector<FormStructure*>& GetFormStructures();
140 // Happens when the autocomplete dialog runs its callback when being closed.
141 void RequestAutocompleteDialogClosed();
143 AutofillClient* client() const { return client_; }
145 const std::string& app_locale() const { return app_locale_; }
147 // Only for testing.
148 void SetTestDelegate(AutofillManagerTestDelegate* delegate);
150 void OnFormsSeen(const std::vector<FormData>& forms,
151 const base::TimeTicks& timestamp);
153 // Processes the submitted |form|, saving any new Autofill data and uploading
154 // the possible field types for the submitted fields to the crowdsourcing
155 // server. Returns false if this form is not relevant for Autofill.
156 bool OnFormSubmitted(const FormData& form,
157 const base::TimeTicks& timestamp);
159 void OnTextFieldDidChange(const FormData& form,
160 const FormFieldData& field,
161 const base::TimeTicks& timestamp);
163 // The |bounding_box| is a window relative value.
164 void OnQueryFormFieldAutofill(int query_id,
165 const FormData& form,
166 const FormFieldData& field,
167 const gfx::RectF& bounding_box,
168 bool display_warning);
169 void OnDidEndTextFieldEditing();
170 void OnHidePopup();
171 void OnSetDataList(const std::vector<base::string16>& values,
172 const std::vector<base::string16>& labels);
174 // Try to label password fields and upload |form|. This differs from
175 // OnFormSubmitted() in a few ways.
176 // - This function will only label the first <input type="password"> field
177 // as |password_type|. Other fields will stay unlabeled, as they
178 // should have been labeled during the upload for OnFormSubmitted().
179 // - This function does not assume that |form| is being uploaded during
180 // the same browsing session as it was originally submitted (as we may
181 // not have the necessary information to classify the form at that time)
182 // so it bypasses the cache and doesn't log the same quality UMA metrics.
183 virtual bool UploadPasswordForm(const FormData& form,
184 const ServerFieldType& pasword_type);
186 // Resets cache.
187 virtual void Reset();
189 // Returns the value of the AutofillEnabled pref.
190 virtual bool IsAutofillEnabled() const;
192 protected:
193 // Test code should prefer to use this constructor.
194 AutofillManager(AutofillDriver* driver,
195 AutofillClient* client,
196 PersonalDataManager* personal_data);
198 // Uploads the form data to the Autofill server.
199 virtual void UploadFormData(const FormStructure& submitted_form);
201 // Logs quality metrics for the |submitted_form| and uploads the form data
202 // to the crowdsourcing server, if appropriate.
203 virtual void UploadFormDataAsyncCallback(
204 const FormStructure* submitted_form,
205 const base::TimeTicks& load_time,
206 const base::TimeTicks& interaction_time,
207 const base::TimeTicks& submission_time);
209 // Maps SuggestionBackendID to and from an integer identifying it. Two of
210 // these intermediate integers are packed by MakeFrontendID to make the IDs
211 // that this class generates for the UI and for IPC.
212 virtual int BackendIDToInt(const SuggestionBackendID& backend_id) const;
213 virtual SuggestionBackendID IntToBackendID(int int_id) const;
215 // Methods for packing and unpacking credit card and profile IDs for sending
216 // and receiving to and from the renderer process.
217 int MakeFrontendID(const SuggestionBackendID& cc_backend_id,
218 const SuggestionBackendID& profile_backend_id) const;
219 void SplitFrontendID(int frontend_id,
220 SuggestionBackendID* cc_backend_id,
221 SuggestionBackendID* profile_backend_id) const;
223 ScopedVector<FormStructure>* form_structures() { return &form_structures_; }
225 // Exposed for testing.
226 AutofillExternalDelegate* external_delegate() {
227 return external_delegate_;
230 private:
231 // AutofillDownloadManager::Observer:
232 void OnLoadedServerPredictions(const std::string& response_xml) override;
234 // CardUnmaskDelegate:
235 void OnUnmaskResponse(const UnmaskResponse& response) override;
236 void OnUnmaskPromptClosed() override;
238 // wallet::RealPanWalletClient::Delegate:
239 IdentityProvider* GetIdentityProvider() override;
240 void OnDidGetRealPan(AutofillClient::GetRealPanResult result,
241 const std::string& real_pan) override;
243 // Returns false if Autofill is disabled or if no Autofill data is available.
244 bool RefreshDataModels();
246 // Returns true if the unique_id refers to a credit card and false if
247 // it refers to a profile.
248 bool IsCreditCard(int unique_id);
250 // Gets the profile referred by |unique_id| and populates |variant|
251 // based on it. Returns true if the profile exists.
252 bool GetProfile(int unique_id,
253 const AutofillProfile** profile,
254 size_t* variant);
256 // Gets the credit card referred by |unique_id| and populates |variant|
257 // based on it. Returns true if the credit card exists.
258 bool GetCreditCard(int unique_id, const CreditCard** credit_card);
260 // Fills or previews the credit card form.
261 // Assumes the form and field are valid.
262 void FillOrPreviewCreditCardForm(
263 AutofillDriver::RendererFormDataAction action,
264 int query_id,
265 const FormData& form,
266 const FormFieldData& field,
267 const CreditCard& credit_card,
268 size_t variant);
270 // Fills or previews the profile form.
271 // Assumes the form and field are valid.
272 void FillOrPreviewProfileForm(
273 AutofillDriver::RendererFormDataAction action,
274 int query_id,
275 const FormData& form,
276 const FormFieldData& field,
277 const AutofillProfile& profile,
278 size_t variant);
280 // Fills or previews |data_model| in the |form|.
281 void FillOrPreviewDataModelForm(AutofillDriver::RendererFormDataAction action,
282 int query_id,
283 const FormData& form,
284 const FormFieldData& field,
285 const AutofillDataModel& data_model,
286 size_t variant,
287 bool is_credit_card);
289 // Fills |form_structure| cached element corresponding to |form|.
290 // Returns false if the cached element was not found.
291 bool FindCachedForm(const FormData& form,
292 FormStructure** form_structure) const WARN_UNUSED_RESULT;
294 // Fills |form_structure| and |autofill_field| with the cached elements
295 // corresponding to |form| and |field|. This might have the side-effect of
296 // updating the cache. Returns false if the |form| is not autofillable, or if
297 // it is not already present in the cache and the cache is full.
298 bool GetCachedFormAndField(const FormData& form,
299 const FormFieldData& field,
300 FormStructure** form_structure,
301 AutofillField** autofill_field) WARN_UNUSED_RESULT;
303 // Returns the field corresponding to |form| and |field| that can be
304 // autofilled. Returns NULL if the field cannot be autofilled.
305 AutofillField* GetAutofillField(const FormData& form,
306 const FormFieldData& field)
307 WARN_UNUSED_RESULT;
309 // Re-parses |live_form| and adds the result to |form_structures_|.
310 // |cached_form| should be a pointer to the existing version of the form, or
311 // NULL if no cached version exists. The updated form is then written into
312 // |updated_form|. Returns false if the cache could not be updated.
313 bool UpdateCachedForm(const FormData& live_form,
314 const FormStructure* cached_form,
315 FormStructure** updated_form) WARN_UNUSED_RESULT;
317 // Returns a list of values from the stored profiles that match |type| and the
318 // value of |field| and returns the labels of the matching profiles. |labels|
319 // is filled with the Profile label.
320 std::vector<Suggestion> GetProfileSuggestions(
321 const FormStructure& form,
322 const FormFieldData& field,
323 const AutofillField& autofill_field) const;
325 // Returns a list of values from the stored credit cards that match |type| and
326 // the value of |field| and returns the labels of the matching credit cards.
327 std::vector<Suggestion> GetCreditCardSuggestions(
328 const FormFieldData& field,
329 const AutofillType& type) const;
331 // Parses the forms using heuristic matching and querying the Autofill server.
332 void ParseForms(const std::vector<FormData>& forms);
334 // Imports the form data, submitted by the user, into |personal_data_|.
335 void ImportFormData(const FormStructure& submitted_form);
337 // If |initial_interaction_timestamp_| is unset or is set to a later time than
338 // |interaction_timestamp|, updates the cached timestamp. The latter check is
339 // needed because IPC messages can arrive out of order.
340 void UpdateInitialInteractionTimestamp(
341 const base::TimeTicks& interaction_timestamp);
343 // Shared code to determine if |form| should be uploaded.
344 bool ShouldUploadForm(const FormStructure& form);
346 // Provides driver-level context to the shared code of the component. Must
347 // outlive this object.
348 AutofillDriver* driver_;
350 AutofillClient* const client_;
352 // Handles real PAN requests.
353 wallet::RealPanWalletClient real_pan_client_;
355 std::string app_locale_;
357 // The personal data manager, used to save and load personal data to/from the
358 // web database. This is overridden by the AutofillManagerTest.
359 // Weak reference.
360 // May be NULL. NULL indicates OTR.
361 PersonalDataManager* personal_data_;
363 std::list<std::string> autofilled_form_signatures_;
365 // Handles queries and uploads to Autofill servers. Will be NULL if
366 // the download manager functionality is disabled.
367 scoped_ptr<AutofillDownloadManager> download_manager_;
369 // Handles single-field autocomplete form data.
370 scoped_ptr<AutocompleteHistoryManager> autocomplete_history_manager_;
372 // Utilities for logging form events.
373 scoped_ptr<AutofillMetrics::FormEventLogger> address_form_event_logger_;
374 scoped_ptr<AutofillMetrics::FormEventLogger> credit_card_form_event_logger_;
376 // Have we logged whether Autofill is enabled for this page load?
377 bool has_logged_autofill_enabled_;
378 // Have we logged an address suggestions count metric for this page?
379 bool has_logged_address_suggestions_count_;
380 // Have we shown Autofill suggestions at least once?
381 bool did_show_suggestions_;
382 // Has the user manually edited at least one form field among the autofillable
383 // ones?
384 bool user_did_type_;
385 // Has the user autofilled a form on this page?
386 bool user_did_autofill_;
387 // Has the user edited a field that was previously autofilled?
388 bool user_did_edit_autofilled_field_;
389 // When the form finished loading.
390 std::map<FormData, base::TimeTicks> forms_loaded_timestamps_;
391 // When the user first interacted with a potentially fillable form on this
392 // page.
393 base::TimeTicks initial_interaction_timestamp_;
395 // Our copy of the form data.
396 ScopedVector<FormStructure> form_structures_;
398 // A copy of the credit card that's currently being unmasked, and data about
399 // the form.
400 CreditCard unmasking_card_;
401 // A copy of the latest card unmasking response.
402 UnmaskResponse unmask_response_;
403 int unmasking_query_id_;
404 FormData unmasking_form_;
405 FormFieldData unmasking_field_;
407 // SuggestionBackendID to ID mapping. We keep two maps to convert back and
408 // forth. These should be used only by BackendIDToInt and IntToBackendID.
409 // Note that the integers are not frontend IDs.
410 mutable std::map<SuggestionBackendID, int> backend_to_int_map_;
411 mutable std::map<int, SuggestionBackendID> int_to_backend_map_;
413 // Delegate to perform external processing (display, selection) on
414 // our behalf. Weak.
415 AutofillExternalDelegate* external_delegate_;
417 // Delegate used in test to get notifications on certain events.
418 AutofillManagerTestDelegate* test_delegate_;
420 base::WeakPtrFactory<AutofillManager> weak_ptr_factory_;
422 friend class AutofillManagerTest;
423 friend class FormStructureBrowserTest;
424 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
425 DeterminePossibleFieldTypesForUpload);
426 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
427 DeterminePossibleFieldTypesForUploadStressTest);
428 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
429 DisabledAutofillDispatchesError);
430 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressFilledFormEvents);
431 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSubmittedFormEvents);
432 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSuggestionsCount);
433 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtPageLoad);
434 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, CreditCardSelectedFormEvents);
435 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, CreditCardFilledFormEvents);
436 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, CreditCardSubmittedFormEvents);
437 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, DeveloperEngagement);
438 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FormFillDuration);
439 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
440 NoQualityMetricsForNonAutofillableForms);
441 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetrics);
442 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsForFailure);
443 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsWithExperimentId);
444 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, SaneMetricsWithCacheMismatch);
445 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, TestExternalDelegate);
446 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
447 TestTabContentsWithExternalDelegate);
448 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
449 UserHappinessFormLoadAndSubmission);
450 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, UserHappinessFormInteraction);
451 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
452 FormSubmittedAutocompleteEnabled);
453 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
454 AutocompleteOffRespected);
455 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
456 AutocompleteOffRespectedWithFlag);
457 DISALLOW_COPY_AND_ASSIGN(AutofillManager);
460 } // namespace autofill
462 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_