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"
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/renderer/form_autofill_util.h"
15 #include "components/autofill/content/renderer/page_click_tracker.h"
16 #include "components/autofill/content/renderer/password_autofill_agent.h"
17 #include "components/autofill/core/common/autofill_constants.h"
18 #include "components/autofill/core/common/autofill_messages.h"
19 #include "components/autofill/core/common/autofill_switches.h"
20 #include "components/autofill/core/common/form_data.h"
21 #include "components/autofill/core/common/form_data_predictions.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/web_element_descriptor.h"
25 #include "content/public/common/ssl_status.h"
26 #include "content/public/common/url_constants.h"
27 #include "content/public/renderer/render_view.h"
28 #include "grit/component_strings.h"
29 #include "net/cert/cert_status_flags.h"
30 #include "third_party/WebKit/public/platform/WebRect.h"
31 #include "third_party/WebKit/public/platform/WebURLRequest.h"
32 #include "third_party/WebKit/public/web/WebDataSource.h"
33 #include "third_party/WebKit/public/web/WebDocument.h"
34 #include "third_party/WebKit/public/web/WebFormControlElement.h"
35 #include "third_party/WebKit/public/web/WebFormElement.h"
36 #include "third_party/WebKit/public/web/WebFrame.h"
37 #include "third_party/WebKit/public/web/WebInputEvent.h"
38 #include "third_party/WebKit/public/web/WebNode.h"
39 #include "third_party/WebKit/public/web/WebNodeCollection.h"
40 #include "third_party/WebKit/public/web/WebOptionElement.h"
41 #include "third_party/WebKit/public/web/WebView.h"
42 #include "ui/base/l10n/l10n_util.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
45 using WebKit::WebAutofillClient;
46 using WebKit::WebFormControlElement;
47 using WebKit::WebFormElement;
48 using WebKit::WebFrame;
49 using WebKit::WebInputElement;
50 using WebKit::WebKeyboardEvent;
51 using WebKit::WebNode;
52 using WebKit::WebNodeCollection;
53 using WebKit::WebOptionElement;
54 using WebKit::WebString;
58 // The size above which we stop triggering autofill for an input text field
59 // (so to avoid sending long strings through IPC).
60 const size_t kMaximumTextSizeForAutofill = 1000;
62 // The maximum number of data list elements to send to the browser process
63 // via IPC (to prevent long IPC messages).
64 const size_t kMaximumDataListSizeForAutofill = 30;
67 // Gets all the data list values (with corresponding label) for the given
69 void GetDataListSuggestions(const WebKit::WebInputElement& element,
70 std::vector<base::string16>* values,
71 std::vector<base::string16>* labels) {
72 WebNodeCollection options = element.dataListOptions();
76 base::string16 prefix = element.editingValue();
77 if (element.isMultiple() &&
78 element.formControlType() == WebString::fromUTF8("email")) {
79 std::vector<base::string16> parts;
80 base::SplitStringDontTrim(prefix, ',', &parts);
82 TrimWhitespace(parts[parts.size() - 1], TRIM_LEADING, &prefix);
84 for (WebOptionElement option = options.firstItem().to<WebOptionElement>();
85 !option.isNull(); option = options.nextItem().to<WebOptionElement>()) {
86 if (!StartsWith(option.value(), prefix, false) ||
87 option.value() == prefix ||
88 !element.isValidValue(option.value()))
91 values->push_back(option.value());
92 if (option.value() != option.label())
93 labels->push_back(option.label());
95 labels->push_back(base::string16());
99 // Trim the vector before sending it to the browser process to ensure we
100 // don't send too much data through the IPC.
101 void TrimStringVectorForIPC(std::vector<base::string16>* strings) {
102 // Limit the size of the vector.
103 if (strings->size() > kMaximumDataListSizeForAutofill)
104 strings->resize(kMaximumDataListSizeForAutofill);
106 // Limit the size of the strings in the vector.
107 for (size_t i = 0; i < strings->size(); ++i) {
108 if ((*strings)[i].length() > kMaximumTextSizeForAutofill)
109 (*strings)[i].resize(kMaximumTextSizeForAutofill);
113 gfx::RectF GetScaledBoundingBox(float scale, WebInputElement* element) {
114 gfx::Rect bounding_box(element->boundsInViewportSpace());
115 return gfx::RectF(bounding_box.x() * scale,
116 bounding_box.y() * scale,
117 bounding_box.width() * scale,
118 bounding_box.height() * scale);
125 AutofillAgent::AutofillAgent(content::RenderView* render_view,
126 PasswordAutofillAgent* password_autofill_agent)
127 : content::RenderViewObserver(render_view),
128 password_autofill_agent_(password_autofill_agent),
129 autofill_query_id_(0),
130 autofill_action_(AUTOFILL_NONE),
131 web_view_(render_view->GetWebView()),
132 display_warning_if_disabled_(false),
133 was_query_node_autofilled_(false),
134 has_shown_autofill_popup_for_current_edit_(false),
135 did_set_node_text_(false),
136 has_new_forms_for_browser_(false),
137 ignore_text_changes_(false),
138 weak_ptr_factory_(this) {
139 render_view->GetWebView()->setAutofillClient(this);
141 // The PageClickTracker is a RenderViewObserver, and hence will be freed when
142 // the RenderView is destroyed.
143 new PageClickTracker(render_view, this);
146 AutofillAgent::~AutofillAgent() {}
148 bool AutofillAgent::OnMessageReceived(const IPC::Message& message) {
150 IPC_BEGIN_MESSAGE_MAP(AutofillAgent, message)
151 IPC_MESSAGE_HANDLER(AutofillMsg_FormDataFilled, OnFormDataFilled)
152 IPC_MESSAGE_HANDLER(AutofillMsg_FieldTypePredictionsAvailable,
153 OnFieldTypePredictionsAvailable)
154 IPC_MESSAGE_HANDLER(AutofillMsg_SetAutofillActionFill,
155 OnSetAutofillActionFill)
156 IPC_MESSAGE_HANDLER(AutofillMsg_ClearForm,
158 IPC_MESSAGE_HANDLER(AutofillMsg_SetAutofillActionPreview,
159 OnSetAutofillActionPreview)
160 IPC_MESSAGE_HANDLER(AutofillMsg_ClearPreviewedForm,
161 OnClearPreviewedForm)
162 IPC_MESSAGE_HANDLER(AutofillMsg_SetNodeText,
164 IPC_MESSAGE_HANDLER(AutofillMsg_AcceptDataListSuggestion,
165 OnAcceptDataListSuggestion)
166 IPC_MESSAGE_HANDLER(AutofillMsg_AcceptPasswordAutofillSuggestion,
167 OnAcceptPasswordAutofillSuggestion)
168 IPC_MESSAGE_HANDLER(AutofillMsg_RequestAutocompleteResult,
169 OnRequestAutocompleteResult)
170 IPC_MESSAGE_HANDLER(AutofillMsg_PageShown,
172 IPC_MESSAGE_UNHANDLED(handled = false)
173 IPC_END_MESSAGE_MAP()
177 void AutofillAgent::DidFinishDocumentLoad(WebFrame* frame) {
178 // Record timestamp on document load. This is used to record overhead of
180 forms_seen_timestamp_ = base::TimeTicks::Now();
182 // The document has now been fully loaded. Scan for forms to be sent up to
184 std::vector<FormData> forms;
185 bool has_more_forms = false;
186 if (!frame->parent()) {
187 form_elements_.clear();
188 has_more_forms = form_cache_.ExtractFormsAndFormElements(
189 *frame, kRequiredAutofillFields, &forms, &form_elements_);
191 form_cache_.ExtractForms(*frame, &forms);
194 autofill::FormsSeenState state = has_more_forms ?
195 autofill::PARTIAL_FORMS_SEEN : autofill::NO_SPECIAL_FORMS_SEEN;
197 // Always communicate to browser process for topmost frame.
198 if (!forms.empty() || !frame->parent()) {
199 Send(new AutofillHostMsg_FormsSeen(routing_id(), forms,
200 forms_seen_timestamp_,
205 void AutofillAgent::DidCommitProvisionalLoad(WebFrame* frame,
206 bool is_new_navigation) {
207 in_flight_request_form_.reset();
210 void AutofillAgent::FrameDetached(WebFrame* frame) {
211 form_cache_.ResetFrame(*frame);
214 void AutofillAgent::WillSubmitForm(WebFrame* frame,
215 const WebFormElement& form) {
217 if (WebFormElementToFormData(form,
218 WebFormControlElement(),
219 REQUIRE_AUTOCOMPLETE,
220 static_cast<ExtractMask>(
221 EXTRACT_VALUE | EXTRACT_OPTION_TEXT),
224 Send(new AutofillHostMsg_FormSubmitted(routing_id(), form_data,
225 base::TimeTicks::Now()));
229 void AutofillAgent::ZoomLevelChanged() {
230 // Any time the zoom level changes, the page's content moves, so any Autofill
231 // popups should be hidden. This is only needed for the new Autofill UI
232 // because WebKit already knows to hide the old UI when this occurs.
236 void AutofillAgent::FocusedNodeChanged(const WebKit::WebNode& node) {
237 if (node.isNull() || !node.isElementNode())
240 WebKit::WebElement web_element = node.toConst<WebKit::WebElement>();
242 if (!web_element.document().frame())
245 const WebInputElement* element = toWebInputElement(&web_element);
247 if (!element || !element->isEnabled() || element->isReadOnly() ||
248 !element->isTextField() || element->isPasswordField())
254 void AutofillAgent::OrientationChangeEvent(int orientation) {
258 void AutofillAgent::DidChangeScrollOffset(WebKit::WebFrame*) {
262 void AutofillAgent::didRequestAutocomplete(WebKit::WebFrame* frame,
263 const WebFormElement& form) {
264 GURL url(frame->document().url());
265 content::SSLStatus ssl_status = render_view()->GetSSLStatusOfFrame(frame);
267 if (!in_flight_request_form_.isNull() ||
268 (url.SchemeIs(content::kHttpsScheme) &&
269 (net::IsCertStatusError(ssl_status.cert_status) ||
270 net::IsCertStatusMinorError(ssl_status.cert_status))) ||
271 !WebFormElementToFormData(form,
272 WebFormControlElement(),
273 REQUIRE_AUTOCOMPLETE,
277 WebFormElement(form).finishRequestAutocomplete(
278 WebFormElement::AutocompleteResultErrorDisabled);
282 // Cancel any pending Autofill requests and hide any currently showing popups.
283 ++autofill_query_id_;
286 in_flight_request_form_ = form;
287 Send(new AutofillHostMsg_RequestAutocomplete(routing_id(), form_data, url));
290 void AutofillAgent::setIgnoreTextChanges(bool ignore) {
291 ignore_text_changes_ = ignore;
294 void AutofillAgent::InputElementClicked(const WebInputElement& element,
298 ShowSuggestions(element, true, false, true);
301 void AutofillAgent::InputElementLostFocus() {
305 void AutofillAgent::didClearAutofillSelection(const WebNode& node) {
306 if (password_autofill_agent_->DidClearAutofillSelection(node))
309 if (!element_.isNull() && node == element_) {
310 ClearPreviewedFormWithElement(element_, was_query_node_autofilled_);
312 // TODO(isherman): There seem to be rare cases where this code *is*
313 // reachable: see [ http://crbug.com/96321#c6 ]. Ideally we would
314 // understand those cases and fix the code to avoid them. However, so far I
315 // have been unable to reproduce such a case locally. If you hit this
316 // NOTREACHED(), please file a bug against me.
321 void AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {
322 password_autofill_agent_->TextFieldDidEndEditing(element);
323 has_shown_autofill_popup_for_current_edit_ = false;
324 Send(new AutofillHostMsg_DidEndTextFieldEditing(routing_id()));
327 void AutofillAgent::textFieldDidChange(const WebInputElement& element) {
328 if (ignore_text_changes_)
331 if (did_set_node_text_) {
332 did_set_node_text_ = false;
336 // We post a task for doing the Autofill as the caret position is not set
337 // properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and
338 // it is needed to trigger autofill.
339 weak_ptr_factory_.InvalidateWeakPtrs();
340 base::MessageLoop::current()->PostTask(
342 base::Bind(&AutofillAgent::TextFieldDidChangeImpl,
343 weak_ptr_factory_.GetWeakPtr(),
347 void AutofillAgent::TextFieldDidChangeImpl(const WebInputElement& element) {
348 // If the element isn't focused then the changes don't matter. This check is
349 // required to properly handle IME interactions.
350 if (!element.focused())
353 if (password_autofill_agent_->TextDidChangeInTextField(element)) {
358 ShowSuggestions(element, false, true, false);
362 if (FindFormAndFieldForInputElement(element, &form, &field, REQUIRE_NONE)) {
363 Send(new AutofillHostMsg_TextFieldDidChange(routing_id(), form, field,
364 base::TimeTicks::Now()));
368 void AutofillAgent::textFieldDidReceiveKeyDown(const WebInputElement& element,
369 const WebKeyboardEvent& event) {
370 if (password_autofill_agent_->TextFieldHandlingKeyDown(element, event)) {
375 if (event.windowsKeyCode == ui::VKEY_DOWN ||
376 event.windowsKeyCode == ui::VKEY_UP)
377 ShowSuggestions(element, true, true, true);
380 void AutofillAgent::AcceptDataListSuggestion(
381 const base::string16& suggested_value) {
382 base::string16 new_value = suggested_value;
383 // If this element takes multiple values then replace the last part with
385 if (element_.isMultiple() &&
386 element_.formControlType() == WebString::fromUTF8("email")) {
387 std::vector<base::string16> parts;
389 base::SplitStringDontTrim(element_.editingValue(), ',', &parts);
390 if (parts.size() == 0)
391 parts.push_back(base::string16());
393 base::string16 last_part = parts.back();
394 // We want to keep just the leading whitespace.
395 for (size_t i = 0; i < last_part.size(); ++i) {
396 if (!IsWhitespace(last_part[i])) {
397 last_part = last_part.substr(0, i);
401 last_part.append(suggested_value);
402 parts[parts.size() - 1] = last_part;
404 new_value = JoinString(parts, ',');
406 SetNodeText(new_value, &element_);
409 void AutofillAgent::OnFormDataFilled(int query_id,
410 const FormData& form) {
411 if (!render_view()->GetWebView() || query_id != autofill_query_id_)
414 was_query_node_autofilled_ = element_.isAutofilled();
416 switch (autofill_action_) {
418 FillForm(form, element_);
419 Send(new AutofillHostMsg_DidFillAutofillFormData(routing_id(),
420 base::TimeTicks::Now()));
422 case AUTOFILL_PREVIEW:
423 PreviewForm(form, element_);
424 Send(new AutofillHostMsg_DidPreviewAutofillFormData(routing_id()));
429 autofill_action_ = AUTOFILL_NONE;
432 void AutofillAgent::OnFieldTypePredictionsAvailable(
433 const std::vector<FormDataPredictions>& forms) {
434 for (size_t i = 0; i < forms.size(); ++i) {
435 form_cache_.ShowPredictions(forms[i]);
439 void AutofillAgent::OnSetAutofillActionFill() {
440 autofill_action_ = AUTOFILL_FILL;
443 void AutofillAgent::OnClearForm() {
444 form_cache_.ClearFormWithElement(element_);
447 void AutofillAgent::OnSetAutofillActionPreview() {
448 autofill_action_ = AUTOFILL_PREVIEW;
451 void AutofillAgent::OnClearPreviewedForm() {
452 didClearAutofillSelection(element_);
455 void AutofillAgent::OnSetNodeText(const base::string16& value) {
456 SetNodeText(value, &element_);
459 void AutofillAgent::OnAcceptDataListSuggestion(const base::string16& value) {
460 AcceptDataListSuggestion(value);
463 void AutofillAgent::OnAcceptPasswordAutofillSuggestion(
464 const base::string16& value) {
465 // We need to make sure this is handled here because the browser process
466 // skipped it handling because it believed it would be handled here. If it
467 // isn't handled here then the browser logic needs to be updated.
468 bool handled = password_autofill_agent_->DidAcceptAutofillSuggestion(
474 void AutofillAgent::OnRequestAutocompleteResult(
475 WebFormElement::AutocompleteResult result, const FormData& form_data) {
476 if (in_flight_request_form_.isNull())
479 if (result == WebFormElement::AutocompleteResultSuccess) {
480 FillFormIncludingNonFocusableElements(form_data, in_flight_request_form_);
481 if (!in_flight_request_form_.checkValidityWithoutDispatchingEvents())
482 result = WebFormElement::AutocompleteResultErrorInvalid;
485 in_flight_request_form_.finishRequestAutocomplete(result);
486 in_flight_request_form_.reset();
489 void AutofillAgent::OnPageShown() {
492 void AutofillAgent::ShowSuggestions(const WebInputElement& element,
493 bool autofill_on_empty_values,
494 bool requires_caret_at_end,
495 bool display_warning_if_disabled) {
496 if (!element.isEnabled() || element.isReadOnly() || !element.isTextField() ||
497 element.isPasswordField() || !element.suggestedValue().isEmpty())
500 // Don't attempt to autofill with values that are too large or if filling
501 // criteria are not met.
502 WebString value = element.editingValue();
503 if (value.length() > kMaximumTextSizeForAutofill ||
504 (!autofill_on_empty_values && value.isEmpty()) ||
505 (requires_caret_at_end &&
506 (element.selectionStart() != element.selectionEnd() ||
507 element.selectionEnd() != static_cast<int>(value.length())))) {
508 // Any popup currently showing is obsolete.
514 if (password_autofill_agent_->ShowSuggestions(element))
517 // If autocomplete is disabled at the field level, ensure that the native
518 // UI won't try to show a warning, since that may conflict with a custom
519 // popup. Note that we cannot use the WebKit method element.autoComplete()
520 // as it does not allow us to distinguish the case where autocomplete is
521 // disabled for *both* the element and for the form.
522 const base::string16 autocomplete_attribute =
523 element.getAttribute("autocomplete");
524 if (LowerCaseEqualsASCII(autocomplete_attribute, "off"))
525 display_warning_if_disabled = false;
527 QueryAutofillSuggestions(element, display_warning_if_disabled);
530 void AutofillAgent::QueryAutofillSuggestions(const WebInputElement& element,
531 bool display_warning_if_disabled) {
532 if (!element.document().frame())
535 static int query_counter = 0;
536 autofill_query_id_ = query_counter++;
537 display_warning_if_disabled_ = display_warning_if_disabled;
539 // If autocomplete is disabled at the form level, we want to see if there
540 // would have been any suggestions were it enabled, so that we can show a
541 // warning. Otherwise, we want to ignore fields that disable autocomplete, so
542 // that the suggestions list does not include suggestions for these form
543 // fields -- see comment 1 on http://crbug.com/69914
544 const RequirementsMask requirements =
545 element.autoComplete() ? REQUIRE_AUTOCOMPLETE : REQUIRE_NONE;
549 if (!FindFormAndFieldForInputElement(element, &form, &field, requirements)) {
550 // If we didn't find the cached form, at least let autocomplete have a shot
551 // at providing suggestions.
552 WebFormControlElementToFormField(element, EXTRACT_VALUE, &field);
555 gfx::RectF bounding_box_scaled =
556 GetScaledBoundingBox(web_view_->pageScaleFactor(), &element_);
558 // Find the datalist values and send them to the browser process.
559 std::vector<base::string16> data_list_values;
560 std::vector<base::string16> data_list_labels;
561 GetDataListSuggestions(element_, &data_list_values, &data_list_labels);
562 TrimStringVectorForIPC(&data_list_values);
563 TrimStringVectorForIPC(&data_list_labels);
565 Send(new AutofillHostMsg_SetDataList(routing_id(),
569 Send(new AutofillHostMsg_QueryFormFieldAutofill(routing_id(),
574 display_warning_if_disabled));
577 void AutofillAgent::FillAutofillFormData(const WebNode& node,
579 AutofillAction action) {
580 DCHECK_GT(unique_id, 0);
582 static int query_counter = 0;
583 autofill_query_id_ = query_counter++;
587 if (!FindFormAndFieldForInputElement(node.toConst<WebInputElement>(), &form,
588 &field, REQUIRE_AUTOCOMPLETE)) {
592 autofill_action_ = action;
593 Send(new AutofillHostMsg_FillAutofillFormData(
594 routing_id(), autofill_query_id_, form, field, unique_id));
597 void AutofillAgent::SetNodeText(const base::string16& value,
598 WebKit::WebInputElement* node) {
599 did_set_node_text_ = true;
600 base::string16 substring = value;
601 substring = substring.substr(0, node->maxLength());
603 node->setEditingValue(substring);
606 void AutofillAgent::HideAutofillUI() {
607 Send(new AutofillHostMsg_HideAutofillUI(routing_id()));
610 // TODO(isherman): Decide if we want to support non-password autofill with AJAX.
611 void AutofillAgent::didAssociateFormControls(
612 const WebKit::WebVector<WebKit::WebNode>& nodes) {
613 for (size_t i = 0; i < nodes.size(); ++i) {
614 WebKit::WebFrame* frame = nodes[i].document().frame();
615 // Only monitors dynamic forms created in the top frame. Dynamic forms
616 // inserted in iframes are not captured yet.
617 if (!frame->parent()) {
618 password_autofill_agent_->OnDynamicFormsSeen(frame);
624 } // namespace autofill