Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / components / autofill / content / renderer / autofill_agent.cc
index 1b37ce2..80326c3 100644 (file)
@@ -15,6 +15,7 @@
 #include "components/autofill/content/renderer/form_autofill_util.h"
 #include "components/autofill/content/renderer/page_click_tracker.h"
 #include "components/autofill/content/renderer/password_autofill_agent.h"
+#include "components/autofill/content/renderer/password_generation_agent.h"
 #include "components/autofill/core/common/autofill_constants.h"
 #include "components/autofill/core/common/autofill_data_validation.h"
 #include "components/autofill/core/common/autofill_switches.h"
 #include "net/cert/cert_status_flags.h"
 #include "third_party/WebKit/public/platform/WebRect.h"
 #include "third_party/WebKit/public/platform/WebURLRequest.h"
+#include "third_party/WebKit/public/web/WebConsoleMessage.h"
 #include "third_party/WebKit/public/web/WebDataSource.h"
 #include "third_party/WebKit/public/web/WebDocument.h"
+#include "third_party/WebKit/public/web/WebElementCollection.h"
 #include "third_party/WebKit/public/web/WebFormControlElement.h"
 #include "third_party/WebKit/public/web/WebFormElement.h"
-#include "third_party/WebKit/public/web/WebFrame.h"
 #include "third_party/WebKit/public/web/WebInputEvent.h"
+#include "third_party/WebKit/public/web/WebLocalFrame.h"
 #include "third_party/WebKit/public/web/WebNode.h"
-#include "third_party/WebKit/public/web/WebNodeCollection.h"
 #include "third_party/WebKit/public/web/WebOptionElement.h"
+#include "third_party/WebKit/public/web/WebTextAreaElement.h"
 #include "third_party/WebKit/public/web/WebView.h"
 #include "ui/base/l10n/l10n_util.h"
 #include "ui/events/keycodes/keyboard_codes.h"
 
 using blink::WebAutofillClient;
+using blink::WebConsoleMessage;
+using blink::WebElement;
+using blink::WebElementCollection;
 using blink::WebFormControlElement;
 using blink::WebFormElement;
 using blink::WebFrame;
 using blink::WebInputElement;
 using blink::WebKeyboardEvent;
+using blink::WebLocalFrame;
 using blink::WebNode;
-using blink::WebNodeCollection;
 using blink::WebOptionElement;
 using blink::WebString;
