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