Home | History | Annotate | Download | only in renderer
      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 
    322   // TODO(gcasto): Remove after crbug.com/423464 has been fixed.
    323   bool show_suggestions = true;
    324 #if defined(OS_ANDROID)
    325   show_suggestions = was_focused;
    326 #endif
    327 
    328   if (show_suggestions) {
    329     ShowSuggestions(element,
    330                     true,
    331                     false,
    332                     true,
    333                     false,
    334                     show_full_suggestion_list,
    335                     show_password_suggestions_only);
    336   }
    337 }
    338 
    339 void AutofillAgent::textFieldDidEndEditing(const WebInputElement& element) {
    340   password_autofill_agent_->TextFieldDidEndEditing(element);
    341   has_shown_autofill_popup_for_current_edit_ = false;
    342   Send(new AutofillHostMsg_DidEndTextFieldEditing(routing_id()));
    343 }
    344 
    345 void AutofillAgent::textFieldDidChange(const WebFormControlElement& element) {
    346   if (ignore_text_changes_)
    347     return;
    348 
    349   DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
    350 
    351   if (did_set_node_text_) {
    352     did_set_node_text_ = false;
    353     return;
    354   }
    355 
    356   // We post a task for doing the Autofill as the caret position is not set
    357   // properly at this point (http://bugs.webkit.org/show_bug.cgi?id=16976) and
    358   // it is needed to trigger autofill.
    359   weak_ptr_factory_.InvalidateWeakPtrs();
    360   base::MessageLoop::current()->PostTask(
    361       FROM_HERE,
    362       base::Bind(&AutofillAgent::TextFieldDidChangeImpl,
    363                  weak_ptr_factory_.GetWeakPtr(),
    364                  element));
    365 }
    366 
    367 void AutofillAgent::TextFieldDidChangeImpl(
    368     const WebFormControlElement& element) {
    369   // If the element isn't focused then the changes don't matter. This check is
    370   // required to properly handle IME interactions.
    371   if (!element.focused())
    372     return;
    373 
    374   const WebInputElement* input_element = toWebInputElement(&element);
    375   if (input_element) {
    376     if (password_generation_agent_ &&
    377         password_generation_agent_->TextDidChangeInTextField(*input_element)) {
    378       is_popup_possibly_visible_ = true;
    379       return;
    380     }
    381 
    382     if (password_autofill_agent_->TextDidChangeInTextField(*input_element)) {
    383       element_ = element;
    384       return;
    385     }
    386   }
    387 
    388   ShowSuggestions(element, false, true, false, false, false, false);
    389 
    390   FormData form;
    391   FormFieldData field;
    392   if (FindFormAndFieldForFormControlElement(element,
    393                                             &form,
    394                                             &field,
    395                                             REQUIRE_NONE)) {
    396     Send(new AutofillHostMsg_TextFieldDidChange(routing_id(), form, field,
    397                                                 base::TimeTicks::Now()));
    398   }
    399 }
    400 
    401 void AutofillAgent::textFieldDidReceiveKeyDown(const WebInputElement& element,
    402                                                const WebKeyboardEvent& event) {
    403   if (password_autofill_agent_->TextFieldHandlingKeyDown(element, event)) {
    404     element_ = element;
    405     return;
    406   }
    407 
    408   if (event.windowsKeyCode == ui::VKEY_DOWN ||
    409       event.windowsKeyCode == ui::VKEY_UP)
    410     ShowSuggestions(element, true, true, true, false, false, false);
    411 }
    412 
    413 void AutofillAgent::openTextDataListChooser(const WebInputElement& element) {
    414   ShowSuggestions(element, true, false, false, true, false, false);
    415 }
    416 
    417 void AutofillAgent::firstUserGestureObserved() {
    418   password_autofill_agent_->FirstUserGestureObserved();
    419 }
    420 
    421 void AutofillAgent::AcceptDataListSuggestion(
    422     const base::string16& suggested_value) {
    423   WebInputElement* input_element = toWebInputElement(&element_);
    424   DCHECK(input_element);
    425   base::string16 new_value = suggested_value;
    426   // If this element takes multiple values then replace the last part with
    427   // the suggestion.
    428   if (input_element->isMultiple() && input_element->isEmailField()) {
    429     std::vector<base::string16> parts;
    430 
    431     base::SplitStringDontTrim(input_element->editingValue(), ',', &parts);
    432     if (parts.size() == 0)
    433       parts.push_back(base::string16());
    434 
    435     base::string16 last_part = parts.back();
    436     // We want to keep just the leading whitespace.
    437     for (size_t i = 0; i < last_part.size(); ++i) {
    438       if (!IsWhitespace(last_part[i])) {
    439         last_part = last_part.substr(0, i);
    440         break;
    441       }
    442     }
    443     last_part.append(suggested_value);
    444     parts[parts.size() - 1] = last_part;
    445 
    446     new_value = JoinString(parts, ',');
    447   }
    448   FillFieldWithValue(new_value, input_element);
    449 }
    450 
    451 void AutofillAgent::OnFieldTypePredictionsAvailable(
    452     const std::vector<FormDataPredictions>& forms) {
    453   for (size_t i = 0; i < forms.size(); ++i) {
    454     form_cache_.ShowPredictions(forms[i]);
    455   }
    456 }
    457 
    458 void AutofillAgent::OnFillForm(int query_id, const FormData& form) {
    459   if (!render_view()->GetWebView() || query_id != autofill_query_id_)
    460     return;
    461 
    462   was_query_node_autofilled_ = element_.isAutofilled();
    463   FillForm(form, element_);
    464   Send(new AutofillHostMsg_DidFillAutofillFormData(routing_id(),
    465                                                    base::TimeTicks::Now()));
    466 }
    467 
    468 void AutofillAgent::OnPing() {
    469   Send(new AutofillHostMsg_PingAck(routing_id()));
    470 }
    471 
    472 void AutofillAgent::OnPreviewForm(int query_id, const FormData& form) {
    473   if (!render_view()->GetWebView() || query_id != autofill_query_id_)
    474     return;
    475 
    476   was_query_node_autofilled_ = element_.isAutofilled();
    477   PreviewForm(form, element_);
    478   Send(new AutofillHostMsg_DidPreviewAutofillFormData(routing_id()));
    479 }
    480 
    481 void AutofillAgent::OnClearForm() {
    482   form_cache_.ClearFormWithElement(element_);
    483 }
    484 
    485 void AutofillAgent::OnClearPreviewedForm() {
    486   if (!element_.isNull()) {
    487     if (password_autofill_agent_->DidClearAutofillSelection(element_))
    488       return;
    489 
    490     ClearPreviewedFormWithElement(element_, was_query_node_autofilled_);
    491   } else {
    492     // TODO(isherman): There seem to be rare cases where this code *is*
    493     // reachable: see [ http://crbug.com/96321#c6 ].  Ideally we would
    494     // understand those cases and fix the code to avoid them.  However, so far I
    495     // have been unable to reproduce such a case locally.  If you hit this
    496     // NOTREACHED(), please file a bug against me.
    497     NOTREACHED();
    498   }
    499 }
    500 
    501 void AutofillAgent::OnFillFieldWithValue(const base::string16& value) {
    502   WebInputElement* input_element = toWebInputElement(&element_);
    503   if (input_element) {
    504     FillFieldWithValue(value, input_element);
    505     input_element->setAutofilled(true);
    506   }
    507 }
    508 
    509 void AutofillAgent::OnPreviewFieldWithValue(const base::string16& value) {
    510   WebInputElement* input_element = toWebInputElement(&element_);
    511   if (input_element)
    512     PreviewFieldWithValue(value, input_element);
    513 }
    514 
    515 void AutofillAgent::OnAcceptDataListSuggestion(const base::string16& value) {
    516   AcceptDataListSuggestion(value);
    517 }
    518 
    519 void AutofillAgent::OnFillPasswordSuggestion(const base::string16& username,
    520                                              const base::string16& password) {
    521   bool handled = password_autofill_agent_->FillSuggestion(
    522       element_,
    523       username,
    524       password);
    525   DCHECK(handled);
    526 }
    527 
    528 void AutofillAgent::OnPreviewPasswordSuggestion(
    529     const base::string16& username,
    530     const base::string16& password) {
    531   bool handled = password_autofill_agent_->PreviewSuggestion(
    532       element_,
    533       username,
    534       password);
    535   DCHECK(handled);
    536 }
    537 
    538 void AutofillAgent::OnRequestAutocompleteResult(
    539     WebFormElement::AutocompleteResult result,
    540     const base::string16& message,
    541     const FormData& form_data) {
    542   if (in_flight_request_form_.isNull())
    543     return;
    544 
    545   if (result == WebFormElement::AutocompleteResultSuccess) {
    546     FillFormIncludingNonFocusableElements(form_data, in_flight_request_form_);
    547     if (!in_flight_request_form_.checkValidity())
    548       result = WebFormElement::AutocompleteResultErrorInvalid;
    549   }
    550 
    551   in_flight_request_form_.finishRequestAutocomplete(result);
    552 
    553   if (!message.empty()) {
    554     const base::string16 prefix(base::ASCIIToUTF16("requestAutocomplete: "));
    555     WebConsoleMessage console_message = WebConsoleMessage(
    556         WebConsoleMessage::LevelLog, WebString(prefix + message));
    557     in_flight_request_form_.document().frame()->addMessageToConsole(
    558         console_message);
    559   }
    560 
    561   in_flight_request_form_.reset();
    562 }
    563 
    564 void AutofillAgent::ShowSuggestions(const WebFormControlElement& element,
    565                                     bool autofill_on_empty_values,
    566                                     bool requires_caret_at_end,
    567                                     bool display_warning_if_disabled,
    568                                     bool datalist_only,
    569                                     bool show_full_suggestion_list,
    570                                     bool show_password_suggestions_only) {
    571   if (!element.isEnabled() || element.isReadOnly())
    572     return;
    573   if (!datalist_only && !element.suggestedValue().isEmpty())
    574     return;
    575 
    576   const WebInputElement* input_element = toWebInputElement(&element);
    577   if (input_element) {
    578     if (!input_element->isTextField() || input_element->isPasswordField())
    579       return;
    580     if (!datalist_only && !input_element->suggestedValue().isEmpty())
    581       return;
    582   } else {
    583     DCHECK(IsTextAreaElement(element));
    584     if (!element.toConst<WebTextAreaElement>().suggestedValue().isEmpty())
    585       return;
    586   }
    587 
    588   // Don't attempt to autofill with values that are too large or if filling
    589   // criteria are not met.
    590   WebString value = element.editingValue();
    591   if (!datalist_only &&
    592       (value.length() > kMaxDataLength ||
    593        (!autofill_on_empty_values && value.isEmpty()) ||
    594        (requires_caret_at_end &&
    595         (element.selectionStart() != element.selectionEnd() ||
    596          element.selectionEnd() != static_cast<int>(value.length()))))) {
    597     // Any popup currently showing is obsolete.
    598     HidePopup();
    599     return;
    600   }
    601 
    602   element_ = element;
    603   if (IsAutofillableInputElement(input_element) &&
    604       (password_autofill_agent_->ShowSuggestions(*input_element,
    605                                                  show_full_suggestion_list) ||
    606        show_password_suggestions_only)) {
    607     is_popup_possibly_visible_ = true;
    608     return;
    609   }
    610 
    611   // If autocomplete is disabled at the field level, ensure that the native
    612   // UI won't try to show a warning, since that may conflict with a custom
    613   // popup. Note that we cannot use the WebKit method element.autoComplete()
    614   // as it does not allow us to distinguish the case where autocomplete is
    615   // disabled for *both* the element and for the form.
    616   const base::string16 autocomplete_attribute =
    617       element.getAttribute("autocomplete");
    618   if (LowerCaseEqualsASCII(autocomplete_attribute, "off"))
    619     display_warning_if_disabled = false;
    620 
    621   QueryAutofillSuggestions(element,
    622                            display_warning_if_disabled,
    623                            datalist_only);
    624 }
    625 
    626 void AutofillAgent::QueryAutofillSuggestions(
    627     const WebFormControlElement& element,
    628     bool display_warning_if_disabled,
    629     bool datalist_only) {
    630   if (!element.document().frame())
    631     return;
    632 
    633   DCHECK(toWebInputElement(&element) || IsTextAreaElement(element));
    634 
    635   static int query_counter = 0;
    636   autofill_query_id_ = query_counter++;
    637   display_warning_if_disabled_ = display_warning_if_disabled;
    638 
    639   // If autocomplete is disabled at the form level, we want to see if there
    640   // would have been any suggestions were it enabled, so that we can show a
    641   // warning.  Otherwise, we want to ignore fields that disable autocomplete, so
    642   // that the suggestions list does not include suggestions for these form
    643   // fields -- see comment 1 on http://crbug.com/69914
    644   const RequirementsMask requirements =
    645       element.autoComplete() ? REQUIRE_AUTOCOMPLETE : REQUIRE_NONE;
    646 
    647   FormData form;
    648   FormFieldData field;
    649   if (!FindFormAndFieldForFormControlElement(element, &form, &field,
    650                                              requirements)) {
    651     // If we didn't find the cached form, at least let autocomplete have a shot
    652     // at providing suggestions.
    653     WebFormControlElementToFormField(element, EXTRACT_VALUE, &field);
    654   }
    655   if (datalist_only)
    656     field.should_autocomplete = false;
    657 
    658   gfx::RectF bounding_box_scaled =
    659       GetScaledBoundingBox(web_view_->pageScaleFactor(), &element_);
    660 
    661   std::vector<base::string16> data_list_values;
    662   std::vector<base::string16> data_list_labels;
    663   const WebInputElement* input_element = toWebInputElement(&element);
    664   if (input_element) {
    665     // Find the datalist values and send them to the browser process.
    666     GetDataListSuggestions(*input_element,
    667                            datalist_only,
    668                            &data_list_values,
    669                            &data_list_labels);
    670     TrimStringVectorForIPC(&data_list_values);
    671     TrimStringVectorForIPC(&data_list_labels);
    672   }
    673 
    674   is_popup_possibly_visible_ = true;
    675   Send(new AutofillHostMsg_SetDataList(routing_id(),
    676                                        data_list_values,
    677                                        data_list_labels));
    678 
    679   Send(new AutofillHostMsg_QueryFormFieldAutofill(routing_id(),
    680                                                   autofill_query_id_,
    681                                                   form,
    682                                                   field,
    683                                                   bounding_box_scaled,
    684                                                   display_warning_if_disabled));
    685 }
    686 
    687 void AutofillAgent::FillFieldWithValue(const base::string16& value,
    688                                        WebInputElement* node) {
    689   did_set_node_text_ = true;
    690   node->setEditingValue(value.substr(0, node->maxLength()));
    691 }
    692 
    693 void AutofillAgent::PreviewFieldWithValue(const base::string16& value,
    694                                           WebInputElement* node) {
    695   was_query_node_autofilled_ = element_.isAutofilled();
    696   node->setSuggestedValue(value.substr(0, node->maxLength()));
    697   node->setAutofilled(true);
    698   node->setSelectionRange(node->value().length(),
    699                           node->suggestedValue().length());
    700 }
    701 
    702 void AutofillAgent::ProcessForms(const WebLocalFrame& frame) {
    703   // Record timestamp of when the forms are first seen. This is used to
    704   // measure the overhead of the Autofill feature.
    705   base::TimeTicks forms_seen_timestamp = base::TimeTicks::Now();
    706 
    707   std::vector<FormData> forms;
    708   form_cache_.ExtractNewForms(frame, &forms);
    709 
    710   // Always communicate to browser process for topmost frame.
    711   if (!forms.empty() ||
    712       (!frame.parent() && !main_frame_processed_)) {
    713     Send(new AutofillHostMsg_FormsSeen(routing_id(), forms,
    714                                        forms_seen_timestamp));
    715   }
    716 
    717   if (!frame.parent())
    718     main_frame_processed_ = true;
    719 }
    720 
    721 void AutofillAgent::HidePopup() {
    722   if (!is_popup_possibly_visible_)
    723     return;
    724 
    725   if (!element_.isNull())
    726     OnClearPreviewedForm();
    727 
    728   is_popup_possibly_visible_ = false;
    729   Send(new AutofillHostMsg_HidePopup(routing_id()));
    730 }
    731 
    732 void AutofillAgent::didAssociateFormControls(const WebVector<WebNode>& nodes) {
    733   for (size_t i = 0; i < nodes.size(); ++i) {
    734     WebLocalFrame* frame = nodes[i].document().frame();
    735     // Only monitors dynamic forms created in the top frame. Dynamic forms
    736     // inserted in iframes are not captured yet. Frame is only processed
    737     // if it has finished loading, otherwise you can end up with a partially
    738     // parsed form.
    739     if (frame && !frame->parent() && !frame->isLoading()) {
    740       ProcessForms(*frame);
    741       password_autofill_agent_->OnDynamicFormsSeen(frame);
    742       return;
    743     }
    744   }
    745 }
    746 
    747 }  // namespace autofill
    748