Allow intent picker for external schemes
[chromium-blink-merge.git] / components / autofill / content / renderer / password_autofill_agent.cc
blob1c836a15c8d4fe4b75a5a4426d5919dd99195bf1
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 // Utility struct for form lookup and autofill. When we parse the DOM to look up
67 // a form, in addition to action and origin URL's we have to compare all
68 // necessary form elements. To avoid having to look these up again when we want
69 // to fill the form, the FindFormElements function stores the pointers
70 // in a FormElements* result, referenced to ensure they are safe to use.
71 struct FormElements {
72 blink::WebFormElement form_element;
73 FormInputElementMap input_elements;
76 typedef std::vector<FormElements*> FormElementsList;
78 bool FillDataContainsUsername(const PasswordFormFillData& fill_data) {
79 return !fill_data.username_field.name.empty();
82 // Utility function to find the unique entry of the |form_element| for the
83 // specified input |field|. On successful find, adds it to |result| and returns
84 // |true|. Otherwise clears the references from each |HTMLInputElement| from
85 // |result| and returns |false|.
86 bool FindFormInputElement(blink::WebFormElement* form_element,
87 const FormFieldData& field,
88 FormElements* result) {
89 blink::WebVector<blink::WebNode> temp_elements;
90 form_element->getNamedElements(field.name, temp_elements);
92 // Match the first input element, if any.
93 // |getNamedElements| may return non-input elements where the names match,
94 // so the results are filtered for input elements.
95 // If more than one match is made, then we have ambiguity (due to misuse
96 // of "name" attribute) so is it considered not found.
97 bool found_input = false;
98 for (size_t i = 0; i < temp_elements.size(); ++i) {
99 if (temp_elements[i].to<blink::WebElement>().hasHTMLTagName("input")) {
100 // Check for a non-unique match.
101 if (found_input) {
102 found_input = false;
103 break;
106 // Only fill saved passwords into password fields and usernames into
107 // text fields.
108 blink::WebInputElement input_element =
109 temp_elements[i].to<blink::WebInputElement>();
110 if (input_element.isPasswordField() !=
111 (field.form_control_type == "password"))
112 continue;
114 // This element matched, add it to our temporary result. It's possible
115 // there are multiple matches, but for purposes of identifying the form
116 // one suffices and if some function needs to deal with multiple
117 // matching elements it can get at them through the FormElement*.
118 // Note: This assignment adds a reference to the InputElement.
119 result->input_elements[field.name] = input_element;
120 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->input_elements.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 the given form element for the specified input elements in
178 // |data|, and add results to |result|.
179 bool FindFormInputElements(blink::WebFormElement* form_element,
180 const PasswordFormFillData& data,
181 FormElements* result) {
182 return FindFormInputElement(form_element, data.password_field, result) &&
183 (!FillDataContainsUsername(data) ||
184 FindFormInputElement(form_element, data.username_field, result));
187 // Helper to locate form elements identified by |data|.
188 void FindFormElements(content::RenderFrame* render_frame,
189 const PasswordFormFillData& data,
190 FormElementsList* results) {
191 DCHECK(results);
193 blink::WebDocument doc = render_frame->GetWebFrame()->document();
194 if (!doc.isHTMLDocument())
195 return;
197 if (data.origin != GetCanonicalOriginForDocument(doc))
198 return;
200 blink::WebVector<blink::WebFormElement> forms;
201 doc.forms(forms);
203 for (size_t i = 0; i < forms.size(); ++i) {
204 blink::WebFormElement fe = forms[i];
206 // Action URL must match.
207 if (data.action != GetCanonicalActionForForm(fe))
208 continue;
210 scoped_ptr<FormElements> curr_elements(new FormElements);
211 if (!FindFormInputElements(&fe, data, curr_elements.get()))
212 continue;
214 // We found the right element.
215 // Note: this assignment adds a reference to |fe|.
216 curr_elements->form_element = fe;
217 results->push_back(curr_elements.release());
221 bool IsElementEditable(const blink::WebInputElement& element) {
222 return element.isEnabled() && !element.isReadOnly();
225 bool DoUsernamesMatch(const base::string16& username1,
226 const base::string16& username2,
227 bool exact_match) {
228 if (exact_match)
229 return username1 == username2;
230 return FieldIsSuggestionSubstringStartingOnTokenBoundary(username1, username2,
231 true);
234 // Returns |true| if the given element is editable. Otherwise, returns |false|.
235 bool IsElementAutocompletable(const blink::WebInputElement& element) {
236 return IsElementEditable(element);
239 // Returns true if the password specified in |form| is a default value.
240 bool PasswordValueIsDefault(const base::string16& password_element,
241 const base::string16& password_value,
242 blink::WebFormElement form_element) {
243 blink::WebVector<blink::WebNode> temp_elements;
244 form_element.getNamedElements(password_element, temp_elements);
246 // We are loose in our definition here and will return true if any of the
247 // appropriately named elements match the element to be saved. Currently
248 // we ignore filling passwords where naming is ambigious anyway.
249 for (size_t i = 0; i < temp_elements.size(); ++i) {
250 if (temp_elements[i].to<blink::WebElement>().getAttribute("value") ==
251 password_value)
252 return true;
254 return false;
257 // Return true if either password_value or new_password_value is not empty and
258 // not default.
259 bool FormContainsNonDefaultPasswordValue(const PasswordForm& password_form,
260 blink::WebFormElement form_element) {
261 return (!password_form.password_value.empty() &&
262 !PasswordValueIsDefault(password_form.password_element,
263 password_form.password_value,
264 form_element)) ||
265 (!password_form.new_password_value.empty() &&
266 !PasswordValueIsDefault(password_form.new_password_element,
267 password_form.new_password_value,
268 form_element));
271 // Log a message including the name, method and action of |form|.
272 void LogHTMLForm(SavePasswordProgressLogger* logger,
273 SavePasswordProgressLogger::StringID message_id,
274 const blink::WebFormElement& form) {
275 logger->LogHTMLForm(message_id,
276 form.name().utf8(),
277 GURL(form.action().utf8()));
281 // Returns true if there are any suggestions to be derived from |fill_data|.
282 // Unless |show_all| is true, only considers suggestions with usernames having
283 // |current_username| as a prefix.
284 bool CanShowSuggestion(const PasswordFormFillData& fill_data,
285 const base::string16& current_username,
286 bool show_all) {
287 base::string16 current_username_lower = base::i18n::ToLower(current_username);
288 for (const auto& usernames : fill_data.other_possible_usernames) {
289 for (size_t i = 0; i < usernames.second.size(); ++i) {
290 if (show_all ||
291 base::StartsWith(
292 base::i18n::ToLower(base::string16(usernames.second[i])),
293 current_username_lower, base::CompareCase::SENSITIVE)) {
294 return true;
299 if (show_all ||
300 base::StartsWith(base::i18n::ToLower(fill_data.username_field.value),
301 current_username_lower, base::CompareCase::SENSITIVE)) {
302 return true;
305 for (const auto& login : fill_data.additional_logins) {
306 if (show_all ||
307 base::StartsWith(base::i18n::ToLower(login.first),
308 current_username_lower,
309 base::CompareCase::SENSITIVE)) {
310 return true;
314 return false;
317 // Returns true if there exists a credential suggestion whose username field is
318 // an exact match to the current username (not just a prefix).
319 bool HasExactMatchSuggestion(const PasswordFormFillData& fill_data,
320 const base::string16& current_username) {
321 if (fill_data.username_field.value == current_username)
322 return true;
324 for (const auto& usernames : fill_data.other_possible_usernames) {
325 for (const auto& username_string : usernames.second) {
326 if (username_string == current_username)
327 return true;
331 for (const auto& login : fill_data.additional_logins) {
332 if (login.first == current_username)
333 return true;
336 return false;
339 // This function attempts to fill |username_element| and |password_element|
340 // with values from |fill_data|. The |password_element| will only have the
341 // suggestedValue set, and will be registered for copying that to the real
342 // value through |registration_callback|. If a match is found, return true and
343 // |nonscript_modified_values| will be modified with the autofilled credentials.
344 bool FillUserNameAndPassword(
345 blink::WebInputElement* username_element,
346 blink::WebInputElement* password_element,
347 const PasswordFormFillData& fill_data,
348 bool exact_username_match,
349 bool set_selection,
350 std::map<const blink::WebInputElement, blink::WebString>*
351 nonscript_modified_values,
352 base::Callback<void(blink::WebInputElement*)> registration_callback) {
353 // Don't fill username if password can't be set.
354 if (!IsElementAutocompletable(*password_element))
355 return false;
357 base::string16 current_username;
358 if (!username_element->isNull()) {
359 current_username = username_element->value();
362 // username and password will contain the match found if any.
363 base::string16 username;
364 base::string16 password;
366 // Look for any suitable matches to current field text.
367 if (DoUsernamesMatch(fill_data.username_field.value, current_username,
368 exact_username_match)) {
369 username = fill_data.username_field.value;
370 password = fill_data.password_field.value;
371 } else {
372 // Scan additional logins for a match.
373 PasswordFormFillData::LoginCollection::const_iterator iter;
374 for (iter = fill_data.additional_logins.begin();
375 iter != fill_data.additional_logins.end();
376 ++iter) {
377 if (DoUsernamesMatch(
378 iter->first, current_username, exact_username_match)) {
379 username = iter->first;
380 password = iter->second.password;
381 break;
385 // Check possible usernames.
386 if (username.empty() && password.empty()) {
387 for (PasswordFormFillData::UsernamesCollection::const_iterator iter =
388 fill_data.other_possible_usernames.begin();
389 iter != fill_data.other_possible_usernames.end();
390 ++iter) {
391 for (size_t i = 0; i < iter->second.size(); ++i) {
392 if (DoUsernamesMatch(
393 iter->second[i], current_username, exact_username_match)) {
394 username = iter->second[i];
395 password = iter->first.password;
396 break;
399 if (!username.empty() && !password.empty())
400 break;
404 if (password.empty())
405 return false;
407 // TODO(tkent): Check maxlength and pattern for both username and password
408 // fields.
410 // Input matches the username, fill in required values.
411 if (!username_element->isNull() &&
412 IsElementAutocompletable(*username_element)) {
413 // TODO(vabr): Why not setSuggestedValue? http://crbug.com/507714
414 username_element->setValue(username, true);
415 (*nonscript_modified_values)[*username_element] = username;
416 username_element->setAutofilled(true);
417 if (set_selection)
418 PreviewSuggestion(username, current_username, username_element);
419 } else if (current_username != username) {
420 // If the username can't be filled and it doesn't match a saved password
421 // as is, don't autofill a password.
422 return false;
425 // Wait to fill in the password until a user gesture occurs. This is to make
426 // sure that we do not fill in the DOM with a password until we believe the
427 // user is intentionally interacting with the page.
428 password_element->setSuggestedValue(password);
429 (*nonscript_modified_values)[*password_element] = password;
430 registration_callback.Run(password_element);
432 password_element->setAutofilled(true);
433 return true;
436 // Attempts to fill |username_element| and |password_element| with the
437 // |fill_data|. Will use the data corresponding to the preferred username,
438 // unless the |username_element| already has a value set. In that case,
439 // attempts to fill the password matching the already filled username, if
440 // such a password exists. The |password_element| will have the
441 // |suggestedValue| set, and |suggestedValue| will be registered for copying to
442 // the real value through |registration_callback|. Returns true if the password
443 // is filled.
444 bool FillFormOnPasswordReceived(
445 const PasswordFormFillData& fill_data,
446 blink::WebInputElement username_element,
447 blink::WebInputElement password_element,
448 std::map<const blink::WebInputElement, blink::WebString>*
449 nonscript_modified_values,
450 base::Callback<void(blink::WebInputElement*)> registration_callback) {
451 // Do not fill if the password field is in a chain of iframes not having
452 // identical origin.
453 blink::WebFrame* cur_frame = password_element.document().frame();
454 blink::WebString bottom_frame_origin =
455 cur_frame->securityOrigin().toString();
457 DCHECK(cur_frame);
459 while (cur_frame->parent()) {
460 cur_frame = cur_frame->parent();
461 if (!bottom_frame_origin.equals(cur_frame->securityOrigin().toString()))
462 return false;
465 // If we can't modify the password, don't try to set the username
466 if (!IsElementAutocompletable(password_element))
467 return false;
469 bool form_contains_username_field = FillDataContainsUsername(fill_data);
470 // If the form contains an autocompletable username field, try to set the
471 // username to the preferred name, but only if:
472 // (a) The fill-on-account-select flag is not set, and
473 // (b) The username element isn't prefilled
475 // If (a) is false, then just mark the username element as autofilled if the
476 // user is not in the "no highlighting" group and return so the fill step is
477 // skipped.
479 // If there is no autocompletable username field, and (a) is false, then the
480 // username element cannot be autofilled, but the user should still be able to
481 // select to fill the password element, so the password element must be marked
482 // as autofilled and the fill step should also be skipped if the user is not
483 // in the "no highlighting" group.
485 // In all other cases, do nothing.
486 bool form_has_fillable_username = form_contains_username_field &&
487 IsElementAutocompletable(username_element);
489 if (ShouldFillOnAccountSelect()) {
490 if (!ShouldHighlightFields()) {
491 return false;
494 if (form_has_fillable_username) {
495 username_element.setAutofilled(true);
496 } else if (username_element.isNull() ||
497 HasExactMatchSuggestion(fill_data, username_element.value())) {
498 password_element.setAutofilled(true);
500 return false;
503 if (form_has_fillable_username && username_element.value().isEmpty()) {
504 // TODO(tkent): Check maxlength and pattern.
505 username_element.setValue(fill_data.username_field.value, true);
508 // Fill if we have an exact match for the username. Note that this sets
509 // username to autofilled.
510 return FillUserNameAndPassword(&username_element,
511 &password_element,
512 fill_data,
513 true /* exact_username_match */,
514 false /* set_selection */,
515 nonscript_modified_values,
516 registration_callback);
519 // Takes a |map| with pointers as keys and linked_ptr as values, and returns
520 // true if |key| is not NULL and |map| contains a non-NULL entry for |key|.
521 // Makes sure not to create an entry as a side effect of using the operator [].
522 template <class Key, class Value>
523 bool ContainsNonNullEntryForNonNullKey(
524 const std::map<Key*, linked_ptr<Value>>& map,
525 Key* key) {
526 if (!key)
527 return false;
528 auto it = map.find(key);
529 return it != map.end() && it->second.get();
533 // Helper function to check if there exist any form on |frame| where its action
534 // equals |action|. Return true if so.
535 bool IsFormVisible(
536 blink::WebFrame* frame,
537 GURL& action) {
538 blink::WebVector<blink::WebFormElement> forms;
539 frame->document().forms(forms);
541 for (size_t i = 0; i < forms.size(); ++i) {
542 const blink::WebFormElement& form = forms[i];
543 if (!IsWebNodeVisible(form))
544 continue;
546 if (action == GetCanonicalActionForForm(form))
547 return true; // Form still exists
550 return false;
553 } // namespace
555 ////////////////////////////////////////////////////////////////////////////////
556 // PasswordAutofillAgent, public:
558 PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame)
559 : content::RenderFrameObserver(render_frame),
560 legacy_(render_frame->GetRenderView(), this),
561 logging_state_active_(false),
562 was_username_autofilled_(false),
563 was_password_autofilled_(false),
564 did_stop_loading_(false),
565 weak_ptr_factory_(this) {
566 Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id()));
569 PasswordAutofillAgent::~PasswordAutofillAgent() {
572 PasswordAutofillAgent::PasswordValueGatekeeper::PasswordValueGatekeeper()
573 : was_user_gesture_seen_(false) {
576 PasswordAutofillAgent::PasswordValueGatekeeper::~PasswordValueGatekeeper() {
579 void PasswordAutofillAgent::PasswordValueGatekeeper::RegisterElement(
580 blink::WebInputElement* element) {
581 if (was_user_gesture_seen_)
582 ShowValue(element);
583 else
584 elements_.push_back(*element);
587 void PasswordAutofillAgent::PasswordValueGatekeeper::OnUserGesture() {
588 was_user_gesture_seen_ = true;
590 for (std::vector<blink::WebInputElement>::iterator it = elements_.begin();
591 it != elements_.end();
592 ++it) {
593 ShowValue(&(*it));
596 elements_.clear();
599 void PasswordAutofillAgent::PasswordValueGatekeeper::Reset() {
600 was_user_gesture_seen_ = false;
601 elements_.clear();
604 void PasswordAutofillAgent::PasswordValueGatekeeper::ShowValue(
605 blink::WebInputElement* element) {
606 if (!element->isNull() && !element->suggestedValue().isEmpty())
607 element->setValue(element->suggestedValue(), true);
610 bool PasswordAutofillAgent::TextFieldDidEndEditing(
611 const blink::WebInputElement& element) {
612 LoginToPasswordInfoMap::const_iterator iter =
613 login_to_password_info_.find(element);
614 if (iter == login_to_password_info_.end())
615 return false;
617 const PasswordInfo& password_info = iter->second;
618 // Don't let autofill overwrite an explicit change made by the user.
619 if (password_info.password_was_edited_last)
620 return false;
622 const PasswordFormFillData& fill_data = password_info.fill_data;
624 // If wait_for_username is false, we should have filled when the text changed.
625 if (!fill_data.wait_for_username)
626 return false;
628 blink::WebInputElement password = password_info.password_field;
629 if (!IsElementEditable(password))
630 return false;
632 blink::WebInputElement username = element; // We need a non-const.
634 // Do not set selection when ending an editing session, otherwise it can
635 // mess with focus.
636 FillUserNameAndPassword(
637 &username, &password, fill_data, true, false,
638 &nonscript_modified_values_,
639 base::Bind(&PasswordValueGatekeeper::RegisterElement,
640 base::Unretained(&gatekeeper_)));
641 return true;
644 bool PasswordAutofillAgent::TextDidChangeInTextField(
645 const blink::WebInputElement& element) {
646 // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
647 blink::WebInputElement mutable_element = element; // We need a non-const.
649 LoginToPasswordInfoMap::iterator iter = login_to_password_info_.find(element);
650 if (iter == login_to_password_info_.end())
651 return false;
653 mutable_element.setAutofilled(false);
654 iter->second.password_was_edited_last = false;
656 // If wait_for_username is true we will fill when the username loses focus.
657 if (iter->second.fill_data.wait_for_username)
658 return false;
660 if (!element.isText() || !IsElementAutocompletable(element) ||
661 !IsElementAutocompletable(iter->second.password_field)) {
662 return false;
665 if (element.nameForAutofill().isEmpty())
666 return false; // If the field has no name, then we won't have values.
668 // Don't attempt to autofill with values that are too large.
669 if (element.value().length() > kMaximumTextSizeForAutocomplete)
670 return false;
672 // Show the popup with the list of available usernames.
673 ShowSuggestionPopup(iter->second.fill_data, element, false, false);
674 return true;
677 void PasswordAutofillAgent::UpdateStateForTextChange(
678 const blink::WebInputElement& element) {
679 // TODO(vabr): Get a mutable argument instead. http://crbug.com/397083
680 blink::WebInputElement mutable_element = element; // We need a non-const.
682 if (element.isTextField())
683 nonscript_modified_values_[element] = element.value();
685 LoginToPasswordInfoMap::iterator password_info_iter =
686 login_to_password_info_.find(element);
687 if (password_info_iter != login_to_password_info_.end()) {
688 password_info_iter->second.username_was_edited = true;
691 DCHECK_EQ(element.document().frame(), render_frame()->GetWebFrame());
693 if (element.isPasswordField()) {
694 // Some login forms have event handlers that put a hash of the password into
695 // a hidden field and then clear the password (http://crbug.com/28910,
696 // http://crbug.com/391693). This method gets called before any of those
697 // handlers run, so save away a copy of the password in case it gets lost.
698 // To honor the user having explicitly cleared the password, even an empty
699 // password will be saved here.
700 ProvisionallySavePassword(element.form(), RESTRICTION_NONE);
702 PasswordToLoginMap::iterator iter = password_to_username_.find(element);
703 if (iter != password_to_username_.end()) {
704 login_to_password_info_[iter->second].password_was_edited_last = true;
705 // Note that the suggested value of |mutable_element| was reset when its
706 // value changed.
707 mutable_element.setAutofilled(false);
712 bool PasswordAutofillAgent::FillSuggestion(
713 const blink::WebNode& node,
714 const blink::WebString& username,
715 const blink::WebString& password) {
716 // The element in context of the suggestion popup.
717 blink::WebInputElement filled_element;
718 PasswordInfo* password_info;
720 if (!FindLoginInfo(node, &filled_element, &password_info) ||
721 !IsElementAutocompletable(filled_element) ||
722 !IsElementAutocompletable(password_info->password_field)) {
723 return false;
726 password_info->password_was_edited_last = false;
727 // Note that in cases where filled_element is the password element, the value
728 // gets overwritten with the correct one below.
729 filled_element.setValue(username, true);
730 filled_element.setAutofilled(true);
732 password_info->password_field.setValue(password, true);
733 password_info->password_field.setAutofilled(true);
735 filled_element.setSelectionRange(filled_element.value().length(),
736 filled_element.value().length());
738 return true;
741 bool PasswordAutofillAgent::PreviewSuggestion(
742 const blink::WebNode& node,
743 const blink::WebString& username,
744 const blink::WebString& password) {
745 blink::WebInputElement username_element;
746 PasswordInfo* password_info;
748 if (!FindLoginInfo(node, &username_element, &password_info) ||
749 !IsElementAutocompletable(username_element) ||
750 !IsElementAutocompletable(password_info->password_field)) {
751 return false;
754 if (username_query_prefix_.empty())
755 username_query_prefix_ = username_element.value();
757 was_username_autofilled_ = username_element.isAutofilled();
758 username_element.setSuggestedValue(username);
759 username_element.setAutofilled(true);
760 ::autofill::PreviewSuggestion(username_element.suggestedValue(),
761 username_query_prefix_, &username_element);
762 was_password_autofilled_ = password_info->password_field.isAutofilled();
763 password_info->password_field.setSuggestedValue(password);
764 password_info->password_field.setAutofilled(true);
766 return true;
769 bool PasswordAutofillAgent::DidClearAutofillSelection(
770 const blink::WebNode& node) {
771 blink::WebInputElement username_element;
772 PasswordInfo* password_info;
773 if (!FindLoginInfo(node, &username_element, &password_info))
774 return false;
776 ClearPreview(&username_element, &password_info->password_field);
777 return true;
780 bool PasswordAutofillAgent::FindPasswordInfoForElement(
781 const blink::WebInputElement& element,
782 const blink::WebInputElement** username_element,
783 PasswordInfo** password_info) {
784 DCHECK(username_element && password_info);
785 if (!element.isPasswordField()) {
786 *username_element = &element;
787 } else {
788 PasswordToLoginMap::const_iterator password_iter =
789 password_to_username_.find(element);
790 if (password_iter == password_to_username_.end())
791 return false;
792 *username_element = &password_iter->second;
795 LoginToPasswordInfoMap::iterator iter =
796 login_to_password_info_.find(**username_element);
798 if (iter == login_to_password_info_.end())
799 return false;
801 *password_info = &iter->second;
802 return true;
805 bool PasswordAutofillAgent::ShowSuggestions(
806 const blink::WebInputElement& element,
807 bool show_all,
808 bool generation_popup_showing) {
809 const blink::WebInputElement* username_element;
810 PasswordInfo* password_info;
811 if (!FindPasswordInfoForElement(element, &username_element, &password_info))
812 return false;
814 // If autocomplete='off' is set on the form elements, no suggestion dialog
815 // should be shown. However, return |true| to indicate that this is a known
816 // password form and that the request to show suggestions has been handled (as
817 // a no-op).
818 if (!IsElementAutocompletable(element) ||
819 !IsElementAutocompletable(password_info->password_field))
820 return true;
822 bool username_is_available =
823 !username_element->isNull() && IsElementEditable(*username_element);
824 // If the element is a password field, a popup should only be shown if there
825 // is no username or the corresponding username element is not editable since
826 // it is only in that case that the username element does not have a
827 // suggestions popup.
828 if (element.isPasswordField() && username_is_available &&
829 (!password_info->fill_data.is_possible_change_password_form ||
830 password_info->username_was_edited))
831 return true;
833 UMA_HISTOGRAM_BOOLEAN(
834 "PasswordManager.AutocompletePopupSuppressedByGeneration",
835 generation_popup_showing);
837 if (generation_popup_showing)
838 return false;
840 // Chrome should never show more than one account for a password element since
841 // this implies that the username element cannot be modified. Thus even if
842 // |show_all| is true, check if the element in question is a password element
843 // for the call to ShowSuggestionPopup.
844 return ShowSuggestionPopup(
845 password_info->fill_data,
846 username_element->isNull() ? element : *username_element,
847 show_all && !element.isPasswordField(), element.isPasswordField());
850 bool PasswordAutofillAgent::OriginCanAccessPasswordManager(
851 const blink::WebSecurityOrigin& origin) {
852 return origin.canAccessPasswordManager();
855 void PasswordAutofillAgent::OnDynamicFormsSeen() {
856 SendPasswordForms(false /* only_visible */);
859 void PasswordAutofillAgent::AJAXSucceeded() {
860 OnSamePageNavigationCompleted();
863 void PasswordAutofillAgent::OnSamePageNavigationCompleted() {
864 if (!ProvisionallySavedPasswordIsValid())
865 return;
866 blink::WebFrame* frame = render_frame()->GetWebFrame();
868 // Prompt to save only if the form is now gone, either invisible or
869 // removed from the DOM.
870 if (IsFormVisible(frame, provisionally_saved_form_->action))
871 return;
873 Send(new AutofillHostMsg_InPageNavigation(routing_id(),
874 *provisionally_saved_form_));
875 provisionally_saved_form_.reset();
878 void PasswordAutofillAgent::FirstUserGestureObserved() {
879 gatekeeper_.OnUserGesture();
882 void PasswordAutofillAgent::SendPasswordForms(bool only_visible) {
883 scoped_ptr<RendererSavePasswordProgressLogger> logger;
884 if (logging_state_active_) {
885 logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
886 logger->LogMessage(Logger::STRING_SEND_PASSWORD_FORMS_METHOD);
887 logger->LogBoolean(Logger::STRING_ONLY_VISIBLE, only_visible);
890 blink::WebFrame* frame = render_frame()->GetWebFrame();
891 // Make sure that this security origin is allowed to use password manager.
892 blink::WebSecurityOrigin origin = frame->document().securityOrigin();
893 if (logger) {
894 logger->LogURL(Logger::STRING_SECURITY_ORIGIN,
895 GURL(origin.toString().utf8()));
897 if (!OriginCanAccessPasswordManager(origin)) {
898 if (logger) {
899 logger->LogMessage(Logger::STRING_SECURITY_ORIGIN_FAILURE);
901 return;
904 // Checks whether the webpage is a redirect page or an empty page.
905 if (IsWebpageEmpty(frame)) {
906 if (logger) {
907 logger->LogMessage(Logger::STRING_WEBPAGE_EMPTY);
909 return;
912 blink::WebVector<blink::WebFormElement> forms;
913 frame->document().forms(forms);
914 if (logger)
915 logger->LogNumber(Logger::STRING_NUMBER_OF_ALL_FORMS, forms.size());
917 std::vector<PasswordForm> password_forms;
918 for (size_t i = 0; i < forms.size(); ++i) {
919 const blink::WebFormElement& form = forms[i];
920 if (only_visible) {
921 bool is_form_visible = IsWebNodeVisible(form);
922 if (logger) {
923 LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE, form);
924 logger->LogBoolean(Logger::STRING_FORM_IS_VISIBLE, is_form_visible);
927 // If requested, ignore non-rendered forms, e.g., those styled with
928 // display:none.
929 if (!is_form_visible)
930 continue;
933 scoped_ptr<PasswordForm> password_form(
934 CreatePasswordForm(form, nullptr, &form_predictions_));
935 if (password_form.get()) {
936 if (logger) {
937 logger->LogPasswordForm(Logger::STRING_FORM_IS_PASSWORD,
938 *password_form);
940 password_forms.push_back(*password_form);
944 if (password_forms.empty() && !only_visible) {
945 // We need to send the PasswordFormsRendered message regardless of whether
946 // there are any forms visible, as this is also the code path that triggers
947 // showing the infobar.
948 return;
951 if (only_visible) {
952 Send(new AutofillHostMsg_PasswordFormsRendered(routing_id(),
953 password_forms,
954 did_stop_loading_));
955 } else {
956 Send(new AutofillHostMsg_PasswordFormsParsed(routing_id(), password_forms));
960 bool PasswordAutofillAgent::OnMessageReceived(const IPC::Message& message) {
961 bool handled = true;
962 IPC_BEGIN_MESSAGE_MAP(PasswordAutofillAgent, message)
963 IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordForm, OnFillPasswordForm)
964 IPC_MESSAGE_HANDLER(AutofillMsg_SetLoggingState, OnSetLoggingState)
965 IPC_MESSAGE_HANDLER(AutofillMsg_AutofillUsernameAndPasswordDataReceived,
966 OnAutofillUsernameAndPasswordDataReceived)
967 IPC_MESSAGE_HANDLER(AutofillMsg_FindFocusedPasswordForm,
968 OnFindFocusedPasswordForm)
969 IPC_MESSAGE_UNHANDLED(handled = false)
970 IPC_END_MESSAGE_MAP()
971 return handled;
974 void PasswordAutofillAgent::DidFinishDocumentLoad() {
975 // The |frame| contents have been parsed, but not yet rendered. Let the
976 // PasswordManager know that forms are loaded, even though we can't yet tell
977 // whether they're visible.
978 SendPasswordForms(false);
981 void PasswordAutofillAgent::DidFinishLoad() {
982 // The |frame| contents have been rendered. Let the PasswordManager know
983 // which of the loaded frames are actually visible to the user. This also
984 // triggers the "Save password?" infobar if the user just submitted a password
985 // form.
986 SendPasswordForms(true);
989 void PasswordAutofillAgent::FrameWillClose() {
990 FrameClosing();
993 void PasswordAutofillAgent::DidCommitProvisionalLoad(
994 bool is_new_navigation, bool is_same_page_navigation) {
995 blink::WebFrame* frame = render_frame()->GetWebFrame();
996 // TODO(dvadym): check if we need to check if it is main frame navigation
997 // http://crbug.com/443155
998 if (frame->parent())
999 return; // Not a top-level navigation.
1001 if (is_same_page_navigation) {
1002 OnSamePageNavigationCompleted();
1006 void PasswordAutofillAgent::DidStartLoading() {
1007 did_stop_loading_ = false;
1010 void PasswordAutofillAgent::DidStopLoading() {
1011 did_stop_loading_ = true;
1014 void PasswordAutofillAgent::FrameDetached() {
1015 // If a sub frame has been destroyed while the user was entering information
1016 // into a password form, try to save the data. See https://crbug.com/450806
1017 // for examples of sites that perform login using this technique.
1018 if (render_frame()->GetWebFrame()->parent() &&
1019 ProvisionallySavedPasswordIsValid()) {
1020 Send(new AutofillHostMsg_InPageNavigation(routing_id(),
1021 *provisionally_saved_form_));
1023 FrameClosing();
1026 void PasswordAutofillAgent::WillSendSubmitEvent(
1027 const blink::WebFormElement& form) {
1028 // Forms submitted via XHR are not seen by WillSubmitForm if the default
1029 // onsubmit handler is overridden. Such submission first gets detected in
1030 // DidStartProvisionalLoad, which no longer knows about the particular form,
1031 // and uses the candidate stored in |provisionally_saved_form_|.
1033 // User-typed password will get stored to |provisionally_saved_form_| in
1034 // TextDidChangeInTextField. Autofilled or JavaScript-copied passwords need to
1035 // be saved here.
1037 // Only non-empty passwords are saved here. Empty passwords were likely
1038 // cleared by some scripts (http://crbug.com/28910, http://crbug.com/391693).
1039 // Had the user cleared the password, |provisionally_saved_form_| would
1040 // already have been updated in TextDidChangeInTextField.
1041 ProvisionallySavePassword(form, RESTRICTION_NON_EMPTY_PASSWORD);
1044 void PasswordAutofillAgent::WillSubmitForm(const blink::WebFormElement& form) {
1045 scoped_ptr<RendererSavePasswordProgressLogger> logger;
1046 if (logging_state_active_) {
1047 logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
1048 logger->LogMessage(Logger::STRING_WILL_SUBMIT_FORM_METHOD);
1049 LogHTMLForm(logger.get(), Logger::STRING_HTML_FORM_FOR_SUBMIT, form);
1052 scoped_ptr<PasswordForm> submitted_form =
1053 CreatePasswordForm(form, &nonscript_modified_values_, &form_predictions_);
1055 // If there is a provisionally saved password, copy over the previous
1056 // password value so we get the user's typed password, not the value that
1057 // may have been transformed for submit.
1058 // TODO(gcasto): Do we need to have this action equality check? Is it trying
1059 // to prevent accidentally copying over passwords from a different form?
1060 if (submitted_form) {
1061 if (logger) {
1062 logger->LogPasswordForm(Logger::STRING_CREATED_PASSWORD_FORM,
1063 *submitted_form);
1065 if (provisionally_saved_form_ &&
1066 submitted_form->action == provisionally_saved_form_->action) {
1067 if (logger)
1068 logger->LogMessage(Logger::STRING_SUBMITTED_PASSWORD_REPLACED);
1069 submitted_form->password_value =
1070 provisionally_saved_form_->password_value;
1071 submitted_form->new_password_value =
1072 provisionally_saved_form_->new_password_value;
1073 submitted_form->username_value =
1074 provisionally_saved_form_->username_value;
1077 // Some observers depend on sending this information now instead of when
1078 // the frame starts loading. If there are redirects that cause a new
1079 // RenderView to be instantiated (such as redirects to the WebStore)
1080 // we will never get to finish the load.
1081 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
1082 *submitted_form));
1083 provisionally_saved_form_.reset();
1084 } else if (logger) {
1085 logger->LogMessage(Logger::STRING_FORM_IS_NOT_PASSWORD);
1089 void PasswordAutofillAgent::LegacyDidStartProvisionalLoad(
1090 blink::WebLocalFrame* navigated_frame) {
1091 scoped_ptr<RendererSavePasswordProgressLogger> logger;
1092 if (logging_state_active_) {
1093 logger.reset(new RendererSavePasswordProgressLogger(this, routing_id()));
1094 logger->LogMessage(Logger::STRING_DID_START_PROVISIONAL_LOAD_METHOD);
1097 if (navigated_frame->parent()) {
1098 if (logger)
1099 logger->LogMessage(Logger::STRING_FRAME_NOT_MAIN_FRAME);
1100 return;
1103 // Bug fix for crbug.com/368690. isProcessingUserGesture() is false when
1104 // the user is performing actions outside the page (e.g. typed url,
1105 // history navigation). We don't want to trigger saving in these cases.
1106 content::DocumentState* document_state =
1107 content::DocumentState::FromDataSource(
1108 navigated_frame->provisionalDataSource());
1109 content::NavigationState* navigation_state =
1110 document_state->navigation_state();
1111 ui::PageTransition type = navigation_state->GetTransitionType();
1112 if (ui::PageTransitionIsWebTriggerable(type) &&
1113 ui::PageTransitionIsNewNavigation(type) &&
1114 !blink::WebUserGestureIndicator::isProcessingUserGesture()) {
1115 // If onsubmit has been called, try and save that form.
1116 if (provisionally_saved_form_) {
1117 if (logger) {
1118 logger->LogPasswordForm(
1119 Logger::STRING_PROVISIONALLY_SAVED_FORM_FOR_FRAME,
1120 *provisionally_saved_form_);
1122 Send(new AutofillHostMsg_PasswordFormSubmitted(
1123 routing_id(), *provisionally_saved_form_));
1124 provisionally_saved_form_.reset();
1125 } else {
1126 // Loop through the forms on the page looking for one that has been
1127 // filled out. If one exists, try and save the credentials.
1128 blink::WebVector<blink::WebFormElement> forms;
1129 render_frame()->GetWebFrame()->document().forms(forms);
1131 bool password_forms_found = false;
1132 for (size_t i = 0; i < forms.size(); ++i) {
1133 blink::WebFormElement form_element = forms[i];
1134 if (logger) {
1135 LogHTMLForm(logger.get(), Logger::STRING_FORM_FOUND_ON_PAGE,
1136 form_element);
1138 scoped_ptr<PasswordForm> password_form(CreatePasswordForm(
1139 form_element, &nonscript_modified_values_, &form_predictions_));
1140 if (password_form.get() && !password_form->username_value.empty() &&
1141 FormContainsNonDefaultPasswordValue(*password_form, form_element)) {
1142 password_forms_found = true;
1143 if (logger) {
1144 logger->LogPasswordForm(Logger::STRING_PASSWORD_FORM_FOUND_ON_PAGE,
1145 *password_form);
1147 Send(new AutofillHostMsg_PasswordFormSubmitted(routing_id(),
1148 *password_form));
1151 if (!password_forms_found && logger)
1152 logger->LogMessage(Logger::STRING_PASSWORD_FORM_NOT_FOUND_ON_PAGE);
1156 // This is a new navigation, so require a new user gesture before filling in
1157 // passwords.
1158 gatekeeper_.Reset();
1161 void PasswordAutofillAgent::OnFillPasswordForm(
1162 int key,
1163 const PasswordFormFillData& form_data) {
1165 FormElementsList forms;
1166 // We own the FormElements* in forms.
1167 FindFormElements(render_frame(), form_data, &forms);
1168 FormElementsList::iterator iter;
1169 for (iter = forms.begin(); iter != forms.end(); ++iter) {
1170 scoped_ptr<FormElements> form_elements(*iter);
1172 // Attach autocomplete listener to enable selecting alternate logins.
1173 blink::WebInputElement username_element, password_element;
1175 // Check whether the password form has a username input field.
1176 bool form_contains_username_field = FillDataContainsUsername(form_data);
1177 if (form_contains_username_field) {
1178 username_element =
1179 form_elements->input_elements[form_data.username_field.name];
1182 // No password field, bail out.
1183 if (form_data.password_field.name.empty())
1184 break;
1186 // We might have already filled this form if there are two <form> elements
1187 // with identical markup.
1188 if (login_to_password_info_.find(username_element) !=
1189 login_to_password_info_.end())
1190 continue;
1192 // Get pointer to password element. (We currently only support single
1193 // password forms).
1194 password_element =
1195 form_elements->input_elements[form_data.password_field.name];
1197 // If wait_for_username is true, we don't want to initially fill the form
1198 // until the user types in a valid username.
1199 if (!form_data.wait_for_username) {
1200 FillFormOnPasswordReceived(
1201 form_data,
1202 username_element,
1203 password_element,
1204 &nonscript_modified_values_,
1205 base::Bind(&PasswordValueGatekeeper::RegisterElement,
1206 base::Unretained(&gatekeeper_)));
1209 PasswordInfo password_info;
1210 password_info.fill_data = form_data;
1211 password_info.password_field = password_element;
1212 login_to_password_info_[username_element] = password_info;
1213 password_to_username_[password_element] = username_element;
1214 login_to_password_info_key_[username_element] = key;
1218 void PasswordAutofillAgent::OnSetLoggingState(bool active) {
1219 logging_state_active_ = active;
1222 void PasswordAutofillAgent::OnAutofillUsernameAndPasswordDataReceived(
1223 const FormsPredictionsMap& predictions) {
1224 form_predictions_ = predictions;
1227 void PasswordAutofillAgent::OnFindFocusedPasswordForm() {
1228 scoped_ptr<PasswordForm> password_form;
1230 blink::WebElement element = render_frame()->GetFocusedElement();
1231 if (!element.isNull() && element.hasHTMLTagName("input")) {
1232 blink::WebInputElement input = element.to<blink::WebInputElement>();
1233 if (input.isPasswordField() && !input.form().isNull()) {
1234 password_form = CreatePasswordForm(
1235 input.form(), &nonscript_modified_values_, &form_predictions_);
1239 if (!password_form.get())
1240 password_form.reset(new PasswordForm());
1242 Send(new AutofillHostMsg_FocusedPasswordFormFound(
1243 routing_id(), *password_form));
1246 ////////////////////////////////////////////////////////////////////////////////
1247 // PasswordAutofillAgent, private:
1249 PasswordAutofillAgent::PasswordInfo::PasswordInfo()
1250 : password_was_edited_last(false),
1251 username_was_edited(false) {
1254 bool PasswordAutofillAgent::ShowSuggestionPopup(
1255 const PasswordFormFillData& fill_data,
1256 const blink::WebInputElement& user_input,
1257 bool show_all,
1258 bool show_on_password_field) {
1259 DCHECK(!user_input.isNull());
1260 blink::WebFrame* frame = user_input.document().frame();
1261 if (!frame)
1262 return false;
1264 blink::WebView* webview = frame->view();
1265 if (!webview)
1266 return false;
1268 FormData form;
1269 FormFieldData field;
1270 FindFormAndFieldForFormControlElement(user_input, &form, &field);
1272 blink::WebInputElement selected_element = user_input;
1273 if (show_on_password_field && !selected_element.isPasswordField()) {
1274 LoginToPasswordInfoMap::const_iterator iter =
1275 login_to_password_info_.find(user_input);
1276 DCHECK(iter != login_to_password_info_.end());
1277 selected_element = iter->second.password_field;
1279 gfx::Rect bounding_box(selected_element.boundsInViewportSpace());
1281 blink::WebInputElement username;
1282 if (!show_on_password_field || !user_input.isPasswordField()) {
1283 username = user_input;
1285 LoginToPasswordInfoKeyMap::const_iterator key_it =
1286 login_to_password_info_key_.find(username);
1287 DCHECK(key_it != login_to_password_info_key_.end());
1289 float scale =
1290 render_frame()->GetRenderView()->GetWebView()->pageScaleFactor();
1291 gfx::RectF bounding_box_scaled(bounding_box.x() * scale,
1292 bounding_box.y() * scale,
1293 bounding_box.width() * scale,
1294 bounding_box.height() * scale);
1295 int options = 0;
1296 if (show_all)
1297 options |= SHOW_ALL;
1298 if (show_on_password_field)
1299 options |= IS_PASSWORD_FIELD;
1300 base::string16 username_string(
1301 username.isNull() ? base::string16()
1302 : static_cast<base::string16>(user_input.value()));
1303 Send(new AutofillHostMsg_ShowPasswordSuggestions(
1304 routing_id(), key_it->second, field.text_direction, username_string,
1305 options, bounding_box_scaled));
1306 username_query_prefix_ = username_string;
1307 return CanShowSuggestion(fill_data, username_string, show_all);
1310 void PasswordAutofillAgent::FrameClosing() {
1311 for (auto const& iter : login_to_password_info_) {
1312 login_to_password_info_key_.erase(iter.first);
1313 password_to_username_.erase(iter.second.password_field);
1315 login_to_password_info_.clear();
1316 provisionally_saved_form_.reset();
1317 nonscript_modified_values_.clear();
1320 bool PasswordAutofillAgent::FindLoginInfo(const blink::WebNode& node,
1321 blink::WebInputElement* found_input,
1322 PasswordInfo** found_password) {
1323 if (!node.isElementNode())
1324 return false;
1326 blink::WebElement element = node.toConst<blink::WebElement>();
1327 if (!element.hasHTMLTagName("input"))
1328 return false;
1330 *found_input = element.to<blink::WebInputElement>();
1331 const blink::WebInputElement* username_element; // ignored
1332 return FindPasswordInfoForElement(*found_input, &username_element,
1333 found_password);
1336 void PasswordAutofillAgent::ClearPreview(
1337 blink::WebInputElement* username,
1338 blink::WebInputElement* password) {
1339 if (!username->suggestedValue().isEmpty()) {
1340 username->setSuggestedValue(blink::WebString());
1341 username->setAutofilled(was_username_autofilled_);
1342 username->setSelectionRange(username_query_prefix_.length(),
1343 username->value().length());
1345 if (!password->suggestedValue().isEmpty()) {
1346 password->setSuggestedValue(blink::WebString());
1347 password->setAutofilled(was_password_autofilled_);
1351 void PasswordAutofillAgent::ProvisionallySavePassword(
1352 const blink::WebFormElement& form,
1353 ProvisionallySaveRestriction restriction) {
1354 scoped_ptr<PasswordForm> password_form(CreatePasswordForm(
1355 form, &nonscript_modified_values_, &form_predictions_));
1356 if (!password_form || (restriction == RESTRICTION_NON_EMPTY_PASSWORD &&
1357 password_form->password_value.empty() &&
1358 password_form->new_password_value.empty())) {
1359 return;
1361 provisionally_saved_form_ = password_form.Pass();
1364 bool PasswordAutofillAgent::ProvisionallySavedPasswordIsValid() {
1365 return provisionally_saved_form_ &&
1366 !provisionally_saved_form_->username_value.empty() &&
1367 !(provisionally_saved_form_->password_value.empty() &&
1368 provisionally_saved_form_->new_password_value.empty());
1371 // LegacyPasswordAutofillAgent -------------------------------------------------
1373 PasswordAutofillAgent::LegacyPasswordAutofillAgent::LegacyPasswordAutofillAgent(
1374 content::RenderView* render_view,
1375 PasswordAutofillAgent* agent)
1376 : content::RenderViewObserver(render_view), agent_(agent) {
1379 PasswordAutofillAgent::LegacyPasswordAutofillAgent::
1380 ~LegacyPasswordAutofillAgent() {
1383 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::OnDestruct() {
1384 // No op. Do not delete |this|.
1387 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStartLoading() {
1388 agent_->DidStartLoading();
1391 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::DidStopLoading() {
1392 agent_->DidStopLoading();
1395 void PasswordAutofillAgent::LegacyPasswordAutofillAgent::
1396 DidStartProvisionalLoad(blink::WebLocalFrame* navigated_frame) {
1397 agent_->LegacyDidStartProvisionalLoad(navigated_frame);
1400 } // namespace autofill