autofill_agent.cc revision 3240926e260ce088908e02ac07a6cf7b0c0cbf44
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/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/web_element_descriptor.h"
24#include "content/public/common/password_form.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/keycodes/keyboard_codes.h"
43#include "ui/base/l10n/l10n_util.h"
44
45using WebKit::WebAutofillClient;
46using WebKit::WebFormControlElement;
47using WebKit::WebFormElement;
48using WebKit::WebFrame;
49using WebKit::WebInputElement;
50using WebKit::WebKeyboardEvent;
51using WebKit::WebNode;
52using WebKit::WebNodeCollection;
53using WebKit::WebOptionElement;
54using WebKit::WebString;
55
56namespace {
57
58// The size above which we stop triggering autofill for an input text field
59// (so to avoid sending long strings through IPC).
60const size_t kMaximumTextSizeForAutofill = 1000;
61
62// The maximum number of data list elements to send to the browser process
63// via IPC (to prevent long IPC messages).
64const size_t kMaximumDataListSizeForAutofill = 30;
65
66const int kAutocheckoutClickTimeout = 3;
67
68
69// Gets all the data list values (with corresponding label) for the given
70// element.
71void GetDataListSuggestions(const WebKit::WebInputElement& element,
72                            std::vector<base::string16>* values,
73                            std::vector<base::string16>* labels) {
74  WebNodeCollection options = element.dataListOptions();
75  if (options.isNull())
76    return;
77
78  base::string16 prefix = element.editingValue();
79  if (element.isMultiple() &&
80      element.formControlType() == WebString::fromUTF8("email")) {
81    std::vector<base::string16> parts;
82    base::SplitStringDontTrim(prefix, ',', &parts);
83    if (parts.size() > 0)
84      TrimWhitespace(parts[parts.size() - 1], TRIM_LEADING, &prefix);
85  }
86  for (WebOptionElement option = options.firstItem().to<WebOptionElement>();
87       !option.isNull(); option = options.nextItem().to<WebOptionElement>()) {
88    if (!StartsWith(option.value(), prefix, false) ||
89        option.value() == prefix ||
90        !element.isValidValue(option.value()))
91      continue;
92
93    values->push_back(option.value());
94    if (option.value() != option.label())
95      labels->push_back(option.label());
96    else
97      labels->push_back(base::string16());
98  }
99}
100
101// Trim the vector before sending it to the browser process to ensure we
102// don't send too much data through the IPC.
103void TrimStringVectorForIPC(std::vector<base::string16>* strings) {
104  // Limit the size of the vector.
105  if (strings->size() > kMaximumDataListSizeForAutofill)
106    strings->resize(kMaximumDataListSizeForAutofill);
107
108  // Limit the size of the strings in the vector.
109  for (size_t i = 0; i < strings->size(); ++i) {
110    if ((*strings)[i].length() > kMaximumTextSizeForAutofill)
111      (*strings)[i].resize(kMaximumTextSizeForAutofill);
112  }
113}
114
115gfx::RectF GetScaledBoundingBox(float scale, WebInputElement* element) {
116  gfx::Rect bounding_box(element->boundsInViewportSpace());
117  return gfx::RectF(bounding_box.x() * scale,
118                    bounding_box.y() * scale,
119                    bounding_box.width() * scale,
120                    bounding_box.height() * scale);
121}
122
123}  // namespace
124
125namespace autofill {
126
127AutofillAgent::AutofillAgent(content::RenderView* render_view,
128                             PasswordAutofillAgent* password_autofill_agent)
129    : content::RenderViewObserver(render_view),
130      password_autofill_agent_(password_autofill_agent),
131      autofill_query_id_(0),
132      autofill_action_(AUTOFILL_NONE),
133      topmost_frame_(NULL),
134      web_view_(render_view->GetWebView()),
135      display_warning_if_disabled_(false),
136      was_query_node_autofilled_(false),
137      has_shown_autofill_popup_for_current_edit_(false),
138      did_set_node_text_(false),
139      autocheckout_click_in_progress_(false),
140      is_autocheckout_supported_(false),
141      has_new_forms_for_browser_(false),
142      ignore_text_changes_(false),
143      weak_ptr_factory_(this) {
144  render_view->GetWebView()->setAutofillClient(this);
145
146  // The PageClickTracker is a RenderViewObserver, and hence will be freed when
147  // the RenderView is destroyed.
148  new PageClickTracker(render_view, this);
149}
150
151AutofillAgent::~AutofillAgent() {}
152
153bool AutofillAgent::OnMessageReceived(const IPC::Message& message) {
154  bool handled = true;
155  IPC_BEGIN_MESSAGE_MAP(AutofillAgent, message)
156    IPC_MESSAGE_HANDLER(AutofillMsg_GetAllForms, OnGetAllForms)
157    IPC_MESSAGE_HANDLER(AutofillMsg_FormDataFilled, OnFormDataFilled)
158    IPC_MESSAGE_HANDLER(AutofillMsg_FieldTypePredictionsAvailable,
159                        OnFieldTypePredictionsAvailable)
160    IPC_MESSAGE_HANDLER(AutofillMsg_SetAutofillActionFill,
161                        OnSetAutofillActionFill)
162    IPC_MESSAGE_HANDLER(AutofillMsg_ClearForm,
163                        OnClearForm)
164    IPC_MESSAGE_HANDLER(AutofillMsg_SetAutofillActionPreview,
165                        OnSetAutofillActionPreview)
166    IPC_MESSAGE_HANDLER(AutofillMsg_ClearPreviewedForm,
167                        OnClearPreviewedForm)
168    IPC_MESSAGE_HANDLER(AutofillMsg_SetNodeText,
169                        OnSetNodeText)
170    IPC_MESSAGE_HANDLER(AutofillMsg_AcceptDataListSuggestion,
171                        OnAcceptDataListSuggestion)
172    IPC_MESSAGE_HANDLER(AutofillMsg_AcceptPasswordAutofillSuggestion,
173                        OnAcceptPasswordAutofillSuggestion)
174    IPC_MESSAGE_HANDLER(AutofillMsg_RequestAutocompleteResult,
175                        OnRequestAutocompleteResult)
176    IPC_MESSAGE_HANDLER(AutofillMsg_FillFormsAndClick,
177                        OnFillFormsAndClick)
178    IPC_MESSAGE_HANDLER(AutofillMsg_AutocheckoutSupported,
179                        OnAutocheckoutSupported)
180    IPC_MESSAGE_UNHANDLED(handled = false)
181  IPC_END_MESSAGE_MAP()
182  return handled;
183}
184
185void AutofillAgent::DidFinishDocumentLoad(WebFrame* frame) {
186  // Record timestamp on document load. This is used to record overhead of
187  // Autofill feature.
188  forms_seen_timestamp_ = base::TimeTicks::Now();
189
190  // The document has now been fully loaded.  Scan for forms to be sent up to
191  // the browser.
192  std::vector<FormData> forms;
193  bool has_more_forms = false;
194  if (!frame->parent()) {
195    topmost_frame_ = frame;
196    form_elements_.clear();
197    has_more_forms = form_cache_.ExtractFormsAndFormElements(
198        *frame, kRequiredAutofillFields, &forms, &form_elements_);
199  } else {
200    form_cache_.ExtractForms(*frame, &forms);
201  }
202
203  autofill::FormsSeenState state = has_more_forms ?
204      autofill::PARTIAL_FORMS_SEEN : autofill::NO_SPECIAL_FORMS_SEEN;
205
206  // Always communicate to browser process for topmost frame.
207  if (!forms.empty() || !frame->parent()) {
208    Send(new AutofillHostMsg_FormsSeen(routing_id(), forms,
209                                       forms_seen_timestamp_,
210                                       state));
211  }
212}
213
214void AutofillAgent::DidStartProvisionalLoad(WebFrame* frame) {
215  if (!frame->parent()) {
216    is_autocheckout_supported_ = false;
217    topmost_frame_ = NULL;
218    if (click_timer_.IsRunning()) {
219      click_timer_.Stop();
220      autocheckout_click_in_progress_ = true;
221    }
222  }
223}
224
225void AutofillAgent::DidFailProvisionalLoad(WebFrame* frame,
226                                           const WebKit::WebURLError& error) {
227  if (!frame->parent() && autocheckout_click_in_progress_) {
228    autocheckout_click_in_progress_ = false;
229    ClickFailed();
230  }
231}
232
233void AutofillAgent::DidCommitProvisionalLoad(WebFrame* frame,
234                                             bool is_new_navigation) {
235  in_flight_request_form_.reset();
236  if (!frame->parent() && autocheckout_click_in_progress_) {
237    autocheckout_click_in_progress_ = false;
238    CompleteAutocheckoutPage(SUCCESS);
239  }
240}
241
242void AutofillAgent::FrameDetached(WebFrame* frame) {
243  form_cache_.ResetFrame(*frame);
244  if (!frame->parent()) {
245    // |frame| is about to be destroyed so we need to clear |top_most_frame_|.
246    topmost_frame_ = NULL;
247    click_timer_.Stop();
248  }
249}
250
251void AutofillAgent::WillSubmitForm(WebFrame* frame,
252                                   const WebFormElement& form) {
253  FormData form_data;
254  if (WebFormElementToFormData(form,
255                               WebFormControlElement(),
256                               REQUIRE_AUTOCOMPLETE,
257                               static_cast<ExtractMask>(
258                                   EXTRACT_VALUE | EXTRACT_OPTION_TEXT),
259                               &form_data,
260                               NULL)) {
261    Send(new AutofillHostMsg_FormSubmitted(routing_id(), form_data,
262                                           base::TimeTicks::Now()));
263  }
264}
265
266void AutofillAgent::ZoomLevelChanged() {
267  // Any time the zoom level changes, the page's content moves, so any Autofill
268  // popups should be hidden. This is only needed for the new Autofill UI
269  // because WebKit already knows to hide the old UI when this occurs.
270  HideAutofillUI();
271}
272
273void AutofillAgent::FocusedNodeChanged(const WebKit::WebNode& node) {
274  if (node.isNull() || !node.isElementNode())
275    return;
276
277  WebKit::WebElement web_element = node.toConst<WebKit::WebElement>();
278
279  if (!web_element.document().frame())
280      return;
281
282  const WebInputElement* element = toWebInputElement(&web_element);
283
284  if (!element || !element->isEnabled() || element->isReadOnly() ||
285      !element->isTextField() || element->isPasswordField())
286    return;
287
288  element_ = *element;
289
290  MaybeShowAutocheckoutBubble();
291}
292
293void AutofillAgent::MaybeShowAutocheckoutBubble() {
294  if (element_.isNull() || !element_.focused())
295    return;
296
297  FormData form;
298  FormFieldData field;
299  // This must be called to short circuit this method if it fails.
300  if (!FindFormAndFieldForInputElement(element_, &form, &field, REQUIRE_NONE))
301    return;
302
303  Send(new AutofillHostMsg_MaybeShowAutocheckoutBubble(
304      routing_id(),
305      form,
306      GetScaledBoundingBox(web_view_->pageScaleFactor(), &element_)));
307}
308
309void AutofillAgent::DidChangeScrollOffset(WebKit::WebFrame*) {
310  HideAutofillUI();
311}
312
313void AutofillAgent::didRequestAutocomplete(WebKit::WebFrame* frame,
314                                           const WebFormElement& form) {
315  GURL url(frame->document().url());
316  content::SSLStatus ssl_status = render_view()->GetSSLStatusOfFrame(frame);
317  FormData form_data;
318  if (!in_flight_request_form_.isNull() ||
319      (url.SchemeIs(chrome::kHttpsScheme) &&
320       (net::IsCertStatusError(ssl_status.cert_status) ||
321        net::IsCertStatusMinorError(ssl_status.cert_status))) ||
322      !WebFormElementToFormData(form,
323                                WebFormControlElement(),
324                                REQUIRE_AUTOCOMPLETE,
325                                EXTRACT_OPTIONS,
326                                &form_data,
327                                NULL)) {
328    WebFormElement(form).finishRequestAutocomplete(
329        WebFormElement::AutocompleteResultErrorDisabled);
330    return;
331  }
332
333  // Cancel any pending Autofill requests and hide any currently showing popups.
334  ++autofill_query_id_;
335  HideAutofillUI();
336
337  in_flight_request_form_ = form;
338  Send(new AutofillHostMsg_RequestAutocomplete(routing_id(), form_data, url));
339}
340
341void AutofillAgent::setIgnoreTextChanges(bool ignore) {
342  ignore_text_changes_ = ignore;
343}
344
345void AutofillAgent::InputElementClicked(const WebInputElement& element,
346                                        bool was_focused,
347                                        bool is_focused) {
348  if (was_focused)
349    ShowSuggestions(element, true, false, true);
350}
351
352void AutofillAgent::InputElementLostFocus() {
353  HideAutofillUI();
354}
355
356void AutofillAgent::didClearAutofillSelection(const WebNode& node) {
357  if (password_autofill_agent_->DidClearAutofillSelection(node))
358    return;
359
360  if (!element_.isNull() && node == element_) {
361    ClearPreviewedFormWithElement(element_, was_query_node_autofilled_);
362  } else {
363    // TODO(isherman): There seem to be rare cases where this code *is*
364    // reachable: see [ http://crbug.com/96321#c6 ].  Ideally we would
365    // understand those cases and fix the code to avoid them.  However, so far I
366    // have been unable to reproduce such a case locally.  If you hit this
367    // NOTREACHED(), please file a bug against me.
368    NOTREACHED();
369  }
370}
371
372void AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {
373  password_autofill_agent_->TextFieldDidEndEditing(element);
374  has_shown_autofill_popup_for_current_edit_ = false;
375  Send(new AutofillHostMsg_DidEndTextFieldEditing(routing_id()));
376}
377
378void AutofillAgent::textFieldDidChange(const WebInputElement& element) {
379  if (ignore_text_changes_)
380    return;
381
382  if (did_set_node_text_) {
383    did_set_node_text_ = false;
384    return;
385  }
386
387  // We post a task for doing the Autofill as the caret position is not set
388  // properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and
389  // it is needed to trigger autofill.
390  weak_ptr_factory_.InvalidateWeakPtrs();
391  base::MessageLoop::current()->PostTask(
392      FROM_HERE,
393      base::Bind(&AutofillAgent::TextFieldDidChangeImpl,
394                 weak_ptr_factory_.GetWeakPtr(),
395                 element));
396}
397
398void AutofillAgent::TextFieldDidChangeImpl(const WebInputElement& element) {
399  // If the element isn't focused then the changes don't matter. This check is
400  // required to properly handle IME interactions.
401  if (!element.focused())
402    return;
403
404  if (password_autofill_agent_->TextDidChangeInTextField(element)) {
405    element_ = element;
406    return;
407  }
408
409  ShowSuggestions(element, false, true, false);
410
411  FormData form;
412  FormFieldData field;
413  if (FindFormAndFieldForInputElement(element, &form, &field, REQUIRE_NONE)) {
414    Send(new AutofillHostMsg_TextFieldDidChange(routing_id(), form, field,
415                                                base::TimeTicks::Now()));
416  }
417}
418
419void AutofillAgent::textFieldDidReceiveKeyDown(const WebInputElement& element,
420                                               const WebKeyboardEvent& event) {
421  if (password_autofill_agent_->TextFieldHandlingKeyDown(element, event)) {
422    element_ = element;
423    return;
424  }
425
426  if (event.windowsKeyCode == ui::VKEY_DOWN ||
427      event.windowsKeyCode == ui::VKEY_UP)
428    ShowSuggestions(element, true, true, true);
429}
430
431void AutofillAgent::AcceptDataListSuggestion(
432    const base::string16& suggested_value) {
433  base::string16 new_value = suggested_value;
434  // If this element takes multiple values then replace the last part with
435  // the suggestion.
436  if (element_.isMultiple() &&
437      element_.formControlType() == WebString::fromUTF8("email")) {
438    std::vector<base::string16> parts;
439
440    base::SplitStringDontTrim(element_.editingValue(), ',', &parts);
441    if (parts.size() == 0)
442      parts.push_back(base::string16());
443
444    base::string16 last_part = parts.back();
445    // We want to keep just the leading whitespace.
446    for (size_t i = 0; i < last_part.size(); ++i) {
447      if (!IsWhitespace(last_part[i])) {
448        last_part = last_part.substr(0, i);
449        break;
450      }
451    }
452    last_part.append(suggested_value);
453    parts[parts.size() - 1] = last_part;
454
455    new_value = JoinString(parts, ',');
456  }
457  SetNodeText(new_value, &element_);
458}
459
460void AutofillAgent::OnFormDataFilled(int query_id,
461                                     const FormData& form) {
462  if (!render_view()->GetWebView() || query_id != autofill_query_id_)
463    return;
464
465  was_query_node_autofilled_ = element_.isAutofilled();
466
467  switch (autofill_action_) {
468    case AUTOFILL_FILL:
469      FillForm(form, element_);
470      Send(new AutofillHostMsg_DidFillAutofillFormData(routing_id(),
471                                                       base::TimeTicks::Now()));
472      break;
473    case AUTOFILL_PREVIEW:
474      PreviewForm(form, element_);
475      Send(new AutofillHostMsg_DidPreviewAutofillFormData(routing_id()));
476      break;
477    default:
478      NOTREACHED();
479  }
480  autofill_action_ = AUTOFILL_NONE;
481}
482
483void AutofillAgent::OnFieldTypePredictionsAvailable(
484    const std::vector<FormDataPredictions>& forms) {
485  for (size_t i = 0; i < forms.size(); ++i) {
486    form_cache_.ShowPredictions(forms[i]);
487  }
488}
489
490void AutofillAgent::OnSetAutofillActionFill() {
491  autofill_action_ = AUTOFILL_FILL;
492}
493
494void AutofillAgent::OnClearForm() {
495  form_cache_.ClearFormWithElement(element_);
496}
497
498void AutofillAgent::OnSetAutofillActionPreview() {
499  autofill_action_ = AUTOFILL_PREVIEW;
500}
501
502void AutofillAgent::OnClearPreviewedForm() {
503  didClearAutofillSelection(element_);
504}
505
506void AutofillAgent::OnSetNodeText(const base::string16& value) {
507  SetNodeText(value, &element_);
508}
509
510void AutofillAgent::OnAcceptDataListSuggestion(const base::string16& value) {
511  AcceptDataListSuggestion(value);
512}
513
514void AutofillAgent::OnAcceptPasswordAutofillSuggestion(
515    const base::string16& value) {
516  // We need to make sure this is handled here because the browser process
517  // skipped it handling because it believed it would be handled here. If it
518  // isn't handled here then the browser logic needs to be updated.
519  bool handled = password_autofill_agent_->DidAcceptAutofillSuggestion(
520      element_,
521      value);
522  DCHECK(handled);
523}
524
525void AutofillAgent::OnGetAllForms() {
526  form_elements_.clear();
527
528  // Force fetch all non empty forms.
529  std::vector<FormData> forms;
530  form_cache_.ExtractFormsAndFormElements(
531      *topmost_frame_, 0, &forms, &form_elements_);
532
533  // OnGetAllForms should only be called if AutofillAgent reported to
534  // AutofillManager that there are more forms
535  DCHECK(!forms.empty());
536
537  // Report to AutofillManager that all forms are being sent.
538  Send(new AutofillHostMsg_FormsSeen(routing_id(), forms,
539                                     forms_seen_timestamp_,
540                                     NO_SPECIAL_FORMS_SEEN));
541}
542
543void AutofillAgent::OnRequestAutocompleteResult(
544    WebFormElement::AutocompleteResult result, const FormData& form_data) {
545  if (in_flight_request_form_.isNull())
546    return;
547
548  if (result == WebFormElement::AutocompleteResultSuccess) {
549    FillFormIncludingNonFocusableElements(form_data, in_flight_request_form_);
550    if (!in_flight_request_form_.checkValidityWithoutDispatchingEvents())
551      result = WebFormElement::AutocompleteResultErrorInvalid;
552  }
553
554  in_flight_request_form_.finishRequestAutocomplete(result);
555  in_flight_request_form_.reset();
556}
557
558void AutofillAgent::OnFillFormsAndClick(
559    const std::vector<FormData>& forms,
560    const std::vector<WebElementDescriptor>& click_elements_before_form_fill,
561    const std::vector<WebElementDescriptor>& click_elements_after_form_fill,
562    const WebElementDescriptor& click_element_descriptor) {
563  DCHECK_EQ(forms.size(), form_elements_.size());
564
565  // Click elements in click_elements_before_form_fill.
566  for (size_t i = 0; i < click_elements_before_form_fill.size(); ++i) {
567    if (!ClickElement(topmost_frame_->document(),
568                      click_elements_before_form_fill[i])) {
569      CompleteAutocheckoutPage(MISSING_CLICK_ELEMENT_BEFORE_FORM_FILLING);
570      return;
571    }
572  }
573
574  // Fill the form.
575  for (size_t i = 0; i < forms.size(); ++i)
576    FillFormForAllElements(forms[i], form_elements_[i]);
577
578  // Click elements in click_elements_after_form_fill.
579  for (size_t i = 0; i < click_elements_after_form_fill.size(); ++i) {
580    if (!ClickElement(topmost_frame_->document(),
581                      click_elements_after_form_fill[i])) {
582      CompleteAutocheckoutPage(MISSING_CLICK_ELEMENT_AFTER_FORM_FILLING);
583      return;
584    }
585  }
586
587  // Exit early if there is nothing to click.
588  if (click_element_descriptor.retrieval_method == WebElementDescriptor::NONE) {
589    CompleteAutocheckoutPage(SUCCESS);
590    return;
591  }
592
593  // It's possible that clicking the element to proceed in an Autocheckout
594  // flow will not actually proceed to the next step in the flow, e.g. there
595  // is a new required field that Autocheckout does not know how to fill.  In
596  // order to capture this case and present the user with an error a timer is
597  // set that informs the browser of the error. |click_timer_| has to be started
598  // before clicking so it can start before DidStartProvisionalLoad started.
599  click_timer_.Start(FROM_HERE,
600                     base::TimeDelta::FromSeconds(kAutocheckoutClickTimeout),
601                     this,
602                     &AutofillAgent::ClickFailed);
603  if (!ClickElement(topmost_frame_->document(),
604                    click_element_descriptor)) {
605    CompleteAutocheckoutPage(MISSING_ADVANCE);
606  }
607}
608
609void AutofillAgent::OnAutocheckoutSupported() {
610  is_autocheckout_supported_ = true;
611  if (has_new_forms_for_browser_)
612    MaybeSendDynamicFormsSeen();
613  MaybeShowAutocheckoutBubble();
614}
615
616void AutofillAgent::CompleteAutocheckoutPage(
617    autofill::AutocheckoutStatus status) {
618  click_timer_.Stop();
619  Send(new AutofillHostMsg_AutocheckoutPageCompleted(routing_id(), status));
620}
621
622void AutofillAgent::ClickFailed() {
623  CompleteAutocheckoutPage(CANNOT_PROCEED);
624}
625
626void AutofillAgent::ShowSuggestions(const WebInputElement& element,
627                                    bool autofill_on_empty_values,
628                                    bool requires_caret_at_end,
629                                    bool display_warning_if_disabled) {
630  if (!element.isEnabled() || element.isReadOnly() || !element.isTextField() ||
631      element.isPasswordField() || !element.suggestedValue().isEmpty())
632    return;
633
634  // Don't attempt to autofill with values that are too large or if filling
635  // criteria are not met.
636  WebString value = element.editingValue();
637  if (value.length() > kMaximumTextSizeForAutofill ||
638      (!autofill_on_empty_values && value.isEmpty()) ||
639      (requires_caret_at_end &&
640       (element.selectionStart() != element.selectionEnd() ||
641        element.selectionEnd() != static_cast<int>(value.length())))) {
642    // Any popup currently showing is obsolete.
643    HideAutofillUI();
644    return;
645  }
646
647  element_ = element;
648  if (password_autofill_agent_->ShowSuggestions(element))
649    return;
650
651  // If autocomplete is disabled at the field level, ensure that the native
652  // UI won't try to show a warning, since that may conflict with a custom
653  // popup. Note that we cannot use the WebKit method element.autoComplete()
654  // as it does not allow us to distinguish the case where autocomplete is
655  // disabled for *both* the element and for the form.
656  const base::string16 autocomplete_attribute =
657      element.getAttribute("autocomplete");
658  if (LowerCaseEqualsASCII(autocomplete_attribute, "off"))
659    display_warning_if_disabled = false;
660
661  QueryAutofillSuggestions(element, display_warning_if_disabled);
662}
663
664void AutofillAgent::QueryAutofillSuggestions(const WebInputElement& element,
665                                             bool display_warning_if_disabled) {
666  if (!element.document().frame())
667    return;
668
669  static int query_counter = 0;
670  autofill_query_id_ = query_counter++;
671  display_warning_if_disabled_ = display_warning_if_disabled;
672
673  // If autocomplete is disabled at the form level, we want to see if there
674  // would have been any suggestions were it enabled, so that we can show a
675  // warning.  Otherwise, we want to ignore fields that disable autocomplete, so
676  // that the suggestions list does not include suggestions for these form
677  // fields -- see comment 1 on http://crbug.com/69914
678  const RequirementsMask requirements =
679      element.autoComplete() ? REQUIRE_AUTOCOMPLETE : REQUIRE_NONE;
680
681  FormData form;
682  FormFieldData field;
683  if (!FindFormAndFieldForInputElement(element, &form, &field, requirements)) {
684    // If we didn't find the cached form, at least let autocomplete have a shot
685    // at providing suggestions.
686    WebFormControlElementToFormField(element, EXTRACT_VALUE, &field);
687  }
688
689  gfx::RectF bounding_box_scaled =
690      GetScaledBoundingBox(web_view_->pageScaleFactor(), &element_);
691
692  // Find the datalist values and send them to the browser process.
693  std::vector<base::string16> data_list_values;
694  std::vector<base::string16> data_list_labels;
695  GetDataListSuggestions(element_, &data_list_values, &data_list_labels);
696  TrimStringVectorForIPC(&data_list_values);
697  TrimStringVectorForIPC(&data_list_labels);
698
699  Send(new AutofillHostMsg_SetDataList(routing_id(),
700                                       data_list_values,
701                                       data_list_labels));
702
703  Send(new AutofillHostMsg_QueryFormFieldAutofill(routing_id(),
704                                                  autofill_query_id_,
705                                                  form,
706                                                  field,
707                                                  bounding_box_scaled,
708                                                  display_warning_if_disabled));
709}
710
711void AutofillAgent::FillAutofillFormData(const WebNode& node,
712                                         int unique_id,
713                                         AutofillAction action) {
714  DCHECK_GT(unique_id, 0);
715
716  static int query_counter = 0;
717  autofill_query_id_ = query_counter++;
718
719  FormData form;
720  FormFieldData field;
721  if (!FindFormAndFieldForInputElement(node.toConst<WebInputElement>(), &form,
722                                       &field, REQUIRE_AUTOCOMPLETE)) {
723    return;
724  }
725
726  autofill_action_ = action;
727  Send(new AutofillHostMsg_FillAutofillFormData(
728      routing_id(), autofill_query_id_, form, field, unique_id));
729}
730
731void AutofillAgent::SetNodeText(const base::string16& value,
732                                WebKit::WebInputElement* node) {
733  did_set_node_text_ = true;
734  base::string16 substring = value;
735  substring = substring.substr(0, node->maxLength());
736
737  node->setEditingValue(substring);
738}
739
740void AutofillAgent::HideAutofillUI() {
741  Send(new AutofillHostMsg_HideAutofillUI(routing_id()));
742}
743
744void AutofillAgent::didAssociateFormControls(
745    const WebKit::WebVector<WebKit::WebNode>& nodes) {
746  for (size_t i = 0; i < nodes.size(); ++i) {
747    WebKit::WebNode node = nodes[i];
748    if (node.document().frame() == topmost_frame_) {
749      forms_seen_timestamp_ = base::TimeTicks::Now();
750      has_new_forms_for_browser_ = true;
751      break;
752    }
753  }
754
755  if (has_new_forms_for_browser_ && is_autocheckout_supported_)
756    MaybeSendDynamicFormsSeen();
757}
758
759void AutofillAgent::MaybeSendDynamicFormsSeen() {
760  has_new_forms_for_browser_ = false;
761  form_elements_.clear();
762  std::vector<FormData> forms;
763  // This will only be called for Autocheckout flows, so send all forms to
764  // save an IPC.
765  form_cache_.ExtractFormsAndFormElements(
766      *topmost_frame_, 0, &forms, &form_elements_);
767  autofill::FormsSeenState state = autofill::DYNAMIC_FORMS_SEEN;
768
769  if (!forms.empty()) {
770    if (click_timer_.IsRunning())
771      click_timer_.Stop();
772    Send(new AutofillHostMsg_FormsSeen(routing_id(), forms,
773                                       forms_seen_timestamp_,
774                                       state));
775  }
776}
777
778}  // namespace autofill
779