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/content/renderer/password_autofill_agent.h"
8 #include "base/command_line.h"
9 #include "base/i18n/case_conversion.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram_macros.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "components/autofill/content/common/autofill_messages.h"
16 #include "components/autofill/content/renderer/form_autofill_util.h"
17 #include "components/autofill/content/renderer/password_form_conversion_utils.h"
18 #include "components/autofill/content/renderer/renderer_save_password_progress_logger.h"
19 #include "components/autofill/core/common/autofill_constants.h"
20 #include "components/autofill/core/common/autofill_switches.h"
21 #include "components/autofill/core/common/form_field_data.h"
22 #include "components/autofill/core/common/password_form.h"
23 #include "components/autofill/core/common/password_form_fill_data.h"
24 #include "content/public/renderer/document_state.h"
25 #include "content/public/renderer/navigation_state.h"
26 #include "content/public/renderer/render_frame.h"
27 #include "content/public/renderer/render_view.h"
28 #include "third_party/WebKit/public/platform/WebVector.h"
29 #include "third_party/WebKit/public/web/WebAutofillClient.h"
30 #include "third_party/WebKit/public/web/WebDocument.h"
31 #include "third_party/WebKit/public/web/WebElement.h"
32 #include "third_party/WebKit/public/web/WebFormElement.h"
33 #include "third_party/WebKit/public/web/WebInputEvent.h"
34 #include "third_party/WebKit/public/web/WebLocalFrame.h"
35 #include "third_party/WebKit/public/web/WebNode.h"
36 #include "third_party/WebKit/public/web/WebNodeList.h"
37 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
38 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
39 #include "third_party/WebKit/public/web/WebView.h"
40 #include "ui/base/page_transition_types.h"
41 #include "ui/events/keycodes/keyboard_codes.h"
47 // The size above which we stop triggering autocomplete.
48 static const size_t kMaximumTextSizeForAutocomplete
= 1000;
50 // Experiment information
51 const char kFillOnAccountSelectFieldTrialName
[] = "FillOnAccountSelect";
52 const char kFillOnAccountSelectFieldTrialEnabledWithHighlightGroup
[] =
53 "EnableWithHighlight";
54 const char kFillOnAccountSelectFieldTrialEnabledWithNoHighlightGroup
[] =
55 "EnableWithNoHighlight";
57 // Maps element names to the actual elements to simplify form filling.
58 typedef std::map
<base::string16
, blink::WebInputElement
> FormInputElementMap
;
60 // Use the shorter name when referencing SavePasswordProgressLogger::StringID
61 // values to spare line breaks. The code provides enough context for that
63 typedef SavePasswordProgressLogger Logger
;
65 // Utility struct for form lookup and autofill. When we parse the DOM to look up
66 // a form, in addition to action and origin URL's we have to compare all
67 // necessary form elements. To avoid having to look these up again when we want
68 // to fill the form, the FindFormElements function stores the pointers
69 // in a FormElements* result, referenced to ensure they are safe to use.
71 blink::WebFormElement form_element
;
72 FormInputElementMap input_elements
;
75 typedef std::vector
<FormElements
*> FormElementsList
;
77 bool FillDataContainsUsername(const PasswordFormFillData
& fill_data
) {
78 return !fill_data
.username_field
.name
.empty();
81 // Utility function to find the unique entry of the |form_element| for the
82 // specified input |field|. On successful find, adds it to |result| and returns
83 // |true|. Otherwise clears the references from each |HTMLInputElement| from
84 // |result| and returns |false|.
85 bool FindFormInputElement(blink::WebFormElement
* form_element
,
86 const FormFieldData
& field
,
87 FormElements
* result
) {
88 blink::WebVector
<blink::WebNode
> temp_elements
;
89 form_element
->getNamedElements(field
.name
, temp_elements
);
91 // Match the first input element, if any.
92 // |getNamedElements| may return non-input elements where the names match,
93 // so the results are filtered for input elements.
94 // If more than one match is made, then we have ambiguity (due to misuse
95 // of "name" attribute) so is it considered not found.
96 bool found_input
= false;
97 for (size_t i
= 0; i
< temp_elements
.size(); ++i
) {
98 if (temp_elements
[i
].to
<blink::WebElement
>().hasHTMLTagName("input")) {
99 // Check for a non-unique match.
105 // Only fill saved passwords into password fields and usernames into
107 blink::WebInputElement input_element
=
108 temp_elements
[i
].to
<blink::WebInputElement
>();
109 if (input_element
.isPasswordField() !=
110 (field
.form_control_type
== "password"))
113 // This element matched, add it to our temporary result. It's possible
114 // there are multiple matches, but for purposes of identifying the form
115 // one suffices and if some function needs to deal with multiple
116 // matching elements it can get at them through the FormElement*.
117 // Note: This assignment adds a reference to the InputElement.
118 result
->input_elements
[field
.name
] = input_element
;
123 // A required element was not found. This is not the right form.
124 // Make sure no input elements from a partially matched form in this
125 // iteration remain in the result set.
126 // Note: clear will remove a reference from each InputElement.
128 result
->input_elements
.clear();
135 bool ShouldFillOnAccountSelect() {
136 std::string group_name
=
137 base::FieldTrialList::FindFullName(kFillOnAccountSelectFieldTrialName
);
139 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
140 switches::kDisableFillOnAccountSelect
)) {
144 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
145 switches::kEnableFillOnAccountSelect
) ||
146 base::CommandLine::ForCurrentProcess()->HasSwitch(
147 switches::kEnableFillOnAccountSelectNoHighlighting
)) {
152 kFillOnAccountSelectFieldTrialEnabledWithHighlightGroup
||
154 kFillOnAccountSelectFieldTrialEnabledWithNoHighlightGroup
;
157 bool ShouldHighlightFields() {
158 std::string group_name
=
159 base::FieldTrialList::FindFullName(kFillOnAccountSelectFieldTrialName
);
160 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
161 switches::kDisableFillOnAccountSelect
) ||
162 base::CommandLine::ForCurrentProcess()->HasSwitch(
163 switches::kEnableFillOnAccountSelect
)) {
167 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
168 switches::kEnableFillOnAccountSelectNoHighlighting
)) {
173 kFillOnAccountSelectFieldTrialEnabledWithNoHighlightGroup
;
176 // Helper to search the given form element for the specified input elements in
177 // |data|, and add results to |result|.
178 bool FindFormInputElements(blink::WebFormElement
* form_element
,
179 const PasswordFormFillData
& data
,
180 FormElements
* result
) {
181 return FindFormInputElement(form_element
, data
.password_field
, result
) &&
182 (!FillDataContainsUsername(data
) ||
183 FindFormInputElement(form_element
, data
.username_field
, result
));
186 // Helper to locate form elements identified by |data|.
187 void FindFormElements(content::RenderFrame
* render_frame
,
188 const PasswordFormFillData
& data
,
189 FormElementsList
* results
) {
192 blink::WebDocument doc
= render_frame
->GetWebFrame()->document();
193 if (!doc
.isHTMLDocument())
196 if (data
.origin
!= GetCanonicalOriginForDocument(doc
))
199 blink::WebVector
<blink::WebFormElement
> forms
;
202 for (size_t i
= 0; i
< forms
.size(); ++i
) {
203 blink::WebFormElement fe
= forms
[i
];
205 // Action URL must match.
206 if (data
.action
!= GetCanonicalActionForForm(fe
))
209 scoped_ptr
<FormElements
> curr_elements(new FormElements
);
210 if (!FindFormInputElements(&fe
, data
, curr_elements
.get()))
213 // We found the right element.
214 // Note: this assignment adds a reference to |fe|.
215 curr_elements
->form_element
= fe
;
216 results
->push_back(curr_elements
.release());
220 bool IsElementEditable(const blink::WebInputElement
& element
) {
221 return element
.isEnabled() && !element
.isReadOnly();
224 bool DoUsernamesMatch(const base::string16
& username1
,
225 const base::string16
& username2
,
228 return username1
== username2
;
229 return base::StartsWith(username1
, username2
, base::CompareCase::SENSITIVE
);
232 // Returns |true| if the given element is editable. Otherwise, returns |false|.
233 bool IsElementAutocompletable(const blink::WebInputElement
& element
) {
234 return IsElementEditable(element
);
237 // Returns true if the password specified in |form| is a default value.
238 bool PasswordValueIsDefault(const base::string16
& password_element
,
239 const base::string16
& password_value
,
240 blink::WebFormElement form_element
) {
241 blink::WebVector
<blink::WebNode
> temp_elements
;
242 form_element
.getNamedElements(password_element
, temp_elements
);
244 // We are loose in our definition here and will return true if any of the
245 // appropriately named elements match the element to be saved. Currently
246 // we ignore filling passwords where naming is ambigious anyway.
247 for (size_t i
= 0; i
< temp_elements
.size(); ++i
) {
248 if (temp_elements
[i
].to
<blink::WebElement
>().getAttribute("value") ==
255 // Return true if either password_value or new_password_value is not empty and
257 bool FormContainsNonDefaultPasswordValue(const PasswordForm
& password_form
,
258 blink::WebFormElement form_element
) {
259 return (!password_form
.password_value
.empty() &&
260 !PasswordValueIsDefault(password_form
.password_element
,
261 password_form
.password_value
,
263 (!password_form
.new_password_value
.empty() &&
264 !PasswordValueIsDefault(password_form
.new_password_element
,
265 password_form
.new_password_value
,
269 // Log a message including the name, method and action of |form|.
270 void LogHTMLForm(SavePasswordProgressLogger
* logger
,
271 SavePasswordProgressLogger::StringID message_id
,
272 const blink::WebFormElement
& form
) {
273 logger
->LogHTMLForm(message_id
,
275 GURL(form
.action().utf8()));
278 // Sets |suggestions_present| to true if there are any suggestions to be derived
279 // from |fill_data|. Unless |show_all| is true, only considers suggestions with
280 // usernames having |current_username| as a prefix. Returns true if a username
281 // from the |fill_data.other_possible_usernames| would be included in the
283 bool GetSuggestionsStats(const PasswordFormFillData
& fill_data
,
284 const base::string16
& current_username
,
286 bool* suggestions_present
) {
287 *suggestions_present
= false;
288 base::string16 current_username_lower
= base::i18n::ToLower(current_username
);
290 for (const auto& usernames
: fill_data
.other_possible_usernames
) {
291 for (size_t i
= 0; i
< usernames
.second
.size(); ++i
) {
294 base::i18n::ToLower(base::string16(usernames
.second
[i
])),
295 current_username_lower
, base::CompareCase::SENSITIVE
)) {
296 *suggestions_present
= true;
303 base::StartsWith(base::i18n::ToLower(fill_data
.username_field
.value
),
304 current_username_lower
, base::CompareCase::SENSITIVE
)) {
305 *suggestions_present
= true;
309 for (const auto& login
: fill_data
.additional_logins
) {
311 base::StartsWith(base::i18n::ToLower(login
.first
),
312 current_username_lower
,
313 base::CompareCase::SENSITIVE
)) {
314 *suggestions_present
= true;
322 // Returns true if there exists a credential suggestion whose username field is
323 // an exact match to the current username (not just a prefix).
324 bool HasExactMatchSuggestion(const PasswordFormFillData
& fill_data
,
325 const base::string16
& current_username
) {
326 if (fill_data
.username_field
.value
== current_username
)
329 for (const auto& usernames
: fill_data
.other_possible_usernames
) {
330 for (const auto& username_string
: usernames
.second
) {
331 if (username_string
== current_username
)
336 for (const auto& login
: fill_data
.additional_logins
) {
337 if (login
.first
== current_username
)
344 // This function attempts to fill |username_element| and |password_element|
345 // with values from |fill_data|. The |password_element| will only have the
346 // |suggestedValue| set, and will be registered for copying that to the real
347 // value through |registration_callback|. The function returns true when
348 // selected username comes from |fill_data.other_possible_usernames|. |options|
349 // should be a bitwise mask of FillUserNameAndPasswordOptions values.
350 bool FillUserNameAndPassword(
351 blink::WebInputElement
* username_element
,
352 blink::WebInputElement
* password_element
,
353 const PasswordFormFillData
& fill_data
,
354 bool exact_username_match
,
356 std::map
<const blink::WebInputElement
, blink::WebString
>&
357 nonscript_modified_values
,
358 base::Callback
<void(blink::WebInputElement
*)> registration_callback
) {
359 bool other_possible_username_selected
= false;
360 // Don't fill username if password can't be set.
361 if (!IsElementAutocompletable(*password_element
))
364 base::string16 current_username
;
365 if (!username_element
->isNull()) {
366 current_username
= username_element
->value();
369 // username and password will contain the match found if any.
370 base::string16 username
;
371 base::string16 password
;
373 // Look for any suitable matches to current field text.
374 if (DoUsernamesMatch(fill_data
.username_field
.value
, current_username
,
375 exact_username_match
)) {
376 username
= fill_data
.username_field
.value
;
377 password
= fill_data
.password_field
.value
;
379 // Scan additional logins for a match.
380 PasswordFormFillData::LoginCollection::const_iterator iter
;
381 for (iter
= fill_data
.additional_logins
.begin();
382 iter
!= fill_data
.additional_logins
.end();
384 if (DoUsernamesMatch(
385 iter
->first
, current_username
, exact_username_match
)) {
386 username
= iter
->first
;
387 password
= iter
->second
.password
;
392 // Check possible usernames.
393 if (username
.empty() && password
.empty()) {
394 for (PasswordFormFillData::UsernamesCollection::const_iterator iter
=
395 fill_data
.other_possible_usernames
.begin();
396 iter
!= fill_data
.other_possible_usernames
.end();
398 for (size_t i
= 0; i
< iter
->second
.size(); ++i
) {
399 if (DoUsernamesMatch(
400 iter
->second
[i
], current_username
, exact_username_match
)) {
401 other_possible_username_selected
= true;
402 username
= iter
->second
[i
];
403 password
= iter
->first
.password
;
407 if (!username
.empty() && !password
.empty())
412 if (password
.empty())
413 return other_possible_username_selected
; // No match was found.
415 // TODO(tkent): Check maxlength and pattern for both username and password
418 // Input matches the username, fill in required values.
419 if (!username_element
->isNull() &&
420 IsElementAutocompletable(*username_element
)) {
421 username_element
->setValue(username
, true);
422 nonscript_modified_values
[*username_element
] = username
;
423 username_element
->setAutofilled(true);
426 username_element
->setSelectionRange(current_username
.length(),
429 } else if (current_username
!= username
) {
430 // If the username can't be filled and it doesn't match a saved password
431 // as is, don't autofill a password.
432 return other_possible_username_selected
;
435 // Wait to fill in the password until a user gesture occurs. This is to make
436 // sure that we do not fill in the DOM with a password until we believe the
437 // user is intentionally interacting with the page.
438 password_element
->setSuggestedValue(password
);
439 nonscript_modified_values
[*password_element
] = password
;
440 registration_callback
.Run(password_element
);
442 password_element
->setAutofilled(true);
443 return other_possible_username_selected
;
446 // Attempts to fill |username_element| and |password_element| with the
447 // |fill_data|. Will use the data corresponding to the preferred username,
448 // unless the |username_element| already has a value set. In that case,
449 // attempts to fill the password matching the already filled username, if
450 // such a password exists. The |password_element| will have the
451 // |suggestedValue| set, and |suggestedValue| will be registered for copying to
452 // the real value through |registration_callback|. Returns true when the
453 // username gets selected from |other_possible_usernames|, else returns false.
454 bool FillFormOnPasswordReceived(
455 const PasswordFormFillData
& fill_data
,
456 blink::WebInputElement username_element
,
457 blink::WebInputElement password_element
,
458 std::map
<const blink::WebInputElement
, blink::WebString
>&
459 nonscript_modified_values
,
460 base::Callback
<void(blink::WebInputElement
*)> registration_callback
) {
461 // Do not fill if the password field is in a chain of iframes not having
463 blink::WebFrame
* cur_frame
= password_element
.document().frame();
464 blink::WebString bottom_frame_origin
=
465 cur_frame
->securityOrigin().toString();
469 while (cur_frame
->parent()) {
470 cur_frame
= cur_frame
->parent();
471 if (!bottom_frame_origin
.equals(cur_frame
->securityOrigin().toString()))
475 // If we can't modify the password, don't try to set the username
476 if (!IsElementAutocompletable(password_element
))
479 bool form_contains_username_field
= FillDataContainsUsername(fill_data
);
480 // If the form contains an autocompletable username field, try to set the
481 // username to the preferred name, but only if:
482 // (a) The fill-on-account-select flag is not set, and
483 // (b) The username element isn't prefilled
485 // If (a) is false, then just mark the username element as autofilled if the
486 // user is not in the "no highlighting" group and return so the fill step is
489 // If there is no autocompletable username field, and (a) is false, then the
490 // username element cannot be autofilled, but the user should still be able to
491 // select to fill the password element, so the password element must be marked
492 // as autofilled and the fill step should also be skipped if the user is not
493 // in the "no highlighting" group.
495 // In all other cases, do nothing.
496 bool form_has_fillable_username
= form_contains_username_field
&&
497 IsElementAutocompletable(username_element
);
499 if (ShouldFillOnAccountSelect()) {
500 if (!ShouldHighlightFields()) {
504 if (form_has_fillable_username
) {
505 username_element
.setAutofilled(true);
506 } else if (username_element
.isNull() ||
507 HasExactMatchSuggestion(fill_data
, username_element
.value())) {
508 password_element
.setAutofilled(true);
513 if (form_has_fillable_username
&& username_element
.value().isEmpty()) {
514 // TODO(tkent): Check maxlength and pattern.
515 username_element
.setValue(fill_data
.username_field
.value
, true);
518 // Fill if we have an exact match for the username. Note that this sets
519 // username to autofilled.
520 return FillUserNameAndPassword(&username_element
,
523 true /* exact_username_match */,
524 false /* set_selection */,
525 nonscript_modified_values
,
526 registration_callback
);
529 // Takes a |map| with pointers as keys and linked_ptr as values, and returns
530 // true if |key| is not NULL and |map| contains a non-NULL entry for |key|.
531 // Makes sure not to create an entry as a side effect of using the operator [].
532 template <class Key
, class Value
>
533 bool ContainsNonNullEntryForNonNullKey(
534 const std::map
<Key
*, linked_ptr
<Value
>>& map
,
538 auto it
= map
.find(key
);
539 return it
!= map
.end() && it
->second
.get();
543 // Helper function to check if there exist any form on |frame| where its action
544 // equals |action|. Return true if so.
546 blink::WebFrame
* frame
,
548 blink::WebVector
<blink::WebFormElement
> forms
;
549 frame
->document().forms(forms
);
551 for (size_t i
= 0; i
< forms
.size(); ++i
) {
552 const blink::WebFormElement
& form
= forms
[i
];
553 if (!IsWebNodeVisible(form
))
556 if (action
== GetCanonicalActionForForm(form
))
557 return true; // Form still exists
565 ////////////////////////////////////////////////////////////////////////////////
566 // PasswordAutofillAgent, public:
568 PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame
* render_frame
)
569 : content::RenderFrameObserver(render_frame
),
570 legacy_(render_frame
->GetRenderView(), this),
571 usernames_usage_(NOTHING_TO_AUTOFILL
),
572 logging_state_active_(false),
573 was_username_autofilled_(false),
574 was_password_autofilled_(false),
575 username_selection_start_(0),
576 did_stop_loading_(false),
577 weak_ptr_factory_(this) {
578 Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id()));
581 PasswordAutofillAgent::~PasswordAutofillAgent() {
584 PasswordAutofillAgent::PasswordValueGatekeeper::PasswordValueGatekeeper()
585 : was_user_gesture_seen_(false) {
588 PasswordAutofillAgent::PasswordValueGatekeeper::~PasswordValueGatekeeper() {
591 void PasswordAutofillAgent::PasswordValueGatekeeper::RegisterElement(
592 blink::WebInputElement
* element
) {
593 if (was_user_gesture_seen_
)
596 elements_
.push_back(*element
);
599 void PasswordAutofillAgent::PasswordValueGatekeeper::OnUserGesture() {
600 was_user_gesture_seen_
= true;
602 for (std::vector
<blink::WebInputElement
>::iterator it
= elements_
.begin();
603 it
!= elements_
.end();
611 void PasswordAutofillAgent::PasswordValueGatekeeper::Reset() {
612 was_user_gesture_seen_
= false;
616 void PasswordAutofillAgent::PasswordValueGatekeeper::ShowValue(
617 blink::WebInputElement
* element
) {
618 if (!element
->isNull() && !element
->suggestedValue().isEmpty())
619 element
->setValue(element
->suggestedValue(), true);
622 bool PasswordAutofillAgent::TextFieldDidEndEditing(
623 const blink::WebInputElement
& element
) {
624 LoginToPasswordInfoMap::const_iterator iter
=
625 login_to_password_info_
.find(element
);
626 if (iter
== login_to_password_info_
.end())
629 const PasswordInfo
& password_info
= iter
->second
;
630 // Don't let autofill overwrite an explicit change made by the user.
631 if (password_info
.password_was_edited_last
)
634 const PasswordFormFillData
& fill_data
= password_info
.fill_data
;
636 // If wait_for_username is false, we should have filled when the text changed.
637 if (!fill_data
.wait_for_username
)
640 blink::WebInputElement password
= password_info
.password_field
;
641 if (!IsElementEditable(password
))
644 blink::WebInputElement username
= element
; // We need a non-const.
646 // Do not set selection when ending an editing session, otherwise it can
648 if (FillUserNameAndPassword(
649 &username
, &password
, fill_data
, true, false,
650 nonscript_modified_values_
,
651 base::Bind(&PasswordValueGatekeeper::RegisterElement
,
652 base::Unretained(&gatekeeper_
)))) {
653 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SELECTED
;
658 bool PasswordAutofillAgent::TextDidChangeInTextField(
659 const blink::WebInputElement
& element
) {
660 // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
661 blink::WebInputElement mutable_element
= element
; // We need a non-const.
663 LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.find(element
);
664 if (iter
== login_to_password_info_
.end())
667 // The input text is being changed, so any autofilled password is now
669 mutable_element
.setAutofilled(false);
670 iter
->second
.password_was_edited_last
= false;
672 blink::WebInputElement password
= iter
->second
.password_field
;
673 if (password
.isAutofilled()) {
674 password
.setValue(base::string16(), true);
675 password
.setAutofilled(false);
678 // If wait_for_username is true we will fill when the username loses focus.
679 if (iter
->second
.fill_data
.wait_for_username
)
682 if (!element
.isText() || !IsElementAutocompletable(element
) ||
683 !IsElementAutocompletable(password
)) {
687 // Don't inline autocomplete if the user is deleting, that would be confusing.
688 // But refresh the popup. Note, since this is ours, return true to signal
689 // no further processing is required.
690 if (iter
->second
.backspace_pressed_last
) {
691 ShowSuggestionPopup(iter
->second
.fill_data
, element
, false, false);
695 blink::WebString name
= element
.nameForAutofill();
697 return false; // If the field has no name, then we won't have values.
699 // Don't attempt to autofill with values that are too large.
700 if (element
.value().length() > kMaximumTextSizeForAutocomplete
)
703 // The caret position should have already been updated.
704 PerformInlineAutocomplete(element
, password
, iter
->second
.fill_data
);
708 bool PasswordAutofillAgent::TextFieldHandlingKeyDown(
709 const blink::WebInputElement
& element
,
710 const blink::WebKeyboardEvent
& event
) {
711 // If using the new Autofill UI that lives in the browser, it will handle
712 // keypresses before this function. This is not currently an issue but if
713 // the keys handled there or here change, this issue may appear.
715 LoginToPasswordInfoMap::iterator iter
= login_to_password_info_
.find(element
);
716 if (iter
== login_to_password_info_
.end())
719 int win_key_code
= event
.windowsKeyCode
;
720 iter
->second
.backspace_pressed_last
=
721 (win_key_code
== ui::VKEY_BACK
|| win_key_code
== ui::VKEY_DELETE
);
725 void PasswordAutofillAgent::UpdateStateForTextChange(
726 const blink::WebInputElement
& element
) {
727 // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
728 blink::WebInputElement mutable_element
= element
; // We need a non-const.
730 if (element
.isTextField())
731 nonscript_modified_values_
[element
] = element
.value();
733 LoginToPasswordInfoMap::iterator password_info_iter
=
734 login_to_password_info_
.find(element
);
735 if (password_info_iter
!= login_to_password_info_
.end()) {
736 password_info_iter
->second
.username_was_edited
= true;
739 DCHECK_EQ(element
.document().frame(), render_frame()->GetWebFrame());
741 if (element
.isPasswordField()) {
742 // Some login forms have event handlers that put a hash of the password into
743 // a hidden field and then clear the password (http://crbug.com/28910,
744 // http://crbug.com/391693). This method gets called before any of those
745 // handlers run, so save away a copy of the password in case it gets lost.
746 // To honor the user having explicitly cleared the password, even an empty
747 // password will be saved here.
748 ProvisionallySavePassword(element
.form(), RESTRICTION_NONE
);
750 PasswordToLoginMap::iterator iter
= password_to_username_
.find(element
);
751 if (iter
!= password_to_username_
.end()) {
752 login_to_password_info_
[iter
->second
].password_was_edited_last
= true;
753 // Note that the suggested value of |mutable_element| was reset when its
755 mutable_element
.setAutofilled(false);
760 bool PasswordAutofillAgent::FillSuggestion(
761 const blink::WebNode
& node
,
762 const blink::WebString
& username
,
763 const blink::WebString
& password
) {
764 // The element in context of the suggestion popup.
765 blink::WebInputElement filled_element
;
766 PasswordInfo
* password_info
;
768 if (!FindLoginInfo(node
, &filled_element
, &password_info
) ||
769 !IsElementAutocompletable(filled_element
) ||
770 !IsElementAutocompletable(password_info
->password_field
)) {
774 password_info
->password_was_edited_last
= false;
775 // Note that in cases where filled_element is the password element, the value
776 // gets overwritten with the correct one below.
777 filled_element
.setValue(username
, true);
778 filled_element
.setAutofilled(true);
780 password_info
->password_field
.setValue(password
, true);
781 password_info
->password_field
.setAutofilled(true);
783 filled_element
.setSelectionRange(filled_element
.value().length(),
784 filled_element
.value().length());
789 bool PasswordAutofillAgent::PreviewSuggestion(
790 const blink::WebNode
& node
,
791 const blink::WebString
& username
,
792 const blink::WebString
& password
) {
793 blink::WebInputElement username_element
;
794 PasswordInfo
* password_info
;
796 if (!FindLoginInfo(node
, &username_element
, &password_info
) ||
797 !IsElementAutocompletable(username_element
) ||
798 !IsElementAutocompletable(password_info
->password_field
)) {
802 was_username_autofilled_
= username_element
.isAutofilled();
803 username_selection_start_
= username_element
.selectionStart();
804 username_element
.setSuggestedValue(username
);
805 username_element
.setAutofilled(true);
806 username_element
.setSelectionRange(
807 username_selection_start_
,
808 username_element
.suggestedValue().length());
810 was_password_autofilled_
= password_info
->password_field
.isAutofilled();
811 password_info
->password_field
.setSuggestedValue(password
);
812 password_info
->password_field
.setAutofilled(true);
817 bool PasswordAutofillAgent::DidClearAutofillSelection(
818 const blink::WebNode
& node
) {
819 blink::WebInputElement username_element
;
820 PasswordInfo
* password_info
;
821 if (!FindLoginInfo(node
, &username_element
, &password_info
))
824 ClearPreview(&username_element
, &password_info
->password_field
);
828 bool PasswordAutofillAgent::FindPasswordInfoForElement(
829 const blink::WebInputElement
& element
,
830 const blink::WebInputElement
** username_element
,
831 PasswordInfo
** password_info
) {
832 DCHECK(username_element
&& password_info
);
833 if (!element
.isPasswordField()) {
834 *username_element
= &element
;
836 PasswordToLoginMap::const_iterator password_iter
=
837 password_to_username_
.find(element
);
838 if (password_iter
== password_to_username_
.end())
840 *username_element
= &password_iter
->second
;
843 LoginToPasswordInfoMap::iterator iter
=
844 login_to_password_info_
.find(**username_element
);
846 if (iter
== login_to_password_info_
.end())
849 *password_info
= &iter
->second
;
853 bool PasswordAutofillAgent::ShowSuggestions(
854 const blink::WebInputElement
& element
,
856 bool generation_popup_showing
) {
857 const blink::WebInputElement
* username_element
;
858 PasswordInfo
* password_info
;
859 if (!FindPasswordInfoForElement(element
, &username_element
, &password_info
))
862 // If autocomplete='off' is set on the form elements, no suggestion dialog
863 // should be shown. However, return |true| to indicate that this is a known
864 // password form and that the request to show suggestions has been handled (as
866 if (!IsElementAutocompletable(element
) ||
867 !IsElementAutocompletable(password_info
->password_field
))
870 bool username_is_available
=
871 !username_element
->isNull() && IsElementEditable(*username_element
);
872 // If the element is a password field, a popup should only be shown if there
873 // is no username or the corresponding username element is not editable since
874 // it is only in that case that the username element does not have a
875 // suggestions popup.
876 if (element
.isPasswordField() && username_is_available
&&
877 (!password_info
->fill_data
.is_possible_change_password_form
||
878 password_info
->username_was_edited
))
881 UMA_HISTOGRAM_BOOLEAN(
882 "PasswordManager.AutocompletePopupSuppressedByGeneration",
883 generation_popup_showing
);
885 if (generation_popup_showing
)
888 // Chrome should never show more than one account for a password element since
889 // this implies that the username element cannot be modified. Thus even if
890 // |show_all| is true, check if the element in question is a password element
891 // for the call to ShowSuggestionPopup.
892 return ShowSuggestionPopup(
893 password_info
->fill_data
,
894 username_element
->isNull() ? element
: *username_element
,
895 show_all
&& !element
.isPasswordField(), element
.isPasswordField());
898 bool PasswordAutofillAgent::OriginCanAccessPasswordManager(
899 const blink::WebSecurityOrigin
& origin
) {
900 return origin
.canAccessPasswordManager();
903 void PasswordAutofillAgent::OnDynamicFormsSeen() {
904 SendPasswordForms(false /* only_visible */);
907 void PasswordAutofillAgent::XHRSucceeded() {
908 if (!ProvisionallySavedPasswordIsValid())
910 blink::WebFrame
* frame
= render_frame()->GetWebFrame();
912 // Prompt to save only if the form is now gone, either invisible or
913 // removed from the DOM.
914 if (IsFormVisible(frame
, provisionally_saved_form_
->action
))
917 Send(new AutofillHostMsg_InPageNavigation(routing_id(),
918 *provisionally_saved_form_
));
919 provisionally_saved_form_
.reset();
922 void PasswordAutofillAgent::FirstUserGestureObserved() {
923 gatekeeper_
.OnUserGesture();
926 void PasswordAutofillAgent::SendPasswordForms(bool only_visible
) {
927 scoped_ptr
<RendererSavePasswordProgressLogger
> logger
;
928 if (logging_state_active_
) {
929 logger
.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
930 logger
->LogMessage(Logger::STRING_SEND_PASSWORD_FORMS_METHOD
);
931 logger
->LogBoolean(Logger::STRING_ONLY_VISIBLE
, only_visible
);
934 blink::WebFrame
* frame
= render_frame()->GetWebFrame();
935 // Make sure that this security origin is allowed to use password manager.
936 blink::WebSecurityOrigin origin
= frame
->document().securityOrigin();
938 logger
->LogURL(Logger::STRING_SECURITY_ORIGIN
,
939 GURL(origin
.toString().utf8()));
941 if (!OriginCanAccessPasswordManager(origin
)) {
943 logger
->LogMessage(Logger::STRING_SECURITY_ORIGIN_FAILURE
);
948 // Checks whether the webpage is a redirect page or an empty page.
949 if (IsWebpageEmpty(frame
)) {
951 logger
->LogMessage(Logger::STRING_WEBPAGE_EMPTY
);
956 blink::WebVector
<blink::WebFormElement
> forms
;
957 frame
->document().forms(forms
);
959 logger
->LogNumber(Logger::STRING_NUMBER_OF_ALL_FORMS
, forms
.size());
961 std::vector
<PasswordForm
> password_forms
;
962 for (size_t i
= 0; i
< forms
.size(); ++i
) {
963 const blink::WebFormElement
& form
= forms
[i
];
965 bool is_form_visible
= IsWebNodeVisible(form
);
967 LogHTMLForm(logger
.get(), Logger::STRING_FORM_FOUND_ON_PAGE
, form
);
968 logger
->LogBoolean(Logger::STRING_FORM_IS_VISIBLE
, is_form_visible
);
971 // If requested, ignore non-rendered forms, e.g., those styled with
973 if (!is_form_visible
)
977 scoped_ptr
<PasswordForm
> password_form(
978 CreatePasswordForm(form
, nullptr, &form_predictions_
));
979 if (password_form
.get()) {
981 logger
->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD
,
984 password_forms
.push_back(*password_form
);
988 if (password_forms
.empty() && !only_visible
) {
989 // We need to send the PasswordFormsRendered message regardless of whether
990 // there are any forms visible, as this is also the code path that triggers
991 // showing the infobar.
996 Send(new AutofillHostMsg_PasswordFormsRendered(routing_id(),
1000 Send(new AutofillHostMsg_PasswordFormsParsed(routing_id(), password_forms
));
1004 bool PasswordAutofillAgent::OnMessageReceived(const IPC::Message
& message
) {
1005 bool handled
= true;
1006 IPC_BEGIN_MESSAGE_MAP(PasswordAutofillAgent
, message
)
1007 IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordForm
, OnFillPasswordForm
)
1008 IPC_MESSAGE_HANDLER(AutofillMsg_SetLoggingState
, OnSetLoggingState
)
1009 IPC_MESSAGE_HANDLER(AutofillMsg_AutofillUsernameAndPasswordDataReceived
,
1010 OnAutofillUsernameAndPasswordDataReceived
)
1011 IPC_MESSAGE_HANDLER(AutofillMsg_FindFocusedPasswordForm
,
1012 OnFindFocusedPasswordForm
)
1013 IPC_MESSAGE_UNHANDLED(handled
= false)
1014 IPC_END_MESSAGE_MAP()
1018 void PasswordAutofillAgent::DidFinishDocumentLoad() {
1019 // The |frame| contents have been parsed, but not yet rendered. Let the
1020 // PasswordManager know that forms are loaded, even though we can't yet tell
1021 // whether they're visible.
1022 SendPasswordForms(false);
1025 void PasswordAutofillAgent::DidFinishLoad() {
1026 // The |frame| contents have been rendered. Let the PasswordManager know
1027 // which of the loaded frames are actually visible to the user. This also
1028 // triggers the "Save password?" infobar if the user just submitted a password
1030 SendPasswordForms(true);
1033 void PasswordAutofillAgent::FrameWillClose() {
1037 void PasswordAutofillAgent::DidCommitProvisionalLoad(
1038 bool is_new_navigation
, bool is_same_page_navigation
) {
1039 if (!ProvisionallySavedPasswordIsValid())
1041 blink::WebFrame
* frame
= render_frame()->GetWebFrame();
1042 // TODO(dvadym): check if we need to check if it is main frame navigation
1043 // http://crbug.com/443155
1044 if (frame
->parent())
1045 return; // Not a top-level navigation.
1047 // Prompt to save only if the form disappeared.
1048 if (IsFormVisible(frame
, provisionally_saved_form_
->action
))
1051 if (is_same_page_navigation
) {
1052 Send(new AutofillHostMsg_InPageNavigation(routing_id(),
1053 *provisionally_saved_form_
));
1054 provisionally_saved_form_
.reset();
1058 void PasswordAutofillAgent::DidStartLoading() {
1059 did_stop_loading_
= false;
1060 if (usernames_usage_
!= NOTHING_TO_AUTOFILL
) {
1061 UMA_HISTOGRAM_ENUMERATION("PasswordManager.OtherPossibleUsernamesUsage",
1062 usernames_usage_
, OTHER_POSSIBLE_USERNAMES_MAX
);
1063 usernames_usage_
= NOTHING_TO_AUTOFILL
;
1067 void PasswordAutofillAgent::DidStopLoading() {
1068 did_stop_loading_
= true;
1071 void PasswordAutofillAgent::FrameDetached() {
1072 // If a sub frame has been destroyed while the user was entering information
1073 // into a password form, try to save the data. See https://crbug.com/450806
1074 // for examples of sites that perform login using this technique.
1075 if (render_frame()->GetWebFrame()->parent() &&
1076 ProvisionallySavedPasswordIsValid()) {
1077 Send(new AutofillHostMsg_InPageNavigation(routing_id(),
1078 *provisionally_saved_form_
));
1083 void PasswordAutofillAgent::WillSendSubmitEvent(
1084 const blink::WebFormElement
& form
) {
1085 // Forms submitted via XHR are not seen by WillSubmitForm if the default
1086 // onsubmit handler is overridden. Such submission first gets detected in
1087 // DidStartProvisionalLoad, which no longer knows about the particular form,
1088 // and uses the candidate stored in |provisionally_saved_form_|.
1090 // User-typed password will get stored to |provisionally_saved_form_| in
1091 // TextDidChangeInTextField. Autofilled or JavaScript-copied passwords need to
1094 // Only non-empty passwords are saved here. Empty passwords were likely
1095 // cleared by some scripts (http://crbug.com/28910, http://crbug.com/391693).
1096 // Had the user cleared the password, |provisionally_saved_form_| would
1097 // already have been updated in TextDidChangeInTextField.
1098 ProvisionallySavePassword(form
, RESTRICTION_NON_EMPTY_PASSWORD
);
1101 void PasswordAutofillAgent::WillSubmitForm(const blink::WebFormElement
& form
) {
1102 scoped_ptr
<RendererSavePasswordProgressLogger
> logger
;
1103 if (logging_state_active_
) {
1104 logger
.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
1105 logger
->LogMessage(Logger::STRING_WILL_SUBMIT_FORM_METHOD
);
1106 LogHTMLForm(logger
.get(), Logger::STRING_HTML_FORM_FOR_SUBMIT
, form
);
1109 scoped_ptr
<PasswordForm
> submitted_form
=
1110 CreatePasswordForm(form
, &nonscript_modified_values_
, &form_predictions_
);
1112 // If there is a provisionally saved password, copy over the previous
1113 // password value so we get the user's typed password, not the value that
1114 // may have been transformed for submit.
1115 // TODO(gcasto): Do we need to have this action equality check? Is it trying
1116 // to prevent accidentally copying over passwords from a different form?
1117 if (submitted_form
) {
1119 logger
->LogPasswordForm(Logger::STRING_CREATED_PASSWORD_FORM
,
1122 if (provisionally_saved_form_
&&
1123 submitted_form
->action
== provisionally_saved_form_
->action
) {
1125 logger
->LogMessage(Logger::STRING_SUBMITTED_PASSWORD_REPLACED
);
1126 submitted_form
->password_value
=
1127 provisionally_saved_form_
->password_value
;
1128 submitted_form
->new_password_value
=
1129 provisionally_saved_form_
->new_password_value
;
1130 submitted_form
->username_value
=
1131 provisionally_saved_form_
->username_value
;
1134 // Some observers depend on sending this information now instead of when
1135 // the frame starts loading. If there are redirects that cause a new
1136 // RenderView to be instantiated (such as redirects to the WebStore)
1137 // we will never get to finish the load.
1138 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
1140 provisionally_saved_form_
.reset();
1141 } else if (logger
) {
1142 logger
->LogMessage(Logger::STRING_FORM_IS_NOT_PASSWORD
);
1146 void PasswordAutofillAgent::LegacyDidStartProvisionalLoad(
1147 blink::WebLocalFrame
* navigated_frame
) {
1148 scoped_ptr
<RendererSavePasswordProgressLogger
> logger
;
1149 if (logging_state_active_
) {
1150 logger
.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
1151 logger
->LogMessage(Logger::STRING_DID_START_PROVISIONAL_LOAD_METHOD
);
1154 if (navigated_frame
->parent()) {
1156 logger
->LogMessage(Logger::STRING_FRAME_NOT_MAIN_FRAME
);
1160 // Bug fix for crbug.com/368690. isProcessingUserGesture() is false when
1161 // the user is performing actions outside the page (e.g. typed url,
1162 // history navigation). We don't want to trigger saving in these cases.
1163 content::DocumentState
* document_state
=
1164 content::DocumentState::FromDataSource(
1165 navigated_frame
->provisionalDataSource());
1166 content::NavigationState
* navigation_state
=
1167 document_state
->navigation_state();
1168 ui::PageTransition type
= navigation_state
->GetTransitionType();
1169 if (ui::PageTransitionIsWebTriggerable(type
) &&
1170 ui::PageTransitionIsNewNavigation(type
) &&
1171 !blink::WebUserGestureIndicator::isProcessingUserGesture()) {
1172 // If onsubmit has been called, try and save that form.
1173 if (provisionally_saved_form_
) {
1175 logger
->LogPasswordForm(
1176 Logger::STRING_PROVISIONALLY_SAVED_FORM_FOR_FRAME
,
1177 *provisionally_saved_form_
);
1179 Send(new AutofillHostMsg_PasswordFormSubmitted(
1180 routing_id(), *provisionally_saved_form_
));
1181 provisionally_saved_form_
.reset();
1183 // Loop through the forms on the page looking for one that has been
1184 // filled out. If one exists, try and save the credentials.
1185 blink::WebVector
<blink::WebFormElement
> forms
;
1186 render_frame()->GetWebFrame()->document().forms(forms
);
1188 bool password_forms_found
= false;
1189 for (size_t i
= 0; i
< forms
.size(); ++i
) {
1190 blink::WebFormElement form_element
= forms
[i
];
1192 LogHTMLForm(logger
.get(), Logger::STRING_FORM_FOUND_ON_PAGE
,
1195 scoped_ptr
<PasswordForm
> password_form(CreatePasswordForm(
1196 form_element
, &nonscript_modified_values_
, &form_predictions_
));
1197 if (password_form
.get() && !password_form
->username_value
.empty() &&
1198 FormContainsNonDefaultPasswordValue(*password_form
, form_element
)) {
1199 password_forms_found
= true;
1201 logger
->LogPasswordForm(Logger::STRING_PASSWORD_FORM_FOUND_ON_PAGE
,
1204 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
1208 if (!password_forms_found
&& logger
)
1209 logger
->LogMessage(Logger::STRING_PASSWORD_FORM_NOT_FOUND_ON_PAGE
);
1213 // This is a new navigation, so require a new user gesture before filling in
1215 gatekeeper_
.Reset();
1218 void PasswordAutofillAgent::OnFillPasswordForm(
1220 const PasswordFormFillData
& form_data
) {
1221 if (usernames_usage_
== NOTHING_TO_AUTOFILL
) {
1222 if (form_data
.other_possible_usernames
.size())
1223 usernames_usage_
= OTHER_POSSIBLE_USERNAMES_PRESENT
;
1224 else if (usernames_usage_
== NOTHING_TO_AUTOFILL
)
1225 usernames_usage_
= OTHER_POSSIBLE_USERNAMES_ABSENT
;
1228 FormElementsList forms
;
1229 // We own the FormElements* in forms.
1230 FindFormElements(render_frame(), form_data
, &forms
);
1231 FormElementsList::iterator iter
;
1232 for (iter
= forms
.begin(); iter
!= forms
.end(); ++iter
) {
1233 scoped_ptr
<FormElements
> form_elements(*iter
);
1235 // Attach autocomplete listener to enable selecting alternate logins.
1236 blink::WebInputElement username_element
, password_element
;
1238 // Check whether the password form has a username input field.
1239 bool form_contains_username_field
= FillDataContainsUsername(form_data
);
1240 if (form_contains_username_field
) {
1242 form_elements
->input_elements
[form_data
.username_field
.name
];
1245 // No password field, bail out.
1246 if (form_data
.password_field
.name
.empty())
1249 // We might have already filled this form if there are two <form> elements
1250 // with identical markup.
1251 if (login_to_password_info_
.find(username_element
) !=
1252 login_to_password_info_
.end())
1255 // Get pointer to password element. (We currently only support single
1258 form_elements
->input_elements
[form_data
.password_field
.name
];
1260 // If wait_for_username is true, we don't want to initially fill the form
1261 // until the user types in a valid username.
1262 if (!form_data
.wait_for_username
&&
1263 FillFormOnPasswordReceived(
1267 nonscript_modified_values_
,
1268 base::Bind(&PasswordValueGatekeeper::RegisterElement
,
1269 base::Unretained(&gatekeeper_
)))) {
1270 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SELECTED
;
1273 PasswordInfo password_info
;
1274 password_info
.fill_data
= form_data
;
1275 password_info
.password_field
= password_element
;
1276 login_to_password_info_
[username_element
] = password_info
;
1277 password_to_username_
[password_element
] = username_element
;
1278 login_to_password_info_key_
[username_element
] = key
;
1282 void PasswordAutofillAgent::OnSetLoggingState(bool active
) {
1283 logging_state_active_
= active
;
1286 void PasswordAutofillAgent::OnAutofillUsernameAndPasswordDataReceived(
1287 const FormsPredictionsMap
& predictions
) {
1288 form_predictions_
= predictions
;
1291 void PasswordAutofillAgent::OnFindFocusedPasswordForm() {
1292 scoped_ptr
<PasswordForm
> password_form
;
1294 blink::WebElement element
= render_frame()->GetFocusedElement();
1295 if (!element
.isNull() && element
.hasHTMLTagName("input")) {
1296 blink::WebInputElement input
= element
.to
<blink::WebInputElement
>();
1297 if (input
.isPasswordField() && !input
.form().isNull()) {
1298 password_form
= CreatePasswordForm(
1299 input
.form(), &nonscript_modified_values_
, &form_predictions_
);
1303 if (!password_form
.get())
1304 password_form
.reset(new PasswordForm());
1306 Send(new AutofillHostMsg_FocusedPasswordFormFound(
1307 routing_id(), *password_form
));
1310 ////////////////////////////////////////////////////////////////////////////////
1311 // PasswordAutofillAgent, private:
1313 PasswordAutofillAgent::PasswordInfo::PasswordInfo()
1314 : backspace_pressed_last(false),
1315 password_was_edited_last(false),
1316 username_was_edited(false) {
1319 bool PasswordAutofillAgent::ShowSuggestionPopup(
1320 const PasswordFormFillData
& fill_data
,
1321 const blink::WebInputElement
& user_input
,
1323 bool show_on_password_field
) {
1324 DCHECK(!user_input
.isNull());
1325 blink::WebFrame
* frame
= user_input
.document().frame();
1329 blink::WebView
* webview
= frame
->view();
1334 FormFieldData field
;
1335 FindFormAndFieldForFormControlElement(user_input
, &form
, &field
);
1337 blink::WebInputElement selected_element
= user_input
;
1338 if (show_on_password_field
&& !selected_element
.isPasswordField()) {
1339 LoginToPasswordInfoMap::const_iterator iter
=
1340 login_to_password_info_
.find(user_input
);
1341 DCHECK(iter
!= login_to_password_info_
.end());
1342 selected_element
= iter
->second
.password_field
;
1344 gfx::Rect
bounding_box(selected_element
.boundsInViewportSpace());
1346 blink::WebInputElement username
;
1347 if (!show_on_password_field
|| !user_input
.isPasswordField()) {
1348 username
= user_input
;
1350 LoginToPasswordInfoKeyMap::const_iterator key_it
=
1351 login_to_password_info_key_
.find(username
);
1352 DCHECK(key_it
!= login_to_password_info_key_
.end());
1355 render_frame()->GetRenderView()->GetWebView()->pageScaleFactor();
1356 gfx::RectF
bounding_box_scaled(bounding_box
.x() * scale
,
1357 bounding_box
.y() * scale
,
1358 bounding_box
.width() * scale
,
1359 bounding_box
.height() * scale
);
1362 options
|= SHOW_ALL
;
1363 if (show_on_password_field
)
1364 options
|= IS_PASSWORD_FIELD
;
1365 base::string16
username_string(
1366 username
.isNull() ? base::string16()
1367 : static_cast<base::string16
>(user_input
.value()));
1368 Send(new AutofillHostMsg_ShowPasswordSuggestions(
1369 routing_id(), key_it
->second
, field
.text_direction
, username_string
,
1370 options
, bounding_box_scaled
));
1372 bool suggestions_present
= false;
1373 if (GetSuggestionsStats(fill_data
, username_string
, show_all
,
1374 &suggestions_present
)) {
1375 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SHOWN
;
1377 return suggestions_present
;
1380 void PasswordAutofillAgent::PerformInlineAutocomplete(
1381 const blink::WebInputElement
& username_input
,
1382 const blink::WebInputElement
& password_input
,
1383 const PasswordFormFillData
& fill_data
) {
1384 DCHECK(!fill_data
.wait_for_username
);
1386 // We need non-const versions of the username and password inputs.
1387 blink::WebInputElement username
= username_input
;
1388 blink::WebInputElement password
= password_input
;
1390 // Don't inline autocomplete if the caret is not at the end.
1391 // TODO(jcivelli): is there a better way to test the caret location?
1392 if (username
.selectionStart() != username
.selectionEnd() ||
1393 username
.selectionEnd() != static_cast<int>(username
.value().length())) {
1397 // Show the popup with the list of available usernames.
1398 ShowSuggestionPopup(fill_data
, username
, false, false);
1400 #if !defined(OS_ANDROID)
1401 // Fill the user and password field with the most relevant match. Android
1402 // only fills in the fields after the user clicks on the suggestion popup.
1403 if (FillUserNameAndPassword(
1407 false /* exact_username_match */,
1408 true /* set selection */,
1409 nonscript_modified_values_
,
1410 base::Bind(&PasswordValueGatekeeper::RegisterElement
,
1411 base::Unretained(&gatekeeper_
)))) {
1412 usernames_usage_
= OTHER_POSSIBLE_USERNAME_SELECTED
;
1417 void PasswordAutofillAgent::FrameClosing() {
1418 for (auto const& iter
: login_to_password_info_
) {
1419 login_to_password_info_key_
.erase(iter
.first
);
1420 password_to_username_
.erase(iter
.second
.password_field
);
1422 login_to_password_info_
.clear();
1423 provisionally_saved_form_
.reset();
1424 nonscript_modified_values_
.clear();
1427 bool PasswordAutofillAgent::FindLoginInfo(const blink::WebNode
& node
,
1428 blink::WebInputElement
* found_input
,
1429 PasswordInfo
** found_password
) {
1430 if (!node
.isElementNode())
1433 blink::WebElement element
= node
.toConst
<blink::WebElement
>();
1434 if (!element
.hasHTMLTagName("input"))
1437 *found_input
= element
.to
<blink::WebInputElement
>();
1438 const blink::WebInputElement
* username_element
; // ignored
1439 return FindPasswordInfoForElement(*found_input
, &username_element
,
1443 void PasswordAutofillAgent::ClearPreview(
1444 blink::WebInputElement
* username
,
1445 blink::WebInputElement
* password
) {
1446 if (!username
->suggestedValue().isEmpty()) {
1447 username
->setSuggestedValue(blink::WebString());
1448 username
->setAutofilled(was_username_autofilled_
);
1449 username
->setSelectionRange(username_selection_start_
,
1450 username
->value().length());
1452 if (!password
->suggestedValue().isEmpty()) {
1453 password
->setSuggestedValue(blink::WebString());
1454 password
->setAutofilled(was_password_autofilled_
);
1458 void PasswordAutofillAgent::ProvisionallySavePassword(
1459 const blink::WebFormElement
& form
,
1460 ProvisionallySaveRestriction restriction
) {
1461 scoped_ptr
<PasswordForm
> password_form(CreatePasswordForm(
1462 form
, &nonscript_modified_values_
, &form_predictions_
));
1463 if (!password_form
|| (restriction
== RESTRICTION_NON_EMPTY_PASSWORD
&&
1464 password_form
->password_value
.empty() &&
1465 password_form
->new_password_value
.empty())) {
1468 provisionally_saved_form_
= password_form
.Pass();
1471 bool PasswordAutofillAgent::ProvisionallySavedPasswordIsValid() {
1472 return provisionally_saved_form_
&&
1473 !provisionally_saved_form_
->username_value
.empty() &&
1474 !(provisionally_saved_form_
->password_value
.empty() &&
1475 provisionally_saved_form_
->new_password_value
.empty());
1478 // LegacyPasswordAutofillAgent -------------------------------------------------
1480 PasswordAutofillAgent::LegacyPasswordAutofillAgent::LegacyPasswordAutofillAgent(
1481 content::RenderView
* render_view
,
1482 PasswordAutofillAgent
* agent
)
1483 : content::RenderViewObserver(render_view
), agent_(agent
) {
1486 PasswordAutofillAgent::LegacyPasswordAutofillAgent::
1487 ~LegacyPasswordAutofillAgent() {
1490 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::OnDestruct() {
1491 // No op. Do not delete |this|.
1494 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStartLoading() {
1495 agent_
->DidStartLoading();
1498 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStopLoading() {
1499 agent_
->DidStopLoading();
1502 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::
1503 DidStartProvisionalLoad(blink::WebLocalFrame
* navigated_frame
) {
1504 agent_
->LegacyDidStartProvisionalLoad(navigated_frame
);
1507 } // namespace autofill