Move StartsWith[ASCII] to base namespace.
[chromium-blink-merge.git] / components / autofill / content / renderer / autofill_agent.cc
blobf73e5912deb79ab6a5edfedc389e73908c0eaaeb
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/autofill_agent.h"
7 #include "base/auto_reset.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/location.h"
11 #include "base/single_thread_task_runner.h"
12 #include "base/strings/string_split.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/thread_task_runner_handle.h"
16 #include "base/time/time.h"
17 #include "components/autofill/content/common/autofill_messages.h"
18 #include "components/autofill/content/renderer/form_autofill_util.h"
19 #include "components/autofill/content/renderer/page_click_tracker.h"
20 #include "components/autofill/content/renderer/password_autofill_agent.h"
21 #include "components/autofill/content/renderer/password_generation_agent.h"
22 #include "components/autofill/core/common/autofill_constants.h"
23 #include "components/autofill/core/common/autofill_data_validation.h"
24 #include "components/autofill/core/common/autofill_switches.h"
25 #include "components/autofill/core/common/form_data.h"
26 #include "components/autofill/core/common/form_data_predictions.h"
27 #include "components/autofill/core/common/form_field_data.h"
28 #include "components/autofill/core/common/password_form.h"
29 #include "components/autofill/core/common/web_element_descriptor.h"
30 #include "content/public/common/content_switches.h"
31 #include "content/public/common/ssl_status.h"
32 #include "content/public/common/url_constants.h"
33 #include "content/public/renderer/render_frame.h"
34 #include "content/public/renderer/render_view.h"
35 #include "net/cert/cert_status_flags.h"
36 #include "third_party/WebKit/public/platform/WebRect.h"
37 #include "third_party/WebKit/public/platform/WebURLRequest.h"
38 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
39 #include "third_party/WebKit/public/web/WebDataSource.h"
40 #include "third_party/WebKit/public/web/WebDocument.h"
41 #include "third_party/WebKit/public/web/WebElementCollection.h"
42 #include "third_party/WebKit/public/web/WebFormControlElement.h"
43 #include "third_party/WebKit/public/web/WebFormElement.h"
44 #include "third_party/WebKit/public/web/WebInputEvent.h"
45 #include "third_party/WebKit/public/web/WebLocalFrame.h"
46 #include "third_party/WebKit/public/web/WebNode.h"
47 #include "third_party/WebKit/public/web/WebOptionElement.h"
48 #include "third_party/WebKit/public/web/WebTextAreaElement.h"
49 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
50 #include "third_party/WebKit/public/web/WebView.h"
51 #include "ui/base/l10n/l10n_util.h"
52 #include "ui/events/keycodes/keyboard_codes.h"
54 using blink::WebAutofillClient;
55 using blink::WebConsoleMessage;
56 using blink::WebDocument;
57 using blink::WebElement;
58 using blink::WebElementCollection;
59 using blink::WebFormControlElement;
60 using blink::WebFormElement;
61 using blink::WebFrame;
62 using blink::WebInputElement;
63 using blink::WebKeyboardEvent;
64 using blink::WebLocalFrame;
65 using blink::WebNode;
66 using blink::WebOptionElement;
67 using blink::WebString;
68 using blink::WebTextAreaElement;
69 using blink::WebUserGestureIndicator;
70 using blink::WebVector;
72 namespace autofill {
74 namespace {
76 // Gets all the data list values (with corresponding label) for the given
77 // element.
78 void GetDataListSuggestions(const WebInputElement& element,
79 bool ignore_current_value,
80 std::vector<base::string16>* values,
81 std::vector<base::string16>* labels) {
82 WebElementCollection options = element.dataListOptions();
83 if (options.isNull())
84 return;
86 base::string16 prefix;
87 if (!ignore_current_value) {
88 prefix = element.editingValue();
89 if (element.isMultiple() && element.isEmailField()) {
90 std::vector<base::string16> parts;
91 base::SplitStringDontTrim(prefix, ',', &parts);
92 if (parts.size() > 0) {
93 base::TrimWhitespace(parts[parts.size() - 1], base::TRIM_LEADING,
94 &prefix);
98 for (WebOptionElement option = options.firstItem().to<WebOptionElement>();
99 !option.isNull(); option = options.nextItem().to<WebOptionElement>()) {
100 if (!base::StartsWith(option.value(), prefix, false) ||
101 option.value() == prefix || !element.isValidValue(option.value()))
102 continue;
104 values->push_back(option.value());
105 if (option.value() != option.label())
106 labels->push_back(option.label());
107 else
108 labels->push_back(base::string16());
112 // Trim the vector before sending it to the browser process to ensure we
113 // don't send too much data through the IPC.
114 void TrimStringVectorForIPC(std::vector<base::string16>* strings) {
115 // Limit the size of the vector.
116 if (strings->size() > kMaxListSize)
117 strings->resize(kMaxListSize);
119 // Limit the size of the strings in the vector.
120 for (size_t i = 0; i < strings->size(); ++i) {
121 if ((*strings)[i].length() > kMaxDataLength)
122 (*strings)[i].resize(kMaxDataLength);
126 // Extract FormData from the form element and return whether the operation was
127 // successful.
128 bool ExtractFormDataOnSave(const WebFormElement& form_element, FormData* data) {
129 return WebFormElementToFormData(
130 form_element, WebFormControlElement(),
131 static_cast<ExtractMask>(EXTRACT_VALUE | EXTRACT_OPTION_TEXT), data,
132 NULL);
135 } // namespace
137 AutofillAgent::ShowSuggestionsOptions::ShowSuggestionsOptions()
138 : autofill_on_empty_values(false),
139 requires_caret_at_end(false),
140 datalist_only(false),
141 show_full_suggestion_list(false),
142 show_password_suggestions_only(false) {
145 AutofillAgent::AutofillAgent(content::RenderFrame* render_frame,
146 PasswordAutofillAgent* password_autofill_agent,
147 PasswordGenerationAgent* password_generation_agent)
148 : content::RenderFrameObserver(render_frame),
149 form_cache_(*render_frame->GetWebFrame()),
150 password_autofill_agent_(password_autofill_agent),
151 password_generation_agent_(password_generation_agent),
152 legacy_(render_frame->GetRenderView(), this),
153 autofill_query_id_(0),
154 was_query_node_autofilled_(false),
155 has_shown_autofill_popup_for_current_edit_(false),
156 ignore_text_changes_(false),
157 is_popup_possibly_visible_(false),
158 weak_ptr_factory_(this) {
159 render_frame->GetWebFrame()->setAutofillClient(this);
161 // This owns itself, and will delete itself when |render_frame| is destructed
162 // (same as AutofillAgent).
163 new PageClickTracker(render_frame, this);
166 AutofillAgent::~AutofillAgent() {}
168 bool AutofillAgent::FormDataCompare::operator()(const FormData& lhs,
169 const FormData& rhs) const {
170 if (lhs.name != rhs.name)
171 return lhs.name < rhs.name;
172 if (lhs.origin != rhs.origin)
173 return lhs.origin < rhs.origin;
174 if (lhs.action != rhs.action)
175 return lhs.action < rhs.action;
176 if (lhs.is_form_tag != rhs.is_form_tag)
177 return lhs.is_form_tag < rhs.is_form_tag;
178 return lhs.fields < rhs.fields;
181 bool AutofillAgent::OnMessageReceived(const IPC::Message& message) {
182 bool handled = true;
183 IPC_BEGIN_MESSAGE_MAP(AutofillAgent, message)
184 IPC_MESSAGE_HANDLER(AutofillMsg_FirstUserGestureObservedInTab,
185 OnFirstUserGestureObservedInTab)
186 IPC_MESSAGE_HANDLER(AutofillMsg_Ping, OnPing)
187 IPC_MESSAGE_HANDLER(AutofillMsg_FillForm, OnFillForm)
188 IPC_MESSAGE_HANDLER(AutofillMsg_PreviewForm, OnPreviewForm)
189 IPC_MESSAGE_HANDLER(AutofillMsg_FieldTypePredictionsAvailable,
190 OnFieldTypePredictionsAvailable)
191 IPC_MESSAGE_HANDLER(AutofillMsg_ClearForm, OnClearForm)
192 IPC_MESSAGE_HANDLER(AutofillMsg_ClearPreviewedForm, OnClearPreviewedForm)
193 IPC_MESSAGE_HANDLER(AutofillMsg_FillFieldWithValue, OnFillFieldWithValue)
194 IPC_MESSAGE_HANDLER(AutofillMsg_PreviewFieldWithValue,
195 OnPreviewFieldWithValue)
196 IPC_MESSAGE_HANDLER(AutofillMsg_AcceptDataListSuggestion,
197 OnAcceptDataListSuggestion)
198 IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordSuggestion,
199 OnFillPasswordSuggestion)
200 IPC_MESSAGE_HANDLER(AutofillMsg_PreviewPasswordSuggestion,
201 OnPreviewPasswordSuggestion)
202 IPC_MESSAGE_HANDLER(AutofillMsg_RequestAutocompleteResult,
203 OnRequestAutocompleteResult)
204 IPC_MESSAGE_UNHANDLED(handled = false)
205 IPC_END_MESSAGE_MAP()
206 return handled;
209 void AutofillAgent::DidCommitProvisionalLoad(bool is_new_navigation,
210 bool is_same_page_navigation) {
211 form_cache_.Reset();
212 submitted_forms_.clear();
215 void AutofillAgent::DidFinishDocumentLoad() {
216 ProcessForms();
219 void AutofillAgent::WillSendSubmitEvent(const WebFormElement& form) {
220 FormData form_data;
221 if (!ExtractFormDataOnSave(form, &form_data))
222 return;
224 // The WillSendSubmitEvent function is called when there is a submit handler
225 // on the form, such as in the case of (but not restricted to)
226 // JavaScript-submitted forms. Sends a WillSubmitForm message to the browser
227 // and remembers for which form it did that in the current frame load, so that
228 // no additional message is sent if AutofillAgent::WillSubmitForm() is called
229 // (which is itself not guaranteed if the submit event is prevented by
230 // JavaScript).
231 Send(new AutofillHostMsg_WillSubmitForm(routing_id(), form_data,
232 base::TimeTicks::Now()));
233 submitted_forms_.insert(form_data);
236 void AutofillAgent::WillSubmitForm(const WebFormElement& form) {
237 FormData form_data;
238 if (!ExtractFormDataOnSave(form, &form_data))
239 return;
241 // If WillSubmitForm message had not been sent for this form, send it.
242 if (!submitted_forms_.count(form_data)) {
243 Send(new AutofillHostMsg_WillSubmitForm(routing_id(), form_data,
244 base::TimeTicks::Now()));
247 Send(new AutofillHostMsg_FormSubmitted(routing_id(), form_data));
250 void AutofillAgent::DidChangeScrollOffset() {
251 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
252 switches::kEnableAccessorySuggestionView)) {
253 return;
255 HidePopup();
258 void AutofillAgent::FocusedNodeChanged(const WebNode& node) {
259 HidePopup();
261 if (node.isNull() || !node.isElementNode())
262 return;
264 WebElement web_element = node.toConst<WebElement>();
265 const WebInputElement* element = toWebInputElement(&web_element);
267 if (!element || !element->isEnabled() || element->isReadOnly() ||
268 !element->isTextField())
269 return;
271 element_ = *element;
274 void AutofillAgent::FocusChangeComplete() {
275 WebDocument doc = render_frame()->GetWebFrame()->document();
276 WebElement focused_element;
277 if (!doc.isNull())
278 focused_element = doc.focusedElement();
280 if (!focused_element.isNull() && password_generation_agent_ &&
281 password_generation_agent_->FocusedNodeHasChanged(focused_element)) {
282 is_popup_possibly_visible_ = true;
286 void AutofillAgent::didRequestAutocomplete(
287 const WebFormElement& form) {
288 DCHECK_EQ(form.document().frame(), render_frame()->GetWebFrame());
290 // Disallow the dialog over non-https or broken https, except when the
291 // ignore SSL flag is passed. See http://crbug.com/272512.
292 // TODO(palmer): this should be moved to the browser process after frames
293 // get their own processes.
294 GURL url(form.document().url());
295 content::SSLStatus ssl_status =
296 render_frame()->GetRenderView()->GetSSLStatusOfFrame(
297 form.document().frame());
298 bool is_safe = url.SchemeIsCryptographic() &&
299 !net::IsCertStatusError(ssl_status.cert_status);
300 bool allow_unsafe = base::CommandLine::ForCurrentProcess()->HasSwitch(
301 ::switches::kReduceSecurityForTesting);
302 FormData form_data;
303 std::string error_message;
304 if (!in_flight_request_form_.isNull()) {
305 error_message = "already active.";
306 } else if (!is_safe && !allow_unsafe) {
307 error_message =
308 "must use a secure connection or --reduce-security-for-testing.";
309 } else if (!WebFormElementToFormData(form,
310 WebFormControlElement(),
311 static_cast<ExtractMask>(
312 EXTRACT_VALUE |
313 EXTRACT_OPTION_TEXT |
314 EXTRACT_OPTIONS),
315 &form_data,
316 NULL)) {
317 error_message = "failed to parse form.";
320 if (!error_message.empty()) {
321 WebConsoleMessage console_message = WebConsoleMessage(
322 WebConsoleMessage::LevelLog,
323 WebString(base::ASCIIToUTF16("requestAutocomplete: ") +
324 base::ASCIIToUTF16(error_message)));
325 form.document().frame()->addMessageToConsole(console_message);
326 WebFormElement(form).finishRequestAutocomplete(
327 WebFormElement::AutocompleteResultErrorDisabled);
328 return;
331 // Cancel any pending Autofill requests and hide any currently showing popups.
332 ++autofill_query_id_;
333 HidePopup();
335 in_flight_request_form_ = form;
336 Send(new AutofillHostMsg_RequestAutocomplete(routing_id(), form_data));
339 void AutofillAgent::setIgnoreTextChanges(bool ignore) {
340 ignore_text_changes_ = ignore;
343 void AutofillAgent::FormControlElementClicked(
344 const WebFormControlElement& element,
345 bool was_focused) {
346 // TODO(estade): Remove this check when PageClickTracker is per-frame.
347 if (element.document().frame() != render_frame()->GetWebFrame())
348 return;
350 const WebInputElement* input_element = toWebInputElement(&element);
351 if (!input_element && !IsTextAreaElement(element))
352 return;
354 ShowSuggestionsOptions options;
355 options.autofill_on_empty_values = true;
356 options.show_full_suggestion_list = element.isAutofilled();
358 // On Android, default to showing the dropdown on field focus.
359 // On desktop, require an extra click after field focus.
360 // See http://crbug.com/427660
361 #if defined(OS_ANDROID)
362 bool single_click_autofill =
363 !base::CommandLine::ForCurrentProcess()->HasSwitch(
364 switches::kDisableSingleClickAutofill);
365 #else
366 bool single_click_autofill =
367 base::CommandLine::ForCurrentProcess()->HasSwitch(
368 switches::kEnableSingleClickAutofill);
369 #endif
371 if (!single_click_autofill) {
372 // Show full suggestions when clicking on an already-focused form field. On
373 // the initial click (not focused yet), only show password suggestions.
374 options.show_full_suggestion_list =
375 options.show_full_suggestion_list || was_focused;
376 options.show_password_suggestions_only = !was_focused;
378 ShowSuggestions(element, options);
381 void AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {
382 password_autofill_agent_->TextFieldDidEndEditing(element);
383 has_shown_autofill_popup_for_current_edit_ = false;
384 Send(new AutofillHostMsg_DidEndTextFieldEditing(routing_id()));
387 void AutofillAgent::textFieldDidChange(const WebFormControlElement& element) {
388 DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
389 if (ignore_text_changes_)
390 return;
392 if (!IsUserGesture())
393 return;
395 // We post a task for doing the Autofill as the caret position is not set
396 // properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and
397 // it is needed to trigger autofill.
398 weak_ptr_factory_.InvalidateWeakPtrs();
399 base::ThreadTaskRunnerHandle::Get()->PostTask(
400 FROM_HERE, base::Bind(&AutofillAgent::TextFieldDidChangeImpl,
401 weak_ptr_factory_.GetWeakPtr(), element));
404 void AutofillAgent::TextFieldDidChangeImpl(
405 const WebFormControlElement& element) {
406 // If the element isn't focused then the changes don't matter. This check is
407 // required to properly handle IME interactions.
408 if (!element.focused())
409 return;
411 const WebInputElement* input_element = toWebInputElement(&element);
412 if (input_element) {
413 // |password_autofill_agent_| keeps track of all text changes even if
414 // it isn't displaying UI.
415 password_autofill_agent_->UpdateStateForTextChange(*input_element);
417 if (password_generation_agent_ &&
418 password_generation_agent_->TextDidChangeInTextField(*input_element)) {
419 is_popup_possibly_visible_ = true;
420 return;
423 if (password_autofill_agent_->TextDidChangeInTextField(*input_element)) {
424 is_popup_possibly_visible_ = true;
425 element_ = element;
426 return;
430 ShowSuggestionsOptions options;
431 options.requires_caret_at_end = true;
432 ShowSuggestions(element, options);
434 FormData form;
435 FormFieldData field;
436 if (FindFormAndFieldForFormControlElement(element, &form, &field)) {
437 Send(new AutofillHostMsg_TextFieldDidChange(routing_id(), form, field,
438 base::TimeTicks::Now()));
442 void AutofillAgent::textFieldDidReceiveKeyDown(const WebInputElement& element,
443 const WebKeyboardEvent& event) {
444 if (password_autofill_agent_->TextFieldHandlingKeyDown(element, event)) {
445 element_ = element;
446 return;
449 if (event.windowsKeyCode == ui::VKEY_DOWN ||
450 event.windowsKeyCode == ui::VKEY_UP) {
451 ShowSuggestionsOptions options;
452 options.autofill_on_empty_values = true;
453 options.requires_caret_at_end = true;
454 ShowSuggestions(element, options);
458 void AutofillAgent::openTextDataListChooser(const WebInputElement& element) {
459 ShowSuggestionsOptions options;
460 options.autofill_on_empty_values = true;
461 options.datalist_only = true;
462 ShowSuggestions(element, options);
465 void AutofillAgent::dataListOptionsChanged(const WebInputElement& element) {
466 if (!is_popup_possibly_visible_ || !element.focused())
467 return;
469 TextFieldDidChangeImpl(element);
472 void AutofillAgent::firstUserGestureObserved() {
473 password_autofill_agent_->FirstUserGestureObserved();
474 Send(new AutofillHostMsg_FirstUserGestureObserved(routing_id()));
477 void AutofillAgent::AcceptDataListSuggestion(
478 const base::string16& suggested_value) {
479 WebInputElement* input_element = toWebInputElement(&element_);
480 DCHECK(input_element);
481 base::string16 new_value = suggested_value;
482 // If this element takes multiple values then replace the last part with
483 // the suggestion.
484 if (input_element->isMultiple() && input_element->isEmailField()) {
485 std::vector<base::string16> parts;
487 base::SplitStringDontTrim(input_element->editingValue(), ',', &parts);
488 if (parts.size() == 0)
489 parts.push_back(base::string16());
491 base::string16 last_part = parts.back();
492 // We want to keep just the leading whitespace.
493 for (size_t i = 0; i < last_part.size(); ++i) {
494 if (!IsWhitespace(last_part[i])) {
495 last_part = last_part.substr(0, i);
496 break;
499 last_part.append(suggested_value);
500 parts[parts.size() - 1] = last_part;
502 new_value = JoinString(parts, ',');
504 FillFieldWithValue(new_value, input_element);
507 void AutofillAgent::OnFieldTypePredictionsAvailable(
508 const std::vector<FormDataPredictions>& forms) {
509 for (size_t i = 0; i < forms.size(); ++i) {
510 form_cache_.ShowPredictions(forms[i]);
514 void AutofillAgent::OnFillForm(int query_id, const FormData& form) {
515 if (query_id != autofill_query_id_)
516 return;
518 was_query_node_autofilled_ = element_.isAutofilled();
519 FillForm(form, element_);
520 Send(new AutofillHostMsg_DidFillAutofillFormData(routing_id(),
521 base::TimeTicks::Now()));
524 void AutofillAgent::OnFirstUserGestureObservedInTab() {
525 password_autofill_agent_->FirstUserGestureObserved();
528 void AutofillAgent::OnPing() {
529 Send(new AutofillHostMsg_PingAck(routing_id()));
532 void AutofillAgent::OnPreviewForm(int query_id, const FormData& form) {
533 if (query_id != autofill_query_id_)
534 return;
536 was_query_node_autofilled_ = element_.isAutofilled();
537 PreviewForm(form, element_);
538 Send(new AutofillHostMsg_DidPreviewAutofillFormData(routing_id()));
541 void AutofillAgent::OnClearForm() {
542 form_cache_.ClearFormWithElement(element_);
545 void AutofillAgent::OnClearPreviewedForm() {
546 if (!element_.isNull()) {
547 if (password_autofill_agent_->DidClearAutofillSelection(element_))
548 return;
550 ClearPreviewedFormWithElement(element_, was_query_node_autofilled_);
551 } else {
552 // TODO(isherman): There seem to be rare cases where this code *is*
553 // reachable: see [ http://crbug.com/96321#c6 ]. Ideally we would
554 // understand those cases and fix the code to avoid them. However, so far I
555 // have been unable to reproduce such a case locally. If you hit this
556 // NOTREACHED(), please file a bug against me.
557 NOTREACHED();
561 void AutofillAgent::OnFillFieldWithValue(const base::string16& value) {
562 WebInputElement* input_element = toWebInputElement(&element_);
563 if (input_element) {
564 FillFieldWithValue(value, input_element);
565 input_element->setAutofilled(true);
569 void AutofillAgent::OnPreviewFieldWithValue(const base::string16& value) {
570 WebInputElement* input_element = toWebInputElement(&element_);
571 if (input_element)
572 PreviewFieldWithValue(value, input_element);
575 void AutofillAgent::OnAcceptDataListSuggestion(const base::string16& value) {
576 AcceptDataListSuggestion(value);
579 void AutofillAgent::OnFillPasswordSuggestion(const base::string16& username,
580 const base::string16& password) {
581 bool handled = password_autofill_agent_->FillSuggestion(
582 element_,
583 username,
584 password);
585 DCHECK(handled);
588 void AutofillAgent::OnPreviewPasswordSuggestion(
589 const base::string16& username,
590 const base::string16& password) {
591 bool handled = password_autofill_agent_->PreviewSuggestion(
592 element_,
593 username,
594 password);
595 DCHECK(handled);
598 void AutofillAgent::OnRequestAutocompleteResult(
599 WebFormElement::AutocompleteResult result,
600 const base::string16& message,
601 const FormData& form_data) {
602 if (in_flight_request_form_.isNull())
603 return;
605 if (result == WebFormElement::AutocompleteResultSuccess) {
606 FillFormIncludingNonFocusableElements(form_data, in_flight_request_form_);
607 if (!in_flight_request_form_.checkValidity())
608 result = WebFormElement::AutocompleteResultErrorInvalid;
611 in_flight_request_form_.finishRequestAutocomplete(result);
613 if (!message.empty()) {
614 const base::string16 prefix(base::ASCIIToUTF16("requestAutocomplete: "));
615 WebConsoleMessage console_message = WebConsoleMessage(
616 WebConsoleMessage::LevelLog, WebString(prefix + message));
617 in_flight_request_form_.document().frame()->addMessageToConsole(
618 console_message);
621 in_flight_request_form_.reset();
624 void AutofillAgent::ShowSuggestions(const WebFormControlElement& element,
625 const ShowSuggestionsOptions& options) {
626 if (!element.isEnabled() || element.isReadOnly())
627 return;
628 if (!options.datalist_only && !element.suggestedValue().isEmpty())
629 return;
631 const WebInputElement* input_element = toWebInputElement(&element);
632 if (input_element) {
633 if (!input_element->isTextField())
634 return;
635 if (!options.datalist_only && !input_element->suggestedValue().isEmpty())
636 return;
637 } else {
638 DCHECK(IsTextAreaElement(element));
639 if (!element.toConst<WebTextAreaElement>().suggestedValue().isEmpty())
640 return;
643 // Don't attempt to autofill with values that are too large or if filling
644 // criteria are not met.
645 WebString value = element.editingValue();
646 if (!options.datalist_only &&
647 (value.length() > kMaxDataLength ||
648 (!options.autofill_on_empty_values && value.isEmpty()) ||
649 (options.requires_caret_at_end &&
650 (element.selectionStart() != element.selectionEnd() ||
651 element.selectionEnd() != static_cast<int>(value.length()))))) {
652 // Any popup currently showing is obsolete.
653 HidePopup();
654 return;
657 element_ = element;
658 if (IsAutofillableInputElement(input_element) &&
659 (password_autofill_agent_->ShowSuggestions(
660 *input_element, options.show_full_suggestion_list) ||
661 options.show_password_suggestions_only)) {
662 is_popup_possibly_visible_ = true;
663 return;
666 // Password field elements should only have suggestions shown by the password
667 // autofill agent.
668 if (input_element && input_element->isPasswordField())
669 return;
671 QueryAutofillSuggestions(element, options.datalist_only);
674 void AutofillAgent::QueryAutofillSuggestions(
675 const WebFormControlElement& element,
676 bool datalist_only) {
677 if (!element.document().frame())
678 return;
680 DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
682 static int query_counter = 0;
683 autofill_query_id_ = query_counter++;
685 FormData form;
686 FormFieldData field;
687 if (!FindFormAndFieldForFormControlElement(element, &form, &field)) {
688 // If we didn't find the cached form, at least let autocomplete have a shot
689 // at providing suggestions.
690 WebFormControlElementToFormField(element, EXTRACT_VALUE, &field);
692 if (datalist_only)
693 field.should_autocomplete = false;
695 gfx::RectF bounding_box_scaled = GetScaledBoundingBox(
696 render_frame()->GetRenderView()->GetWebView()->pageScaleFactor(),
697 &element_);
699 std::vector<base::string16> data_list_values;
700 std::vector<base::string16> data_list_labels;
701 const WebInputElement* input_element = toWebInputElement(&element);
702 if (input_element) {
703 // Find the datalist values and send them to the browser process.
704 GetDataListSuggestions(*input_element,
705 datalist_only,
706 &data_list_values,
707 &data_list_labels);
708 TrimStringVectorForIPC(&data_list_values);
709 TrimStringVectorForIPC(&data_list_labels);
712 is_popup_possibly_visible_ = true;
713 Send(new AutofillHostMsg_SetDataList(routing_id(),
714 data_list_values,
715 data_list_labels));
717 Send(new AutofillHostMsg_QueryFormFieldAutofill(
718 routing_id(), autofill_query_id_, form, field, bounding_box_scaled));
721 void AutofillAgent::FillFieldWithValue(const base::string16& value,
722 WebInputElement* node) {
723 base::AutoReset<bool> auto_reset(&ignore_text_changes_, true);
724 node->setEditingValue(value.substr(0, node->maxLength()));
727 void AutofillAgent::PreviewFieldWithValue(const base::string16& value,
728 WebInputElement* node) {
729 was_query_node_autofilled_ = element_.isAutofilled();
730 node->setSuggestedValue(value.substr(0, node->maxLength()));
731 node->setAutofilled(true);
732 node->setSelectionRange(node->value().length(),
733 node->suggestedValue().length());
736 void AutofillAgent::ProcessForms() {
737 // Record timestamp of when the forms are first seen. This is used to
738 // measure the overhead of the Autofill feature.
739 base::TimeTicks forms_seen_timestamp = base::TimeTicks::Now();
741 WebLocalFrame* frame = render_frame()->GetWebFrame();
742 std::vector<FormData> forms = form_cache_.ExtractNewForms();
744 // Always communicate to browser process for topmost frame.
745 if (!forms.empty() || !frame->parent()) {
746 Send(new AutofillHostMsg_FormsSeen(routing_id(), forms,
747 forms_seen_timestamp));
751 void AutofillAgent::HidePopup() {
752 if (!is_popup_possibly_visible_)
753 return;
754 is_popup_possibly_visible_ = false;
755 Send(new AutofillHostMsg_HidePopup(routing_id()));
758 bool AutofillAgent::IsUserGesture() const {
759 return WebUserGestureIndicator::isProcessingUserGesture();
762 void AutofillAgent::didAssociateFormControls(const WebVector<WebNode>& nodes) {
763 for (size_t i = 0; i < nodes.size(); ++i) {
764 WebLocalFrame* frame = nodes[i].document().frame();
765 // Only monitors dynamic forms created in the top frame. Dynamic forms
766 // inserted in iframes are not captured yet. Frame is only processed
767 // if it has finished loading, otherwise you can end up with a partially
768 // parsed form.
769 if (frame && !frame->isLoading()) {
770 ProcessForms();
771 password_autofill_agent_->OnDynamicFormsSeen();
772 if (password_generation_agent_)
773 password_generation_agent_->OnDynamicFormsSeen();
774 return;
779 void AutofillAgent::xhrSucceeded() {
780 password_autofill_agent_->XHRSucceeded();
783 // LegacyAutofillAgent ---------------------------------------------------------
785 AutofillAgent::LegacyAutofillAgent::LegacyAutofillAgent(
786 content::RenderView* render_view,
787 AutofillAgent* agent)
788 : content::RenderViewObserver(render_view), agent_(agent) {
791 AutofillAgent::LegacyAutofillAgent::~LegacyAutofillAgent() {
794 void AutofillAgent::LegacyAutofillAgent::OnDestruct() {
795 // No-op. Don't delete |this|.
798 void AutofillAgent::LegacyAutofillAgent::FocusChangeComplete() {
799 agent_->FocusChangeComplete();
802 } // namespace autofill