Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / autofill / content / renderer / password_autofill_agent.cc
blob28a5398b82ea6dccf6c5749aa7ff9b313fcc7e3e
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"
7 #include "base/bind.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/autofill_util.h"
22 #include "components/autofill/core/common/form_field_data.h"
23 #include "components/autofill/core/common/password_form.h"
24 #include "components/autofill/core/common/password_form_fill_data.h"
25 #include "content/public/renderer/document_state.h"
26 #include "content/public/renderer/navigation_state.h"
27 #include "content/public/renderer/render_frame.h"
28 #include "content/public/renderer/render_view.h"
29 #include "third_party/WebKit/public/platform/WebVector.h"
30 #include "third_party/WebKit/public/web/WebAutofillClient.h"
31 #include "third_party/WebKit/public/web/WebDocument.h"
32 #include "third_party/WebKit/public/web/WebElement.h"
33 #include "third_party/WebKit/public/web/WebFormElement.h"
34 #include "third_party/WebKit/public/web/WebInputEvent.h"
35 #include "third_party/WebKit/public/web/WebLocalFrame.h"
36 #include "third_party/WebKit/public/web/WebNode.h"
37 #include "third_party/WebKit/public/web/WebNodeList.h"
38 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
39 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
40 #include "third_party/WebKit/public/web/WebView.h"
41 #include "ui/base/page_transition_types.h"
42 #include "ui/events/keycodes/keyboard_codes.h"
43 #include "url/gurl.h"
45 namespace autofill {
46 namespace {
48 // The size above which we stop triggering autocomplete.
49 static const size_t kMaximumTextSizeForAutocomplete = 1000;
51 // Experiment information
52 const char kFillOnAccountSelectFieldTrialName[] = "FillOnAccountSelect";
53 const char kFillOnAccountSelectFieldTrialEnabledWithHighlightGroup[] =
54 "EnableWithHighlight";
55 const char kFillOnAccountSelectFieldTrialEnabledWithNoHighlightGroup[] =
56 "EnableWithNoHighlight";
58 // Maps element names to the actual elements to simplify form filling.
59 typedef std::map<base::string16, blink::WebInputElement> FormInputElementMap;
61 // Use the shorter name when referencing SavePasswordProgressLogger::StringID
62 // values to spare line breaks. The code provides enough context for that
63 // already.
64 typedef SavePasswordProgressLogger Logger;
66 typedef std::vector<FormInputElementMap> FormElementsList;
68 bool FillDataContainsFillableUsername(const PasswordFormFillData& fill_data) {
69 return !fill_data.username_field.name.empty() &&
70 (!fill_data.additional_logins.empty() ||
71 !fill_data.username_field.value.empty());
74 // Returns true if |control_elements| contains an element named |name| and is
75 // visible.
76 bool IsNamedElementVisible(
77 const std::vector<blink::WebFormControlElement>& control_elements,
78 const base::string16& name) {
79 for (size_t i = 0; i < control_elements.size(); ++i) {
80 if (control_elements[i].nameForAutofill() == name) {
81 return IsWebNodeVisible(control_elements[i]);
84 return false;
87 // Utility function to find the unique entry of |control_elements| for the
88 // specified input |field|. On successful find, adds it to |result| and returns
89 // |true|. Otherwise clears the references from each |HTMLInputElement| from
90 // |result| and returns |false|.
91 bool FindFormInputElement(
92 const std::vector<blink::WebFormControlElement>& control_elements,
93 const FormFieldData& field,
94 FormInputElementMap* result) {
95 // Match the first input element, if any.
96 // If more than one match is made, then we have ambiguity (due to misuse
97 // of "name" attribute) so is it considered not found.
98 bool found_input = false;
99 for (size_t i = 0; i < control_elements.size(); ++i) {
100 if (control_elements[i].nameForAutofill() != field.name)
101 continue;
103 if (!control_elements[i].hasHTMLTagName("input"))
104 continue;
106 // Check for a non-unique match.
107 if (found_input) {
108 found_input = false;
109 break;
112 // Only fill saved passwords into password fields and usernames into
113 // text fields.
114 const blink::WebInputElement input_element =
115 control_elements[i].toConst<blink::WebInputElement>();
116 if (input_element.isPasswordField() !=
117 (field.form_control_type == "password"))
118 continue;
120 (*result)[field.name] = input_element;
121 found_input = true;
124 // A required element was not found. This is not the right form.
125 // Make sure no input elements from a partially matched form in this
126 // iteration remain in the result set.
127 // Note: clear will remove a reference from each InputElement.
128 if (!found_input) {
129 result->clear();
130 return false;
133 return true;
136 bool ShouldFillOnAccountSelect() {
137 std::string group_name =
138 base::FieldTrialList::FindFullName(kFillOnAccountSelectFieldTrialName);
140 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
141 switches::kDisableFillOnAccountSelect)) {
142 return false;
145 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
146 switches::kEnableFillOnAccountSelect) ||
147 base::CommandLine::ForCurrentProcess()->HasSwitch(
148 switches::kEnableFillOnAccountSelectNoHighlighting)) {
149 return true;
152 return group_name ==
153 kFillOnAccountSelectFieldTrialEnabledWithHighlightGroup ||
154 group_name ==
155 kFillOnAccountSelectFieldTrialEnabledWithNoHighlightGroup;
158 bool ShouldHighlightFields() {
159 std::string group_name =
160 base::FieldTrialList::FindFullName(kFillOnAccountSelectFieldTrialName);
161 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
162 switches::kDisableFillOnAccountSelect) ||
163 base::CommandLine::ForCurrentProcess()->HasSwitch(
164 switches::kEnableFillOnAccountSelect)) {
165 return true;
168 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
169 switches::kEnableFillOnAccountSelectNoHighlighting)) {
170 return false;
173 return group_name !=
174 kFillOnAccountSelectFieldTrialEnabledWithNoHighlightGroup;
177 // Helper to search through |control_elements| for the specified input elements
178 // in |data|, and add results to |result|.
179 bool FindFormInputElements(
180 const std::vector<blink::WebFormControlElement>& control_elements,
181 const PasswordFormFillData& data,
182 FormInputElementMap* result) {
183 return FindFormInputElement(control_elements, data.password_field, result) &&
184 (!FillDataContainsFillableUsername(data) ||
185 FindFormInputElement(control_elements, data.username_field, result));
188 // Helper to locate form elements identified by |data|.
189 void FindFormElements(content::RenderFrame* render_frame,
190 const PasswordFormFillData& data,
191 FormElementsList* results) {
192 DCHECK(results);
194 blink::WebDocument doc = render_frame->GetWebFrame()->document();
195 if (!doc.isHTMLDocument())
196 return;
198 if (data.origin != GetCanonicalOriginForDocument(doc))
199 return;
201 blink::WebVector<blink::WebFormElement> forms;
202 doc.forms(forms);
204 for (size_t i = 0; i < forms.size(); ++i) {
205 blink::WebFormElement fe = forms[i];
207 // Action URL must match.
208 if (data.action != GetCanonicalActionForForm(fe))
209 continue;
211 std::vector<blink::WebFormControlElement> control_elements =
212 ExtractAutofillableElementsInForm(fe);
213 FormInputElementMap cur_map;
214 if (FindFormInputElements(control_elements, data, &cur_map))
215 results->push_back(cur_map);
217 // If the element to be filled are not in a <form> element, the "action" and
218 // origin should be the same.
219 if (data.action != data.origin)
220 return;
222 std::vector<blink::WebFormControlElement> control_elements =
223 GetUnownedAutofillableFormFieldElements(doc.all(), nullptr);
224 FormInputElementMap unowned_elements_map;
225 if (FindFormInputElements(control_elements, data, &unowned_elements_map))
226 results->push_back(unowned_elements_map);
229 bool IsElementEditable(const blink::WebInputElement& element) {
230 return element.isEnabled() && !element.isReadOnly();
233 bool DoUsernamesMatch(const base::string16& username1,
234 const base::string16& username2,
235 bool exact_match) {
236 if (exact_match)
237 return username1 == username2;
238 return FieldIsSuggestionSubstringStartingOnTokenBoundary(username1, username2,
239 true);
242 // Returns |true| if the given element is editable. Otherwise, returns |false|.
243 bool IsElementAutocompletable(const blink::WebInputElement& element) {
244 return IsElementEditable(element);
247 // Return true if either password_value or new_password_value is not empty and
248 // not default.
249 bool FormContainsNonDefaultPasswordValue(const PasswordForm& password_form) {
250 return (!password_form.password_value.empty() &&
251 !password_form.password_value_is_default) ||
252 (!password_form.new_password_value.empty() &&
253 !password_form.new_password_value_is_default);
256 // Log a message including the name, method and action of |form|.
257 void LogHTMLForm(SavePasswordProgressLogger* logger,
258 SavePasswordProgressLogger::StringID message_id,
259 const blink::WebFormElement& form) {
260 logger->LogHTMLForm(message_id,
261 form.name().utf8(),
262 GURL(form.action().utf8()));
266 // Returns true if there are any suggestions to be derived from |fill_data|.
267 // Unless |show_all| is true, only considers suggestions with usernames having
268 // |current_username| as a prefix.
269 bool CanShowSuggestion(const PasswordFormFillData& fill_data,
270 const base::string16& current_username,
271 bool show_all) {
272 base::string16 current_username_lower = base::i18n::ToLower(current_username);
273 for (const auto& usernames : fill_data.other_possible_usernames) {
274 for (size_t i = 0; i < usernames.second.size(); ++i) {
275 if (show_all ||
276 base::StartsWith(
277 base::i18n::ToLower(base::string16(usernames.second[i])),
278 current_username_lower, base::CompareCase::SENSITIVE)) {
279 return true;
284 if (show_all ||
285 base::StartsWith(base::i18n::ToLower(fill_data.username_field.value),
286 current_username_lower, base::CompareCase::SENSITIVE)) {
287 return true;
290 for (const auto& login : fill_data.additional_logins) {
291 if (show_all ||
292 base::StartsWith(base::i18n::ToLower(login.first),
293 current_username_lower,
294 base::CompareCase::SENSITIVE)) {
295 return true;
299 return false;
302 // Returns true if there exists a credential suggestion whose username field is
303 // an exact match to the current username (not just a prefix).
304 bool HasExactMatchSuggestion(const PasswordFormFillData& fill_data,
305 const base::string16& current_username) {
306 if (fill_data.username_field.value == current_username)
307 return true;
309 for (const auto& usernames : fill_data.other_possible_usernames) {
310 for (const auto& username_string : usernames.second) {
311 if (username_string == current_username)
312 return true;
316 for (const auto& login : fill_data.additional_logins) {
317 if (login.first == current_username)
318 return true;
321 return false;
324 // This function attempts to fill |username_element| and |password_element|
325 // with values from |fill_data|. The |password_element| will only have the
326 // suggestedValue set, and will be registered for copying that to the real
327 // value through |registration_callback|. If a match is found, return true and
328 // |nonscript_modified_values| will be modified with the autofilled credentials.
329 bool FillUserNameAndPassword(
330 blink::WebInputElement* username_element,
331 blink::WebInputElement* password_element,
332 const PasswordFormFillData& fill_data,
333 bool exact_username_match,
334 bool set_selection,
335 std::map<const blink::WebInputElement, blink::WebString>*
336 nonscript_modified_values,
337 base::Callback<void(blink::WebInputElement*)> registration_callback) {
338 // Don't fill username if password can't be set.
339 if (!IsElementAutocompletable(*password_element))
340 return false;
342 base::string16 current_username;
343 if (!username_element->isNull()) {
344 current_username = username_element->value();
347 // username and password will contain the match found if any.
348 base::string16 username;
349 base::string16 password;
351 // Look for any suitable matches to current field text.
352 if (DoUsernamesMatch(fill_data.username_field.value, current_username,
353 exact_username_match)) {
354 username = fill_data.username_field.value;
355 password = fill_data.password_field.value;
356 } else {
357 // Scan additional logins for a match.
358 PasswordFormFillData::LoginCollection::const_iterator iter;
359 for (iter = fill_data.additional_logins.begin();
360 iter != fill_data.additional_logins.end();
361 ++iter) {
362 if (DoUsernamesMatch(
363 iter->first, current_username, exact_username_match)) {
364 username = iter->first;
365 password = iter->second.password;
366 break;
370 // Check possible usernames.
371 if (username.empty() && password.empty()) {
372 for (PasswordFormFillData::UsernamesCollection::const_iterator iter =
373 fill_data.other_possible_usernames.begin();
374 iter != fill_data.other_possible_usernames.end();
375 ++iter) {
376 for (size_t i = 0; i < iter->second.size(); ++i) {
377 if (DoUsernamesMatch(
378 iter->second[i], current_username, exact_username_match)) {
379 username = iter->second[i];
380 password = iter->first.password;
381 break;
384 if (!username.empty() && !password.empty())
385 break;
389 if (password.empty())
390 return false;
392 // TODO(tkent): Check maxlength and pattern for both username and password
393 // fields.
395 // Input matches the username, fill in required values.
396 if (!username_element->isNull() &&
397 IsElementAutocompletable(*username_element)) {
398 // TODO(vabr): Why not setSuggestedValue? http://crbug.com/507714
399 username_element->setValue(username, true);
400 (*nonscript_modified_values)[*username_element] = username;
401 username_element->setAutofilled(true);
402 if (set_selection)
403 PreviewSuggestion(username, current_username, username_element);
404 } else if (current_username != username) {
405 // If the username can't be filled and it doesn't match a saved password
406 // as is, don't autofill a password.
407 return false;
410 // Wait to fill in the password until a user gesture occurs. This is to make
411 // sure that we do not fill in the DOM with a password until we believe the
412 // user is intentionally interacting with the page.
413 password_element->setSuggestedValue(password);
414 (*nonscript_modified_values)[*password_element] = password;
415 registration_callback.Run(password_element);
417 password_element->setAutofilled(true);
418 return true;
421 // Attempts to fill |username_element| and |password_element| with the
422 // |fill_data|. Will use the data corresponding to the preferred username,
423 // unless the |username_element| already has a value set. In that case,
424 // attempts to fill the password matching the already filled username, if
425 // such a password exists. The |password_element| will have the
426 // |suggestedValue| set, and |suggestedValue| will be registered for copying to
427 // the real value through |registration_callback|. Returns true if the password
428 // is filled.
429 bool FillFormOnPasswordReceived(
430 const PasswordFormFillData& fill_data,
431 blink::WebInputElement username_element,
432 blink::WebInputElement password_element,
433 std::map<const blink::WebInputElement, blink::WebString>*
434 nonscript_modified_values,
435 base::Callback<void(blink::WebInputElement*)> registration_callback) {
436 // Do not fill if the password field is in a chain of iframes not having
437 // identical origin.
438 blink::WebFrame* cur_frame = password_element.document().frame();
439 blink::WebString bottom_frame_origin =
440 cur_frame->securityOrigin().toString();
442 DCHECK(cur_frame);
444 while (cur_frame->parent()) {
445 cur_frame = cur_frame->parent();
446 if (!bottom_frame_origin.equals(cur_frame->securityOrigin().toString()))
447 return false;
450 // If we can't modify the password, don't try to set the username
451 if (!IsElementAutocompletable(password_element))
452 return false;
454 bool form_contains_fillable_username_field =
455 FillDataContainsFillableUsername(fill_data);
456 // If the form contains an autocompletable username field, try to set the
457 // username to the preferred name, but only if:
458 // (a) The fill-on-account-select flag is not set, and
459 // (b) The username element isn't prefilled
461 // If (a) is false, then just mark the username element as autofilled if the
462 // user is not in the "no highlighting" group and return so the fill step is
463 // skipped.
465 // If there is no autocompletable username field, and (a) is false, then the
466 // username element cannot be autofilled, but the user should still be able to
467 // select to fill the password element, so the password element must be marked
468 // as autofilled and the fill step should also be skipped if the user is not
469 // in the "no highlighting" group.
471 // In all other cases, do nothing.
472 bool form_has_fillable_username = form_contains_fillable_username_field &&
473 IsElementAutocompletable(username_element);
475 if (ShouldFillOnAccountSelect()) {
476 if (!ShouldHighlightFields()) {
477 return false;
480 if (form_has_fillable_username) {
481 username_element.setAutofilled(true);
482 } else if (username_element.isNull() ||
483 HasExactMatchSuggestion(fill_data, username_element.value())) {
484 password_element.setAutofilled(true);
486 return false;
489 if (form_has_fillable_username && username_element.value().isEmpty()) {
490 // TODO(tkent): Check maxlength and pattern.
491 username_element.setValue(fill_data.username_field.value, true);
494 // Fill if we have an exact match for the username. Note that this sets
495 // username to autofilled.
496 return FillUserNameAndPassword(&username_element,
497 &password_element,
498 fill_data,
499 true /* exact_username_match */,
500 false /* set_selection */,
501 nonscript_modified_values,
502 registration_callback);
505 // Takes a |map| with pointers as keys and linked_ptr as values, and returns
506 // true if |key| is not NULL and |map| contains a non-NULL entry for |key|.
507 // Makes sure not to create an entry as a side effect of using the operator [].
508 template <class Key, class Value>
509 bool ContainsNonNullEntryForNonNullKey(
510 const std::map<Key*, linked_ptr<Value>>& map,
511 Key* key) {
512 if (!key)
513 return false;
514 auto it = map.find(key);
515 return it != map.end() && it->second.get();
519 // Helper function to check if there exist any form on |frame| where its action
520 // equals |action| or input elements outside a <form> tag if |action| equals
521 // the current url. Return true if so.
522 bool IsFormVisible(
523 blink::WebFrame* frame,
524 const GURL& action,
525 const FormsPredictionsMap& form_predictions) {
526 blink::WebVector<blink::WebFormElement> forms;
527 frame->document().forms(forms);
529 for (size_t i = 0; i < forms.size(); ++i) {
530 const blink::WebFormElement& form = forms[i];
531 if (!IsWebNodeVisible(form))
532 continue;
534 if (action == GetCanonicalActionForForm(form))
535 return true; // Form still exists
538 scoped_ptr<PasswordForm> unowned_password_form(
539 CreatePasswordFormFromUnownedInputElements(
540 *frame, nullptr, &form_predictions));
541 std::vector<blink::WebFormControlElement> control_elements =
542 GetUnownedAutofillableFormFieldElements(frame->document().all(), nullptr);
543 if (unowned_password_form &&
544 action == unowned_password_form->action &&
545 IsNamedElementVisible(control_elements,
546 unowned_password_form->username_element) &&
547 IsNamedElementVisible(control_elements,
548 unowned_password_form->password_element)) {
549 return true;
552 return false;
555 } // namespace
557 ////////////////////////////////////////////////////////////////////////////////
558 // PasswordAutofillAgent, public:
560 PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame)
561 : content::RenderFrameObserver(render_frame),
562 legacy_(render_frame->GetRenderView(), this),
563 logging_state_active_(false),
564 was_username_autofilled_(false),
565 was_password_autofilled_(false),
566 did_stop_loading_(false),
567 weak_ptr_factory_(this) {
568 Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id()));
571 PasswordAutofillAgent::~PasswordAutofillAgent() {
574 PasswordAutofillAgent::PasswordValueGatekeeper::PasswordValueGatekeeper()
575 : was_user_gesture_seen_(false) {
578 PasswordAutofillAgent::PasswordValueGatekeeper::~PasswordValueGatekeeper() {
581 void PasswordAutofillAgent::PasswordValueGatekeeper::RegisterElement(
582 blink::WebInputElement* element) {
583 if (was_user_gesture_seen_)
584 ShowValue(element);
585 else
586 elements_.push_back(*element);
589 void PasswordAutofillAgent::PasswordValueGatekeeper::OnUserGesture() {
590 was_user_gesture_seen_ = true;
592 for (std::vector<blink::WebInputElement>::iterator it = elements_.begin();
593 it != elements_.end();
594 ++it) {
595 ShowValue(&(*it));
598 elements_.clear();
601 void PasswordAutofillAgent::PasswordValueGatekeeper::Reset() {
602 was_user_gesture_seen_ = false;
603 elements_.clear();
606 void PasswordAutofillAgent::PasswordValueGatekeeper::ShowValue(
607 blink::WebInputElement* element) {
608 if (!element->isNull() && !element->suggestedValue().isEmpty())
609 element->setValue(element->suggestedValue(), true);
612 bool PasswordAutofillAgent::TextFieldDidEndEditing(
613 const blink::WebInputElement& element) {
614 LoginToPasswordInfoMap::const_iterator iter =
615 login_to_password_info_.find(element);
616 if (iter == login_to_password_info_.end())
617 return false;
619 const PasswordInfo& password_info = iter->second;
620 // Don't let autofill overwrite an explicit change made by the user.
621 if (password_info.password_was_edited_last)
622 return false;
624 const PasswordFormFillData& fill_data = password_info.fill_data;
626 // If wait_for_username is false, we should have filled when the text changed.
627 if (!fill_data.wait_for_username)
628 return false;
630 blink::WebInputElement password = password_info.password_field;
631 if (!IsElementEditable(password))
632 return false;
634 blink::WebInputElement username = element; // We need a non-const.
636 // Do not set selection when ending an editing session, otherwise it can
637 // mess with focus.
638 FillUserNameAndPassword(
639 &username, &password, fill_data, true, false,
640 &nonscript_modified_values_,
641 base::Bind(&PasswordValueGatekeeper::RegisterElement,
642 base::Unretained(&gatekeeper_)));
643 return true;
646 bool PasswordAutofillAgent::TextDidChangeInTextField(
647 const blink::WebInputElement& element) {
648 // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
649 blink::WebInputElement mutable_element = element; // We need a non-const.
650 mutable_element.setAutofilled(false);
652 LoginToPasswordInfoMap::iterator iter = login_to_password_info_.find(element);
653 if (iter != login_to_password_info_.end()) {
654 iter->second.password_was_edited_last = false;
655 // If wait_for_username is true we will fill when the username loses focus.
656 if (iter->second.fill_data.wait_for_username)
657 return false;
660 // Show the popup with the list of available usernames.
661 return ShowSuggestions(element, false, false);
664 void PasswordAutofillAgent::UpdateStateForTextChange(
665 const blink::WebInputElement& element) {
666 // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
667 blink::WebInputElement mutable_element = element; // We need a non-const.
669 if (element.isTextField())
670 nonscript_modified_values_[element] = element.value();
672 LoginToPasswordInfoMap::iterator password_info_iter =
673 login_to_password_info_.find(element);
674 if (password_info_iter != login_to_password_info_.end()) {
675 password_info_iter->second.username_was_edited = true;
678 DCHECK_EQ(element.document().frame(), render_frame()->GetWebFrame());
680 if (element.isPasswordField()) {
681 // Some login forms have event handlers that put a hash of the password into
682 // a hidden field and then clear the password (http://crbug.com/28910,
683 // http://crbug.com/391693). This method gets called before any of those
684 // handlers run, so save away a copy of the password in case it gets lost.
685 // To honor the user having explicitly cleared the password, even an empty
686 // password will be saved here.
687 scoped_ptr<PasswordForm> password_form;
688 if (element.form().isNull()) {
689 password_form = CreatePasswordFormFromUnownedInputElements(
690 *element.document().frame(), &nonscript_modified_values_,
691 &form_predictions_);
692 } else {
693 password_form = CreatePasswordFormFromWebForm(
694 element.form(), &nonscript_modified_values_, &form_predictions_);
696 ProvisionallySavePassword(password_form.Pass(), RESTRICTION_NONE);
698 PasswordToLoginMap::iterator iter = password_to_username_.find(element);
699 if (iter != password_to_username_.end()) {
700 login_to_password_info_[iter->second].password_was_edited_last = true;
701 // Note that the suggested value of |mutable_element| was reset when its
702 // value changed.
703 mutable_element.setAutofilled(false);
708 bool PasswordAutofillAgent::FillSuggestion(
709 const blink::WebNode& node,
710 const blink::WebString& username,
711 const blink::WebString& password) {
712 // The element in context of the suggestion popup.
713 blink::WebInputElement filled_element;
714 PasswordInfo* password_info;
716 if (!FindLoginInfo(node, &filled_element, &password_info) ||
717 !IsElementAutocompletable(filled_element) ||
718 !IsElementAutocompletable(password_info->password_field)) {
719 return false;
722 password_info->password_was_edited_last = false;
723 // Note that in cases where filled_element is the password element, the value
724 // gets overwritten with the correct one below.
725 filled_element.setValue(username, true);
726 filled_element.setAutofilled(true);
728 password_info->password_field.setValue(password, true);
729 password_info->password_field.setAutofilled(true);
731 filled_element.setSelectionRange(filled_element.value().length(),
732 filled_element.value().length());
734 return true;
737 bool PasswordAutofillAgent::PreviewSuggestion(
738 const blink::WebNode& node,
739 const blink::WebString& username,
740 const blink::WebString& password) {
741 blink::WebInputElement username_element;
742 PasswordInfo* password_info;
744 if (!FindLoginInfo(node, &username_element, &password_info) ||
745 !IsElementAutocompletable(username_element) ||
746 !IsElementAutocompletable(password_info->password_field)) {
747 return false;
750 if (username_query_prefix_.empty())
751 username_query_prefix_ = username_element.value();
753 was_username_autofilled_ = username_element.isAutofilled();
754 username_element.setSuggestedValue(username);
755 username_element.setAutofilled(true);
756 ::autofill::PreviewSuggestion(username_element.suggestedValue(),
757 username_query_prefix_, &username_element);
758 was_password_autofilled_ = password_info->password_field.isAutofilled();
759 password_info->password_field.setSuggestedValue(password);
760 password_info->password_field.setAutofilled(true);
762 return true;
765 bool PasswordAutofillAgent::DidClearAutofillSelection(
766 const blink::WebNode& node) {
767 blink::WebInputElement username_element;
768 PasswordInfo* password_info;
769 if (!FindLoginInfo(node, &username_element, &password_info))
770 return false;
772 ClearPreview(&username_element, &password_info->password_field);
773 return true;
776 bool PasswordAutofillAgent::FindPasswordInfoForElement(
777 const blink::WebInputElement& element,
778 const blink::WebInputElement** username_element,
779 PasswordInfo** password_info) {
780 DCHECK(username_element && password_info);
781 if (!element.isPasswordField()) {
782 *username_element = &element;
783 } else {
784 PasswordToLoginMap::const_iterator password_iter =
785 password_to_username_.find(element);
786 if (password_iter == password_to_username_.end())
787 return false;
788 *username_element = &password_iter->second;
791 LoginToPasswordInfoMap::iterator iter =
792 login_to_password_info_.find(**username_element);
794 if (iter == login_to_password_info_.end())
795 return false;
797 *password_info = &iter->second;
798 return true;
801 bool PasswordAutofillAgent::ShowSuggestions(
802 const blink::WebInputElement& element,
803 bool show_all,
804 bool generation_popup_showing) {
805 const blink::WebInputElement* username_element;
806 PasswordInfo* password_info;
807 if (!FindPasswordInfoForElement(element, &username_element, &password_info))
808 return false;
810 // If autocomplete='off' is set on the form elements, no suggestion dialog
811 // should be shown. However, return |true| to indicate that this is a known
812 // password form and that the request to show suggestions has been handled (as
813 // a no-op).
814 if (!element.isTextField() || !IsElementAutocompletable(element) ||
815 !IsElementAutocompletable(password_info->password_field))
816 return true;
818 if (element.nameForAutofill().isEmpty())
819 return false; // If the field has no name, then we won't have values.
821 // Don't attempt to autofill with values that are too large.
822 if (element.value().length() > kMaximumTextSizeForAutocomplete)
823 return false;
825 bool username_is_available =
826 !username_element->isNull() && IsElementEditable(*username_element);
827 // If the element is a password field, a popup should only be shown if there
828 // is no username or the corresponding username element is not editable since
829 // it is only in that case that the username element does not have a
830 // suggestions popup.
831 if (element.isPasswordField() && username_is_available &&
832 (!password_info->fill_data.is_possible_change_password_form ||
833 password_info->username_was_edited))
834 return true;
836 UMA_HISTOGRAM_BOOLEAN(
837 "PasswordManager.AutocompletePopupSuppressedByGeneration",
838 generation_popup_showing);
840 if (generation_popup_showing)
841 return false;
843 // Chrome should never show more than one account for a password element since
844 // this implies that the username element cannot be modified. Thus even if
845 // |show_all| is true, check if the element in question is a password element
846 // for the call to ShowSuggestionPopup.
847 return ShowSuggestionPopup(
848 password_info->fill_data,
849 username_element->isNull() ? element : *username_element,
850 show_all && !element.isPasswordField(), element.isPasswordField());
853 bool PasswordAutofillAgent::OriginCanAccessPasswordManager(
854 const blink::WebSecurityOrigin& origin) {
855 return origin.canAccessPasswordManager();
858 void PasswordAutofillAgent::OnDynamicFormsSeen() {
859 SendPasswordForms(false /* only_visible */);
862 void PasswordAutofillAgent::AJAXSucceeded() {
863 OnSamePageNavigationCompleted();
866 void PasswordAutofillAgent::OnSamePageNavigationCompleted() {
867 if (!ProvisionallySavedPasswordIsValid())
868 return;
870 // Prompt to save only if the form is now gone, either invisible or
871 // removed from the DOM.
872 blink::WebFrame* frame = render_frame()->GetWebFrame();
873 if (IsFormVisible(frame, provisionally_saved_form_->action,
874 form_predictions_))
875 return;
877 Send(new AutofillHostMsg_InPageNavigation(routing_id(),
878 *provisionally_saved_form_));
879 provisionally_saved_form_.reset();
882 void PasswordAutofillAgent::FirstUserGestureObserved() {
883 gatekeeper_.OnUserGesture();
886 void PasswordAutofillAgent::SendPasswordForms(bool only_visible) {
887 scoped_ptr<RendererSavePasswordProgressLogger> logger;
888 if (logging_state_active_) {
889 logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
890 logger->LogMessage(Logger::STRING_SEND_PASSWORD_FORMS_METHOD);
891 logger->LogBoolean(Logger::STRING_ONLY_VISIBLE, only_visible);
894 blink::WebFrame* frame = render_frame()->GetWebFrame();
895 // Make sure that this security origin is allowed to use password manager.
896 blink::WebSecurityOrigin origin = frame->document().securityOrigin();
897 if (logger) {
898 logger->LogURL(Logger::STRING_SECURITY_ORIGIN,
899 GURL(origin.toString().utf8()));
901 if (!OriginCanAccessPasswordManager(origin)) {
902 if (logger) {
903 logger->LogMessage(Logger::STRING_SECURITY_ORIGIN_FAILURE);
905 return;
908 // Checks whether the webpage is a redirect page or an empty page.
909 if (IsWebpageEmpty(frame)) {
910 if (logger) {
911 logger->LogMessage(Logger::STRING_WEBPAGE_EMPTY);
913 return;
916 blink::WebVector<blink::WebFormElement> forms;
917 frame->document().forms(forms);
918 if (logger)
919 logger->LogNumber(Logger::STRING_NUMBER_OF_ALL_FORMS, forms.size());
921 std::vector<PasswordForm> password_forms;
922 for (size_t i = 0; i < forms.size(); ++i) {
923 const blink::WebFormElement& form = forms[i];
924 if (only_visible) {
925 bool is_form_visible = IsWebNodeVisible(form);
926 if (logger) {
927 LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE, form);
928 logger->LogBoolean(Logger::STRING_FORM_IS_VISIBLE, is_form_visible);
931 // If requested, ignore non-rendered forms, e.g., those styled with
932 // display:none.
933 if (!is_form_visible)
934 continue;
937 scoped_ptr<PasswordForm> password_form(
938 CreatePasswordFormFromWebForm(form, nullptr, &form_predictions_));
939 if (password_form) {
940 if (logger) {
941 logger->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD,
942 *password_form);
944 password_forms.push_back(*password_form);
948 // See if there are any unattached input elements that could be used for
949 // password submission.
950 scoped_ptr<PasswordForm> password_form(
951 CreatePasswordFormFromUnownedInputElements(*frame,
952 nullptr,
953 &form_predictions_));
954 if (password_form) {
955 if (logger) {
956 logger->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD,
957 *password_form);
959 password_forms.push_back(*password_form);
962 if (password_forms.empty() && !only_visible) {
963 // We need to send the PasswordFormsRendered message regardless of whether
964 // there are any forms visible, as this is also the code path that triggers
965 // showing the infobar.
966 return;
969 if (only_visible) {
970 Send(new AutofillHostMsg_PasswordFormsRendered(routing_id(),
971 password_forms,
972 did_stop_loading_));
973 } else {
974 Send(new AutofillHostMsg_PasswordFormsParsed(routing_id(), password_forms));
978 bool PasswordAutofillAgent::OnMessageReceived(const IPC::Message& message) {
979 bool handled = true;
980 IPC_BEGIN_MESSAGE_MAP(PasswordAutofillAgent, message)
981 IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordForm, OnFillPasswordForm)
982 IPC_MESSAGE_HANDLER(AutofillMsg_SetLoggingState, OnSetLoggingState)
983 IPC_MESSAGE_HANDLER(AutofillMsg_AutofillUsernameAndPasswordDataReceived,
984 OnAutofillUsernameAndPasswordDataReceived)
985 IPC_MESSAGE_HANDLER(AutofillMsg_FindFocusedPasswordForm,
986 OnFindFocusedPasswordForm)
987 IPC_MESSAGE_UNHANDLED(handled = false)
988 IPC_END_MESSAGE_MAP()
989 return handled;
992 void PasswordAutofillAgent::DidFinishDocumentLoad() {
993 // The |frame| contents have been parsed, but not yet rendered. Let the
994 // PasswordManager know that forms are loaded, even though we can't yet tell
995 // whether they're visible.
996 SendPasswordForms(false);
999 void PasswordAutofillAgent::DidFinishLoad() {
1000 // The |frame| contents have been rendered. Let the PasswordManager know
1001 // which of the loaded frames are actually visible to the user. This also
1002 // triggers the "Save password?" infobar if the user just submitted a password
1003 // form.
1004 SendPasswordForms(true);
1007 void PasswordAutofillAgent::FrameWillClose() {
1008 FrameClosing();
1011 void PasswordAutofillAgent::DidCommitProvisionalLoad(
1012 bool is_new_navigation, bool is_same_page_navigation) {
1013 blink::WebFrame* frame = render_frame()->GetWebFrame();
1014 // TODO(dvadym): check if we need to check if it is main frame navigation
1015 // http://crbug.com/443155
1016 if (frame->parent())
1017 return; // Not a top-level navigation.
1019 if (is_same_page_navigation) {
1020 OnSamePageNavigationCompleted();
1024 void PasswordAutofillAgent::DidStartLoading() {
1025 did_stop_loading_ = false;
1028 void PasswordAutofillAgent::DidStopLoading() {
1029 did_stop_loading_ = true;
1032 void PasswordAutofillAgent::FrameDetached() {
1033 // If a sub frame has been destroyed while the user was entering information
1034 // into a password form, try to save the data. See https://crbug.com/450806
1035 // for examples of sites that perform login using this technique.
1036 if (render_frame()->GetWebFrame()->parent() &&
1037 ProvisionallySavedPasswordIsValid()) {
1038 Send(new AutofillHostMsg_InPageNavigation(routing_id(),
1039 *provisionally_saved_form_));
1041 FrameClosing();
1044 void PasswordAutofillAgent::WillSendSubmitEvent(
1045 const blink::WebFormElement& form) {
1046 // Forms submitted via XHR are not seen by WillSubmitForm if the default
1047 // onsubmit handler is overridden. Such submission first gets detected in
1048 // DidStartProvisionalLoad, which no longer knows about the particular form,
1049 // and uses the candidate stored in |provisionally_saved_form_|.
1051 // User-typed password will get stored to |provisionally_saved_form_| in
1052 // TextDidChangeInTextField. Autofilled or JavaScript-copied passwords need to
1053 // be saved here.
1055 // Only non-empty passwords are saved here. Empty passwords were likely
1056 // cleared by some scripts (http://crbug.com/28910, http://crbug.com/391693).
1057 // Had the user cleared the password, |provisionally_saved_form_| would
1058 // already have been updated in TextDidChangeInTextField.
1059 scoped_ptr<PasswordForm> password_form = CreatePasswordFormFromWebForm(
1060 form, &nonscript_modified_values_, &form_predictions_);
1061 ProvisionallySavePassword(password_form.Pass(),
1062 RESTRICTION_NON_EMPTY_PASSWORD);
1065 void PasswordAutofillAgent::WillSubmitForm(const blink::WebFormElement& form) {
1066 scoped_ptr<RendererSavePasswordProgressLogger> logger;
1067 if (logging_state_active_) {
1068 logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
1069 logger->LogMessage(Logger::STRING_WILL_SUBMIT_FORM_METHOD);
1070 LogHTMLForm(logger.get(), Logger::STRING_HTML_FORM_FOR_SUBMIT, form);
1073 scoped_ptr<PasswordForm> submitted_form =
1074 CreatePasswordFormFromWebForm(form, &nonscript_modified_values_,
1075 &form_predictions_);
1077 // If there is a provisionally saved password, copy over the previous
1078 // password value so we get the user's typed password, not the value that
1079 // may have been transformed for submit.
1080 // TODO(gcasto): Do we need to have this action equality check? Is it trying
1081 // to prevent accidentally copying over passwords from a different form?
1082 if (submitted_form) {
1083 if (logger) {
1084 logger->LogPasswordForm(Logger::STRING_CREATED_PASSWORD_FORM,
1085 *submitted_form);
1087 if (provisionally_saved_form_ &&
1088 submitted_form->action == provisionally_saved_form_->action) {
1089 if (logger)
1090 logger->LogMessage(Logger::STRING_SUBMITTED_PASSWORD_REPLACED);
1091 submitted_form->password_value =
1092 provisionally_saved_form_->password_value;
1093 submitted_form->new_password_value =
1094 provisionally_saved_form_->new_password_value;
1095 submitted_form->username_value =
1096 provisionally_saved_form_->username_value;
1099 // Some observers depend on sending this information now instead of when
1100 // the frame starts loading. If there are redirects that cause a new
1101 // RenderView to be instantiated (such as redirects to the WebStore)
1102 // we will never get to finish the load.
1103 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
1104 *submitted_form));
1105 provisionally_saved_form_.reset();
1106 } else if (logger) {
1107 logger->LogMessage(Logger::STRING_FORM_IS_NOT_PASSWORD);
1111 void PasswordAutofillAgent::LegacyDidStartProvisionalLoad(
1112 blink::WebLocalFrame* navigated_frame) {
1113 scoped_ptr<RendererSavePasswordProgressLogger> logger;
1114 if (logging_state_active_) {
1115 logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
1116 logger->LogMessage(Logger::STRING_DID_START_PROVISIONAL_LOAD_METHOD);
1119 if (navigated_frame->parent()) {
1120 if (logger)
1121 logger->LogMessage(Logger::STRING_FRAME_NOT_MAIN_FRAME);
1122 return;
1125 // Bug fix for crbug.com/368690. isProcessingUserGesture() is false when
1126 // the user is performing actions outside the page (e.g. typed url,
1127 // history navigation). We don't want to trigger saving in these cases.
1128 content::DocumentState* document_state =
1129 content::DocumentState::FromDataSource(
1130 navigated_frame->provisionalDataSource());
1131 content::NavigationState* navigation_state =
1132 document_state->navigation_state();
1133 ui::PageTransition type = navigation_state->GetTransitionType();
1134 if (ui::PageTransitionIsWebTriggerable(type) &&
1135 ui::PageTransitionIsNewNavigation(type) &&
1136 !blink::WebUserGestureIndicator::isProcessingUserGesture()) {
1137 // If onsubmit has been called, try and save that form.
1138 if (provisionally_saved_form_) {
1139 if (logger) {
1140 logger->LogPasswordForm(
1141 Logger::STRING_PROVISIONALLY_SAVED_FORM_FOR_FRAME,
1142 *provisionally_saved_form_);
1144 Send(new AutofillHostMsg_PasswordFormSubmitted(
1145 routing_id(), *provisionally_saved_form_));
1146 provisionally_saved_form_.reset();
1147 } else {
1148 ScopedVector<PasswordForm> possible_submitted_forms;
1149 // Loop through the forms on the page looking for one that has been
1150 // filled out. If one exists, try and save the credentials.
1151 blink::WebVector<blink::WebFormElement> forms;
1152 render_frame()->GetWebFrame()->document().forms(forms);
1154 bool password_forms_found = false;
1155 for (size_t i = 0; i < forms.size(); ++i) {
1156 blink::WebFormElement form_element = forms[i];
1157 if (logger) {
1158 LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE,
1159 form_element);
1161 possible_submitted_forms.push_back(CreatePasswordFormFromWebForm(
1162 form_element, &nonscript_modified_values_, &form_predictions_));
1165 possible_submitted_forms.push_back(
1166 CreatePasswordFormFromUnownedInputElements(
1167 *render_frame()->GetWebFrame(),
1168 &nonscript_modified_values_,
1169 &form_predictions_));
1171 for (const PasswordForm* password_form : possible_submitted_forms) {
1172 if (password_form && !password_form->username_value.empty() &&
1173 FormContainsNonDefaultPasswordValue(*password_form)) {
1174 password_forms_found = true;
1175 if (logger) {
1176 logger->LogPasswordForm(Logger::STRING_PASSWORD_FORM_FOUND_ON_PAGE,
1177 *password_form);
1179 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
1180 *password_form));
1181 break;
1185 if (!password_forms_found && logger)
1186 logger->LogMessage(Logger::STRING_PASSWORD_FORM_NOT_FOUND_ON_PAGE);
1190 // This is a new navigation, so require a new user gesture before filling in
1191 // passwords.
1192 gatekeeper_.Reset();
1195 void PasswordAutofillAgent::OnFillPasswordForm(
1196 int key,
1197 const PasswordFormFillData& form_data) {
1199 FormElementsList forms;
1200 FindFormElements(render_frame(), form_data, &forms);
1201 FormElementsList::iterator iter;
1202 for (iter = forms.begin(); iter != forms.end(); ++iter) {
1203 // Attach autocomplete listener to enable selecting alternate logins.
1204 blink::WebInputElement username_element, password_element;
1206 // Check whether the password form has a username input field.
1207 bool form_contains_fillable_username_field =
1208 FillDataContainsFillableUsername(form_data);
1209 if (form_contains_fillable_username_field) {
1210 username_element =
1211 (*iter)[form_data.username_field.name];
1214 // No password field, bail out.
1215 if (form_data.password_field.name.empty())
1216 break;
1218 // We might have already filled this form if there are two <form> elements
1219 // with identical markup.
1220 if (login_to_password_info_.find(username_element) !=
1221 login_to_password_info_.end())
1222 continue;
1224 // Get pointer to password element. (We currently only support single
1225 // password forms).
1226 password_element = (*iter)[form_data.password_field.name];
1228 // If wait_for_username is true, we don't want to initially fill the form
1229 // until the user types in a valid username.
1230 if (!form_data.wait_for_username) {
1231 FillFormOnPasswordReceived(
1232 form_data,
1233 username_element,
1234 password_element,
1235 &nonscript_modified_values_,
1236 base::Bind(&PasswordValueGatekeeper::RegisterElement,
1237 base::Unretained(&gatekeeper_)));
1240 PasswordInfo password_info;
1241 password_info.fill_data = form_data;
1242 password_info.password_field = password_element;
1243 login_to_password_info_[username_element] = password_info;
1244 password_to_username_[password_element] = username_element;
1245 login_to_password_info_key_[username_element] = key;
1249 void PasswordAutofillAgent::OnSetLoggingState(bool active) {
1250 logging_state_active_ = active;
1253 void PasswordAutofillAgent::OnAutofillUsernameAndPasswordDataReceived(
1254 const FormsPredictionsMap& predictions) {
1255 form_predictions_ = predictions;
1258 void PasswordAutofillAgent::OnFindFocusedPasswordForm() {
1259 scoped_ptr<PasswordForm> password_form;
1261 blink::WebElement element = render_frame()->GetFocusedElement();
1262 if (!element.isNull() && element.hasHTMLTagName("input")) {
1263 blink::WebInputElement input = element.to<blink::WebInputElement>();
1264 if (input.isPasswordField() && !input.form().isNull()) {
1265 if (!input.form().isNull()) {
1266 password_form = CreatePasswordFormFromWebForm(
1267 input.form(), &nonscript_modified_values_, &form_predictions_);
1268 } else {
1269 password_form = CreatePasswordFormFromUnownedInputElements(
1270 *render_frame()->GetWebFrame(),
1271 &nonscript_modified_values_, &form_predictions_);
1272 // Only try to use this form if |input| is one of the password elements
1273 // for |password_form|.
1274 if (password_form->password_element != input.nameForAutofill() &&
1275 password_form->new_password_element != input.nameForAutofill())
1276 password_form.reset();
1281 if (!password_form)
1282 password_form.reset(new PasswordForm());
1284 Send(new AutofillHostMsg_FocusedPasswordFormFound(
1285 routing_id(), *password_form));
1288 ////////////////////////////////////////////////////////////////////////////////
1289 // PasswordAutofillAgent, private:
1291 PasswordAutofillAgent::PasswordInfo::PasswordInfo()
1292 : password_was_edited_last(false),
1293 username_was_edited(false) {
1296 bool PasswordAutofillAgent::ShowSuggestionPopup(
1297 const PasswordFormFillData& fill_data,
1298 const blink::WebInputElement& user_input,
1299 bool show_all,
1300 bool show_on_password_field) {
1301 DCHECK(!user_input.isNull());
1302 blink::WebFrame* frame = user_input.document().frame();
1303 if (!frame)
1304 return false;
1306 blink::WebView* webview = frame->view();
1307 if (!webview)
1308 return false;
1310 if (user_input.isPasswordField() && !user_input.isAutofilled() &&
1311 !user_input.value().isEmpty()) {
1312 Send(new AutofillHostMsg_HidePopup(routing_id()));
1313 return false;
1316 FormData form;
1317 FormFieldData field;
1318 FindFormAndFieldForFormControlElement(user_input, &form, &field);
1320 blink::WebInputElement selected_element = user_input;
1321 if (show_on_password_field && !selected_element.isPasswordField()) {
1322 LoginToPasswordInfoMap::const_iterator iter =
1323 login_to_password_info_.find(user_input);
1324 DCHECK(iter != login_to_password_info_.end());
1325 selected_element = iter->second.password_field;
1327 gfx::Rect bounding_box(selected_element.boundsInViewportSpace());
1329 blink::WebInputElement username;
1330 if (!show_on_password_field || !user_input.isPasswordField()) {
1331 username = user_input;
1333 LoginToPasswordInfoKeyMap::const_iterator key_it =
1334 login_to_password_info_key_.find(username);
1335 DCHECK(key_it != login_to_password_info_key_.end());
1337 float scale =
1338 render_frame()->GetRenderView()->GetWebView()->pageScaleFactor();
1339 gfx::RectF bounding_box_scaled(bounding_box.x() * scale,
1340 bounding_box.y() * scale,
1341 bounding_box.width() * scale,
1342 bounding_box.height() * scale);
1343 int options = 0;
1344 if (show_all)
1345 options |= SHOW_ALL;
1346 if (show_on_password_field)
1347 options |= IS_PASSWORD_FIELD;
1348 base::string16 username_string(
1349 username.isNull() ? base::string16()
1350 : static_cast<base::string16>(user_input.value()));
1351 Send(new AutofillHostMsg_ShowPasswordSuggestions(
1352 routing_id(), key_it->second, field.text_direction, username_string,
1353 options, bounding_box_scaled));
1354 username_query_prefix_ = username_string;
1355 return CanShowSuggestion(fill_data, username_string, show_all);
1358 void PasswordAutofillAgent::FrameClosing() {
1359 for (auto const& iter : login_to_password_info_) {
1360 login_to_password_info_key_.erase(iter.first);
1361 password_to_username_.erase(iter.second.password_field);
1363 login_to_password_info_.clear();
1364 provisionally_saved_form_.reset();
1365 nonscript_modified_values_.clear();
1368 bool PasswordAutofillAgent::FindLoginInfo(const blink::WebNode& node,
1369 blink::WebInputElement* found_input,
1370 PasswordInfo** found_password) {
1371 if (!node.isElementNode())
1372 return false;
1374 blink::WebElement element = node.toConst<blink::WebElement>();
1375 if (!element.hasHTMLTagName("input"))
1376 return false;
1378 *found_input = element.to<blink::WebInputElement>();
1379 const blink::WebInputElement* username_element; // ignored
1380 return FindPasswordInfoForElement(*found_input, &username_element,
1381 found_password);
1384 void PasswordAutofillAgent::ClearPreview(
1385 blink::WebInputElement* username,
1386 blink::WebInputElement* password) {
1387 if (!username->suggestedValue().isEmpty()) {
1388 username->setSuggestedValue(blink::WebString());
1389 username->setAutofilled(was_username_autofilled_);
1390 username->setSelectionRange(username_query_prefix_.length(),
1391 username->value().length());
1393 if (!password->suggestedValue().isEmpty()) {
1394 password->setSuggestedValue(blink::WebString());
1395 password->setAutofilled(was_password_autofilled_);
1399 void PasswordAutofillAgent::ProvisionallySavePassword(
1400 scoped_ptr<PasswordForm> password_form,
1401 ProvisionallySaveRestriction restriction) {
1402 if (!password_form || (restriction == RESTRICTION_NON_EMPTY_PASSWORD &&
1403 password_form->password_value.empty() &&
1404 password_form->new_password_value.empty())) {
1405 return;
1407 provisionally_saved_form_ = password_form.Pass();
1410 bool PasswordAutofillAgent::ProvisionallySavedPasswordIsValid() {
1411 return provisionally_saved_form_ &&
1412 !provisionally_saved_form_->username_value.empty() &&
1413 !(provisionally_saved_form_->password_value.empty() &&
1414 provisionally_saved_form_->new_password_value.empty());
1417 // LegacyPasswordAutofillAgent -------------------------------------------------
1419 PasswordAutofillAgent::LegacyPasswordAutofillAgent::LegacyPasswordAutofillAgent(
1420 content::RenderView* render_view,
1421 PasswordAutofillAgent* agent)
1422 : content::RenderViewObserver(render_view), agent_(agent) {
1425 PasswordAutofillAgent::LegacyPasswordAutofillAgent::
1426 ~LegacyPasswordAutofillAgent() {
1429 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::OnDestruct() {
1430 // No op. Do not delete |this|.
1433 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStartLoading() {
1434 agent_->DidStartLoading();
1437 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStopLoading() {
1438 agent_->DidStopLoading();
1441 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::
1442 DidStartProvisionalLoad(blink::WebLocalFrame* navigated_frame) {
1443 agent_->LegacyDidStartProvisionalLoad(navigated_frame);
1446 } // namespace autofill