ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / components / autofill / content / renderer / autofill_agent.cc
blob25f63ef7d69a0fdbe37d3400ef4d75b37e34b559
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/bind.h"
8 #include "base/command_line.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/strings/string_split.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/time/time.h"
14 #include "components/autofill/content/common/autofill_messages.h"
15 #include "components/autofill/content/renderer/form_autofill_util.h"
16 #include "components/autofill/content/renderer/page_click_tracker.h"
17 #include "components/autofill/content/renderer/password_autofill_agent.h"
18 #include "components/autofill/content/renderer/password_generation_agent.h"
19 #include "components/autofill/core/common/autofill_constants.h"
20 #include "components/autofill/core/common/autofill_data_validation.h"
21 #include "components/autofill/core/common/autofill_switches.h"
22 #include "components/autofill/core/common/form_data.h"
23 #include "components/autofill/core/common/form_data_predictions.h"
24 #include "components/autofill/core/common/form_field_data.h"
25 #include "components/autofill/core/common/password_form.h"
26 #include "components/autofill/core/common/web_element_descriptor.h"
27 #include "content/public/common/content_switches.h"
28 #include "content/public/common/ssl_status.h"
29 #include "content/public/common/url_constants.h"
30 #include "content/public/renderer/render_frame.h"
31 #include "content/public/renderer/render_view.h"
32 #include "net/cert/cert_status_flags.h"
33 #include "third_party/WebKit/public/platform/WebRect.h"
34 #include "third_party/WebKit/public/platform/WebURLRequest.h"
35 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
36 #include "third_party/WebKit/public/web/WebDataSource.h"
37 #include "third_party/WebKit/public/web/WebDocument.h"
38 #include "third_party/WebKit/public/web/WebElementCollection.h"
39 #include "third_party/WebKit/public/web/WebFormControlElement.h"
40 #include "third_party/WebKit/public/web/WebFormElement.h"
41 #include "third_party/WebKit/public/web/WebInputEvent.h"
42 #include "third_party/WebKit/public/web/WebLocalFrame.h"
43 #include "third_party/WebKit/public/web/WebNode.h"
44 #include "third_party/WebKit/public/web/WebOptionElement.h"
45 #include "third_party/WebKit/public/web/WebTextAreaElement.h"
46 #include "third_party/WebKit/public/web/WebView.h"
47 #include "ui/base/l10n/l10n_util.h"
48 #include "ui/events/keycodes/keyboard_codes.h"
50 using blink::WebAutofillClient;
51 using blink::WebConsoleMessage;
52 using blink::WebDocument;
53 using blink::WebElement;
54 using blink::WebElementCollection;
55 using blink::WebFormControlElement;
56 using blink::WebFormElement;
57 using blink::WebFrame;
58 using blink::WebInputElement;
59 using blink::WebKeyboardEvent;
60 using blink::WebLocalFrame;
61 using blink::WebNode;
62 using blink::WebOptionElement;
63 using blink::WebString;
64 using blink::WebTextAreaElement;
65 using blink::WebVector;
67 namespace autofill {
69 namespace {
71 // Gets all the data list values (with corresponding label) for the given
72 // element.
73 void GetDataListSuggestions(const WebInputElement& element,
74 bool ignore_current_value,
75 std::vector<base::string16>* values,
76 std::vector<base::string16>* labels) {
77 WebElementCollection options = element.dataListOptions();
78 if (options.isNull())
79 return;
81 base::string16 prefix;
82 if (!ignore_current_value) {
83 prefix = element.editingValue();
84 if (element.isMultiple() && element.isEmailField()) {
85 std::vector<base::string16> parts;
86 base::SplitStringDontTrim(prefix, ',', &parts);
87 if (parts.size() > 0) {
88 base::TrimWhitespace(parts[parts.size() - 1], base::TRIM_LEADING,
89 &prefix);
93 for (WebOptionElement option = options.firstItem().to<WebOptionElement>();
94 !option.isNull(); option = options.nextItem().to<WebOptionElement>()) {
95 if (!StartsWith(option.value(), prefix, false) ||
96 option.value() == prefix ||
97 !element.isValidValue(option.value()))
98 continue;
100 values->push_back(option.value());
101 if (option.value() != option.label())
102 labels->push_back(option.label());
103 else
104 labels->push_back(base::string16());
108 // Trim the vector before sending it to the browser process to ensure we
109 // don't send too much data through the IPC.
110 void TrimStringVectorForIPC(std::vector<base::string16>* strings) {
111 // Limit the size of the vector.
112 if (strings->size() > kMaxListSize)
113 strings->resize(kMaxListSize);
115 // Limit the size of the strings in the vector.
116 for (size_t i = 0; i < strings->size(); ++i) {
117 if ((*strings)[i].length() > kMaxDataLength)
118 (*strings)[i].resize(kMaxDataLength);
122 } // namespace
124 AutofillAgent::ShowSuggestionsOptions::ShowSuggestionsOptions()
125 : autofill_on_empty_values(false),
126 requires_caret_at_end(false),
127 display_warning_if_disabled(false),
128 datalist_only(false),
129 show_full_suggestion_list(false),
130 show_password_suggestions_only(false) {
133 AutofillAgent::AutofillAgent(content::RenderFrame* render_frame,
134 PasswordAutofillAgent* password_autofill_agent,
135 PasswordGenerationAgent* password_generation_agent)
136 : content::RenderFrameObserver(render_frame),
137 form_cache_(*render_frame->GetWebFrame()),
138 password_autofill_agent_(password_autofill_agent),
139 password_generation_agent_(password_generation_agent),
140 legacy_(render_frame->GetRenderView(), this),
141 autofill_query_id_(0),
142 display_warning_if_disabled_(false),
143 was_query_node_autofilled_(false),
144 has_shown_autofill_popup_for_current_edit_(false),
145 did_set_node_text_(false),
146 ignore_text_changes_(false),
147 is_popup_possibly_visible_(false),
148 weak_ptr_factory_(this) {
149 render_frame->GetWebFrame()->setAutofillClient(this);
151 // This owns itself, and will delete itself when |render_frame| is destructed
152 // (same as AutofillAgent).
153 new PageClickTracker(render_frame, this);
156 AutofillAgent::~AutofillAgent() {}
158 bool AutofillAgent::OnMessageReceived(const IPC::Message& message) {
159 bool handled = true;
160 IPC_BEGIN_MESSAGE_MAP(AutofillAgent, message)
161 IPC_MESSAGE_HANDLER(AutofillMsg_FirstUserGestureObservedInTab,
162 OnFirstUserGestureObservedInTab)
163 IPC_MESSAGE_HANDLER(AutofillMsg_Ping, OnPing)
164 IPC_MESSAGE_HANDLER(AutofillMsg_FillForm, OnFillForm)
165 IPC_MESSAGE_HANDLER(AutofillMsg_PreviewForm, OnPreviewForm)
166 IPC_MESSAGE_HANDLER(AutofillMsg_FieldTypePredictionsAvailable,
167 OnFieldTypePredictionsAvailable)
168 IPC_MESSAGE_HANDLER(AutofillMsg_ClearForm, OnClearForm)
169 IPC_MESSAGE_HANDLER(AutofillMsg_ClearPreviewedForm, OnClearPreviewedForm)
170 IPC_MESSAGE_HANDLER(AutofillMsg_FillFieldWithValue, OnFillFieldWithValue)
171 IPC_MESSAGE_HANDLER(AutofillMsg_PreviewFieldWithValue,
172 OnPreviewFieldWithValue)
173 IPC_MESSAGE_HANDLER(AutofillMsg_AcceptDataListSuggestion,
174 OnAcceptDataListSuggestion)
175 IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordSuggestion,
176 OnFillPasswordSuggestion)
177 IPC_MESSAGE_HANDLER(AutofillMsg_PreviewPasswordSuggestion,
178 OnPreviewPasswordSuggestion)
179 IPC_MESSAGE_HANDLER(AutofillMsg_RequestAutocompleteResult,
180 OnRequestAutocompleteResult)
181 IPC_MESSAGE_UNHANDLED(handled = false)
182 IPC_END_MESSAGE_MAP()
183 return handled;
186 void AutofillAgent::DidCommitProvisionalLoad(bool is_new_navigation,
187 bool is_same_page_navigation) {
188 form_cache_.Reset();
191 void AutofillAgent::DidFinishDocumentLoad() {
192 ProcessForms();
195 void AutofillAgent::WillSubmitForm(const WebFormElement& form) {
196 FormData form_data;
197 if (WebFormElementToFormData(form,
198 WebFormControlElement(),
199 REQUIRE_NONE,
200 static_cast<ExtractMask>(
201 EXTRACT_VALUE | EXTRACT_OPTION_TEXT),
202 &form_data,
203 NULL)) {
204 Send(new AutofillHostMsg_FormSubmitted(routing_id(), form_data,
205 base::TimeTicks::Now()));
209 void AutofillAgent::DidChangeScrollOffset() {
210 HidePopup();
213 void AutofillAgent::FocusedNodeChanged(const WebNode& node) {
214 HidePopup();
216 if (node.isNull() || !node.isElementNode())
217 return;
219 WebElement web_element = node.toConst<WebElement>();
220 const WebInputElement* element = toWebInputElement(&web_element);
222 if (!element || !element->isEnabled() || element->isReadOnly() ||
223 !element->isTextField())
224 return;
226 element_ = *element;
229 void AutofillAgent::FocusChangeComplete() {
230 WebDocument doc = render_frame()->GetWebFrame()->document();
231 WebElement focused_element;
232 if (!doc.isNull())
233 focused_element = doc.focusedElement();
235 if (!focused_element.isNull() && password_generation_agent_ &&
236 password_generation_agent_->FocusedNodeHasChanged(focused_element)) {
237 is_popup_possibly_visible_ = true;
241 void AutofillAgent::didRequestAutocomplete(
242 const WebFormElement& form) {
243 DCHECK_EQ(form.document().frame(), render_frame()->GetWebFrame());
245 // Disallow the dialog over non-https or broken https, except when the
246 // ignore SSL flag is passed. See http://crbug.com/272512.
247 // TODO(palmer): this should be moved to the browser process after frames
248 // get their own processes.
249 GURL url(form.document().url());
250 content::SSLStatus ssl_status =
251 render_frame()->GetRenderView()->GetSSLStatusOfFrame(
252 form.document().frame());
253 bool is_safe = url.SchemeIs(url::kHttpsScheme) &&
254 !net::IsCertStatusError(ssl_status.cert_status);
255 bool allow_unsafe = base::CommandLine::ForCurrentProcess()->HasSwitch(
256 ::switches::kReduceSecurityForTesting);
257 FormData form_data;
258 std::string error_message;
259 if (!in_flight_request_form_.isNull()) {
260 error_message = "already active.";
261 } else if (!is_safe && !allow_unsafe) {
262 error_message =
263 "must use a secure connection or --reduce-security-for-testing.";
264 } else if (!WebFormElementToFormData(form,
265 WebFormControlElement(),
266 REQUIRE_AUTOCOMPLETE,
267 static_cast<ExtractMask>(
268 EXTRACT_VALUE |
269 EXTRACT_OPTION_TEXT |
270 EXTRACT_OPTIONS),
271 &form_data,
272 NULL)) {
273 error_message = "failed to parse form.";
276 if (!error_message.empty()) {
277 WebConsoleMessage console_message = WebConsoleMessage(
278 WebConsoleMessage::LevelLog,
279 WebString(base::ASCIIToUTF16("requestAutocomplete: ") +
280 base::ASCIIToUTF16(error_message)));
281 form.document().frame()->addMessageToConsole(console_message);
282 WebFormElement(form).finishRequestAutocomplete(
283 WebFormElement::AutocompleteResultErrorDisabled);
284 return;
287 // Cancel any pending Autofill requests and hide any currently showing popups.
288 ++autofill_query_id_;
289 HidePopup();
291 in_flight_request_form_ = form;
292 Send(new AutofillHostMsg_RequestAutocomplete(routing_id(), form_data));
295 void AutofillAgent::setIgnoreTextChanges(bool ignore) {
296 ignore_text_changes_ = ignore;
299 void AutofillAgent::FormControlElementClicked(
300 const WebFormControlElement& element,
301 bool was_focused) {
302 // TODO(estade): Remove this check when PageClickTracker is per-frame.
303 if (element.document().frame() != render_frame()->GetWebFrame())
304 return;
306 const WebInputElement* input_element = toWebInputElement(&element);
307 if (!input_element && !IsTextAreaElement(element))
308 return;
310 ShowSuggestionsOptions options;
311 options.autofill_on_empty_values = true;
312 options.display_warning_if_disabled = true;
313 options.show_full_suggestion_list = element.isAutofilled();
315 // On Android, default to showing the dropdown on field focus.
316 // On desktop, require an extra click after field focus.
317 // See http://crbug.com/427660
318 #if defined(OS_ANDROID)
319 bool single_click_autofill =
320 !base::CommandLine::ForCurrentProcess()->HasSwitch(
321 switches::kDisableSingleClickAutofill);
322 #else
323 bool single_click_autofill =
324 base::CommandLine::ForCurrentProcess()->HasSwitch(
325 switches::kEnableSingleClickAutofill);
326 #endif
328 if (!single_click_autofill) {
329 // Show full suggestions when clicking on an already-focused form field. On
330 // the initial click (not focused yet), only show password suggestions.
331 options.show_full_suggestion_list =
332 options.show_full_suggestion_list || was_focused;
333 options.show_password_suggestions_only = !was_focused;
335 ShowSuggestions(element, options);
338 void AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {
339 password_autofill_agent_->TextFieldDidEndEditing(element);
340 has_shown_autofill_popup_for_current_edit_ = false;
341 Send(new AutofillHostMsg_DidEndTextFieldEditing(routing_id()));
344 void AutofillAgent::textFieldDidChange(const WebFormControlElement& element) {
345 if (ignore_text_changes_)
346 return;
348 DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
350 if (did_set_node_text_) {
351 did_set_node_text_ = false;
352 return;
355 // We post a task for doing the Autofill as the caret position is not set
356 // properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and
357 // it is needed to trigger autofill.
358 weak_ptr_factory_.InvalidateWeakPtrs();
359 base::MessageLoop::current()->PostTask(
360 FROM_HERE,
361 base::Bind(&AutofillAgent::TextFieldDidChangeImpl,
362 weak_ptr_factory_.GetWeakPtr(),
363 element));
366 void AutofillAgent::TextFieldDidChangeImpl(
367 const WebFormControlElement& element) {
368 // If the element isn't focused then the changes don't matter. This check is
369 // required to properly handle IME interactions.
370 if (!element.focused())
371 return;
373 const WebInputElement* input_element = toWebInputElement(&element);
374 if (input_element) {
375 if (password_generation_agent_ &&
376 password_generation_agent_->TextDidChangeInTextField(*input_element)) {
377 is_popup_possibly_visible_ = true;
378 return;
381 if (password_autofill_agent_->TextDidChangeInTextField(*input_element)) {
382 is_popup_possibly_visible_ = true;
383 element_ = element;
384 return;
388 ShowSuggestionsOptions options;
389 options.requires_caret_at_end = true;
390 ShowSuggestions(element, options);
392 FormData form;
393 FormFieldData field;
394 if (FindFormAndFieldForFormControlElement(element,
395 &form,
396 &field,
397 REQUIRE_NONE)) {
398 Send(new AutofillHostMsg_TextFieldDidChange(routing_id(), form, field,
399 base::TimeTicks::Now()));
403 void AutofillAgent::textFieldDidReceiveKeyDown(const WebInputElement& element,
404 const WebKeyboardEvent& event) {
405 if (password_autofill_agent_->TextFieldHandlingKeyDown(element, event)) {
406 element_ = element;
407 return;
410 if (event.windowsKeyCode == ui::VKEY_DOWN ||
411 event.windowsKeyCode == ui::VKEY_UP) {
412 ShowSuggestionsOptions options;
413 options.autofill_on_empty_values = true;
414 options.requires_caret_at_end = true;
415 options.display_warning_if_disabled = true;
416 ShowSuggestions(element, options);
420 void AutofillAgent::openTextDataListChooser(const WebInputElement& element) {
421 ShowSuggestionsOptions options;
422 options.autofill_on_empty_values = true;
423 options.datalist_only = true;
424 ShowSuggestions(element, options);
427 void AutofillAgent::dataListOptionsChanged(const WebInputElement& element) {
428 if (!is_popup_possibly_visible_ || !element.focused())
429 return;
431 TextFieldDidChangeImpl(element);
434 void AutofillAgent::firstUserGestureObserved() {
435 password_autofill_agent_->FirstUserGestureObserved();
436 Send(new AutofillHostMsg_FirstUserGestureObserved(routing_id()));
439 void AutofillAgent::AcceptDataListSuggestion(
440 const base::string16& suggested_value) {
441 WebInputElement* input_element = toWebInputElement(&element_);
442 DCHECK(input_element);
443 base::string16 new_value = suggested_value;
444 // If this element takes multiple values then replace the last part with
445 // the suggestion.
446 if (input_element->isMultiple() && input_element->isEmailField()) {
447 std::vector<base::string16> parts;
449 base::SplitStringDontTrim(input_element->editingValue(), ',', &parts);
450 if (parts.size() == 0)
451 parts.push_back(base::string16());
453 base::string16 last_part = parts.back();
454 // We want to keep just the leading whitespace.
455 for (size_t i = 0; i < last_part.size(); ++i) {
456 if (!IsWhitespace(last_part[i])) {
457 last_part = last_part.substr(0, i);
458 break;
461 last_part.append(suggested_value);
462 parts[parts.size() - 1] = last_part;
464 new_value = JoinString(parts, ',');
466 FillFieldWithValue(new_value, input_element);
469 void AutofillAgent::OnFieldTypePredictionsAvailable(
470 const std::vector<FormDataPredictions>& forms) {
471 for (size_t i = 0; i < forms.size(); ++i) {
472 form_cache_.ShowPredictions(forms[i]);
476 void AutofillAgent::OnFillForm(int query_id, const FormData& form) {
477 if (query_id != autofill_query_id_)
478 return;
480 was_query_node_autofilled_ = element_.isAutofilled();
481 FillForm(form, element_);
482 Send(new AutofillHostMsg_DidFillAutofillFormData(routing_id(),
483 base::TimeTicks::Now()));
486 void AutofillAgent::OnFirstUserGestureObservedInTab() {
487 password_autofill_agent_->FirstUserGestureObserved();
490 void AutofillAgent::OnPing() {
491 Send(new AutofillHostMsg_PingAck(routing_id()));
494 void AutofillAgent::OnPreviewForm(int query_id, const FormData& form) {
495 if (query_id != autofill_query_id_)
496 return;
498 was_query_node_autofilled_ = element_.isAutofilled();
499 PreviewForm(form, element_);
500 Send(new AutofillHostMsg_DidPreviewAutofillFormData(routing_id()));
503 void AutofillAgent::OnClearForm() {
504 form_cache_.ClearFormWithElement(element_);
507 void AutofillAgent::OnClearPreviewedForm() {
508 if (!element_.isNull()) {
509 if (password_autofill_agent_->DidClearAutofillSelection(element_))
510 return;
512 ClearPreviewedFormWithElement(element_, was_query_node_autofilled_);
513 } else {
514 // TODO(isherman): There seem to be rare cases where this code *is*
515 // reachable: see [ http://crbug.com/96321#c6 ]. Ideally we would
516 // understand those cases and fix the code to avoid them. However, so far I
517 // have been unable to reproduce such a case locally. If you hit this
518 // NOTREACHED(), please file a bug against me.
519 NOTREACHED();
523 void AutofillAgent::OnFillFieldWithValue(const base::string16& value) {
524 WebInputElement* input_element = toWebInputElement(&element_);
525 if (input_element) {
526 FillFieldWithValue(value, input_element);
527 input_element->setAutofilled(true);
531 void AutofillAgent::OnPreviewFieldWithValue(const base::string16& value) {
532 WebInputElement* input_element = toWebInputElement(&element_);
533 if (input_element)
534 PreviewFieldWithValue(value, input_element);
537 void AutofillAgent::OnAcceptDataListSuggestion(const base::string16& value) {
538 AcceptDataListSuggestion(value);
541 void AutofillAgent::OnFillPasswordSuggestion(const base::string16& username,
542 const base::string16& password) {
543 bool handled = password_autofill_agent_->FillSuggestion(
544 element_,
545 username,
546 password);
547 DCHECK(handled);
550 void AutofillAgent::OnPreviewPasswordSuggestion(
551 const base::string16& username,
552 const base::string16& password) {
553 bool handled = password_autofill_agent_->PreviewSuggestion(
554 element_,
555 username,
556 password);
557 DCHECK(handled);
560 void AutofillAgent::OnRequestAutocompleteResult(
561 WebFormElement::AutocompleteResult result,
562 const base::string16& message,
563 const FormData& form_data) {
564 if (in_flight_request_form_.isNull())
565 return;
567 if (result == WebFormElement::AutocompleteResultSuccess) {
568 FillFormIncludingNonFocusableElements(form_data, in_flight_request_form_);
569 if (!in_flight_request_form_.checkValidity())
570 result = WebFormElement::AutocompleteResultErrorInvalid;
573 in_flight_request_form_.finishRequestAutocomplete(result);
575 if (!message.empty()) {
576 const base::string16 prefix(base::ASCIIToUTF16("requestAutocomplete: "));
577 WebConsoleMessage console_message = WebConsoleMessage(
578 WebConsoleMessage::LevelLog, WebString(prefix + message));
579 in_flight_request_form_.document().frame()->addMessageToConsole(
580 console_message);
583 in_flight_request_form_.reset();
586 void AutofillAgent::ShowSuggestions(const WebFormControlElement& element,
587 const ShowSuggestionsOptions& options) {
588 if (!element.isEnabled() || element.isReadOnly())
589 return;
590 if (!options.datalist_only && !element.suggestedValue().isEmpty())
591 return;
593 const WebInputElement* input_element = toWebInputElement(&element);
594 if (input_element) {
595 if (!input_element->isTextField())
596 return;
597 if (!options.datalist_only && !input_element->suggestedValue().isEmpty())
598 return;
599 } else {
600 DCHECK(IsTextAreaElement(element));
601 if (!element.toConst<WebTextAreaElement>().suggestedValue().isEmpty())
602 return;
605 // Don't attempt to autofill with values that are too large or if filling
606 // criteria are not met.
607 WebString value = element.editingValue();
608 if (!options.datalist_only &&
609 (value.length() > kMaxDataLength ||
610 (!options.autofill_on_empty_values && value.isEmpty()) ||
611 (options.requires_caret_at_end &&
612 (element.selectionStart() != element.selectionEnd() ||
613 element.selectionEnd() != static_cast<int>(value.length()))))) {
614 // Any popup currently showing is obsolete.
615 HidePopup();
616 return;
619 element_ = element;
620 if (IsAutofillableInputElement(input_element) &&
621 (password_autofill_agent_->ShowSuggestions(
622 *input_element, options.show_full_suggestion_list) ||
623 options.show_password_suggestions_only)) {
624 is_popup_possibly_visible_ = true;
625 return;
628 // Password field elements should only have suggestions shown by the password
629 // autofill agent.
630 if (input_element && input_element->isPasswordField())
631 return;
633 // If autocomplete is disabled at the field level, ensure that the native
634 // UI won't try to show a warning, since that may conflict with a custom
635 // popup. Note that we cannot use the WebKit method element.autoComplete()
636 // as it does not allow us to distinguish the case where autocomplete is
637 // disabled for *both* the element and for the form.
638 bool display_warning = options.display_warning_if_disabled;
639 if (display_warning) {
640 const base::string16 autocomplete_attribute =
641 element.getAttribute("autocomplete");
642 if (LowerCaseEqualsASCII(autocomplete_attribute, "off"))
643 display_warning = false;
646 QueryAutofillSuggestions(element, display_warning, options.datalist_only);
649 void AutofillAgent::QueryAutofillSuggestions(
650 const WebFormControlElement& element,
651 bool display_warning_if_disabled,
652 bool datalist_only) {
653 if (!element.document().frame())
654 return;
656 DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
658 static int query_counter = 0;
659 autofill_query_id_ = query_counter++;
660 display_warning_if_disabled_ = display_warning_if_disabled;
662 // If autocomplete is disabled at the form level, we want to see if there
663 // would have been any suggestions were it enabled, so that we can show a
664 // warning. Otherwise, we want to ignore fields that disable autocomplete, so
665 // that the suggestions list does not include suggestions for these form
666 // fields -- see comment 1 on http://crbug.com/69914
667 RequirementsMask requirements =
668 element.autoComplete() ? REQUIRE_AUTOCOMPLETE : REQUIRE_NONE;
670 // If we're ignoring autocomplete="off", always extract everything.
671 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
672 switches::kRespectAutocompleteOffForAutofill)) {
673 requirements = REQUIRE_NONE;
676 FormData form;
677 FormFieldData field;
678 if (!FindFormAndFieldForFormControlElement(element, &form, &field,
679 requirements)) {
680 // If we didn't find the cached form, at least let autocomplete have a shot
681 // at providing suggestions.
682 WebFormControlElementToFormField(element, EXTRACT_VALUE, &field);
684 if (datalist_only)
685 field.should_autocomplete = false;
687 gfx::RectF bounding_box_scaled = GetScaledBoundingBox(
688 render_frame()->GetRenderView()->GetWebView()->pageScaleFactor(),
689 &element_);
691 std::vector<base::string16> data_list_values;
692 std::vector<base::string16> data_list_labels;
693 const WebInputElement* input_element = toWebInputElement(&element);
694 if (input_element) {
695 // Find the datalist values and send them to the browser process.
696 GetDataListSuggestions(*input_element,
697 datalist_only,
698 &data_list_values,
699 &data_list_labels);
700 TrimStringVectorForIPC(&data_list_values);
701 TrimStringVectorForIPC(&data_list_labels);
704 is_popup_possibly_visible_ = true;
705 Send(new AutofillHostMsg_SetDataList(routing_id(),
706 data_list_values,
707 data_list_labels));
709 Send(new AutofillHostMsg_QueryFormFieldAutofill(routing_id(),
710 autofill_query_id_,
711 form,
712 field,
713 bounding_box_scaled,
714 display_warning_if_disabled));
717 void AutofillAgent::FillFieldWithValue(const base::string16& value,
718 WebInputElement* node) {
719 did_set_node_text_ = true;
720 node->setEditingValue(value.substr(0, node->maxLength()));
723 void AutofillAgent::PreviewFieldWithValue(const base::string16& value,
724 WebInputElement* node) {
725 was_query_node_autofilled_ = element_.isAutofilled();
726 node->setSuggestedValue(value.substr(0, node->maxLength()));
727 node->setAutofilled(true);
728 node->setSelectionRange(node->value().length(),
729 node->suggestedValue().length());
732 void AutofillAgent::ProcessForms() {
733 // Record timestamp of when the forms are first seen. This is used to
734 // measure the overhead of the Autofill feature.
735 base::TimeTicks forms_seen_timestamp = base::TimeTicks::Now();
737 WebLocalFrame* frame = render_frame()->GetWebFrame();
738 std::vector<FormData> forms = form_cache_.ExtractNewForms();
740 // Always communicate to browser process for topmost frame.
741 if (!forms.empty() || !frame->parent()) {
742 Send(new AutofillHostMsg_FormsSeen(routing_id(), forms,
743 forms_seen_timestamp));
747 void AutofillAgent::HidePopup() {
748 if (!is_popup_possibly_visible_)
749 return;
750 is_popup_possibly_visible_ = false;
751 Send(new AutofillHostMsg_HidePopup(routing_id()));
754 void AutofillAgent::didAssociateFormControls(const WebVector<WebNode>& nodes) {
755 for (size_t i = 0; i < nodes.size(); ++i) {
756 WebLocalFrame* frame = nodes[i].document().frame();
757 // Only monitors dynamic forms created in the top frame. Dynamic forms
758 // inserted in iframes are not captured yet. Frame is only processed
759 // if it has finished loading, otherwise you can end up with a partially
760 // parsed form.
761 if (frame && !frame->isLoading()) {
762 ProcessForms();
763 password_autofill_agent_->OnDynamicFormsSeen();
764 if (password_generation_agent_)
765 password_generation_agent_->OnDynamicFormsSeen();
766 return;
771 // LegacyAutofillAgent ---------------------------------------------------------
773 AutofillAgent::LegacyAutofillAgent::LegacyAutofillAgent(
774 content::RenderView* render_view,
775 AutofillAgent* agent)
776 : content::RenderViewObserver(render_view), agent_(agent) {
779 AutofillAgent::LegacyAutofillAgent::~LegacyAutofillAgent() {
782 void AutofillAgent::LegacyAutofillAgent::OnDestruct() {
783 // No-op. Don't delete |this|.
786 void AutofillAgent::LegacyAutofillAgent::FocusChangeComplete() {
787 agent_->FocusChangeComplete();
790 } // namespace autofill