Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / components / autofill / content / renderer / autofill_agent.cc
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.
4
5 #include "components/autofill/content/renderer/autofill_agent.h"
6
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_view.h"
31 #include "net/cert/cert_status_flags.h"
32 #include "third_party/WebKit/public/platform/WebRect.h"
33 #include "third_party/WebKit/public/platform/WebURLRequest.h"
34 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
35 #include "third_party/WebKit/public/web/WebDataSource.h"
36 #include "third_party/WebKit/public/web/WebDocument.h"
37 #include "third_party/WebKit/public/web/WebElementCollection.h"
38 #include "third_party/WebKit/public/web/WebFormControlElement.h"
39 #include "third_party/WebKit/public/web/WebFormElement.h"
40 #include "third_party/WebKit/public/web/WebInputEvent.h"
41 #include "third_party/WebKit/public/web/WebLocalFrame.h"
42 #include "third_party/WebKit/public/web/WebNode.h"
43 #include "third_party/WebKit/public/web/WebOptionElement.h"
44 #include "third_party/WebKit/public/web/WebTextAreaElement.h"
45 #include "third_party/WebKit/public/web/WebView.h"
46 #include "ui/base/l10n/l10n_util.h"
47 #include "ui/events/keycodes/keyboard_codes.h"
48
49 using blink::WebAutofillClient;
50 using blink::WebConsoleMessage;
51 using blink::WebElement;
52 using blink::WebElementCollection;
53 using blink::WebFormControlElement;
54 using blink::WebFormElement;
55 using blink::WebFrame;
56 using blink::WebInputElement;
57 using blink::WebKeyboardEvent;
58 using blink::WebLocalFrame;
59 using blink::WebNode;
60 using blink::WebOptionElement;
61 using blink::WebString;
62 using blink::WebTextAreaElement;
63 using blink::WebVector;
64
65 namespace autofill {
66
67 namespace {
68
69 // Gets all the data list values (with corresponding label) for the given
70 // element.
71 void GetDataListSuggestions(const WebInputElement& element,
72                             bool ignore_current_value,
73                             std::vector<base::string16>* values,
74                             std::vector<base::string16>* labels) {
75   WebElementCollection options = element.dataListOptions();
76   if (options.isNull())
77     return;
78
79   base::string16 prefix;
80   if (!ignore_current_value) {
81     prefix = element.editingValue();
82     if (element.isMultiple() && element.isEmailField()) {
83       std::vector<base::string16> parts;
84       base::SplitStringDontTrim(prefix, ',', &parts);
85       if (parts.size() > 0) {
86         base::TrimWhitespace(parts[parts.size() - 1], base::TRIM_LEADING,
87                              &prefix);
88       }
89     }
90   }
91   for (WebOptionElement option = options.firstItem().to<WebOptionElement>();
92        !option.isNull(); option = options.nextItem().to<WebOptionElement>()) {
93     if (!StartsWith(option.value(), prefix, false) ||
94         option.value() == prefix ||
95         !element.isValidValue(option.value()))
96       continue;
97
98     values->push_back(option.value());
99     if (option.value() != option.label())
100       labels->push_back(option.label());
101     else
102       labels->push_back(base::string16());
103   }
104 }
105
106 // Trim the vector before sending it to the browser process to ensure we
107 // don't send too much data through the IPC.
108 void TrimStringVectorForIPC(std::vector<base::string16>* strings) {
109   // Limit the size of the vector.
110   if (strings->size() > kMaxListSize)
111     strings->resize(kMaxListSize);
112
113   // Limit the size of the strings in the vector.
114   for (size_t i = 0; i < strings->size(); ++i) {
115     if ((*strings)[i].length() > kMaxDataLength)
116       (*strings)[i].resize(kMaxDataLength);
117   }
118 }
119
120 }  // namespace
121
122 AutofillAgent::AutofillAgent(content::RenderView* render_view,
123                              PasswordAutofillAgent* password_autofill_agent,
124                              PasswordGenerationAgent* password_generation_agent)
125     : content::RenderViewObserver(render_view),
126       password_autofill_agent_(password_autofill_agent),
127       password_generation_agent_(password_generation_agent),
128       autofill_query_id_(0),
129       web_view_(render_view->GetWebView()),
130       display_warning_if_disabled_(false),
131       was_query_node_autofilled_(false),
132       has_shown_autofill_popup_for_current_edit_(false),
133       did_set_node_text_(false),
134       ignore_text_changes_(false),
135       is_popup_possibly_visible_(false),
136       main_frame_processed_(false),
137       weak_ptr_factory_(this) {
138   render_view->GetWebView()->setAutofillClient(this);
139
140   // The PageClickTracker is a RenderViewObserver, and hence will be freed when
141   // the RenderView is destroyed.
142   new PageClickTracker(render_view, this);
143 }
144
145 AutofillAgent::~AutofillAgent() {}
146
147 bool AutofillAgent::OnMessageReceived(const IPC::Message& message) {
148   bool handled = true;
149   IPC_BEGIN_MESSAGE_MAP(AutofillAgent, message)
150     IPC_MESSAGE_HANDLER(AutofillMsg_Ping, OnPing)
151     IPC_MESSAGE_HANDLER(AutofillMsg_FillForm, OnFillForm)
152     IPC_MESSAGE_HANDLER(AutofillMsg_PreviewForm, OnPreviewForm)
153     IPC_MESSAGE_HANDLER(AutofillMsg_FieldTypePredictionsAvailable,
154                         OnFieldTypePredictionsAvailable)
155     IPC_MESSAGE_HANDLER(AutofillMsg_ClearForm, OnClearForm)
156     IPC_MESSAGE_HANDLER(AutofillMsg_ClearPreviewedForm, OnClearPreviewedForm)
157     IPC_MESSAGE_HANDLER(AutofillMsg_FillFieldWithValue, OnFillFieldWithValue)
158     IPC_MESSAGE_HANDLER(AutofillMsg_PreviewFieldWithValue,
159                         OnPreviewFieldWithValue)
160     IPC_MESSAGE_HANDLER(AutofillMsg_AcceptDataListSuggestion,
161                         OnAcceptDataListSuggestion)
162     IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordSuggestion,
163                         OnFillPasswordSuggestion)
164     IPC_MESSAGE_HANDLER(AutofillMsg_PreviewPasswordSuggestion,
165                         OnPreviewPasswordSuggestion)
166     IPC_MESSAGE_HANDLER(AutofillMsg_RequestAutocompleteResult,
167                         OnRequestAutocompleteResult)
168     IPC_MESSAGE_UNHANDLED(handled = false)
169   IPC_END_MESSAGE_MAP()
170   return handled;
171 }
172
173 void AutofillAgent::DidFinishDocumentLoad(WebLocalFrame* frame) {
174   // If the main frame just finished loading, we should process it.
175   if (!frame->parent())
176     main_frame_processed_ = false;
177
178   ProcessForms(*frame);
179 }
180
181 void AutofillAgent::DidCommitProvisionalLoad(WebLocalFrame* frame,
182                                              bool is_new_navigation) {
183   form_cache_.ResetFrame(*frame);
184 }
185
186 void AutofillAgent::FrameDetached(WebFrame* frame) {
187   form_cache_.ResetFrame(*frame);
188 }
189
190 void AutofillAgent::FrameWillClose(WebFrame* frame) {
191   if (in_flight_request_form_.isNull())
192     return;
193
194   for (WebFrame* temp = in_flight_request_form_.document().frame();
195        temp; temp = temp->parent()) {
196     if (temp == frame) {
197       Send(new AutofillHostMsg_CancelRequestAutocomplete(routing_id()));
198       break;
199     }
200   }
201 }
202
203 void AutofillAgent::WillSubmitForm(WebLocalFrame* frame,
204                                    const WebFormElement& form) {
205   FormData form_data;
206   if (WebFormElementToFormData(form,
207                                WebFormControlElement(),
208                                REQUIRE_NONE,
209                                static_cast<ExtractMask>(
210                                    EXTRACT_VALUE | EXTRACT_OPTION_TEXT),
211                                &form_data,
212                                NULL)) {
213     Send(new AutofillHostMsg_FormSubmitted(routing_id(), form_data,
214                                            base::TimeTicks::Now()));
215   }
216 }
217
218 void AutofillAgent::FocusedNodeChanged(const WebNode& node) {
219   HidePopup();
220
221   if (password_generation_agent_ &&
222       password_generation_agent_->FocusedNodeHasChanged(node)) {
223     is_popup_possibly_visible_ = true;
224     return;
225   }
226
227   if (node.isNull() || !node.isElementNode())
228     return;
229
230   WebElement web_element = node.toConst<WebElement>();
231
232   if (!web_element.document().frame())
233       return;
234
235   const WebInputElement* element = toWebInputElement(&web_element);
236
237   if (!element || !element->isEnabled() || element->isReadOnly() ||
238       !element->isTextField() || element->isPasswordField())
239     return;
240
241   element_ = *element;
242 }
243
244 void AutofillAgent::OrientationChangeEvent() {
245   HidePopup();
246 }
247
248 void AutofillAgent::Resized() {
249   HidePopup();
250 }
251
252 void AutofillAgent::DidChangeScrollOffset(WebLocalFrame*) {
253   HidePopup();
254 }
255
256 void AutofillAgent::didRequestAutocomplete(
257     const WebFormElement& form) {
258   // Disallow the dialog over non-https or broken https, except when the
259   // ignore SSL flag is passed. See http://crbug.com/272512.
260   // TODO(palmer): this should be moved to the browser process after frames
261   // get their own processes.
262   GURL url(form.document().url());
263   content::SSLStatus ssl_status =
264       render_view()->GetSSLStatusOfFrame(form.document().frame());
265   bool is_safe = url.SchemeIs(url::kHttpsScheme) &&
266       !net::IsCertStatusError(ssl_status.cert_status);
267   bool allow_unsafe = CommandLine::ForCurrentProcess()->HasSwitch(
268       ::switches::kReduceSecurityForTesting);
269
270   FormData form_data;
271   std::string error_message;
272   if (!in_flight_request_form_.isNull()) {
273     error_message = "already active.";
274   } else if (!is_safe && !allow_unsafe) {
275     error_message =
276         "must use a secure connection or --reduce-security-for-testing.";
277   } else if (!WebFormElementToFormData(form,
278                                        WebFormControlElement(),
279                                        REQUIRE_AUTOCOMPLETE,
280                                        static_cast<ExtractMask>(
281                                            EXTRACT_VALUE |
282                                            EXTRACT_OPTION_TEXT |
283                                            EXTRACT_OPTIONS),
284                                        &form_data,
285                                        NULL)) {
286     error_message = "failed to parse form.";
287   }
288
289   if (!error_message.empty()) {
290     WebConsoleMessage console_message = WebConsoleMessage(
291         WebConsoleMessage::LevelLog,
292         WebString(base::ASCIIToUTF16("requestAutocomplete: ") +
293                       base::ASCIIToUTF16(error_message)));
294     form.document().frame()->addMessageToConsole(console_message);
295     WebFormElement(form).finishRequestAutocomplete(
296         WebFormElement::AutocompleteResultErrorDisabled);
297     return;
298   }
299
300   // Cancel any pending Autofill requests and hide any currently showing popups.
301   ++autofill_query_id_;
302   HidePopup();
303
304   in_flight_request_form_ = form;
305   Send(new AutofillHostMsg_RequestAutocomplete(routing_id(), form_data, url));
306 }
307
308 void AutofillAgent::setIgnoreTextChanges(bool ignore) {
309   ignore_text_changes_ = ignore;
310 }
311
312 void AutofillAgent::FormControlElementClicked(
313     const WebFormControlElement& element,
314     bool was_focused) {
315   const WebInputElement* input_element = toWebInputElement(&element);
316   if (!input_element && !IsTextAreaElement(element))
317     return;
318
319   bool show_full_suggestion_list = element.isAutofilled() || was_focused;
320   bool show_password_suggestions_only = !was_focused;
321   ShowSuggestions(element,
322                   true,
323                   false,
324                   true,
325                   false,
326                   show_full_suggestion_list,
327                   show_password_suggestions_only);
328 }
329
330 void AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {
331   password_autofill_agent_->TextFieldDidEndEditing(element);
332   has_shown_autofill_popup_for_current_edit_ = false;
333   Send(new AutofillHostMsg_DidEndTextFieldEditing(routing_id()));
334 }
335
336 void AutofillAgent::textFieldDidChange(const WebFormControlElement& element) {
337   if (ignore_text_changes_)
338     return;
339
340   DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
341
342   if (did_set_node_text_) {
343     did_set_node_text_ = false;
344     return;
345   }
346
347   // We post a task for doing the Autofill as the caret position is not set
348   // properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and
349   // it is needed to trigger autofill.
350   weak_ptr_factory_.InvalidateWeakPtrs();
351   base::MessageLoop::current()->PostTask(
352       FROM_HERE,
353       base::Bind(&AutofillAgent::TextFieldDidChangeImpl,
354                  weak_ptr_factory_.GetWeakPtr(),
355                  element));
356 }
357
358 void AutofillAgent::TextFieldDidChangeImpl(
359     const WebFormControlElement& element) {
360   // If the element isn't focused then the changes don't matter. This check is
361   // required to properly handle IME interactions.
362   if (!element.focused())
363     return;
364
365   const WebInputElement* input_element = toWebInputElement(&element);
366   if (input_element) {
367     if (password_generation_agent_ &&
368         password_generation_agent_->TextDidChangeInTextField(*input_element)) {
369       is_popup_possibly_visible_ = true;
370       return;
371     }
372
373     if (password_autofill_agent_->TextDidChangeInTextField(*input_element)) {
374       element_ = element;
375       return;
376     }
377   }
378
379   ShowSuggestions(element, false, true, false, false, false, false);
380
381   FormData form;
382   FormFieldData field;
383   if (FindFormAndFieldForFormControlElement(element,
384                                             &form,
385                                             &field,
386                                             REQUIRE_NONE)) {
387     Send(new AutofillHostMsg_TextFieldDidChange(routing_id(), form, field,
388                                                 base::TimeTicks::Now()));
389   }
390 }
391
392 void AutofillAgent::textFieldDidReceiveKeyDown(const WebInputElement& element,
393                                                const WebKeyboardEvent& event) {
394   if (password_autofill_agent_->TextFieldHandlingKeyDown(element, event)) {
395     element_ = element;
396     return;
397   }
398
399   if (event.windowsKeyCode == ui::VKEY_DOWN ||
400       event.windowsKeyCode == ui::VKEY_UP)
401     ShowSuggestions(element, true, true, true, false, false, false);
402 }
403
404 void AutofillAgent::openTextDataListChooser(const WebInputElement& element) {
405   ShowSuggestions(element, true, false, false, true, false, false);
406 }
407
408 void AutofillAgent::firstUserGestureObserved() {
409   password_autofill_agent_->FirstUserGestureObserved();
410 }
411
412 void AutofillAgent::AcceptDataListSuggestion(
413     const base::string16& suggested_value) {
414   WebInputElement* input_element = toWebInputElement(&element_);
415   DCHECK(input_element);
416   base::string16 new_value = suggested_value;
417   // If this element takes multiple values then replace the last part with
418   // the suggestion.
419   if (input_element->isMultiple() && input_element->isEmailField()) {
420     std::vector<base::string16> parts;
421
422     base::SplitStringDontTrim(input_element->editingValue(), ',', &parts);
423     if (parts.size() == 0)
424       parts.push_back(base::string16());
425
426     base::string16 last_part = parts.back();
427     // We want to keep just the leading whitespace.
428     for (size_t i = 0; i < last_part.size(); ++i) {
429       if (!IsWhitespace(last_part[i])) {
430         last_part = last_part.substr(0, i);
431         break;
432       }
433     }
434     last_part.append(suggested_value);
435     parts[parts.size() - 1] = last_part;
436
437     new_value = JoinString(parts, ',');
438   }
439   FillFieldWithValue(new_value, input_element);
440 }
441
442 void AutofillAgent::OnFieldTypePredictionsAvailable(
443     const std::vector<FormDataPredictions>& forms) {
444   for (size_t i = 0; i < forms.size(); ++i) {
445     form_cache_.ShowPredictions(forms[i]);
446   }
447 }
448
449 void AutofillAgent::OnFillForm(int query_id, const FormData& form) {
450   if (!render_view()->GetWebView() || query_id != autofill_query_id_)
451     return;
452
453   was_query_node_autofilled_ = element_.isAutofilled();
454   FillForm(form, element_);
455   Send(new AutofillHostMsg_DidFillAutofillFormData(routing_id(),
456                                                    base::TimeTicks::Now()));
457 }
458
459 void AutofillAgent::OnPing() {
460   Send(new AutofillHostMsg_PingAck(routing_id()));
461 }
462
463 void AutofillAgent::OnPreviewForm(int query_id, const FormData& form) {
464   if (!render_view()->GetWebView() || query_id != autofill_query_id_)
465     return;
466
467   was_query_node_autofilled_ = element_.isAutofilled();
468   PreviewForm(form, element_);
469   Send(new AutofillHostMsg_DidPreviewAutofillFormData(routing_id()));
470 }
471
472 void AutofillAgent::OnClearForm() {
473   form_cache_.ClearFormWithElement(element_);
474 }
475
476 void AutofillAgent::OnClearPreviewedForm() {
477   if (!element_.isNull()) {
478     if (password_autofill_agent_->DidClearAutofillSelection(element_))
479       return;
480
481     ClearPreviewedFormWithElement(element_, was_query_node_autofilled_);
482   } else {
483     // TODO(isherman): There seem to be rare cases where this code *is*
484     // reachable: see [ http://crbug.com/96321#c6 ].  Ideally we would
485     // understand those cases and fix the code to avoid them.  However, so far I
486     // have been unable to reproduce such a case locally.  If you hit this
487     // NOTREACHED(), please file a bug against me.
488     NOTREACHED();
489   }
490 }
491
492 void AutofillAgent::OnFillFieldWithValue(const base::string16& value) {
493   WebInputElement* input_element = toWebInputElement(&element_);
494   if (input_element) {
495     FillFieldWithValue(value, input_element);
496     input_element->setAutofilled(true);
497   }
498 }
499
500 void AutofillAgent::OnPreviewFieldWithValue(const base::string16& value) {
501   WebInputElement* input_element = toWebInputElement(&element_);
502   if (input_element)
503     PreviewFieldWithValue(value, input_element);
504 }
505
506 void AutofillAgent::OnAcceptDataListSuggestion(const base::string16& value) {
507   AcceptDataListSuggestion(value);
508 }
509
510 void AutofillAgent::OnFillPasswordSuggestion(const base::string16& username,
511                                              const base::string16& password) {
512   bool handled = password_autofill_agent_->FillSuggestion(
513       element_,
514       username,
515       password);
516   DCHECK(handled);
517 }
518
519 void AutofillAgent::OnPreviewPasswordSuggestion(
520     const base::string16& username,
521     const base::string16& password) {
522   bool handled = password_autofill_agent_->PreviewSuggestion(
523       element_,
524       username,
525       password);
526   DCHECK(handled);
527 }
528
529 void AutofillAgent::OnRequestAutocompleteResult(
530     WebFormElement::AutocompleteResult result,
531     const base::string16& message,
532     const FormData& form_data) {
533   if (in_flight_request_form_.isNull())
534     return;
535
536   if (result == WebFormElement::AutocompleteResultSuccess) {
537     FillFormIncludingNonFocusableElements(form_data, in_flight_request_form_);
538     if (!in_flight_request_form_.checkValidity())
539       result = WebFormElement::AutocompleteResultErrorInvalid;
540   }
541
542   in_flight_request_form_.finishRequestAutocomplete(result);
543
544   if (!message.empty()) {
545     const base::string16 prefix(base::ASCIIToUTF16("requestAutocomplete: "));
546     WebConsoleMessage console_message = WebConsoleMessage(
547         WebConsoleMessage::LevelLog, WebString(prefix + message));
548     in_flight_request_form_.document().frame()->addMessageToConsole(
549         console_message);
550   }
551
552   in_flight_request_form_.reset();
553 }
554
555 void AutofillAgent::ShowSuggestions(const WebFormControlElement& element,
556                                     bool autofill_on_empty_values,
557                                     bool requires_caret_at_end,
558                                     bool display_warning_if_disabled,
559                                     bool datalist_only,
560                                     bool show_full_suggestion_list,
561                                     bool show_password_suggestions_only) {
562   if (!element.isEnabled() || element.isReadOnly())
563     return;
564   if (!datalist_only && !element.suggestedValue().isEmpty())
565     return;
566
567   const WebInputElement* input_element = toWebInputElement(&element);
568   if (input_element) {
569     if (!input_element->isTextField() || input_element->isPasswordField())
570       return;
571     if (!datalist_only && !input_element->suggestedValue().isEmpty())
572       return;
573   } else {
574     DCHECK(IsTextAreaElement(element));
575     if (!element.toConst<WebTextAreaElement>().suggestedValue().isEmpty())
576       return;
577   }
578
579   // Don't attempt to autofill with values that are too large or if filling
580   // criteria are not met.
581   WebString value = element.editingValue();
582   if (!datalist_only &&
583       (value.length() > kMaxDataLength ||
584        (!autofill_on_empty_values && value.isEmpty()) ||
585        (requires_caret_at_end &&
586         (element.selectionStart() != element.selectionEnd() ||
587          element.selectionEnd() != static_cast<int>(value.length()))))) {
588     // Any popup currently showing is obsolete.
589     HidePopup();
590     return;
591   }
592
593   element_ = element;
594   if (IsAutofillableInputElement(input_element) &&
595       (password_autofill_agent_->ShowSuggestions(*input_element,
596                                                  show_full_suggestion_list) ||
597        show_password_suggestions_only)) {
598     is_popup_possibly_visible_ = true;
599     return;
600   }
601
602   // If autocomplete is disabled at the field level, ensure that the native
603   // UI won't try to show a warning, since that may conflict with a custom
604   // popup. Note that we cannot use the WebKit method element.autoComplete()
605   // as it does not allow us to distinguish the case where autocomplete is
606   // disabled for *both* the element and for the form.
607   const base::string16 autocomplete_attribute =
608       element.getAttribute("autocomplete");
609   if (LowerCaseEqualsASCII(autocomplete_attribute, "off"))
610     display_warning_if_disabled = false;
611
612   QueryAutofillSuggestions(element,
613                            display_warning_if_disabled,
614                            datalist_only);
615 }
616
617 void AutofillAgent::QueryAutofillSuggestions(
618     const WebFormControlElement& element,
619     bool display_warning_if_disabled,
620     bool datalist_only) {
621   if (!element.document().frame())
622     return;
623
624   DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
625
626   static int query_counter = 0;
627   autofill_query_id_ = query_counter++;
628   display_warning_if_disabled_ = display_warning_if_disabled;
629
630   // If autocomplete is disabled at the form level, we want to see if there
631   // would have been any suggestions were it enabled, so that we can show a
632   // warning.  Otherwise, we want to ignore fields that disable autocomplete, so
633   // that the suggestions list does not include suggestions for these form
634   // fields -- see comment 1 on http://crbug.com/69914
635   const RequirementsMask requirements =
636       element.autoComplete() ? REQUIRE_AUTOCOMPLETE : REQUIRE_NONE;
637
638   FormData form;
639   FormFieldData field;
640   if (!FindFormAndFieldForFormControlElement(element, &form, &field,
641                                              requirements)) {
642     // If we didn't find the cached form, at least let autocomplete have a shot
643     // at providing suggestions.
644     WebFormControlElementToFormField(element, EXTRACT_VALUE, &field);
645   }
646   if (datalist_only)
647     field.should_autocomplete = false;
648
649   gfx::RectF bounding_box_scaled =
650       GetScaledBoundingBox(web_view_->pageScaleFactor(), &element_);
651
652   std::vector<base::string16> data_list_values;
653   std::vector<base::string16> data_list_labels;
654   const WebInputElement* input_element = toWebInputElement(&element);
655   if (input_element) {
656     // Find the datalist values and send them to the browser process.
657     GetDataListSuggestions(*input_element,
658                            datalist_only,
659                            &data_list_values,
660                            &data_list_labels);
661     TrimStringVectorForIPC(&data_list_values);
662     TrimStringVectorForIPC(&data_list_labels);
663   }
664
665   is_popup_possibly_visible_ = true;
666   Send(new AutofillHostMsg_SetDataList(routing_id(),
667                                        data_list_values,
668                                        data_list_labels));
669
670   Send(new AutofillHostMsg_QueryFormFieldAutofill(routing_id(),
671                                                   autofill_query_id_,
672                                                   form,
673                                                   field,
674                                                   bounding_box_scaled,
675                                                   display_warning_if_disabled));
676 }
677
678 void AutofillAgent::FillFieldWithValue(const base::string16& value,
679                                        WebInputElement* node) {
680   did_set_node_text_ = true;
681   node->setEditingValue(value.substr(0, node->maxLength()));
682 }
683
684 void AutofillAgent::PreviewFieldWithValue(const base::string16& value,
685                                           WebInputElement* node) {
686   was_query_node_autofilled_ = element_.isAutofilled();
687   node->setSuggestedValue(value.substr(0, node->maxLength()));
688   node->setAutofilled(true);
689   node->setSelectionRange(node->value().length(),
690                           node->suggestedValue().length());
691 }
692
693 void AutofillAgent::ProcessForms(const WebLocalFrame& frame) {
694   // Record timestamp of when the forms are first seen. This is used to
695   // measure the overhead of the Autofill feature.
696   base::TimeTicks forms_seen_timestamp = base::TimeTicks::Now();
697
698   std::vector<FormData> forms;
699   form_cache_.ExtractNewForms(frame, &forms);
700
701   // Always communicate to browser process for topmost frame.
702   if (!forms.empty() ||
703       (!frame.parent() && !main_frame_processed_)) {
704     Send(new AutofillHostMsg_FormsSeen(routing_id(), forms,
705                                        forms_seen_timestamp));
706   }
707
708   if (!frame.parent())
709     main_frame_processed_ = true;
710 }
711
712 void AutofillAgent::HidePopup() {
713   if (!is_popup_possibly_visible_)
714     return;
715
716   if (!element_.isNull())
717     OnClearPreviewedForm();
718
719   is_popup_possibly_visible_ = false;
720   Send(new AutofillHostMsg_HidePopup(routing_id()));
721 }
722
723 void AutofillAgent::didAssociateFormControls(const WebVector<WebNode>& nodes) {
724   for (size_t i = 0; i < nodes.size(); ++i) {
725     WebLocalFrame* frame = nodes[i].document().frame();
726     // Only monitors dynamic forms created in the top frame. Dynamic forms
727     // inserted in iframes are not captured yet. Frame is only processed
728     // if it has finished loading, otherwise you can end up with a partially
729     // parsed form.
730     if (frame && !frame->parent() && !frame->isLoading()) {
731       ProcessForms(*frame);
732       password_autofill_agent_->OnDynamicFormsSeen(frame);
733       return;
734     }
735   }
736 }
737
738 }  // namespace autofill