Revert "Fix broken channel icon in chrome://help on CrOS" and try again
[chromium-blink-merge.git] / components / autofill / content / renderer / password_autofill_agent.cc
blobf9172c5e7a47b7710bcda0bf4b45d7e2ce06c845
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.
651 LoginToPasswordInfoMap::iterator iter = login_to_password_info_.find(element);
652 if (iter == login_to_password_info_.end())
653 return false;
655 mutable_element.setAutofilled(false);
656 iter->second.password_was_edited_last = false;
658 // If wait_for_username is true we will fill when the username loses focus.
659 if (iter->second.fill_data.wait_for_username)
660 return false;
662 if (!element.isText() || !IsElementAutocompletable(element) ||
663 !IsElementAutocompletable(iter->second.password_field)) {
664 return false;
667 if (element.nameForAutofill().isEmpty())
668 return false; // If the field has no name, then we won't have values.
670 // Don't attempt to autofill with values that are too large.
671 if (element.value().length() > kMaximumTextSizeForAutocomplete)
672 return false;
674 // Show the popup with the list of available usernames.
675 ShowSuggestionPopup(iter->second.fill_data, element, false, false);
676 return true;
679 void PasswordAutofillAgent::UpdateStateForTextChange(
680 const blink::WebInputElement& element) {
681 // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
682 blink::WebInputElement mutable_element = element; // We need a non-const.
684 if (element.isTextField())
685 nonscript_modified_values_[element] = element.value();
687 LoginToPasswordInfoMap::iterator password_info_iter =
688 login_to_password_info_.find(element);
689 if (password_info_iter != login_to_password_info_.end()) {
690 password_info_iter->second.username_was_edited = true;
693 DCHECK_EQ(element.document().frame(), render_frame()->GetWebFrame());
695 if (element.isPasswordField()) {
696 // Some login forms have event handlers that put a hash of the password into
697 // a hidden field and then clear the password (http://crbug.com/28910,
698 // http://crbug.com/391693). This method gets called before any of those
699 // handlers run, so save away a copy of the password in case it gets lost.
700 // To honor the user having explicitly cleared the password, even an empty
701 // password will be saved here.
702 scoped_ptr<PasswordForm> password_form;
703 if (element.form().isNull()) {
704 password_form = CreatePasswordFormFromUnownedInputElements(
705 *element.document().frame(), &nonscript_modified_values_,
706 &form_predictions_);
707 } else {
708 password_form = CreatePasswordFormFromWebForm(
709 element.form(), &nonscript_modified_values_, &form_predictions_);
711 ProvisionallySavePassword(password_form.Pass(), RESTRICTION_NONE);
713 PasswordToLoginMap::iterator iter = password_to_username_.find(element);
714 if (iter != password_to_username_.end()) {
715 login_to_password_info_[iter->second].password_was_edited_last = true;
716 // Note that the suggested value of |mutable_element| was reset when its
717 // value changed.
718 mutable_element.setAutofilled(false);
723 bool PasswordAutofillAgent::FillSuggestion(
724 const blink::WebNode& node,
725 const blink::WebString& username,
726 const blink::WebString& password) {
727 // The element in context of the suggestion popup.
728 blink::WebInputElement filled_element;
729 PasswordInfo* password_info;
731 if (!FindLoginInfo(node, &filled_element, &password_info) ||
732 !IsElementAutocompletable(filled_element) ||
733 !IsElementAutocompletable(password_info->password_field)) {
734 return false;
737 password_info->password_was_edited_last = false;
738 // Note that in cases where filled_element is the password element, the value
739 // gets overwritten with the correct one below.
740 filled_element.setValue(username, true);
741 filled_element.setAutofilled(true);
743 password_info->password_field.setValue(password, true);
744 password_info->password_field.setAutofilled(true);
746 filled_element.setSelectionRange(filled_element.value().length(),
747 filled_element.value().length());
749 return true;
752 bool PasswordAutofillAgent::PreviewSuggestion(
753 const blink::WebNode& node,
754 const blink::WebString& username,
755 const blink::WebString& password) {
756 blink::WebInputElement username_element;
757 PasswordInfo* password_info;
759 if (!FindLoginInfo(node, &username_element, &password_info) ||
760 !IsElementAutocompletable(username_element) ||
761 !IsElementAutocompletable(password_info->password_field)) {
762 return false;
765 if (username_query_prefix_.empty())
766 username_query_prefix_ = username_element.value();
768 was_username_autofilled_ = username_element.isAutofilled();
769 username_element.setSuggestedValue(username);
770 username_element.setAutofilled(true);
771 ::autofill::PreviewSuggestion(username_element.suggestedValue(),
772 username_query_prefix_, &username_element);
773 was_password_autofilled_ = password_info->password_field.isAutofilled();
774 password_info->password_field.setSuggestedValue(password);
775 password_info->password_field.setAutofilled(true);
777 return true;
780 bool PasswordAutofillAgent::DidClearAutofillSelection(
781 const blink::WebNode& node) {
782 blink::WebInputElement username_element;
783 PasswordInfo* password_info;
784 if (!FindLoginInfo(node, &username_element, &password_info))
785 return false;
787 ClearPreview(&username_element, &password_info->password_field);
788 return true;
791 bool PasswordAutofillAgent::FindPasswordInfoForElement(
792 const blink::WebInputElement& element,
793 const blink::WebInputElement** username_element,
794 PasswordInfo** password_info) {
795 DCHECK(username_element && password_info);
796 if (!element.isPasswordField()) {
797 *username_element = &element;
798 } else {
799 PasswordToLoginMap::const_iterator password_iter =
800 password_to_username_.find(element);
801 if (password_iter == password_to_username_.end())
802 return false;
803 *username_element = &password_iter->second;
806 LoginToPasswordInfoMap::iterator iter =
807 login_to_password_info_.find(**username_element);
809 if (iter == login_to_password_info_.end())
810 return false;
812 *password_info = &iter->second;
813 return true;
816 bool PasswordAutofillAgent::ShowSuggestions(
817 const blink::WebInputElement& element,
818 bool show_all,
819 bool generation_popup_showing) {
820 const blink::WebInputElement* username_element;
821 PasswordInfo* password_info;
822 if (!FindPasswordInfoForElement(element, &username_element, &password_info))
823 return false;
825 // If autocomplete='off' is set on the form elements, no suggestion dialog
826 // should be shown. However, return |true| to indicate that this is a known
827 // password form and that the request to show suggestions has been handled (as
828 // a no-op).
829 if (!IsElementAutocompletable(element) ||
830 !IsElementAutocompletable(password_info->password_field))
831 return true;
833 bool username_is_available =
834 !username_element->isNull() && IsElementEditable(*username_element);
835 // If the element is a password field, a popup should only be shown if there
836 // is no username or the corresponding username element is not editable since
837 // it is only in that case that the username element does not have a
838 // suggestions popup.
839 if (element.isPasswordField() && username_is_available &&
840 (!password_info->fill_data.is_possible_change_password_form ||
841 password_info->username_was_edited))
842 return true;
844 UMA_HISTOGRAM_BOOLEAN(
845 "PasswordManager.AutocompletePopupSuppressedByGeneration",
846 generation_popup_showing);
848 if (generation_popup_showing)
849 return false;
851 // Chrome should never show more than one account for a password element since
852 // this implies that the username element cannot be modified. Thus even if
853 // |show_all| is true, check if the element in question is a password element
854 // for the call to ShowSuggestionPopup.
855 return ShowSuggestionPopup(
856 password_info->fill_data,
857 username_element->isNull() ? element : *username_element,
858 show_all && !element.isPasswordField(), element.isPasswordField());
861 bool PasswordAutofillAgent::OriginCanAccessPasswordManager(
862 const blink::WebSecurityOrigin& origin) {
863 return origin.canAccessPasswordManager();
866 void PasswordAutofillAgent::OnDynamicFormsSeen() {
867 SendPasswordForms(false /* only_visible */);
870 void PasswordAutofillAgent::AJAXSucceeded() {
871 OnSamePageNavigationCompleted();
874 void PasswordAutofillAgent::OnSamePageNavigationCompleted() {
875 if (!ProvisionallySavedPasswordIsValid())
876 return;
878 // Prompt to save only if the form is now gone, either invisible or
879 // removed from the DOM.
880 blink::WebFrame* frame = render_frame()->GetWebFrame();
881 if (IsFormVisible(frame, provisionally_saved_form_->action,
882 form_predictions_))
883 return;
885 Send(new AutofillHostMsg_InPageNavigation(routing_id(),
886 *provisionally_saved_form_));
887 provisionally_saved_form_.reset();
890 void PasswordAutofillAgent::FirstUserGestureObserved() {
891 gatekeeper_.OnUserGesture();
894 void PasswordAutofillAgent::SendPasswordForms(bool only_visible) {
895 scoped_ptr<RendererSavePasswordProgressLogger> logger;
896 if (logging_state_active_) {
897 logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
898 logger->LogMessage(Logger::STRING_SEND_PASSWORD_FORMS_METHOD);
899 logger->LogBoolean(Logger::STRING_ONLY_VISIBLE, only_visible);
902 blink::WebFrame* frame = render_frame()->GetWebFrame();
903 // Make sure that this security origin is allowed to use password manager.
904 blink::WebSecurityOrigin origin = frame->document().securityOrigin();
905 if (logger) {
906 logger->LogURL(Logger::STRING_SECURITY_ORIGIN,
907 GURL(origin.toString().utf8()));
909 if (!OriginCanAccessPasswordManager(origin)) {
910 if (logger) {
911 logger->LogMessage(Logger::STRING_SECURITY_ORIGIN_FAILURE);
913 return;
916 // Checks whether the webpage is a redirect page or an empty page.
917 if (IsWebpageEmpty(frame)) {
918 if (logger) {
919 logger->LogMessage(Logger::STRING_WEBPAGE_EMPTY);
921 return;
924 blink::WebVector<blink::WebFormElement> forms;
925 frame->document().forms(forms);
926 if (logger)
927 logger->LogNumber(Logger::STRING_NUMBER_OF_ALL_FORMS, forms.size());
929 std::vector<PasswordForm> password_forms;
930 for (size_t i = 0; i < forms.size(); ++i) {
931 const blink::WebFormElement& form = forms[i];
932 if (only_visible) {
933 bool is_form_visible = IsWebNodeVisible(form);
934 if (logger) {
935 LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE, form);
936 logger->LogBoolean(Logger::STRING_FORM_IS_VISIBLE, is_form_visible);
939 // If requested, ignore non-rendered forms, e.g., those styled with
940 // display:none.
941 if (!is_form_visible)
942 continue;
945 scoped_ptr<PasswordForm> password_form(
946 CreatePasswordFormFromWebForm(form, nullptr, &form_predictions_));
947 if (password_form) {
948 if (logger) {
949 logger->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD,
950 *password_form);
952 password_forms.push_back(*password_form);
956 // See if there are any unattached input elements that could be used for
957 // password submission.
958 scoped_ptr<PasswordForm> password_form(
959 CreatePasswordFormFromUnownedInputElements(*frame,
960 nullptr,
961 &form_predictions_));
962 if (password_form) {
963 if (logger) {
964 logger->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD,
965 *password_form);
967 password_forms.push_back(*password_form);
970 if (password_forms.empty() && !only_visible) {
971 // We need to send the PasswordFormsRendered message regardless of whether
972 // there are any forms visible, as this is also the code path that triggers
973 // showing the infobar.
974 return;
977 if (only_visible) {
978 Send(new AutofillHostMsg_PasswordFormsRendered(routing_id(),
979 password_forms,
980 did_stop_loading_));
981 } else {
982 Send(new AutofillHostMsg_PasswordFormsParsed(routing_id(), password_forms));
986 bool PasswordAutofillAgent::OnMessageReceived(const IPC::Message& message) {
987 bool handled = true;
988 IPC_BEGIN_MESSAGE_MAP(PasswordAutofillAgent, message)
989 IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordForm, OnFillPasswordForm)
990 IPC_MESSAGE_HANDLER(AutofillMsg_SetLoggingState, OnSetLoggingState)
991 IPC_MESSAGE_HANDLER(AutofillMsg_AutofillUsernameAndPasswordDataReceived,
992 OnAutofillUsernameAndPasswordDataReceived)
993 IPC_MESSAGE_HANDLER(AutofillMsg_FindFocusedPasswordForm,
994 OnFindFocusedPasswordForm)
995 IPC_MESSAGE_UNHANDLED(handled = false)
996 IPC_END_MESSAGE_MAP()
997 return handled;
1000 void PasswordAutofillAgent::DidFinishDocumentLoad() {
1001 // The |frame| contents have been parsed, but not yet rendered. Let the
1002 // PasswordManager know that forms are loaded, even though we can't yet tell
1003 // whether they're visible.
1004 SendPasswordForms(false);
1007 void PasswordAutofillAgent::DidFinishLoad() {
1008 // The |frame| contents have been rendered. Let the PasswordManager know
1009 // which of the loaded frames are actually visible to the user. This also
1010 // triggers the "Save password?" infobar if the user just submitted a password
1011 // form.
1012 SendPasswordForms(true);
1015 void PasswordAutofillAgent::FrameWillClose() {
1016 FrameClosing();
1019 void PasswordAutofillAgent::DidCommitProvisionalLoad(
1020 bool is_new_navigation, bool is_same_page_navigation) {
1021 blink::WebFrame* frame = render_frame()->GetWebFrame();
1022 // TODO(dvadym): check if we need to check if it is main frame navigation
1023 // http://crbug.com/443155
1024 if (frame->parent())
1025 return; // Not a top-level navigation.
1027 if (is_same_page_navigation) {
1028 OnSamePageNavigationCompleted();
1032 void PasswordAutofillAgent::DidStartLoading() {
1033 did_stop_loading_ = false;
1036 void PasswordAutofillAgent::DidStopLoading() {
1037 did_stop_loading_ = true;
1040 void PasswordAutofillAgent::FrameDetached() {
1041 // If a sub frame has been destroyed while the user was entering information
1042 // into a password form, try to save the data. See https://crbug.com/450806
1043 // for examples of sites that perform login using this technique.
1044 if (render_frame()->GetWebFrame()->parent() &&
1045 ProvisionallySavedPasswordIsValid()) {
1046 Send(new AutofillHostMsg_InPageNavigation(routing_id(),
1047 *provisionally_saved_form_));
1049 FrameClosing();
1052 void PasswordAutofillAgent::WillSendSubmitEvent(
1053 const blink::WebFormElement& form) {
1054 // Forms submitted via XHR are not seen by WillSubmitForm if the default
1055 // onsubmit handler is overridden. Such submission first gets detected in
1056 // DidStartProvisionalLoad, which no longer knows about the particular form,
1057 // and uses the candidate stored in |provisionally_saved_form_|.
1059 // User-typed password will get stored to |provisionally_saved_form_| in
1060 // TextDidChangeInTextField. Autofilled or JavaScript-copied passwords need to
1061 // be saved here.
1063 // Only non-empty passwords are saved here. Empty passwords were likely
1064 // cleared by some scripts (http://crbug.com/28910, http://crbug.com/391693).
1065 // Had the user cleared the password, |provisionally_saved_form_| would
1066 // already have been updated in TextDidChangeInTextField.
1067 scoped_ptr<PasswordForm> password_form = CreatePasswordFormFromWebForm(
1068 form, &nonscript_modified_values_, &form_predictions_);
1069 ProvisionallySavePassword(password_form.Pass(),
1070 RESTRICTION_NON_EMPTY_PASSWORD);
1073 void PasswordAutofillAgent::WillSubmitForm(const blink::WebFormElement& form) {
1074 scoped_ptr<RendererSavePasswordProgressLogger> logger;
1075 if (logging_state_active_) {
1076 logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
1077 logger->LogMessage(Logger::STRING_WILL_SUBMIT_FORM_METHOD);
1078 LogHTMLForm(logger.get(), Logger::STRING_HTML_FORM_FOR_SUBMIT, form);
1081 scoped_ptr<PasswordForm> submitted_form =
1082 CreatePasswordFormFromWebForm(form, &nonscript_modified_values_,
1083 &form_predictions_);
1085 // If there is a provisionally saved password, copy over the previous
1086 // password value so we get the user's typed password, not the value that
1087 // may have been transformed for submit.
1088 // TODO(gcasto): Do we need to have this action equality check? Is it trying
1089 // to prevent accidentally copying over passwords from a different form?
1090 if (submitted_form) {
1091 if (logger) {
1092 logger->LogPasswordForm(Logger::STRING_CREATED_PASSWORD_FORM,
1093 *submitted_form);
1095 if (provisionally_saved_form_ &&
1096 submitted_form->action == provisionally_saved_form_->action) {
1097 if (logger)
1098 logger->LogMessage(Logger::STRING_SUBMITTED_PASSWORD_REPLACED);
1099 submitted_form->password_value =
1100 provisionally_saved_form_->password_value;
1101 submitted_form->new_password_value =
1102 provisionally_saved_form_->new_password_value;
1103 submitted_form->username_value =
1104 provisionally_saved_form_->username_value;
1107 // Some observers depend on sending this information now instead of when
1108 // the frame starts loading. If there are redirects that cause a new
1109 // RenderView to be instantiated (such as redirects to the WebStore)
1110 // we will never get to finish the load.
1111 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
1112 *submitted_form));
1113 provisionally_saved_form_.reset();
1114 } else if (logger) {
1115 logger->LogMessage(Logger::STRING_FORM_IS_NOT_PASSWORD);
1119 void PasswordAutofillAgent::LegacyDidStartProvisionalLoad(
1120 blink::WebLocalFrame* navigated_frame) {
1121 scoped_ptr<RendererSavePasswordProgressLogger> logger;
1122 if (logging_state_active_) {
1123 logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
1124 logger->LogMessage(Logger::STRING_DID_START_PROVISIONAL_LOAD_METHOD);
1127 if (navigated_frame->parent()) {
1128 if (logger)
1129 logger->LogMessage(Logger::STRING_FRAME_NOT_MAIN_FRAME);
1130 return;
1133 // Bug fix for crbug.com/368690. isProcessingUserGesture() is false when
1134 // the user is performing actions outside the page (e.g. typed url,
1135 // history navigation). We don't want to trigger saving in these cases.
1136 content::DocumentState* document_state =
1137 content::DocumentState::FromDataSource(
1138 navigated_frame->provisionalDataSource());
1139 content::NavigationState* navigation_state =
1140 document_state->navigation_state();
1141 ui::PageTransition type = navigation_state->GetTransitionType();
1142 if (ui::PageTransitionIsWebTriggerable(type) &&
1143 ui::PageTransitionIsNewNavigation(type) &&
1144 !blink::WebUserGestureIndicator::isProcessingUserGesture()) {
1145 // If onsubmit has been called, try and save that form.
1146 if (provisionally_saved_form_) {
1147 if (logger) {
1148 logger->LogPasswordForm(
1149 Logger::STRING_PROVISIONALLY_SAVED_FORM_FOR_FRAME,
1150 *provisionally_saved_form_);
1152 Send(new AutofillHostMsg_PasswordFormSubmitted(
1153 routing_id(), *provisionally_saved_form_));
1154 provisionally_saved_form_.reset();
1155 } else {
1156 ScopedVector<PasswordForm> possible_submitted_forms;
1157 // Loop through the forms on the page looking for one that has been
1158 // filled out. If one exists, try and save the credentials.
1159 blink::WebVector<blink::WebFormElement> forms;
1160 render_frame()->GetWebFrame()->document().forms(forms);
1162 bool password_forms_found = false;
1163 for (size_t i = 0; i < forms.size(); ++i) {
1164 blink::WebFormElement form_element = forms[i];
1165 if (logger) {
1166 LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE,
1167 form_element);
1169 possible_submitted_forms.push_back(CreatePasswordFormFromWebForm(
1170 form_element, &nonscript_modified_values_, &form_predictions_));
1173 possible_submitted_forms.push_back(
1174 CreatePasswordFormFromUnownedInputElements(
1175 *render_frame()->GetWebFrame(),
1176 &nonscript_modified_values_,
1177 &form_predictions_));
1179 for (const PasswordForm* password_form : possible_submitted_forms) {
1180 if (password_form && !password_form->username_value.empty() &&
1181 FormContainsNonDefaultPasswordValue(*password_form)) {
1182 password_forms_found = true;
1183 if (logger) {
1184 logger->LogPasswordForm(Logger::STRING_PASSWORD_FORM_FOUND_ON_PAGE,
1185 *password_form);
1187 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
1188 *password_form));
1189 break;
1193 if (!password_forms_found && logger)
1194 logger->LogMessage(Logger::STRING_PASSWORD_FORM_NOT_FOUND_ON_PAGE);
1198 // This is a new navigation, so require a new user gesture before filling in
1199 // passwords.
1200 gatekeeper_.Reset();
1203 void PasswordAutofillAgent::OnFillPasswordForm(
1204 int key,
1205 const PasswordFormFillData& form_data) {
1207 FormElementsList forms;
1208 FindFormElements(render_frame(), form_data, &forms);
1209 FormElementsList::iterator iter;
1210 for (iter = forms.begin(); iter != forms.end(); ++iter) {
1211 // Attach autocomplete listener to enable selecting alternate logins.
1212 blink::WebInputElement username_element, password_element;
1214 // Check whether the password form has a username input field.
1215 bool form_contains_fillable_username_field =
1216 FillDataContainsFillableUsername(form_data);
1217 if (form_contains_fillable_username_field) {
1218 username_element =
1219 (*iter)[form_data.username_field.name];
1222 // No password field, bail out.
1223 if (form_data.password_field.name.empty())
1224 break;
1226 // We might have already filled this form if there are two <form> elements
1227 // with identical markup.
1228 if (login_to_password_info_.find(username_element) !=
1229 login_to_password_info_.end())
1230 continue;
1232 // Get pointer to password element. (We currently only support single
1233 // password forms).
1234 password_element = (*iter)[form_data.password_field.name];
1236 // If wait_for_username is true, we don't want to initially fill the form
1237 // until the user types in a valid username.
1238 if (!form_data.wait_for_username) {
1239 FillFormOnPasswordReceived(
1240 form_data,
1241 username_element,
1242 password_element,
1243 &nonscript_modified_values_,
1244 base::Bind(&PasswordValueGatekeeper::RegisterElement,
1245 base::Unretained(&gatekeeper_)));
1248 PasswordInfo password_info;
1249 password_info.fill_data = form_data;
1250 password_info.password_field = password_element;
1251 login_to_password_info_[username_element] = password_info;
1252 password_to_username_[password_element] = username_element;
1253 login_to_password_info_key_[username_element] = key;
1257 void PasswordAutofillAgent::OnSetLoggingState(bool active) {
1258 logging_state_active_ = active;
1261 void PasswordAutofillAgent::OnAutofillUsernameAndPasswordDataReceived(
1262 const FormsPredictionsMap& predictions) {
1263 form_predictions_ = predictions;
1266 void PasswordAutofillAgent::OnFindFocusedPasswordForm() {
1267 scoped_ptr<PasswordForm> password_form;
1269 blink::WebElement element = render_frame()->GetFocusedElement();
1270 if (!element.isNull() && element.hasHTMLTagName("input")) {
1271 blink::WebInputElement input = element.to<blink::WebInputElement>();
1272 if (input.isPasswordField() && !input.form().isNull()) {
1273 if (!input.form().isNull()) {
1274 password_form = CreatePasswordFormFromWebForm(
1275 input.form(), &nonscript_modified_values_, &form_predictions_);
1276 } else {
1277 password_form = CreatePasswordFormFromUnownedInputElements(
1278 *render_frame()->GetWebFrame(),
1279 &nonscript_modified_values_, &form_predictions_);
1280 // Only try to use this form if |input| is one of the password elements
1281 // for |password_form|.
1282 if (password_form->password_element != input.nameForAutofill() &&
1283 password_form->new_password_element != input.nameForAutofill())
1284 password_form.reset();
1289 if (!password_form)
1290 password_form.reset(new PasswordForm());
1292 Send(new AutofillHostMsg_FocusedPasswordFormFound(
1293 routing_id(), *password_form));
1296 ////////////////////////////////////////////////////////////////////////////////
1297 // PasswordAutofillAgent, private:
1299 PasswordAutofillAgent::PasswordInfo::PasswordInfo()
1300 : password_was_edited_last(false),
1301 username_was_edited(false) {
1304 bool PasswordAutofillAgent::ShowSuggestionPopup(
1305 const PasswordFormFillData& fill_data,
1306 const blink::WebInputElement& user_input,
1307 bool show_all,
1308 bool show_on_password_field) {
1309 DCHECK(!user_input.isNull());
1310 blink::WebFrame* frame = user_input.document().frame();
1311 if (!frame)
1312 return false;
1314 blink::WebView* webview = frame->view();
1315 if (!webview)
1316 return false;
1318 FormData form;
1319 FormFieldData field;
1320 FindFormAndFieldForFormControlElement(user_input, &form, &field);
1322 blink::WebInputElement selected_element = user_input;
1323 if (show_on_password_field && !selected_element.isPasswordField()) {
1324 LoginToPasswordInfoMap::const_iterator iter =
1325 login_to_password_info_.find(user_input);
1326 DCHECK(iter != login_to_password_info_.end());
1327 selected_element = iter->second.password_field;
1329 gfx::Rect bounding_box(selected_element.boundsInViewportSpace());
1331 blink::WebInputElement username;
1332 if (!show_on_password_field || !user_input.isPasswordField()) {
1333 username = user_input;
1335 LoginToPasswordInfoKeyMap::const_iterator key_it =
1336 login_to_password_info_key_.find(username);
1337 DCHECK(key_it != login_to_password_info_key_.end());
1339 float scale =
1340 render_frame()->GetRenderView()->GetWebView()->pageScaleFactor();
1341 gfx::RectF bounding_box_scaled(bounding_box.x() * scale,
1342 bounding_box.y() * scale,
1343 bounding_box.width() * scale,
1344 bounding_box.height() * scale);
1345 int options = 0;
1346 if (show_all)
1347 options |= SHOW_ALL;
1348 if (show_on_password_field)
1349 options |= IS_PASSWORD_FIELD;
1350 base::string16 username_string(
1351 username.isNull() ? base::string16()
1352 : static_cast<base::string16>(user_input.value()));
1353 Send(new AutofillHostMsg_ShowPasswordSuggestions(
1354 routing_id(), key_it->second, field.text_direction, username_string,
1355 options, bounding_box_scaled));
1356 username_query_prefix_ = username_string;
1357 return CanShowSuggestion(fill_data, username_string, show_all);
1360 void PasswordAutofillAgent::FrameClosing() {
1361 for (auto const& iter : login_to_password_info_) {
1362 login_to_password_info_key_.erase(iter.first);
1363 password_to_username_.erase(iter.second.password_field);
1365 login_to_password_info_.clear();
1366 provisionally_saved_form_.reset();
1367 nonscript_modified_values_.clear();
1370 bool PasswordAutofillAgent::FindLoginInfo(const blink::WebNode& node,
1371 blink::WebInputElement* found_input,
1372 PasswordInfo** found_password) {
1373 if (!node.isElementNode())
1374 return false;
1376 blink::WebElement element = node.toConst<blink::WebElement>();
1377 if (!element.hasHTMLTagName("input"))
1378 return false;
1380 *found_input = element.to<blink::WebInputElement>();
1381 const blink::WebInputElement* username_element; // ignored
1382 return FindPasswordInfoForElement(*found_input, &username_element,
1383 found_password);
1386 void PasswordAutofillAgent::ClearPreview(
1387 blink::WebInputElement* username,
1388 blink::WebInputElement* password) {
1389 if (!username->suggestedValue().isEmpty()) {
1390 username->setSuggestedValue(blink::WebString());
1391 username->setAutofilled(was_username_autofilled_);
1392 username->setSelectionRange(username_query_prefix_.length(),
1393 username->value().length());
1395 if (!password->suggestedValue().isEmpty()) {
1396 password->setSuggestedValue(blink::WebString());
1397 password->setAutofilled(was_password_autofilled_);
1401 void PasswordAutofillAgent::ProvisionallySavePassword(
1402 scoped_ptr<PasswordForm> password_form,
1403 ProvisionallySaveRestriction restriction) {
1404 if (!password_form || (restriction == RESTRICTION_NON_EMPTY_PASSWORD &&
1405 password_form->password_value.empty() &&
1406 password_form->new_password_value.empty())) {
1407 return;
1409 provisionally_saved_form_ = password_form.Pass();
1412 bool PasswordAutofillAgent::ProvisionallySavedPasswordIsValid() {
1413 return provisionally_saved_form_ &&
1414 !provisionally_saved_form_->username_value.empty() &&
1415 !(provisionally_saved_form_->password_value.empty() &&
1416 provisionally_saved_form_->new_password_value.empty());
1419 // LegacyPasswordAutofillAgent -------------------------------------------------
1421 PasswordAutofillAgent::LegacyPasswordAutofillAgent::LegacyPasswordAutofillAgent(
1422 content::RenderView* render_view,
1423 PasswordAutofillAgent* agent)
1424 : content::RenderViewObserver(render_view), agent_(agent) {
1427 PasswordAutofillAgent::LegacyPasswordAutofillAgent::
1428 ~LegacyPasswordAutofillAgent() {
1431 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::OnDestruct() {
1432 // No op. Do not delete |this|.
1435 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStartLoading() {
1436 agent_->DidStartLoading();
1439 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStopLoading() {
1440 agent_->DidStopLoading();
1443 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::
1444 DidStartProvisionalLoad(blink::WebLocalFrame* navigated_frame) {
1445 agent_->LegacyDidStartProvisionalLoad(navigated_frame);
1448 } // namespace autofill