+using blink::WebTextAreaElement;
+using blink::WebVector;
 
 namespace autofill {
 
@@ -61,11 +69,11 @@ namespace {
 
 // Gets all the data list values (with corresponding label) for the given
 // element.
-void GetDataListSuggestions(const blink::WebInputElement& element,
+void GetDataListSuggestions(const WebInputElement& element,
                             bool ignore_current_value,
                             std::vector<base::string16>* values,
                             std::vector<base::string16>* labels) {
-  WebNodeCollection options = element.dataListOptions();
+  WebElementCollection options = element.dataListOptions();
   if (options.isNull())
     return;
 
@@ -76,8 +84,10 @@ void GetDataListSuggestions(const blink::WebInputElement& element,
         element.formControlType() == WebString::fromUTF8("email")) {
       std::vector<base::string16> parts;
       base::SplitStringDontTrim(prefix, ',', &parts);
-      if (parts.size() > 0)
-        TrimWhitespace(parts[parts.size() - 1], TRIM_LEADING, &prefix);
+      if (parts.size() > 0) {
+        base::TrimWhitespace(parts[parts.size() - 1], base::TRIM_LEADING,
+                             &prefix);
+      }
     }
   }
   for (WebOptionElement option = options.firstItem().to<WebOptionElement>();
@@ -109,22 +119,15 @@ void TrimStringVectorForIPC(std::vector<base::string16>* strings) {
   }
 }
 
-gfx::RectF GetScaledBoundingBox(float scale, WebInputElement* element) {
-  gfx::Rect bounding_box(element->boundsInViewportSpace());
-  return gfx::RectF(bounding_box.x() * scale,
-                    bounding_box.y() * scale,
-                    bounding_box.width() * scale,
-                    bounding_box.height() * scale);
-}
-
 }  // namespace
 
 AutofillAgent::AutofillAgent(content::RenderView* render_view,
-                             PasswordAutofillAgent* password_autofill_agent)
+                             PasswordAutofillAgent* password_autofill_agent,
+                             PasswordGenerationAgent* password_generation_agent)
     : content::RenderViewObserver(render_view),
       password_autofill_agent_(password_autofill_agent),
+      password_generation_agent_(password_generation_agent),
       autofill_query_id_(0),
-      autofill_action_(AUTOFILL_NONE),
       web_view_(render_view->GetWebView()),
       display_warning_if_disabled_(false),
       was_query_node_autofilled_(false),
@@ -132,6 +135,7 @@ AutofillAgent::AutofillAgent(content::RenderView* render_view,
       did_set_node_text_(false),
       has_new_forms_for_browser_(false),
       ignore_text_changes_(false),
+      is_popup_possibly_visible_(false),
       weak_ptr_factory_(this) {
   render_view->GetWebView()->setAutofillClient(this);
 
@@ -145,29 +149,27 @@ AutofillAgent::~AutofillAgent() {}
 bool AutofillAgent::OnMessageReceived(const IPC::Message& message) {
   bool handled = true;
   IPC_BEGIN_MESSAGE_MAP(AutofillAgent, message)
-    IPC_MESSAGE_HANDLER(AutofillMsg_FormDataFilled, OnFormDataFilled)
+    IPC_MESSAGE_HANDLER(AutofillMsg_FillForm, OnFillForm)
+    IPC_MESSAGE_HANDLER(AutofillMsg_PreviewForm, OnPreviewForm)
     IPC_MESSAGE_HANDLER(AutofillMsg_FieldTypePredictionsAvailable,
                         OnFieldTypePredictionsAvailable)
-    IPC_MESSAGE_HANDLER(AutofillMsg_SetAutofillActionFill,
-                        OnSetAutofillActionFill)
     IPC_MESSAGE_HANDLER(AutofillMsg_ClearForm, OnClearForm)
-    IPC_MESSAGE_HANDLER(AutofillMsg_SetAutofillActionPreview,
-                        OnSetAutofillActionPreview)
     IPC_MESSAGE_HANDLER(AutofillMsg_ClearPreviewedForm, OnClearPreviewedForm)
-    IPC_MESSAGE_HANDLER(AutofillMsg_SetNodeText, OnSetNodeText)
+    IPC_MESSAGE_HANDLER(AutofillMsg_FillFieldWithValue, OnFillFieldWithValue)
+    IPC_MESSAGE_HANDLER(AutofillMsg_PreviewFieldWithValue,
+                        OnPreviewFieldWithValue)
     IPC_MESSAGE_HANDLER(AutofillMsg_AcceptDataListSuggestion,
                         OnAcceptDataListSuggestion)
     IPC_MESSAGE_HANDLER(AutofillMsg_AcceptPasswordAutofillSuggestion,
                         OnAcceptPasswordAutofillSuggestion)
     IPC_MESSAGE_HANDLER(AutofillMsg_RequestAutocompleteResult,
                         OnRequestAutocompleteResult)
-    IPC_MESSAGE_HANDLER(AutofillMsg_PageShown, OnPageShown)
     IPC_MESSAGE_UNHANDLED(handled = false)
   IPC_END_MESSAGE_MAP()
   return handled;
 }
 
-void AutofillAgent::DidFinishDocumentLoad(WebFrame* frame) {
+void AutofillAgent::DidFinishDocumentLoad(WebLocalFrame* frame) {
   // Record timestamp on document load. This is used to record overhead of
   // Autofill feature.
   forms_seen_timestamp_ = base::TimeTicks::Now();
@@ -195,16 +197,24 @@ void AutofillAgent::DidFinishDocumentLoad(WebFrame* frame) {
   }
 }
 
-void AutofillAgent::DidCommitProvisionalLoad(WebFrame* frame,
-                                             bool is_new_navigation) {
-  in_flight_request_form_.reset();
-}
-
 void AutofillAgent::FrameDetached(WebFrame* frame) {
   form_cache_.ResetFrame(*frame);
 }
 
-void AutofillAgent::WillSubmitForm(WebFrame* frame,
+void AutofillAgent::FrameWillClose(WebFrame* frame) {
+  if (in_flight_request_form_.isNull())
+    return;
+
+  for (WebFrame* temp = in_flight_request_form_.document().frame();
+       temp; temp = temp->parent()) {
+    if (temp == frame) {
+      Send(new AutofillHostMsg_CancelRequestAutocomplete(routing_id()));
+      break;
+    }
+  }
+}
+
+void AutofillAgent::WillSubmitForm(WebLocalFrame* frame,
                                    const WebFormElement& form) {
   FormData form_data;
   if (WebFormElementToFormData(form,
@@ -223,14 +233,20 @@ void AutofillAgent::ZoomLevelChanged() {
   // Any time the zoom level changes, the page's content moves, so any Autofill
   // popups should be hidden. This is only needed for the new Autofill UI
   // because WebKit already knows to hide the old UI when this occurs.
-  HideAutofillUI();
+  HidePopup();
 }
 
-void AutofillAgent::FocusedNodeChanged(const blink::WebNode& node) {
+void AutofillAgent::FocusedNodeChanged(const WebNode& node) {
+  if (password_generation_agent_ &&
+      password_generation_agent_->FocusedNodeHasChanged(node)) {
+    is_popup_possibly_visible_ = true;
+    return;
+  }
+
   if (node.isNull() || !node.isElementNode())
     return;
 
-  blink::WebElement web_element = node.toConst<blink::WebElement>();
+  WebElement web_element = node.toConst<WebElement>();
 
   if (!web_element.document().frame())
       return;
@@ -244,36 +260,52 @@ void AutofillAgent::FocusedNodeChanged(const blink::WebNode& node) {
   element_ = *element;
 }
 
-void AutofillAgent::OrientationChangeEvent(int orientation) {
-  HideAutofillUI();
+void AutofillAgent::OrientationChangeEvent() {
+  HidePopup();
 }
 
-void AutofillAgent::DidChangeScrollOffset(blink::WebFrame*) {
-  HideAutofillUI();
+void AutofillAgent::DidChangeScrollOffset(WebLocalFrame*) {
+  HidePopup();
 }
 
-void AutofillAgent::didRequestAutocomplete(blink::WebFrame* frame,
-                                           const WebFormElement& form) {
+void AutofillAgent::didRequestAutocomplete(
+    const WebFormElement& form,
+    const blink::WebAutocompleteParams& details) {
+  // TODO(estade): honor |details|.
+
   // Disallow the dialog over non-https or broken https, except when the
   // ignore SSL flag is passed. See http://crbug.com/272512.
   // TODO(palmer): this should be moved to the browser process after frames
   // get their own processes.
-  GURL url(frame->document().url());
-  content::SSLStatus ssl_status = render_view()->GetSSLStatusOfFrame(frame);
-  bool is_safe = url.SchemeIs(content::kHttpsScheme) &&
+  GURL url(form.document().url());
+  content::SSLStatus ssl_status =
+      render_view()->GetSSLStatusOfFrame(form.document().frame());
+  bool is_safe = url.SchemeIs(url::kHttpsScheme) &&
       !net::IsCertStatusError(ssl_status.cert_status);
   bool allow_unsafe = CommandLine::ForCurrentProcess()->HasSwitch(
       ::switches::kReduceSecurityForTesting);
 
   FormData form_data;
-  if (!in_flight_request_form_.isNull() ||
-      (!is_safe && !allow_unsafe) ||
-      !WebFormElementToFormData(form,
-                                WebFormControlElement(),
-                                REQUIRE_AUTOCOMPLETE,
-                                EXTRACT_OPTIONS,
-                                &form_data,
-                                NULL)) {
+  std::string error_message;
+  if (!in_flight_request_form_.isNull()) {
+    error_message = "already active.";
+  } else if (!is_safe && !allow_unsafe) {
+    error_message =
+        "must use a secure connection or --reduce-security-for-testing.";
+  } else if (!WebFormElementToFormData(form,
+                                       WebFormControlElement(),
+                                       REQUIRE_AUTOCOMPLETE,
+                                       EXTRACT_OPTIONS,
+                                       &form_data,
+                                       NULL)) {
+    error_message = "failed to parse form.";
+  }
+
+  if (!error_message.empty()) {
+    WebConsoleMessage console_message = WebConsoleMessage(
+        WebConsoleMessage::LevelLog,
+        WebString(base::ASCIIToUTF16("requestAutocomplete: ") +
+                      base::ASCIIToUTF16(error_message)));
     WebFormElement(form).finishRequestAutocomplete(
         WebFormElement::AutocompleteResultErrorDisabled);
     return;
@@ -281,7 +313,7 @@ void AutofillAgent::didRequestAutocomplete(blink::WebFrame* frame,
 
   // Cancel any pending Autofill requests and hide any currently showing popups.
   ++autofill_query_id_;
-  HideAutofillUI();
+  HidePopup();
 
   in_flight_request_form_ = form;
   Send(new AutofillHostMsg_RequestAutocomplete(routing_id(), form_data, url));
@@ -291,15 +323,19 @@ void AutofillAgent::setIgnoreTextChanges(bool ignore) {
   ignore_text_changes_ = ignore;
 }
 
-void AutofillAgent::InputElementClicked(const WebInputElement& element,
-                                        bool was_focused,
-                                        bool is_focused) {
+void AutofillAgent::FormControlElementClicked(
+    const WebFormControlElement& element,
+    bool was_focused) {
+  const WebInputElement* input_element = toWebInputElement(&element);
+  if (!input_element && !IsTextAreaElement(element))
+    return;
+
   if (was_focused)
     ShowSuggestions(element, true, false, true, false);
 }
 
-void AutofillAgent::InputElementLostFocus() {
-  HideAutofillUI();
+void AutofillAgent::FormControlElementLostFocus() {
+  HidePopup();
 }
 
 void AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {
@@ -308,10 +344,12 @@ void AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {
   Send(new AutofillHostMsg_DidEndTextFieldEditing(routing_id()));
 }
 
-void AutofillAgent::textFieldDidChange(const WebInputElement& element) {
+void AutofillAgent::textFieldDidChange(const WebFormControlElement& element) {
   if (ignore_text_changes_)
     return;
 
+  DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
+
   if (did_set_node_text_) {
     did_set_node_text_ = false;
     return;
@@ -328,22 +366,35 @@ void AutofillAgent::textFieldDidChange(const WebInputElement& element) {
                  element));
 }
 
-void AutofillAgent::TextFieldDidChangeImpl(const WebInputElement& element) {
+void AutofillAgent::TextFieldDidChangeImpl(
+    const WebFormControlElement& element) {
   // If the element isn't focused then the changes don't matter. This check is
   // required to properly handle IME interactions.
   if (!element.focused())
     return;
 
-  if (password_autofill_agent_->TextDidChangeInTextField(element)) {
-    element_ = element;
-    return;
+  const WebInputElement* input_element = toWebInputElement(&element);
+  if (input_element) {
+    if (password_generation_agent_ &&
+        password_generation_agent_->TextDidChangeInTextField(*input_element)) {
+      is_popup_possibly_visible_ = true;
+      return;
+    }
+
+    if (password_autofill_agent_->TextDidChangeInTextField(*input_element)) {
+      element_ = element;
+      return;
+    }
   }
 
   ShowSuggestions(element, false, true, false, false);
 
   FormData form;
   FormFieldData field;
-  if (FindFormAndFieldForInputElement(element, &form, &field, REQUIRE_NONE)) {
+  if (FindFormAndFieldForFormControlElement(element,
+                                            &form,
+                                            &field,
+                                            REQUIRE_NONE)) {
     Send(new AutofillHostMsg_TextFieldDidChange(routing_id(), form, field,
                                                 base::TimeTicks::Now()));
   }
@@ -365,16 +416,22 @@ void AutofillAgent::openTextDataListChooser(const WebInputElement& element) {
     ShowSuggestions(element, true, false, false, true);
 }
 
+void AutofillAgent::firstUserGestureObserved() {
+  password_autofill_agent_->FirstUserGestureObserved();
+}
+
 void AutofillAgent::AcceptDataListSuggestion(
     const base::string16& suggested_value) {
+  WebInputElement* input_element = toWebInputElement(&element_);
+  DCHECK(input_element);
   base::string16 new_value = suggested_value;
   // If this element takes multiple values then replace the last part with
   // the suggestion.
-  if (element_.isMultiple() &&
-      element_.formControlType() == WebString::fromUTF8("email")) {
+  if (input_element->isMultiple() &&
+      input_element->formControlType() == WebString::fromUTF8("email")) {
     std::vector<base::string16> parts;
 
-    base::SplitStringDontTrim(element_.editingValue(), ',', &parts);
+    base::SplitStringDontTrim(input_element->editingValue(), ',', &parts);
     if (parts.size() == 0)
       parts.push_back(base::string16());
 
@@ -391,30 +448,7 @@ void AutofillAgent::AcceptDataListSuggestion(
 
     new_value = JoinString(parts, ',');
   }
-  SetNodeText(new_value, &element_);
-}
-
-void AutofillAgent::OnFormDataFilled(int query_id,
-                                     const FormData& form) {
-  if (!render_view()->GetWebView() || query_id != autofill_query_id_)
-    return;
-
-  was_query_node_autofilled_ = element_.isAutofilled();
-
-  switch (autofill_action_) {
-    case AUTOFILL_FILL:
-      FillForm(form, element_);
-      Send(new AutofillHostMsg_DidFillAutofillFormData(routing_id(),
-                                                       base::TimeTicks::Now()));
-      break;
-    case AUTOFILL_PREVIEW:
-      PreviewForm(form, element_);
-      Send(new AutofillHostMsg_DidPreviewAutofillFormData(routing_id()));
-      break;
-    default:
-      NOTREACHED();
-  }
-  autofill_action_ = AUTOFILL_NONE;
+  FillFieldWithValue(new_value, input_element);
 }
 
 void AutofillAgent::OnFieldTypePredictionsAvailable(
@@ -424,18 +458,29 @@ void AutofillAgent::OnFieldTypePredictionsAvailable(
   }
 }
 
-void AutofillAgent::OnSetAutofillActionFill() {
-  autofill_action_ = AUTOFILL_FILL;
+void AutofillAgent::OnFillForm(int query_id, const FormData& form) {
+  if (!render_view()->GetWebView() || query_id != autofill_query_id_)
+    return;
+
+  was_query_node_autofilled_ = element_.isAutofilled();
+  FillForm(form, element_);
+  Send(new AutofillHostMsg_DidFillAutofillFormData(routing_id(),
+                                                   base::TimeTicks::Now()));
+}
+
+void AutofillAgent::OnPreviewForm(int query_id, const FormData& form) {
+  if (!render_view()->GetWebView() || query_id != autofill_query_id_)
+    return;
+
+  was_query_node_autofilled_ = element_.isAutofilled();
+  PreviewForm(form, element_);
+  Send(new AutofillHostMsg_DidPreviewAutofillFormData(routing_id()));
 }
 
 void AutofillAgent::OnClearForm() {
   form_cache_.ClearFormWithElement(element_);
 }
 
-void AutofillAgent::OnSetAutofillActionPreview() {
-  autofill_action_ = AUTOFILL_PREVIEW;
-}
-
 void AutofillAgent::OnClearPreviewedForm() {
   if (!element_.isNull()) {
     if (password_autofill_agent_->DidClearAutofillSelection(element_))
@@ -452,8 +497,16 @@ void AutofillAgent::OnClearPreviewedForm() {
   }
 }
 
-void AutofillAgent::OnSetNodeText(const base::string16& value) {
-  SetNodeText(value, &element_);
+void AutofillAgent::OnFillFieldWithValue(const base::string16& value) {
+  WebInputElement* input_element = toWebInputElement(&element_);
+  if (input_element)
+    FillFieldWithValue(value, input_element);
+}
+
+void AutofillAgent::OnPreviewFieldWithValue(const base::string16& value) {
+  WebInputElement* input_element = toWebInputElement(&element_);
+  if (input_element)
+    PreviewFieldWithValue(value, input_element);
 }
 
 void AutofillAgent::OnAcceptDataListSuggestion(const base::string16& value) {
@@ -461,45 +514,61 @@ void AutofillAgent::OnAcceptDataListSuggestion(const base::string16& value) {
 }
 
 void AutofillAgent::OnAcceptPasswordAutofillSuggestion(
-    const base::string16& username) {
-  // We need to make sure this is handled here because the browser process
-  // skipped it handling because it believed it would be handled here. If it
-  // isn't handled here then the browser logic needs to be updated.
-  bool handled = password_autofill_agent_->DidAcceptAutofillSuggestion(
+    const base::string16& username,
+    const base::string16& password) {
+  bool handled = password_autofill_agent_->AcceptSuggestion(
       element_,
-      username);
+      username,
+      password);
   DCHECK(handled);
 }
 
 void AutofillAgent::OnRequestAutocompleteResult(
-    WebFormElement::AutocompleteResult result, const FormData& form_data) {
+    WebFormElement::AutocompleteResult result,
+    const base::string16& message,
+    const FormData& form_data) {
   if (in_flight_request_form_.isNull())
     return;
 
   if (result == WebFormElement::AutocompleteResultSuccess) {
     FillFormIncludingNonFocusableElements(form_data, in_flight_request_form_);
-    if (!in_flight_request_form_.checkValidityWithoutDispatchingEvents())
+    if (!in_flight_request_form_.checkValidity())
       result = WebFormElement::AutocompleteResultErrorInvalid;
   }
 
   in_flight_request_form_.finishRequestAutocomplete(result);
-  in_flight_request_form_.reset();
-}
 
-void AutofillAgent::OnPageShown() {
+  if (!message.empty()) {
+    const base::string16 prefix(base::ASCIIToUTF16("requestAutocomplete: "));
+    WebConsoleMessage console_message = WebConsoleMessage(
+        WebConsoleMessage::LevelLog, WebString(prefix + message));
+    in_flight_request_form_.document().frame()->addMessageToConsole(
+        console_message);
+  }
+
+  in_flight_request_form_.reset();
 }
 
-void AutofillAgent::ShowSuggestions(const WebInputElement& element,
+void AutofillAgent::ShowSuggestions(const WebFormControlElement& element,
                                     bool autofill_on_empty_values,
                                     bool requires_caret_at_end,
                                     bool display_warning_if_disabled,
                                     bool datalist_only) {
-  if (!element.isEnabled() || element.isReadOnly() || !element.isTextField() ||
-      element.isPasswordField())
-    return;
-  if (!datalist_only && !element.suggestedValue().isEmpty())
+  if (!element.isEnabled() || element.isReadOnly())
     return;
 
+  const WebInputElement* input_element = toWebInputElement(&element);
+  if (input_element) {
+    if (!input_element->isTextField() || input_element->isPasswordField())
+      return;
+    if (!datalist_only && !input_element->suggestedValue().isEmpty())
+      return;
+  } else {
+    DCHECK(IsTextAreaElement(element));
+    if (!element.toConst<WebTextAreaElement>().suggestedValue().isEmpty())
+      return;
+  }
+
   // Don't attempt to autofill with values that are too large or if filling
   // criteria are not met.
   WebString value = element.editingValue();
@@ -510,13 +579,16 @@ void AutofillAgent::ShowSuggestions(const WebInputElement& element,
         (element.selectionStart() != element.selectionEnd() ||
          element.selectionEnd() != static_cast<int>(value.length()))))) {
     // Any popup currently showing is obsolete.
-    HideAutofillUI();
+    HidePopup();
     return;
   }
 
   element_ = element;
-  if (password_autofill_agent_->ShowSuggestions(element))
+  if (input_element &&
+      password_autofill_agent_->ShowSuggestions(*input_element)) {
+    is_popup_possibly_visible_ = true;
     return;
+  }
 
   // If autocomplete is disabled at the field level, ensure that the native
   // UI won't try to show a warning, since that may conflict with a custom
@@ -533,12 +605,15 @@ void AutofillAgent::ShowSuggestions(const WebInputElement& element,
                            datalist_only);
 }
 
-void AutofillAgent::QueryAutofillSuggestions(const WebInputElement& element,
-                                             bool display_warning_if_disabled,
-                                             bool datalist_only) {
+void AutofillAgent::QueryAutofillSuggestions(
+    const WebFormControlElement& element,
+    bool display_warning_if_disabled,
+    bool datalist_only) {
   if (!element.document().frame())
     return;
 
+  DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
+
   static int query_counter = 0;
   autofill_query_id_ = query_counter++;
   display_warning_if_disabled_ = display_warning_if_disabled;
@@ -553,7 +628,8 @@ void AutofillAgent::QueryAutofillSuggestions(const WebInputElement& element,
 
   FormData form;
   FormFieldData field;
-  if (!FindFormAndFieldForInputElement(element, &form, &field, requirements)) {
+  if (!FindFormAndFieldForFormControlElement(element, &form, &field,
+                                             requirements)) {
     // If we didn't find the cached form, at least let autocomplete have a shot
     // at providing suggestions.
     WebFormControlElementToFormField(element, EXTRACT_VALUE, &field);
@@ -564,16 +640,20 @@ void AutofillAgent::QueryAutofillSuggestions(const WebInputElement& element,
   gfx::RectF bounding_box_scaled =
       GetScaledBoundingBox(web_view_->pageScaleFactor(), &element_);
 
-  // Find the datalist values and send them to the browser process.
   std::vector<base::string16> data_list_values;
   std::vector<base::string16> data_list_labels;
-  GetDataListSuggestions(element_,
-                         datalist_only,
-                         &data_list_values,
-                         &data_list_labels);
-  TrimStringVectorForIPC(&data_list_values);
-  TrimStringVectorForIPC(&data_list_labels);
+  const WebInputElement* input_element = toWebInputElement(&element);
+  if (input_element) {
+    // Find the datalist values and send them to the browser process.
+    GetDataListSuggestions(*input_element,
+                           datalist_only,
+                           &data_list_values,
+                           &data_list_labels);
+    TrimStringVectorForIPC(&data_list_values);
+    TrimStringVectorForIPC(&data_list_labels);
+  }
 
+  is_popup_possibly_visible_ = true;
   Send(new AutofillHostMsg_SetDataList(routing_id(),
                                        data_list_values,
                                        data_list_labels));
@@ -586,50 +666,40 @@ void AutofillAgent::QueryAutofillSuggestions(const WebInputElement& element,
                                                   display_warning_if_disabled));
 }
 
-void AutofillAgent::FillAutofillFormData(const WebNode& node,
-                                         int unique_id,
-                                         AutofillAction action) {
-  DCHECK_GT(unique_id, 0);
-
-  static int query_counter = 0;
-  autofill_query_id_ = query_counter++;
-
-  FormData form;
-  FormFieldData field;
-  if (!FindFormAndFieldForInputElement(node.toConst<WebInputElement>(), &form,
-                                       &field, REQUIRE_AUTOCOMPLETE)) {
-    return;
-  }
-
-  autofill_action_ = action;
-  Send(new AutofillHostMsg_FillAutofillFormData(
-      routing_id(), autofill_query_id_, form, field, unique_id));
-}
-
-void AutofillAgent::SetNodeText(const base::string16& value,
-                                blink::WebInputElement* node) {
+void AutofillAgent::FillFieldWithValue(const base::string16& value,
+                                       WebInputElement* node) {
   did_set_node_text_ = true;
-  base::string16 substring = value;
-  substring = substring.substr(0, node->maxLength());
+  node->setEditingValue(value.substr(0, node->maxLength()));
+  node->setAutofilled(true);
+}
 
-  node->setEditingValue(substring);
+void AutofillAgent::PreviewFieldWithValue(const base::string16& value,
+                                          WebInputElement* node) {
+  was_query_node_autofilled_ = element_.isAutofilled();
+  node->setSuggestedValue(value.substr(0, node->maxLength()));
+  node->setAutofilled(true);
+  node->setSelectionRange(node->value().length(),
+                          node->suggestedValue().length());
 }
 
-void AutofillAgent::HideAutofillUI() {
+void AutofillAgent::HidePopup() {
+  if (!is_popup_possibly_visible_)
+    return;
+
   if (!element_.isNull())
     OnClearPreviewedForm();
 
-  Send(new AutofillHostMsg_HideAutofillUI(routing_id()));
+  is_popup_possibly_visible_ = false;
+  Send(new AutofillHostMsg_HidePopup(routing_id()));
 }
 
 // TODO(isherman): Decide if we want to support non-password autofill with AJAX.
-void AutofillAgent::didAssociateFormControls(
-    const blink::WebVector<blink::WebNode>& nodes) {
+void AutofillAgent::didAssociateFormControls(const WebVector<WebNode>& nodes) {
   for (size_t i = 0; i < nodes.size(); ++i) {
-    blink::WebFrame* frame = nodes[i].document().frame();
+    WebFrame* frame = nodes[i].document().frame();
     // Only monitors dynamic forms created in the top frame. Dynamic forms
     // inserted in iframes are not captured yet.
-    if (!frame->parent()) {
+    if (frame && !frame->parent()) {
       password_autofill_agent_->OnDynamicFormsSeen(frame);
       return;
     }