Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / components / autofill / content / renderer / autofill_agent.cc
blobbf1f54a3a13beb0f25d6dcec881e19512ad53dcb
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/message_loop/message_loop.h"
11 #include "base/strings/string_split.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/time/time.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/page_click_tracker.h"
18 #include "components/autofill/content/renderer/password_autofill_agent.h"
19 #include "components/autofill/content/renderer/password_generation_agent.h"
20 #include "components/autofill/core/common/autofill_constants.h"
21 #include "components/autofill/core/common/autofill_data_validation.h"
22 #include "components/autofill/core/common/autofill_switches.h"
23 #include "components/autofill/core/common/form_data.h"
24 #include "components/autofill/core/common/form_data_predictions.h"
25 #include "components/autofill/core/common/form_field_data.h"
26 #include "components/autofill/core/common/password_form.h"
27 #include "components/autofill/core/common/web_element_descriptor.h"
28 #include "content/public/common/content_switches.h"
29 #include "content/public/common/ssl_status.h"
30 #include "content/public/common/url_constants.h"
31 #include "content/public/renderer/render_frame.h"
32 #include "content/public/renderer/render_view.h"
33 #include "net/cert/cert_status_flags.h"
34 #include "third_party/WebKit/public/platform/WebRect.h"
35 #include "third_party/WebKit/public/platform/WebURLRequest.h"
36 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
37 #include "third_party/WebKit/public/web/WebDataSource.h"
38 #include "third_party/WebKit/public/web/WebDocument.h"
39 #include "third_party/WebKit/public/web/WebElementCollection.h"
40 #include "third_party/WebKit/public/web/WebFormControlElement.h"
41 #include "third_party/WebKit/public/web/WebFormElement.h"
42 #include "third_party/WebKit/public/web/WebInputEvent.h"
43 #include "third_party/WebKit/public/web/WebLocalFrame.h"
44 #include "third_party/WebKit/public/web/WebNode.h"
45 #include "third_party/WebKit/public/web/WebOptionElement.h"
46 #include "third_party/WebKit/public/web/WebTextAreaElement.h"
47 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
48 #include "third_party/WebKit/public/web/WebView.h"
49 #include "ui/base/l10n/l10n_util.h"
50 #include "ui/events/keycodes/keyboard_codes.h"
52 using blink::WebAutofillClient;
53 using blink::WebConsoleMessage;
54 using blink::WebDocument;
55 using blink::WebElement;
56 using blink::WebElementCollection;
57 using blink::WebFormControlElement;
58 using blink::WebFormElement;
59 using blink::WebFrame;
60 using blink::WebInputElement;
61 using blink::WebKeyboardEvent;
62 using blink::WebLocalFrame;
63 using blink::WebNode;
64 using blink::WebOptionElement;
65 using blink::WebString;
66 using blink::WebTextAreaElement;
67 using blink::WebUserGestureIndicator;
68 using blink::WebVector;
70 namespace autofill {
72 namespace {
74 // Gets all the data list values (with corresponding label) for the given
75 // element.
76 void GetDataListSuggestions(const WebInputElement& element,
77 bool ignore_current_value,
78 std::vector<base::string16>* values,
79 std::vector<base::string16>* labels) {
80 WebElementCollection options = element.dataListOptions();
81 if (options.isNull())
82 return;
84 base::string16 prefix;
85 if (!ignore_current_value) {
86 prefix = element.editingValue();
87 if (element.isMultiple() && element.isEmailField()) {
88 std::vector<base::string16> parts;
89 base::SplitStringDontTrim(prefix, ',', &parts);
90 if (parts.size() > 0) {
91 base::TrimWhitespace(parts[parts.size() - 1], base::TRIM_LEADING,
92 &prefix);
96 for (WebOptionElement option = options.firstItem().to<WebOptionElement>();
97 !option.isNull(); option = options.nextItem().to<WebOptionElement>()) {
98 if (!StartsWith(option.value(), prefix, false) ||
99 option.value() == prefix ||
100 !element.isValidValue(option.value()))
101 continue;
103 values->push_back(option.value());
104 if (option.value() != option.label())
105 labels->push_back(option.label());
106 else
107 labels->push_back(base::string16());
111 // Trim the vector before sending it to the browser process to ensure we
112 // don't send too much data through the IPC.
113 void TrimStringVectorForIPC(std::vector<base::string16>* strings) {
114 // Limit the size of the vector.
115 if (strings->size() > kMaxListSize)
116 strings->resize(kMaxListSize);
118 // Limit the size of the strings in the vector.
119 for (size_t i = 0; i < strings->size(); ++i) {
120 if ((*strings)[i].length() > kMaxDataLength)
121 (*strings)[i].resize(kMaxDataLength);
125 // Extract FormData from the form element and return whether the operation was
126 // successful.
127 bool ExtractFormDataOnSave(const WebFormElement& form_element, FormData* data) {
128 return WebFormElementToFormData(
129 form_element, WebFormControlElement(),
130 static_cast<ExtractMask>(EXTRACT_VALUE | EXTRACT_OPTION_TEXT), data,
131 NULL);
134 } // namespace
136 AutofillAgent::ShowSuggestionsOptions::ShowSuggestionsOptions()
137 : autofill_on_empty_values(false),
138 requires_caret_at_end(false),
139 datalist_only(false),
140 show_full_suggestion_list(false),
141 show_password_suggestions_only(false) {
144 AutofillAgent::AutofillAgent(content::RenderFrame* render_frame,
145 PasswordAutofillAgent* password_autofill_agent,
146 PasswordGenerationAgent* password_generation_agent)
147 : content::RenderFrameObserver(render_frame),
148 form_cache_(*render_frame->GetWebFrame()),
149 password_autofill_agent_(password_autofill_agent),
150 password_generation_agent_(password_generation_agent),
151 legacy_(render_frame->GetRenderView(), this),
152 autofill_query_id_(0),
153 was_query_node_autofilled_(false),
154 has_shown_autofill_popup_for_current_edit_(false),
155 ignore_text_changes_(false),
156 is_popup_possibly_visible_(false),
157 weak_ptr_factory_(this) {
158 render_frame->GetWebFrame()->setAutofillClient(this);
160 // This owns itself, and will delete itself when |render_frame| is destructed
161 // (same as AutofillAgent).
162 new PageClickTracker(render_frame, this);
165 AutofillAgent::~AutofillAgent() {}
167 bool AutofillAgent::FormDataCompare::operator()(const FormData& lhs,
168 const FormData& rhs) const {
169 if (lhs.name != rhs.name)
170 return lhs.name < rhs.name;
171 if (lhs.origin != rhs.origin)
172 return lhs.origin < rhs.origin;
173 if (lhs.action != rhs.action)
174 return lhs.action < rhs.action;
175 if (lhs.is_form_tag != rhs.is_form_tag)
176 return lhs.is_form_tag < rhs.is_form_tag;
177 return lhs.fields < rhs.fields;
180 bool AutofillAgent::OnMessageReceived(const IPC::Message& message) {
181 bool handled = true;
182 IPC_BEGIN_MESSAGE_MAP(AutofillAgent, message)
183 IPC_MESSAGE_HANDLER(AutofillMsg_FirstUserGestureObservedInTab,
184 OnFirstUserGestureObservedInTab)
185 IPC_MESSAGE_HANDLER(AutofillMsg_Ping, OnPing)
186 IPC_MESSAGE_HANDLER(AutofillMsg_FillForm, OnFillForm)
187 IPC_MESSAGE_HANDLER(AutofillMsg_PreviewForm, OnPreviewForm)
188 IPC_MESSAGE_HANDLER(AutofillMsg_FieldTypePredictionsAvailable,
189 OnFieldTypePredictionsAvailable)
190 IPC_MESSAGE_HANDLER(AutofillMsg_ClearForm, OnClearForm)
191 IPC_MESSAGE_HANDLER(AutofillMsg_ClearPreviewedForm, OnClearPreviewedForm)
192 IPC_MESSAGE_HANDLER(AutofillMsg_FillFieldWithValue, OnFillFieldWithValue)
193 IPC_MESSAGE_HANDLER(AutofillMsg_PreviewFieldWithValue,
194 OnPreviewFieldWithValue)
195 IPC_MESSAGE_HANDLER(AutofillMsg_AcceptDataListSuggestion,
196 OnAcceptDataListSuggestion)
197 IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordSuggestion,
198 OnFillPasswordSuggestion)
199 IPC_MESSAGE_HANDLER(AutofillMsg_PreviewPasswordSuggestion,
200 OnPreviewPasswordSuggestion)
201 IPC_MESSAGE_HANDLER(AutofillMsg_RequestAutocompleteResult,
202 OnRequestAutocompleteResult)
203 IPC_MESSAGE_UNHANDLED(handled = false)
204 IPC_END_MESSAGE_MAP()
205 return handled;
208 void AutofillAgent::DidCommitProvisionalLoad(bool is_new_navigation,
209 bool is_same_page_navigation) {
210 form_cache_.Reset();
211 submitted_forms_.clear();
214 void AutofillAgent::DidFinishDocumentLoad() {
215 ProcessForms();
218 void AutofillAgent::WillSendSubmitEvent(const WebFormElement& form) {
219 FormData form_data;
220 if (!ExtractFormDataOnSave(form, &form_data))
221 return;
223 // The WillSendSubmitEvent function is called when there is a submit handler
224 // on the form, such as in the case of (but not restricted to)
225 // JavaScript-submitted forms. Sends a WillSubmitForm message to the browser
226 // and remembers for which form it did that in the current frame load, so that
227 // no additional message is sent if AutofillAgent::WillSubmitForm() is called
228 // (which is itself not guaranteed if the submit event is prevented by
229 // JavaScript).
230 Send(new AutofillHostMsg_WillSubmitForm(routing_id(), form_data,
231 base::TimeTicks::Now()));
232 submitted_forms_.insert(form_data);
235 void AutofillAgent::WillSubmitForm(const WebFormElement& form) {
236 FormData form_data;
237 if (!ExtractFormDataOnSave(form, &form_data))
238 return;
240 // If WillSubmitForm message had not been sent for this form, send it.
241 if (!submitted_forms_.count(form_data)) {
242 Send(new AutofillHostMsg_WillSubmitForm(routing_id(), form_data,
243 base::TimeTicks::Now()));
246 Send(new AutofillHostMsg_FormSubmitted(routing_id(), form_data));
249 void AutofillAgent::DidChangeScrollOffset() {
250 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
251 switches::kEnableAccessorySuggestionView)) {
252 return;
254 HidePopup();
257 void AutofillAgent::FocusedNodeChanged(const WebNode& node) {
258 HidePopup();
260 if (node.isNull() || !node.isElementNode())
261 return;
263 WebElement web_element = node.toConst<WebElement>();
264 const WebInputElement* element = toWebInputElement(&web_element);
266 if (!element || !element->isEnabled() || element->isReadOnly() ||
267 !element->isTextField())
268 return;
270 element_ = *element;
273 void AutofillAgent::FocusChangeComplete() {
274 WebDocument doc = render_frame()->GetWebFrame()->document();
275 WebElement focused_element;
276 if (!doc.isNull())
277 focused_element = doc.focusedElement();
279 if (!focused_element.isNull() && password_generation_agent_ &&
280 password_generation_agent_->FocusedNodeHasChanged(focused_element)) {
281 is_popup_possibly_visible_ = true;
285 void AutofillAgent::didRequestAutocomplete(
286 const WebFormElement& form) {
287 DCHECK_EQ(form.document().frame(), render_frame()->GetWebFrame());
289 // Disallow the dialog over non-https or broken https, except when the
290 // ignore SSL flag is passed. See http://crbug.com/272512.
291 // TODO(palmer): this should be moved to the browser process after frames
292 // get their own processes.
293 GURL url(form.document().url());
294 content::SSLStatus ssl_status =
295 render_frame()->GetRenderView()->GetSSLStatusOfFrame(
296 form.document().frame());
297 bool is_safe = url.SchemeIs(url::kHttpsScheme) &&
298 !net::IsCertStatusError(ssl_status.cert_status);
299 bool allow_unsafe = base::CommandLine::ForCurrentProcess()->HasSwitch(
300 ::switches::kReduceSecurityForTesting);
301 FormData form_data;
302 std::string error_message;
303 if (!in_flight_request_form_.isNull()) {
304 error_message = "already active.";
305 } else if (!is_safe && !allow_unsafe) {
306 error_message =
307 "must use a secure connection or --reduce-security-for-testing.";
308 } else if (!WebFormElementToFormData(form,
309 WebFormControlElement(),
310 static_cast<ExtractMask>(
311 EXTRACT_VALUE |
312 EXTRACT_OPTION_TEXT |
313 EXTRACT_OPTIONS),
314 &form_data,
315 NULL)) {
316 error_message = "failed to parse form.";
319 if (!error_message.empty()) {
320 WebConsoleMessage console_message = WebConsoleMessage(
321 WebConsoleMessage::LevelLog,
322 WebString(base::ASCIIToUTF16("requestAutocomplete: ") +
323 base::ASCIIToUTF16(error_message)));
324 form.document().frame()->addMessageToConsole(console_message);
325 WebFormElement(form).finishRequestAutocomplete(
326 WebFormElement::AutocompleteResultErrorDisabled);
327 return;
330 // Cancel any pending Autofill requests and hide any currently showing popups.
331 ++autofill_query_id_;
332 HidePopup();
334 in_flight_request_form_ = form;
335 Send(new AutofillHostMsg_RequestAutocomplete(routing_id(), form_data));
338 void AutofillAgent::setIgnoreTextChanges(bool ignore) {
339 ignore_text_changes_ = ignore;
342 void AutofillAgent::FormControlElementClicked(
343 const WebFormControlElement& element,
344 bool was_focused) {
345 // TODO(estade): Remove this check when PageClickTracker is per-frame.
346 if (element.document().frame() != render_frame()->GetWebFrame())
347 return;
349 const WebInputElement* input_element = toWebInputElement(&element);
350 if (!input_element && !IsTextAreaElement(element))
351 return;
353 ShowSuggestionsOptions options;
354 options.autofill_on_empty_values = true;
355 options.show_full_suggestion_list = element.isAutofilled();
357 // On Android, default to showing the dropdown on field focus.
358 // On desktop, require an extra click after field focus.
359 // See http://crbug.com/427660
360 #if defined(OS_ANDROID)
361 bool single_click_autofill =
362 !base::CommandLine::ForCurrentProcess()->HasSwitch(
363 switches::kDisableSingleClickAutofill);
364 #else
365 bool single_click_autofill =
366 base::CommandLine::ForCurrentProcess()->HasSwitch(
367 switches::kEnableSingleClickAutofill);
368 #endif
370 if (!single_click_autofill) {
371 // Show full suggestions when clicking on an already-focused form field. On
372 // the initial click (not focused yet), only show password suggestions.
373 options.show_full_suggestion_list =
374 options.show_full_suggestion_list || was_focused;
375 options.show_password_suggestions_only = !was_focused;
377 ShowSuggestions(element, options);
380 void AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {
381 password_autofill_agent_->TextFieldDidEndEditing(element);
382 has_shown_autofill_popup_for_current_edit_ = false;
383 Send(new AutofillHostMsg_DidEndTextFieldEditing(routing_id()));
386 void AutofillAgent::textFieldDidChange(const WebFormControlElement& element) {
387 DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
388 if (ignore_text_changes_)
389 return;
391 if (!IsUserGesture())
392 return;
394 // We post a task for doing the Autofill as the caret position is not set
395 // properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and
396 // it is needed to trigger autofill.
397 weak_ptr_factory_.InvalidateWeakPtrs();
398 base::MessageLoop::current()->PostTask(
399 FROM_HERE,
400 base::Bind(&AutofillAgent::TextFieldDidChangeImpl,
401 weak_ptr_factory_.GetWeakPtr(),
402 element));
405 void AutofillAgent::TextFieldDidChangeImpl(
406 const WebFormControlElement& element) {
407 // If the element isn't focused then the changes don't matter. This check is
408 // required to properly handle IME interactions.
409 if (!element.focused())
410 return;
412 const WebInputElement* input_element = toWebInputElement(&element);
413 if (input_element) {
414 if (password_generation_agent_ &&
415 password_generation_agent_->TextDidChangeInTextField(*input_element)) {
416 is_popup_possibly_visible_ = true;
417 return;
420 if (password_autofill_agent_->TextDidChangeInTextField(*input_element)) {
421 is_popup_possibly_visible_ = true;
422 element_ = element;
423 return;
427 ShowSuggestionsOptions options;
428 options.requires_caret_at_end = true;
429 ShowSuggestions(element, options);
431 FormData form;
432 FormFieldData field;
433 if (FindFormAndFieldForFormControlElement(element, &form, &field)) {
434 Send(new AutofillHostMsg_TextFieldDidChange(routing_id(), form, field,
435 base::TimeTicks::Now()));
439 void AutofillAgent::textFieldDidReceiveKeyDown(const WebInputElement& element,
440 const WebKeyboardEvent& event) {
441 if (password_autofill_agent_->TextFieldHandlingKeyDown(element, event)) {
442 element_ = element;
443 return;
446 if (event.windowsKeyCode == ui::VKEY_DOWN ||
447 event.windowsKeyCode == ui::VKEY_UP) {
448 ShowSuggestionsOptions options;
449 options.autofill_on_empty_values = true;
450 options.requires_caret_at_end = true;
451 ShowSuggestions(element, options);
455 void AutofillAgent::openTextDataListChooser(const WebInputElement& element) {
456 ShowSuggestionsOptions options;
457 options.autofill_on_empty_values = true;
458 options.datalist_only = true;
459 ShowSuggestions(element, options);
462 void AutofillAgent::dataListOptionsChanged(const WebInputElement& element) {
463 if (!is_popup_possibly_visible_ || !element.focused())
464 return;
466 TextFieldDidChangeImpl(element);
469 void AutofillAgent::firstUserGestureObserved() {
470 password_autofill_agent_->FirstUserGestureObserved();
471 Send(new AutofillHostMsg_FirstUserGestureObserved(routing_id()));
474 void AutofillAgent::AcceptDataListSuggestion(
475 const base::string16& suggested_value) {
476 WebInputElement* input_element = toWebInputElement(&element_);
477 DCHECK(input_element);
478 base::string16 new_value = suggested_value;
479 // If this element takes multiple values then replace the last part with
480 // the suggestion.
481 if (input_element->isMultiple() && input_element->isEmailField()) {
482 std::vector<base::string16> parts;
484 base::SplitStringDontTrim(input_element->editingValue(), ',', &parts);
485 if (parts.size() == 0)
486 parts.push_back(base::string16());
488 base::string16 last_part = parts.back();
489 // We want to keep just the leading whitespace.
490 for (size_t i = 0; i < last_part.size(); ++i) {
491 if (!IsWhitespace(last_part[i])) {
492 last_part = last_part.substr(0, i);
493 break;
496 last_part.append(suggested_value);
497 parts[parts.size() - 1] = last_part;
499 new_value = JoinString(parts, ',');
501 FillFieldWithValue(new_value, input_element);
504 void AutofillAgent::OnFieldTypePredictionsAvailable(
505 const std::vector<FormDataPredictions>& forms) {
506 for (size_t i = 0; i < forms.size(); ++i) {
507 form_cache_.ShowPredictions(forms[i]);
511 void AutofillAgent::OnFillForm(int query_id, const FormData& form) {
512 if (query_id != autofill_query_id_)
513 return;
515 was_query_node_autofilled_ = element_.isAutofilled();
516 FillForm(form, element_);
517 Send(new AutofillHostMsg_DidFillAutofillFormData(routing_id(),
518 base::TimeTicks::Now()));
521 void AutofillAgent::OnFirstUserGestureObservedInTab() {
522 password_autofill_agent_->FirstUserGestureObserved();
525 void AutofillAgent::OnPing() {
526 Send(new AutofillHostMsg_PingAck(routing_id()));
529 void AutofillAgent::OnPreviewForm(int query_id, const FormData& form) {
530 if (query_id != autofill_query_id_)
531 return;
533 was_query_node_autofilled_ = element_.isAutofilled();
534 PreviewForm(form, element_);
535 Send(new AutofillHostMsg_DidPreviewAutofillFormData(routing_id()));
538 void AutofillAgent::OnClearForm() {
539 form_cache_.ClearFormWithElement(element_);
542 void AutofillAgent::OnClearPreviewedForm() {
543 if (!element_.isNull()) {
544 if (password_autofill_agent_->DidClearAutofillSelection(element_))
545 return;
547 ClearPreviewedFormWithElement(element_, was_query_node_autofilled_);
548 } else {
549 // TODO(isherman): There seem to be rare cases where this code *is*
550 // reachable: see [ http://crbug.com/96321#c6 ]. Ideally we would
551 // understand those cases and fix the code to avoid them. However, so far I
552 // have been unable to reproduce such a case locally. If you hit this
553 // NOTREACHED(), please file a bug against me.
554 NOTREACHED();
558 void AutofillAgent::OnFillFieldWithValue(const base::string16& value) {
559 WebInputElement* input_element = toWebInputElement(&element_);
560 if (input_element) {
561 FillFieldWithValue(value, input_element);
562 input_element->setAutofilled(true);
566 void AutofillAgent::OnPreviewFieldWithValue(const base::string16& value) {
567 WebInputElement* input_element = toWebInputElement(&element_);
568 if (input_element)
569 PreviewFieldWithValue(value, input_element);
572 void AutofillAgent::OnAcceptDataListSuggestion(const base::string16& value) {
573 AcceptDataListSuggestion(value);
576 void AutofillAgent::OnFillPasswordSuggestion(const base::string16& username,
577 const base::string16& password) {
578 bool handled = password_autofill_agent_->FillSuggestion(
579 element_,
580 username,
581 password);
582 DCHECK(handled);
585 void AutofillAgent::OnPreviewPasswordSuggestion(
586 const base::string16& username,
587 const base::string16& password) {
588 bool handled = password_autofill_agent_->PreviewSuggestion(
589 element_,
590 username,
591 password);
592 DCHECK(handled);
595 void AutofillAgent::OnRequestAutocompleteResult(
596 WebFormElement::AutocompleteResult result,
597 const base::string16& message,
598 const FormData& form_data) {
599 if (in_flight_request_form_.isNull())
600 return;
602 if (result == WebFormElement::AutocompleteResultSuccess) {
603 FillFormIncludingNonFocusableElements(form_data, in_flight_request_form_);
604 if (!in_flight_request_form_.checkValidity())
605 result = WebFormElement::AutocompleteResultErrorInvalid;
608 in_flight_request_form_.finishRequestAutocomplete(result);
610 if (!message.empty()) {
611 const base::string16 prefix(base::ASCIIToUTF16("requestAutocomplete: "));
612 WebConsoleMessage console_message = WebConsoleMessage(
613 WebConsoleMessage::LevelLog, WebString(prefix + message));
614 in_flight_request_form_.document().frame()->addMessageToConsole(
615 console_message);
618 in_flight_request_form_.reset();
621 void AutofillAgent::ShowSuggestions(const WebFormControlElement& element,
622 const ShowSuggestionsOptions& options) {
623 if (!element.isEnabled() || element.isReadOnly())
624 return;
625 if (!options.datalist_only && !element.suggestedValue().isEmpty())
626 return;
628 const WebInputElement* input_element = toWebInputElement(&element);
629 if (input_element) {
630 if (!input_element->isTextField())
631 return;
632 if (!options.datalist_only && !input_element->suggestedValue().isEmpty())
633 return;
634 } else {
635 DCHECK(IsTextAreaElement(element));
636 if (!element.toConst<WebTextAreaElement>().suggestedValue().isEmpty())
637 return;
640 // Don't attempt to autofill with values that are too large or if filling
641 // criteria are not met.
642 WebString value = element.editingValue();
643 if (!options.datalist_only &&
644 (value.length() > kMaxDataLength ||
645 (!options.autofill_on_empty_values && value.isEmpty()) ||
646 (options.requires_caret_at_end &&
647 (element.selectionStart() != element.selectionEnd() ||
648 element.selectionEnd() != static_cast<int>(value.length()))))) {
649 // Any popup currently showing is obsolete.
650 HidePopup();
651 return;
654 element_ = element;
655 if (IsAutofillableInputElement(input_element) &&
656 (password_autofill_agent_->ShowSuggestions(
657 *input_element, options.show_full_suggestion_list) ||
658 options.show_password_suggestions_only)) {
659 is_popup_possibly_visible_ = true;
660 return;
663 // Password field elements should only have suggestions shown by the password
664 // autofill agent.
665 if (input_element && input_element->isPasswordField())
666 return;
668 QueryAutofillSuggestions(element, options.datalist_only);
671 void AutofillAgent::QueryAutofillSuggestions(
672 const WebFormControlElement& element,
673 bool datalist_only) {
674 if (!element.document().frame())
675 return;
677 DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
679 static int query_counter = 0;
680 autofill_query_id_ = query_counter++;
682 FormData form;
683 FormFieldData field;
684 if (!FindFormAndFieldForFormControlElement(element, &form, &field)) {
685 // If we didn't find the cached form, at least let autocomplete have a shot
686 // at providing suggestions.
687 WebFormControlElementToFormField(element, EXTRACT_VALUE, &field);
689 if (datalist_only)
690 field.should_autocomplete = false;
692 gfx::RectF bounding_box_scaled = GetScaledBoundingBox(
693 render_frame()->GetRenderView()->GetWebView()->pageScaleFactor(),
694 &element_);
696 std::vector<base::string16> data_list_values;
697 std::vector<base::string16> data_list_labels;
698 const WebInputElement* input_element = toWebInputElement(&element);
699 if (input_element) {
700 // Find the datalist values and send them to the browser process.
701 GetDataListSuggestions(*input_element,
702 datalist_only,
703 &data_list_values,
704 &data_list_labels);
705 TrimStringVectorForIPC(&data_list_values);
706 TrimStringVectorForIPC(&data_list_labels);
709 is_popup_possibly_visible_ = true;
710 Send(new AutofillHostMsg_SetDataList(routing_id(),
711 data_list_values,
712 data_list_labels));
714 Send(new AutofillHostMsg_QueryFormFieldAutofill(
715 routing_id(), autofill_query_id_, form, field, bounding_box_scaled));
718 void AutofillAgent::FillFieldWithValue(const base::string16& value,
719 WebInputElement* node) {
720 base::AutoReset<bool> auto_reset(&ignore_text_changes_, true);
721 node->setEditingValue(value.substr(0, node->maxLength()));
724 void AutofillAgent::PreviewFieldWithValue(const base::string16& value,
725 WebInputElement* node) {
726 was_query_node_autofilled_ = element_.isAutofilled();
727 node->setSuggestedValue(value.substr(0, node->maxLength()));
728 node->setAutofilled(true);
729 node->setSelectionRange(node->value().length(),
730 node->suggestedValue().length());
733 void AutofillAgent::ProcessForms() {
734 // Record timestamp of when the forms are first seen. This is used to
735 // measure the overhead of the Autofill feature.
736 base::TimeTicks forms_seen_timestamp = base::TimeTicks::Now();
738 WebLocalFrame* frame = render_frame()->GetWebFrame();
739 std::vector<FormData> forms = form_cache_.ExtractNewForms();
741 // Always communicate to browser process for topmost frame.
742 if (!forms.empty() || !frame->parent()) {
743 Send(new AutofillHostMsg_FormsSeen(routing_id(), forms,
744 forms_seen_timestamp));
748 void AutofillAgent::HidePopup() {
749 if (!is_popup_possibly_visible_)
750 return;
751 is_popup_possibly_visible_ = false;
752 Send(new AutofillHostMsg_HidePopup(routing_id()));
755 bool AutofillAgent::IsUserGesture() const {
756 return WebUserGestureIndicator::isProcessingUserGesture();
759 void AutofillAgent::didAssociateFormControls(const WebVector<WebNode>& nodes) {
760 for (size_t i = 0; i < nodes.size(); ++i) {
761 WebLocalFrame* frame = nodes[i].document().frame();
762 // Only monitors dynamic forms created in the top frame. Dynamic forms
763 // inserted in iframes are not captured yet. Frame is only processed
764 // if it has finished loading, otherwise you can end up with a partially
765 // parsed form.
766 if (frame && !frame->isLoading()) {
767 ProcessForms();
768 password_autofill_agent_->OnDynamicFormsSeen();
769 if (password_generation_agent_)
770 password_generation_agent_->OnDynamicFormsSeen();
771 return;
776 void AutofillAgent::xhrSucceeded() {
777 password_autofill_agent_->XHRSucceeded();
780 // LegacyAutofillAgent ---------------------------------------------------------
782 AutofillAgent::LegacyAutofillAgent::LegacyAutofillAgent(
783 content::RenderView* render_view,
784 AutofillAgent* agent)
785 : content::RenderViewObserver(render_view), agent_(agent) {
788 AutofillAgent::LegacyAutofillAgent::~LegacyAutofillAgent() {
791 void AutofillAgent::LegacyAutofillAgent::OnDestruct() {
792 // No-op. Don't delete |this|.
795 void AutofillAgent::LegacyAutofillAgent::FocusChangeComplete() {
796 agent_->FocusChangeComplete();
799 } // namespace autofill