summaryrefslogtreecommitdiffstats
path: root/toolkit/components/autocomplete
diff options
context:
space:
mode:
Diffstat (limited to 'toolkit/components/autocomplete')
-rw-r--r--toolkit/components/autocomplete/moz.build28
-rw-r--r--toolkit/components/autocomplete/nsAutoCompleteController.cpp2087
-rw-r--r--toolkit/components/autocomplete/nsAutoCompleteController.h176
-rw-r--r--toolkit/components/autocomplete/nsAutoCompleteSimpleResult.cpp292
-rw-r--r--toolkit/components/autocomplete/nsAutoCompleteSimpleResult.h44
-rw-r--r--toolkit/components/autocomplete/nsIAutoCompleteController.idl173
-rw-r--r--toolkit/components/autocomplete/nsIAutoCompleteInput.idl181
-rw-r--r--toolkit/components/autocomplete/nsIAutoCompletePopup.idl71
-rw-r--r--toolkit/components/autocomplete/nsIAutoCompleteResult.idl89
-rw-r--r--toolkit/components/autocomplete/nsIAutoCompleteSearch.idl74
-rw-r--r--toolkit/components/autocomplete/nsIAutoCompleteSimpleResult.idl116
-rw-r--r--toolkit/components/autocomplete/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/autocomplete/tests/unit/head_autocomplete.js206
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_330578.js45
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_378079.js285
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_393191.js272
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_440866.js285
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_463023.js12
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_660156.js101
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js276
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js45
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_autofillSelectedPopupIndex.js78
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js96
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_completeDefaultIndex_casing.js63
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalCompleteValue.js48
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalCompleteValueSelectedIndex.js119
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_defaultIndex.js107
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_forceComplete.js104
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalDefaultCompleteValue.js66
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_immediate_search.js157
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_insertMatchAt.js14
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_previousResult.js280
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_stopSearch.js187
-rw-r--r--toolkit/components/autocomplete/tests/unit/xpcshell.ini24
34 files changed, 6208 insertions, 0 deletions
diff --git a/toolkit/components/autocomplete/moz.build b/toolkit/components/autocomplete/moz.build
new file mode 100644
index 000000000..f3817d642
--- /dev/null
+++ b/toolkit/components/autocomplete/moz.build
@@ -0,0 +1,28 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
+
+XPIDL_SOURCES += [
+ 'nsIAutoCompleteController.idl',
+ 'nsIAutoCompleteInput.idl',
+ 'nsIAutoCompletePopup.idl',
+ 'nsIAutoCompleteResult.idl',
+ 'nsIAutoCompleteSearch.idl',
+ 'nsIAutoCompleteSimpleResult.idl',
+]
+
+XPIDL_MODULE = 'autocomplete'
+
+UNIFIED_SOURCES += [
+ 'nsAutoCompleteController.cpp',
+ 'nsAutoCompleteSimpleResult.cpp',
+]
+
+FINAL_LIBRARY = 'xul'
+
+with Files('**'):
+ BUG_COMPONENT = ('Toolkit', 'Autocomplete')
diff --git a/toolkit/components/autocomplete/nsAutoCompleteController.cpp b/toolkit/components/autocomplete/nsAutoCompleteController.cpp
new file mode 100644
index 000000000..5d69ea1a3
--- /dev/null
+++ b/toolkit/components/autocomplete/nsAutoCompleteController.cpp
@@ -0,0 +1,2087 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsAutoCompleteController.h"
+#include "nsAutoCompleteSimpleResult.h"
+
+#include "nsAutoPtr.h"
+#include "nsNetCID.h"
+#include "nsIIOService.h"
+#include "nsToolkitCompsCID.h"
+#include "nsIServiceManager.h"
+#include "nsReadableUtils.h"
+#include "nsUnicharUtils.h"
+#include "nsIScriptSecurityManager.h"
+#include "nsITreeBoxObject.h"
+#include "nsITreeColumns.h"
+#include "nsIObserverService.h"
+#include "nsIDOMKeyEvent.h"
+#include "mozilla/Services.h"
+#include "mozilla/ModuleUtils.h"
+
+static const char *kAutoCompleteSearchCID = "@mozilla.org/autocomplete/search;1?name=";
+
+namespace {
+
+void
+SetTextValue(nsIAutoCompleteInput* aInput,
+ const nsString& aValue,
+ uint16_t aReason) {
+ nsresult rv = aInput->SetTextValueWithReason(aValue, aReason);
+ if (NS_FAILED(rv)) {
+ aInput->SetTextValue(aValue);
+ }
+}
+
+} // anon namespace
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(nsAutoCompleteController)
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsAutoCompleteController)
+ tmp->SetInput(nullptr);
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsAutoCompleteController)
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mInput)
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSearches)
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResults)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_IMPL_CYCLE_COLLECTING_ADDREF(nsAutoCompleteController)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(nsAutoCompleteController)
+NS_INTERFACE_TABLE_HEAD(nsAutoCompleteController)
+ NS_INTERFACE_TABLE(nsAutoCompleteController, nsIAutoCompleteController,
+ nsIAutoCompleteObserver, nsITimerCallback, nsITreeView)
+ NS_INTERFACE_TABLE_TO_MAP_SEGUE_CYCLE_COLLECTION(nsAutoCompleteController)
+NS_INTERFACE_MAP_END
+
+nsAutoCompleteController::nsAutoCompleteController() :
+ mDefaultIndexCompleted(false),
+ mPopupClosedByCompositionStart(false),
+ mProhibitAutoFill(false),
+ mUserClearedAutoFill(false),
+ mClearingAutoFillSearchesAgain(false),
+ mCompositionState(eCompositionState_None),
+ mSearchStatus(nsAutoCompleteController::STATUS_NONE),
+ mRowCount(0),
+ mSearchesOngoing(0),
+ mSearchesFailed(0),
+ mFirstSearchResult(false),
+ mImmediateSearchesCount(0),
+ mCompletedSelectionIndex(-1)
+{
+}
+
+nsAutoCompleteController::~nsAutoCompleteController()
+{
+ SetInput(nullptr);
+}
+
+////////////////////////////////////////////////////////////////////////
+//// nsIAutoCompleteController
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetSearchStatus(uint16_t *aSearchStatus)
+{
+ *aSearchStatus = mSearchStatus;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetMatchCount(uint32_t *aMatchCount)
+{
+ *aMatchCount = mRowCount;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetInput(nsIAutoCompleteInput **aInput)
+{
+ *aInput = mInput;
+ NS_IF_ADDREF(*aInput);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::SetInitiallySelectedIndex(int32_t aSelectedIndex)
+{
+ // First forward to the popup.
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+ NS_ENSURE_STATE(input);
+ nsCOMPtr<nsIAutoCompletePopup> popup;
+ input->GetPopup(getter_AddRefs(popup));
+ NS_ENSURE_STATE(popup);
+ popup->SetSelectedIndex(aSelectedIndex);
+
+ // Now take care of internal stuff.
+ bool completeSelection;
+ if (NS_SUCCEEDED(input->GetCompleteSelectedIndex(&completeSelection)) &&
+ completeSelection) {
+ mCompletedSelectionIndex = aSelectedIndex;
+ }
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::SetInput(nsIAutoCompleteInput *aInput)
+{
+ // Don't do anything if the input isn't changing.
+ if (mInput == aInput)
+ return NS_OK;
+
+ // Clear out the current search context
+ if (mInput) {
+ // Stop all searches in case they are async.
+ StopSearch();
+ ClearResults();
+ ClosePopup();
+ mSearches.Clear();
+ }
+
+ mInput = aInput;
+
+ // Nothing more to do if the input was just being set to null.
+ if (!aInput)
+ return NS_OK;
+
+ nsAutoString newValue;
+ aInput->GetTextValue(newValue);
+
+ // Clear out this reference in case the new input's popup has no tree
+ mTree = nullptr;
+
+ // Reset all search state members to default values
+ mSearchString = newValue;
+ mPlaceholderCompletionString.Truncate();
+ mDefaultIndexCompleted = false;
+ mProhibitAutoFill = false;
+ mSearchStatus = nsIAutoCompleteController::STATUS_NONE;
+ mRowCount = 0;
+ mSearchesOngoing = 0;
+ mCompletedSelectionIndex = -1;
+
+ // Initialize our list of search objects
+ uint32_t searchCount;
+ aInput->GetSearchCount(&searchCount);
+ mResults.SetCapacity(searchCount);
+ mSearches.SetCapacity(searchCount);
+ mImmediateSearchesCount = 0;
+
+ const char *searchCID = kAutoCompleteSearchCID;
+
+ // Since the controller can be used as a service it's important to reset this.
+ mClearingAutoFillSearchesAgain = false;
+
+ for (uint32_t i = 0; i < searchCount; ++i) {
+ // Use the search name to create the contract id string for the search service
+ nsAutoCString searchName;
+ aInput->GetSearchAt(i, searchName);
+ nsAutoCString cid(searchCID);
+ cid.Append(searchName);
+
+ // Use the created cid to get a pointer to the search service and store it for later
+ nsCOMPtr<nsIAutoCompleteSearch> search = do_GetService(cid.get());
+ if (search) {
+ mSearches.AppendObject(search);
+
+ // Count immediate searches.
+ nsCOMPtr<nsIAutoCompleteSearchDescriptor> searchDesc =
+ do_QueryInterface(search);
+ if (searchDesc) {
+ uint16_t searchType = nsIAutoCompleteSearchDescriptor::SEARCH_TYPE_DELAYED;
+ if (NS_SUCCEEDED(searchDesc->GetSearchType(&searchType)) &&
+ searchType == nsIAutoCompleteSearchDescriptor::SEARCH_TYPE_IMMEDIATE) {
+ mImmediateSearchesCount++;
+ }
+
+ if (!mClearingAutoFillSearchesAgain) {
+ searchDesc->GetClearingAutoFillSearchesAgain(&mClearingAutoFillSearchesAgain);
+ }
+ }
+ }
+ }
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::StartSearch(const nsAString &aSearchString)
+{
+ mSearchString = aSearchString;
+ StartSearches();
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::HandleText(bool *_retval)
+{
+ *_retval = false;
+ // Note: the events occur in the following order when IME is used.
+ // 1. a compositionstart event(HandleStartComposition)
+ // 2. some input events (HandleText), eCompositionState_Composing
+ // 3. a compositionend event(HandleEndComposition)
+ // 4. an input event(HandleText), eCompositionState_Committing
+ // We should do nothing during composition.
+ if (mCompositionState == eCompositionState_Composing) {
+ return NS_OK;
+ }
+
+ bool handlingCompositionCommit =
+ (mCompositionState == eCompositionState_Committing);
+ bool popupClosedByCompositionStart = mPopupClosedByCompositionStart;
+ if (handlingCompositionCommit) {
+ mCompositionState = eCompositionState_None;
+ mPopupClosedByCompositionStart = false;
+ }
+
+ if (!mInput) {
+ // Stop all searches in case they are async.
+ StopSearch();
+ // Note: if now is after blur and IME end composition,
+ // check mInput before calling.
+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=193544#c31
+ NS_ERROR("Called before attaching to the control or after detaching from the control");
+ return NS_OK;
+ }
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+ nsAutoString newValue;
+ input->GetTextValue(newValue);
+
+ // Stop all searches in case they are async.
+ StopSearch();
+
+ if (!mInput) {
+ // StopSearch() can call PostSearchCleanup() which might result
+ // in a blur event, which could null out mInput, so we need to check it
+ // again. See bug #395344 for more details
+ return NS_OK;
+ }
+
+ bool disabled;
+ input->GetDisableAutoComplete(&disabled);
+ NS_ENSURE_TRUE(!disabled, NS_OK);
+
+ // Usually we don't search again if the new string is the same as the last one.
+ // However, if this is called immediately after compositionend event,
+ // we need to search the same value again since the search was canceled
+ // at compositionstart event handler.
+ // The new string might also be the same as the last search if the autofilled
+ // portion was cleared. In this case, we may want to search again.
+
+ // Whether the user removed some text at the end.
+ bool userRemovedText =
+ newValue.Length() < mSearchString.Length() &&
+ Substring(mSearchString, 0, newValue.Length()).Equals(newValue);
+
+ // Whether the user is repeating the previous search.
+ bool repeatingPreviousSearch = !userRemovedText &&
+ newValue.Equals(mSearchString);
+
+ mUserClearedAutoFill =
+ repeatingPreviousSearch &&
+ newValue.Length() < mPlaceholderCompletionString.Length() &&
+ Substring(mPlaceholderCompletionString, 0, newValue.Length()).Equals(newValue);
+ bool searchAgainOnAutoFillClear = mUserClearedAutoFill && mClearingAutoFillSearchesAgain;
+
+ if (!handlingCompositionCommit &&
+ !searchAgainOnAutoFillClear &&
+ newValue.Length() > 0 &&
+ repeatingPreviousSearch) {
+ return NS_OK;
+ }
+
+ if (userRemovedText || searchAgainOnAutoFillClear) {
+ if (userRemovedText) {
+ // We need to throw away previous results so we don't try to search
+ // through them again.
+ ClearResults();
+ }
+ mProhibitAutoFill = true;
+ mPlaceholderCompletionString.Truncate();
+ } else {
+ mProhibitAutoFill = false;
+ }
+
+ mSearchString = newValue;
+
+ // Don't search if the value is empty
+ if (newValue.Length() == 0) {
+ // If autocomplete popup was closed by compositionstart event handler,
+ // we should reopen it forcibly even if the value is empty.
+ if (popupClosedByCompositionStart && handlingCompositionCommit) {
+ bool cancel;
+ HandleKeyNavigation(nsIDOMKeyEvent::DOM_VK_DOWN, &cancel);
+ return NS_OK;
+ }
+ ClosePopup();
+ return NS_OK;
+ }
+
+ *_retval = true;
+ StartSearches();
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::HandleEnter(bool aIsPopupSelection,
+ nsIDOMEvent *aEvent,
+ bool *_retval)
+{
+ *_retval = false;
+ if (!mInput)
+ return NS_OK;
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+
+ // allow the event through unless there is something selected in the popup
+ input->GetPopupOpen(_retval);
+ if (*_retval) {
+ nsCOMPtr<nsIAutoCompletePopup> popup;
+ input->GetPopup(getter_AddRefs(popup));
+
+ if (popup) {
+ int32_t selectedIndex;
+ popup->GetSelectedIndex(&selectedIndex);
+ *_retval = selectedIndex >= 0;
+ }
+ }
+
+ // Stop the search, and handle the enter.
+ StopSearch();
+ EnterMatch(aIsPopupSelection, aEvent);
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::HandleEscape(bool *_retval)
+{
+ *_retval = false;
+ if (!mInput)
+ return NS_OK;
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+
+ // allow the event through if the popup is closed
+ input->GetPopupOpen(_retval);
+
+ // Stop all searches in case they are async.
+ StopSearch();
+ ClearResults();
+ RevertTextValue();
+ ClosePopup();
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::HandleStartComposition()
+{
+ NS_ENSURE_TRUE(mCompositionState != eCompositionState_Composing, NS_OK);
+
+ mPopupClosedByCompositionStart = false;
+ mCompositionState = eCompositionState_Composing;
+
+ if (!mInput)
+ return NS_OK;
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+ bool disabled;
+ input->GetDisableAutoComplete(&disabled);
+ if (disabled)
+ return NS_OK;
+
+ // Stop all searches in case they are async.
+ StopSearch();
+
+ bool isOpen = false;
+ input->GetPopupOpen(&isOpen);
+ if (isOpen) {
+ ClosePopup();
+
+ bool stillOpen = false;
+ input->GetPopupOpen(&stillOpen);
+ mPopupClosedByCompositionStart = !stillOpen;
+ }
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::HandleEndComposition()
+{
+ NS_ENSURE_TRUE(mCompositionState == eCompositionState_Composing, NS_OK);
+
+ // We can't yet retrieve the committed value from the editor, since it isn't
+ // completely committed yet. Set mCompositionState to
+ // eCompositionState_Committing, so that when HandleText() is called (in
+ // response to the "input" event), we know that we should handle the
+ // committed text.
+ mCompositionState = eCompositionState_Committing;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::HandleTab()
+{
+ bool cancel;
+ return HandleEnter(false, nullptr, &cancel);
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::HandleKeyNavigation(uint32_t aKey, bool *_retval)
+{
+ // By default, don't cancel the event
+ *_retval = false;
+
+ if (!mInput) {
+ // Stop all searches in case they are async.
+ StopSearch();
+ // Note: if now is after blur and IME end composition,
+ // check mInput before calling.
+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=193544#c31
+ NS_ERROR("Called before attaching to the control or after detaching from the control");
+ return NS_OK;
+ }
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+ nsCOMPtr<nsIAutoCompletePopup> popup;
+ input->GetPopup(getter_AddRefs(popup));
+ NS_ENSURE_TRUE(popup != nullptr, NS_ERROR_FAILURE);
+
+ bool disabled;
+ input->GetDisableAutoComplete(&disabled);
+ NS_ENSURE_TRUE(!disabled, NS_OK);
+
+ if (aKey == nsIDOMKeyEvent::DOM_VK_UP ||
+ aKey == nsIDOMKeyEvent::DOM_VK_DOWN ||
+ aKey == nsIDOMKeyEvent::DOM_VK_PAGE_UP ||
+ aKey == nsIDOMKeyEvent::DOM_VK_PAGE_DOWN)
+ {
+ // Prevent the input from handling up/down events, as it may move
+ // the cursor to home/end on some systems
+ *_retval = true;
+
+ bool isOpen = false;
+ input->GetPopupOpen(&isOpen);
+ if (isOpen) {
+ bool reverse = aKey == nsIDOMKeyEvent::DOM_VK_UP ||
+ aKey == nsIDOMKeyEvent::DOM_VK_PAGE_UP ? true : false;
+ bool page = aKey == nsIDOMKeyEvent::DOM_VK_PAGE_UP ||
+ aKey == nsIDOMKeyEvent::DOM_VK_PAGE_DOWN ? true : false;
+
+ // Fill in the value of the textbox with whatever is selected in the popup
+ // if the completeSelectedIndex attribute is set. We check this before
+ // calling SelectBy of an earlier attempt to avoid crashing.
+ bool completeSelection;
+ input->GetCompleteSelectedIndex(&completeSelection);
+
+ // Instruct the result view to scroll by the given amount and direction
+ popup->SelectBy(reverse, page);
+
+ if (completeSelection)
+ {
+ int32_t selectedIndex;
+ popup->GetSelectedIndex(&selectedIndex);
+ if (selectedIndex >= 0) {
+ // A result is selected, so fill in its value
+ nsAutoString value;
+ if (NS_SUCCEEDED(GetResultValueAt(selectedIndex, false, value))) {
+ // If the result is the previously autofilled string, then restore
+ // the search string and selection that existed when the result was
+ // autofilled. Else, fill the result and move the caret to the end.
+ int32_t start;
+ if (value.Equals(mPlaceholderCompletionString,
+ nsCaseInsensitiveStringComparator())) {
+ start = mSearchString.Length();
+ value = mPlaceholderCompletionString;
+ SetTextValue(input, value,
+ nsIAutoCompleteInput::TEXTVALUE_REASON_COMPLETEDEFAULT);
+ } else {
+ start = value.Length();
+ SetTextValue(input, value,
+ nsIAutoCompleteInput::TEXTVALUE_REASON_COMPLETESELECTED);
+ }
+
+ input->SelectTextRange(start, value.Length());
+ }
+ mCompletedSelectionIndex = selectedIndex;
+ } else {
+ // Nothing is selected, so fill in the last typed value
+ SetTextValue(input, mSearchString,
+ nsIAutoCompleteInput::TEXTVALUE_REASON_REVERT);
+ input->SelectTextRange(mSearchString.Length(), mSearchString.Length());
+ mCompletedSelectionIndex = -1;
+ }
+ }
+ } else {
+#ifdef XP_MACOSX
+ // on Mac, only show the popup if the caret is at the start or end of
+ // the input and there is no selection, so that the default defined key
+ // shortcuts for up and down move to the beginning and end of the field
+ // otherwise.
+ int32_t start, end;
+ if (aKey == nsIDOMKeyEvent::DOM_VK_UP) {
+ input->GetSelectionStart(&start);
+ input->GetSelectionEnd(&end);
+ if (start > 0 || start != end)
+ *_retval = false;
+ }
+ else if (aKey == nsIDOMKeyEvent::DOM_VK_DOWN) {
+ nsAutoString text;
+ input->GetTextValue(text);
+ input->GetSelectionStart(&start);
+ input->GetSelectionEnd(&end);
+ if (start != end || end < (int32_t)text.Length())
+ *_retval = false;
+ }
+#endif
+ if (*_retval) {
+ // Open the popup if there has been a previous search, or else kick off a new search
+ if (!mResults.IsEmpty()) {
+ if (mRowCount) {
+ OpenPopup();
+ }
+ } else {
+ // Stop all searches in case they are async.
+ StopSearch();
+
+ if (!mInput) {
+ // StopSearch() can call PostSearchCleanup() which might result
+ // in a blur event, which could null out mInput, so we need to check it
+ // again. See bug #395344 for more details
+ return NS_OK;
+ }
+
+ // Some script may have changed the value of the text field since our
+ // last keypress or after our focus handler and we don't want to search
+ // for a stale string.
+ nsAutoString value;
+ input->GetTextValue(value);
+ mSearchString = value;
+
+ StartSearches();
+ }
+ }
+ }
+ } else if ( aKey == nsIDOMKeyEvent::DOM_VK_LEFT
+ || aKey == nsIDOMKeyEvent::DOM_VK_RIGHT
+#ifndef XP_MACOSX
+ || aKey == nsIDOMKeyEvent::DOM_VK_HOME
+#endif
+ )
+ {
+ // The user hit a text-navigation key.
+ bool isOpen = false;
+ input->GetPopupOpen(&isOpen);
+
+ // If minresultsforpopup > 1 and there's less matches than the minimum
+ // required, the popup is not open, but the search suggestion is showing
+ // inline, so we should proceed as if we had the popup.
+ uint32_t minResultsForPopup;
+ input->GetMinResultsForPopup(&minResultsForPopup);
+ if (isOpen || (mRowCount > 0 && mRowCount < minResultsForPopup)) {
+ // For completeSelectedIndex autocomplete fields, if the popup shouldn't
+ // close when the caret is moved, don't adjust the text value or caret
+ // position.
+ if (isOpen) {
+ bool noRollup;
+ input->GetNoRollupOnCaretMove(&noRollup);
+ if (noRollup) {
+ bool completeSelection;
+ input->GetCompleteSelectedIndex(&completeSelection);
+ if (completeSelection) {
+ return NS_OK;
+ }
+ }
+ }
+
+ int32_t selectedIndex;
+ popup->GetSelectedIndex(&selectedIndex);
+ bool shouldComplete;
+ input->GetCompleteDefaultIndex(&shouldComplete);
+ if (selectedIndex >= 0) {
+ // The pop-up is open and has a selection, take its value
+ nsAutoString value;
+ if (NS_SUCCEEDED(GetResultValueAt(selectedIndex, false, value))) {
+ SetTextValue(input, value,
+ nsIAutoCompleteInput::TEXTVALUE_REASON_COMPLETESELECTED);
+ input->SelectTextRange(value.Length(), value.Length());
+ }
+ }
+ else if (shouldComplete) {
+ // We usually try to preserve the casing of what user has typed, but
+ // if he wants to autocomplete, we will replace the value with the
+ // actual autocomplete result. Note that the autocomplete input can also
+ // be showing e.g. "bar >> foo bar" if the search matched "bar", a
+ // word not at the start of the full value "foo bar".
+ // The user wants explicitely to use that result, so this ensures
+ // association of the result with the autocompleted text.
+ nsAutoString value;
+ nsAutoString inputValue;
+ input->GetTextValue(inputValue);
+ if (NS_SUCCEEDED(GetDefaultCompleteValue(-1, false, value))) {
+ nsAutoString suggestedValue;
+ int32_t pos = inputValue.Find(" >> ");
+ if (pos > 0) {
+ inputValue.Right(suggestedValue, inputValue.Length() - pos - 4);
+ } else {
+ suggestedValue = inputValue;
+ }
+
+ if (value.Equals(suggestedValue, nsCaseInsensitiveStringComparator())) {
+ SetTextValue(input, value,
+ nsIAutoCompleteInput::TEXTVALUE_REASON_COMPLETEDEFAULT);
+ input->SelectTextRange(value.Length(), value.Length());
+ }
+ }
+ }
+
+ // Close the pop-up even if nothing was selected
+ ClearSearchTimer();
+ ClosePopup();
+ }
+ // Update last-searched string to the current input, since the input may
+ // have changed. Without this, subsequent backspaces look like text
+ // additions, not text deletions.
+ nsAutoString value;
+ input->GetTextValue(value);
+ mSearchString = value;
+ }
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::HandleDelete(bool *_retval)
+{
+ *_retval = false;
+ if (!mInput)
+ return NS_OK;
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+ bool isOpen = false;
+ input->GetPopupOpen(&isOpen);
+ if (!isOpen || mRowCount <= 0) {
+ // Nothing left to delete, proceed as normal
+ bool unused = false;
+ HandleText(&unused);
+ return NS_OK;
+ }
+
+ nsCOMPtr<nsIAutoCompletePopup> popup;
+ input->GetPopup(getter_AddRefs(popup));
+
+ int32_t index, searchIndex, rowIndex;
+ popup->GetSelectedIndex(&index);
+ if (index == -1) {
+ // No row is selected in the list
+ bool unused = false;
+ HandleText(&unused);
+ return NS_OK;
+ }
+
+ RowIndexToSearch(index, &searchIndex, &rowIndex);
+ NS_ENSURE_TRUE(searchIndex >= 0 && rowIndex >= 0, NS_ERROR_FAILURE);
+
+ nsIAutoCompleteResult *result = mResults.SafeObjectAt(searchIndex);
+ NS_ENSURE_TRUE(result, NS_ERROR_FAILURE);
+
+ nsAutoString search;
+ input->GetSearchParam(search);
+
+ // Clear the row in our result and in the DB.
+ result->RemoveValueAt(rowIndex, true);
+ --mRowCount;
+
+ // We removed it, so make sure we cancel the event that triggered this call.
+ *_retval = true;
+
+ // Unselect the current item.
+ popup->SetSelectedIndex(-1);
+
+ // Tell the tree that the row count changed.
+ if (mTree)
+ mTree->RowCountChanged(mRowCount, -1);
+
+ // Adjust index, if needed.
+ if (index >= (int32_t)mRowCount)
+ index = mRowCount - 1;
+
+ if (mRowCount > 0) {
+ // There are still rows in the popup, select the current index again.
+ popup->SetSelectedIndex(index);
+
+ // Complete to the new current value.
+ bool shouldComplete = false;
+ input->GetCompleteDefaultIndex(&shouldComplete);
+ if (shouldComplete) {
+ nsAutoString value;
+ if (NS_SUCCEEDED(GetResultValueAt(index, false, value))) {
+ CompleteValue(value);
+ }
+ }
+
+ // Invalidate the popup.
+ popup->Invalidate(nsIAutoCompletePopup::INVALIDATE_REASON_DELETE);
+ } else {
+ // Nothing left in the popup, clear any pending search timers and
+ // close the popup.
+ ClearSearchTimer();
+ uint32_t minResults;
+ input->GetMinResultsForPopup(&minResults);
+ if (minResults) {
+ ClosePopup();
+ }
+ }
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::GetResultAt(int32_t aIndex, nsIAutoCompleteResult** aResult,
+ int32_t* aRowIndex)
+{
+ int32_t searchIndex;
+ RowIndexToSearch(aIndex, &searchIndex, aRowIndex);
+ NS_ENSURE_TRUE(searchIndex >= 0 && *aRowIndex >= 0, NS_ERROR_FAILURE);
+
+ *aResult = mResults.SafeObjectAt(searchIndex);
+ NS_ENSURE_TRUE(*aResult, NS_ERROR_FAILURE);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetValueAt(int32_t aIndex, nsAString & _retval)
+{
+ GetResultLabelAt(aIndex, _retval);
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetLabelAt(int32_t aIndex, nsAString & _retval)
+{
+ GetResultLabelAt(aIndex, _retval);
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetCommentAt(int32_t aIndex, nsAString & _retval)
+{
+ int32_t rowIndex;
+ nsIAutoCompleteResult* result;
+ nsresult rv = GetResultAt(aIndex, &result, &rowIndex);
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ return result->GetCommentAt(rowIndex, _retval);
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetStyleAt(int32_t aIndex, nsAString & _retval)
+{
+ int32_t rowIndex;
+ nsIAutoCompleteResult* result;
+ nsresult rv = GetResultAt(aIndex, &result, &rowIndex);
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ return result->GetStyleAt(rowIndex, _retval);
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetImageAt(int32_t aIndex, nsAString & _retval)
+{
+ int32_t rowIndex;
+ nsIAutoCompleteResult* result;
+ nsresult rv = GetResultAt(aIndex, &result, &rowIndex);
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ return result->GetImageAt(rowIndex, _retval);
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetFinalCompleteValueAt(int32_t aIndex,
+ nsAString & _retval)
+{
+ int32_t rowIndex;
+ nsIAutoCompleteResult* result;
+ nsresult rv = GetResultAt(aIndex, &result, &rowIndex);
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ return result->GetFinalCompleteValueAt(rowIndex, _retval);
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::SetSearchString(const nsAString &aSearchString)
+{
+ mSearchString = aSearchString;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetSearchString(nsAString &aSearchString)
+{
+ aSearchString = mSearchString;
+ return NS_OK;
+}
+
+void
+nsAutoCompleteController::HandleSearchResult(nsIAutoCompleteSearch *aSearch,
+ nsIAutoCompleteResult *aResult)
+{
+ // Look up the index of the search which is returning.
+ for (uint32_t i = 0; i < mSearches.Length(); ++i) {
+ if (mSearches[i] == aSearch) {
+ ProcessResult(i, aResult);
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////////////////
+//// nsIAutoCompleteObserver
+
+NS_IMETHODIMP
+nsAutoCompleteController::OnUpdateSearchResult(nsIAutoCompleteSearch *aSearch, nsIAutoCompleteResult* aResult)
+{
+ MOZ_ASSERT(mSearches.Contains(aSearch));
+
+ ClearResults();
+ HandleSearchResult(aSearch, aResult);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::OnSearchResult(nsIAutoCompleteSearch *aSearch, nsIAutoCompleteResult* aResult)
+{
+ MOZ_ASSERT(mSearchesOngoing > 0 && mSearches.Contains(aSearch));
+
+ // If this is the first search result we are processing
+ // we should clear out the previously cached results.
+ if (mFirstSearchResult) {
+ ClearResults();
+ mFirstSearchResult = false;
+ }
+
+ uint16_t result = 0;
+ if (aResult) {
+ aResult->GetSearchResult(&result);
+ }
+
+ // If our results are incremental, the search is still ongoing.
+ if (result != nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING &&
+ result != nsIAutoCompleteResult::RESULT_NOMATCH_ONGOING) {
+ --mSearchesOngoing;
+ }
+
+ HandleSearchResult(aSearch, aResult);
+
+ if (mSearchesOngoing == 0) {
+ // If this is the last search to return, cleanup.
+ PostSearchCleanup();
+ }
+
+ return NS_OK;
+}
+
+////////////////////////////////////////////////////////////////////////
+//// nsITimerCallback
+
+NS_IMETHODIMP
+nsAutoCompleteController::Notify(nsITimer *timer)
+{
+ mTimer = nullptr;
+
+ if (mImmediateSearchesCount == 0) {
+ // If there were no immediate searches, BeforeSearches has not yet been
+ // called, so do it now.
+ nsresult rv = BeforeSearches();
+ if (NS_FAILED(rv))
+ return rv;
+ }
+ StartSearch(nsIAutoCompleteSearchDescriptor::SEARCH_TYPE_DELAYED);
+ AfterSearches();
+ return NS_OK;
+}
+
+////////////////////////////////////////////////////////////////////////
+// nsITreeView
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetRowCount(int32_t *aRowCount)
+{
+ *aRowCount = mRowCount;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetRowProperties(int32_t index, nsAString& aProps)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetCellProperties(int32_t row, nsITreeColumn* col,
+ nsAString& aProps)
+{
+ if (row >= 0) {
+ GetStyleAt(row, aProps);
+ }
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetColumnProperties(nsITreeColumn* col, nsAString& aProps)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetImageSrc(int32_t row, nsITreeColumn* col, nsAString& _retval)
+{
+ const char16_t* colID;
+ col->GetIdConst(&colID);
+
+ if (NS_LITERAL_STRING("treecolAutoCompleteValue").Equals(colID))
+ return GetImageAt(row, _retval);
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetProgressMode(int32_t row, nsITreeColumn* col, int32_t* _retval)
+{
+ NS_NOTREACHED("tree has no progress cells");
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetCellValue(int32_t row, nsITreeColumn* col, nsAString& _retval)
+{
+ NS_NOTREACHED("all of our cells are text");
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetCellText(int32_t row, nsITreeColumn* col, nsAString& _retval)
+{
+ const char16_t* colID;
+ col->GetIdConst(&colID);
+
+ if (NS_LITERAL_STRING("treecolAutoCompleteValue").Equals(colID))
+ GetValueAt(row, _retval);
+ else if (NS_LITERAL_STRING("treecolAutoCompleteComment").Equals(colID))
+ GetCommentAt(row, _retval);
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::IsContainer(int32_t index, bool *_retval)
+{
+ *_retval = false;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::IsContainerOpen(int32_t index, bool *_retval)
+{
+ NS_NOTREACHED("no container cells");
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::IsContainerEmpty(int32_t index, bool *_retval)
+{
+ NS_NOTREACHED("no container cells");
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetLevel(int32_t index, int32_t *_retval)
+{
+ *_retval = 0;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetParentIndex(int32_t rowIndex, int32_t *_retval)
+{
+ *_retval = -1;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::HasNextSibling(int32_t rowIndex, int32_t afterIndex, bool *_retval)
+{
+ *_retval = false;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::ToggleOpenState(int32_t index)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::SetTree(nsITreeBoxObject *tree)
+{
+ mTree = tree;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::GetSelection(nsITreeSelection * *aSelection)
+{
+ *aSelection = mSelection;
+ NS_IF_ADDREF(*aSelection);
+ return NS_OK;
+}
+
+NS_IMETHODIMP nsAutoCompleteController::SetSelection(nsITreeSelection * aSelection)
+{
+ mSelection = aSelection;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::SelectionChanged()
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::SetCellValue(int32_t row, nsITreeColumn* col, const nsAString& value)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::SetCellText(int32_t row, nsITreeColumn* col, const nsAString& value)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::CycleHeader(nsITreeColumn* col)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::CycleCell(int32_t row, nsITreeColumn* col)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::IsEditable(int32_t row, nsITreeColumn* col, bool *_retval)
+{
+ *_retval = false;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::IsSelectable(int32_t row, nsITreeColumn* col, bool *_retval)
+{
+ *_retval = false;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::IsSeparator(int32_t index, bool *_retval)
+{
+ *_retval = false;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::IsSorted(bool *_retval)
+{
+ *_retval = false;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::CanDrop(int32_t index, int32_t orientation,
+ nsIDOMDataTransfer* dataTransfer, bool *_retval)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::Drop(int32_t row, int32_t orientation, nsIDOMDataTransfer* dataTransfer)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::PerformAction(const char16_t *action)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::PerformActionOnRow(const char16_t *action, int32_t row)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::PerformActionOnCell(const char16_t* action, int32_t row, nsITreeColumn* col)
+{
+ return NS_OK;
+}
+
+////////////////////////////////////////////////////////////////////////
+//// nsAutoCompleteController
+
+nsresult
+nsAutoCompleteController::OpenPopup()
+{
+ uint32_t minResults;
+ mInput->GetMinResultsForPopup(&minResults);
+
+ if (mRowCount >= minResults) {
+ return mInput->SetPopupOpen(true);
+ }
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::ClosePopup()
+{
+ if (!mInput) {
+ return NS_OK;
+ }
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+
+ bool isOpen = false;
+ input->GetPopupOpen(&isOpen);
+ if (!isOpen)
+ return NS_OK;
+
+ nsCOMPtr<nsIAutoCompletePopup> popup;
+ input->GetPopup(getter_AddRefs(popup));
+ NS_ENSURE_TRUE(popup != nullptr, NS_ERROR_FAILURE);
+ popup->SetSelectedIndex(-1);
+ return input->SetPopupOpen(false);
+}
+
+nsresult
+nsAutoCompleteController::BeforeSearches()
+{
+ NS_ENSURE_STATE(mInput);
+
+ mSearchStatus = nsIAutoCompleteController::STATUS_SEARCHING;
+ mDefaultIndexCompleted = false;
+
+ // The first search result will clear mResults array, though we should pass
+ // the previous result to each search to allow them to reuse it. So we
+ // temporarily cache current results till AfterSearches().
+ if (!mResultCache.AppendObjects(mResults)) {
+ return NS_ERROR_OUT_OF_MEMORY;
+ }
+
+ mSearchesOngoing = mSearches.Length();
+ mSearchesFailed = 0;
+ mFirstSearchResult = true;
+
+ // notify the input that the search is beginning
+ mInput->OnSearchBegin();
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::StartSearch(uint16_t aSearchType)
+{
+ NS_ENSURE_STATE(mInput);
+ nsCOMPtr<nsIAutoCompleteInput> input = mInput;
+
+ // Iterate a copy of |mSearches| so that we don't run into trouble if the
+ // array is mutated while we're still in the loop. An nsIAutoCompleteSearch
+ // implementation could synchronously start a new search when StartSearch()
+ // is called and that would lead to assertions down the way.
+ nsCOMArray<nsIAutoCompleteSearch> searchesCopy(mSearches);
+ for (uint32_t i = 0; i < searchesCopy.Length(); ++i) {
+ nsCOMPtr<nsIAutoCompleteSearch> search = searchesCopy[i];
+
+ // Filter on search type. Not all the searches implement this interface,
+ // in such a case just consider them delayed.
+ uint16_t searchType = nsIAutoCompleteSearchDescriptor::SEARCH_TYPE_DELAYED;
+ nsCOMPtr<nsIAutoCompleteSearchDescriptor> searchDesc =
+ do_QueryInterface(search);
+ if (searchDesc)
+ searchDesc->GetSearchType(&searchType);
+ if (searchType != aSearchType)
+ continue;
+
+ nsIAutoCompleteResult *result = mResultCache.SafeObjectAt(i);
+
+ if (result) {
+ uint16_t searchResult;
+ result->GetSearchResult(&searchResult);
+ if (searchResult != nsIAutoCompleteResult::RESULT_SUCCESS &&
+ searchResult != nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING &&
+ searchResult != nsIAutoCompleteResult::RESULT_NOMATCH)
+ result = nullptr;
+ }
+
+ nsAutoString searchParam;
+ nsresult rv = input->GetSearchParam(searchParam);
+ if (NS_FAILED(rv))
+ return rv;
+
+ // FormFill expects the searchParam to only contain the input element id,
+ // other consumers may have other expectations, so this modifies it only
+ // for new consumers handling autoFill by themselves.
+ if (mProhibitAutoFill && mClearingAutoFillSearchesAgain) {
+ searchParam.AppendLiteral(" prohibit-autofill");
+ }
+
+ uint32_t userContextId;
+ rv = input->GetUserContextId(&userContextId);
+ if (NS_SUCCEEDED(rv) &&
+ userContextId != nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID) {
+ searchParam.AppendLiteral(" user-context-id:");
+ searchParam.AppendInt(userContextId, 10);
+ }
+
+ rv = search->StartSearch(mSearchString, searchParam, result, static_cast<nsIAutoCompleteObserver *>(this));
+ if (NS_FAILED(rv)) {
+ ++mSearchesFailed;
+ MOZ_ASSERT(mSearchesOngoing > 0);
+ --mSearchesOngoing;
+ }
+ // Because of the joy of nested event loops (which can easily happen when some
+ // code uses a generator for an asynchronous AutoComplete search),
+ // nsIAutoCompleteSearch::StartSearch might cause us to be detached from our input
+ // field. The next time we iterate, we'd be touching something that we shouldn't
+ // be, and result in a crash.
+ if (!mInput) {
+ // The search operation has been finished.
+ return NS_OK;
+ }
+ }
+
+ return NS_OK;
+}
+
+void
+nsAutoCompleteController::AfterSearches()
+{
+ mResultCache.Clear();
+ if (mSearchesFailed == mSearches.Length())
+ PostSearchCleanup();
+}
+
+NS_IMETHODIMP
+nsAutoCompleteController::StopSearch()
+{
+ // Stop the timer if there is one
+ ClearSearchTimer();
+
+ // Stop any ongoing asynchronous searches
+ if (mSearchStatus == nsIAutoCompleteController::STATUS_SEARCHING) {
+ for (uint32_t i = 0; i < mSearches.Length(); ++i) {
+ nsCOMPtr<nsIAutoCompleteSearch> search = mSearches[i];
+ search->StopSearch();
+ }
+ mSearchesOngoing = 0;
+ // since we were searching, but now we've stopped,
+ // we need to call PostSearchCleanup()
+ PostSearchCleanup();
+ }
+ return NS_OK;
+}
+
+void
+nsAutoCompleteController::MaybeCompletePlaceholder()
+{
+ MOZ_ASSERT(mInput);
+
+ if (!mInput) { // or mInput depending on what you choose
+ MOZ_ASSERT_UNREACHABLE("Input should always be valid at this point");
+ return;
+ }
+
+ int32_t selectionStart;
+ mInput->GetSelectionStart(&selectionStart);
+ int32_t selectionEnd;
+ mInput->GetSelectionEnd(&selectionEnd);
+
+ // Check if the current input should be completed with the placeholder string
+ // from the last completion until the actual search results come back.
+ // The new input string needs to be compatible with the last completed string.
+ // E.g. if the new value is "fob", but the last completion was "foobar",
+ // then the last completion is incompatible.
+ // If the search string is the same as the last completion value, then don't
+ // complete the value again (this prevents completion to happen e.g. if the
+ // cursor is moved and StartSeaches() is invoked).
+ // In addition, the selection must be at the end of the current input to
+ // trigger the placeholder completion.
+ bool usePlaceholderCompletion =
+ !mUserClearedAutoFill &&
+ !mPlaceholderCompletionString.IsEmpty() &&
+ mPlaceholderCompletionString.Length() > mSearchString.Length() &&
+ selectionEnd == selectionStart &&
+ selectionEnd == (int32_t)mSearchString.Length() &&
+ StringBeginsWith(mPlaceholderCompletionString, mSearchString,
+ nsCaseInsensitiveStringComparator());
+
+ if (usePlaceholderCompletion) {
+ CompleteValue(mPlaceholderCompletionString);
+ } else {
+ mPlaceholderCompletionString.Truncate();
+ }
+}
+
+nsresult
+nsAutoCompleteController::StartSearches()
+{
+ // Don't create a new search timer if we're already waiting for one to fire.
+ // If we don't check for this, we won't be able to cancel the original timer
+ // and may crash when it fires (bug 236659).
+ if (mTimer || !mInput)
+ return NS_OK;
+
+ // Check if the current input should be completed with the placeholder string
+ // from the last completion until the actual search results come back.
+ MaybeCompletePlaceholder();
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+
+ // Get the timeout for delayed searches.
+ uint32_t timeout;
+ input->GetTimeout(&timeout);
+
+ uint32_t immediateSearchesCount = mImmediateSearchesCount;
+ if (timeout == 0) {
+ // All the searches should be executed immediately.
+ immediateSearchesCount = mSearches.Length();
+ }
+
+ if (immediateSearchesCount > 0) {
+ nsresult rv = BeforeSearches();
+ if (NS_FAILED(rv))
+ return rv;
+ StartSearch(nsIAutoCompleteSearchDescriptor::SEARCH_TYPE_IMMEDIATE);
+
+ if (mSearches.Length() == immediateSearchesCount) {
+ // Either all searches are immediate, or the timeout is 0. In the
+ // latter case we still have to execute the delayed searches, otherwise
+ // this will be a no-op.
+ StartSearch(nsIAutoCompleteSearchDescriptor::SEARCH_TYPE_DELAYED);
+
+ // All the searches have been started, just finish.
+ AfterSearches();
+ return NS_OK;
+ }
+ }
+
+ MOZ_ASSERT(timeout > 0, "Trying to delay searches with a 0 timeout!");
+
+ // Now start the delayed searches.
+ nsresult rv;
+ mTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
+ if (NS_FAILED(rv))
+ return rv;
+ rv = mTimer->InitWithCallback(this, timeout, nsITimer::TYPE_ONE_SHOT);
+ if (NS_FAILED(rv))
+ mTimer = nullptr;
+
+ return rv;
+}
+
+nsresult
+nsAutoCompleteController::ClearSearchTimer()
+{
+ if (mTimer) {
+ mTimer->Cancel();
+ mTimer = nullptr;
+ }
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::EnterMatch(bool aIsPopupSelection,
+ nsIDOMEvent *aEvent)
+{
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+ nsCOMPtr<nsIAutoCompletePopup> popup;
+ input->GetPopup(getter_AddRefs(popup));
+ NS_ENSURE_TRUE(popup != nullptr, NS_ERROR_FAILURE);
+
+ bool forceComplete;
+ input->GetForceComplete(&forceComplete);
+
+ // Ask the popup if it wants to enter a special value into the textbox
+ nsAutoString value;
+ popup->GetOverrideValue(value);
+ if (value.IsEmpty()) {
+ bool shouldComplete;
+ input->GetCompleteDefaultIndex(&shouldComplete);
+ bool completeSelection;
+ input->GetCompleteSelectedIndex(&completeSelection);
+
+ int32_t selectedIndex;
+ popup->GetSelectedIndex(&selectedIndex);
+ if (selectedIndex >= 0) {
+ nsAutoString inputValue;
+ input->GetTextValue(inputValue);
+ if (aIsPopupSelection || !completeSelection) {
+ // We need to fill-in the value if:
+ // * completeselectedindex is false
+ // * A row in the popup was confirmed
+ //
+ // TODO: This is not totally correct, cause it will also confirm
+ // a result selected with a simple mouseover, that could also have
+ // happened accidentally, maybe touching a touchpad.
+ // The reason is that autocomplete.xml sets selectedIndex on mousemove
+ // making impossible, in the !completeSelection case, to distinguish if
+ // the user wanted to confirm autoFill or the popup entry.
+ // The solution may be to change autocomplete.xml to set selectedIndex
+ // only on popupClick, but that requires changing the selection behavior.
+ GetResultValueAt(selectedIndex, true, value);
+ } else if (mDefaultIndexCompleted &&
+ inputValue.Equals(mPlaceholderCompletionString,
+ nsCaseInsensitiveStringComparator())) {
+ // We also need to fill-in the value if the default index completion was
+ // confirmed, though we cannot use the selectedIndex cause the selection
+ // may have been changed by the mouse in the meanwhile.
+ GetFinalDefaultCompleteValue(value);
+ } else if (mCompletedSelectionIndex != -1) {
+ // If completeselectedindex is true, and EnterMatch was not invoked by
+ // mouse-clicking a match (for example the user pressed Enter),
+ // don't fill in the value as it will have already been filled in as
+ // needed, unless the selected match has a final complete value that
+ // differs from the user-facing value.
+ nsAutoString finalValue;
+ GetResultValueAt(mCompletedSelectionIndex, true, finalValue);
+ if (!inputValue.Equals(finalValue)) {
+ value = finalValue;
+ }
+ // Note that if the user opens the popup, mouses over entries without
+ // ever selecting one with the keyboard, and then hits enter, none of
+ // the above cases will be hit, since mouseover doesn't activate
+ // completeselectedindex and thus mCompletedSelectionIndex would be
+ // -1.
+ }
+ } else if (shouldComplete) {
+ // We usually try to preserve the casing of what user has typed, but
+ // if he wants to autocomplete, we will replace the value with the
+ // actual autocomplete result.
+ // The user wants explicitely to use that result, so this ensures
+ // association of the result with the autocompleted text.
+ nsAutoString defaultIndexValue;
+ if (NS_SUCCEEDED(GetFinalDefaultCompleteValue(defaultIndexValue)))
+ value = defaultIndexValue;
+ }
+
+ if (forceComplete && value.IsEmpty() && shouldComplete) {
+ // See if inputValue is one of the autocomplete results. It can be an
+ // identical value, or if it matched the middle of a result it can be
+ // something like "bar >> foobar" (user entered bar and foobar is
+ // the result value).
+ // If the current search matches one of the autocomplete results, we
+ // should use that result, and not overwrite it with the default value.
+ // It's indeed possible EnterMatch gets called a second time (for example
+ // by the blur handler) and it should not overwrite the current match.
+ nsAutoString inputValue;
+ input->GetTextValue(inputValue);
+ nsAutoString suggestedValue;
+ int32_t pos = inputValue.Find(" >> ");
+ if (pos > 0) {
+ inputValue.Right(suggestedValue, inputValue.Length() - pos - 4);
+ } else {
+ suggestedValue = inputValue;
+ }
+
+ for (uint32_t i = 0; i < mResults.Length(); ++i) {
+ nsIAutoCompleteResult *result = mResults[i];
+ if (result) {
+ uint32_t matchCount = 0;
+ result->GetMatchCount(&matchCount);
+ for (uint32_t j = 0; j < matchCount; ++j) {
+ nsAutoString matchValue;
+ result->GetValueAt(j, matchValue);
+ if (suggestedValue.Equals(matchValue, nsCaseInsensitiveStringComparator())) {
+ nsAutoString finalMatchValue;
+ result->GetFinalCompleteValueAt(j, finalMatchValue);
+ value = finalMatchValue;
+ break;
+ }
+ }
+ }
+ }
+ // The value should have been set at this point. If not, then it's not
+ // a value that should be autocompleted.
+ }
+ else if (forceComplete && value.IsEmpty() && completeSelection) {
+ // Since nothing was selected, and forceComplete is specified, that means
+ // we have to find the first default match and enter it instead.
+ for (uint32_t i = 0; i < mResults.Length(); ++i) {
+ nsIAutoCompleteResult *result = mResults[i];
+ if (result) {
+ int32_t defaultIndex;
+ result->GetDefaultIndex(&defaultIndex);
+ if (defaultIndex >= 0) {
+ result->GetFinalCompleteValueAt(defaultIndex, value);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ nsCOMPtr<nsIObserverService> obsSvc =
+ mozilla::services::GetObserverService();
+ NS_ENSURE_STATE(obsSvc);
+ obsSvc->NotifyObservers(input, "autocomplete-will-enter-text", nullptr);
+
+ if (!value.IsEmpty()) {
+ SetTextValue(input, value, nsIAutoCompleteInput::TEXTVALUE_REASON_ENTERMATCH);
+ input->SelectTextRange(value.Length(), value.Length());
+ mSearchString = value;
+ }
+
+ obsSvc->NotifyObservers(input, "autocomplete-did-enter-text", nullptr);
+ ClosePopup();
+
+ bool cancel;
+ input->OnTextEntered(aEvent, &cancel);
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::RevertTextValue()
+{
+ // StopSearch() can call PostSearchCleanup() which might result
+ // in a blur event, which could null out mInput, so we need to check it
+ // again. See bug #408463 for more details
+ if (!mInput)
+ return NS_OK;
+
+ nsAutoString oldValue(mSearchString);
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+
+ bool cancel = false;
+ input->OnTextReverted(&cancel);
+
+ if (!cancel) {
+ nsCOMPtr<nsIObserverService> obsSvc =
+ mozilla::services::GetObserverService();
+ NS_ENSURE_STATE(obsSvc);
+ obsSvc->NotifyObservers(input, "autocomplete-will-revert-text", nullptr);
+
+ nsAutoString inputValue;
+ input->GetTextValue(inputValue);
+ // Don't change the value if it is the same to prevent sending useless events.
+ // NOTE: how can |RevertTextValue| be called with inputValue != oldValue?
+ if (!oldValue.Equals(inputValue)) {
+ SetTextValue(input, oldValue, nsIAutoCompleteInput::TEXTVALUE_REASON_REVERT);
+ }
+
+ obsSvc->NotifyObservers(input, "autocomplete-did-revert-text", nullptr);
+ }
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::ProcessResult(int32_t aSearchIndex, nsIAutoCompleteResult *aResult)
+{
+ NS_ENSURE_STATE(mInput);
+ MOZ_ASSERT(aResult, "ProcessResult should always receive a result");
+ NS_ENSURE_ARG(aResult);
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+
+ uint16_t searchResult = 0;
+ aResult->GetSearchResult(&searchResult);
+
+ // The following code supports incremental updating results in 2 ways:
+ // * The search may reuse the same result, just by adding entries to it.
+ // * The search may send a new result every time. In this case we merge
+ // the results and proceed on the same code path as before.
+ // This way both mSearches and mResults can be indexed by the search index,
+ // cause we'll always have only one result per search.
+ if (mResults.IndexOf(aResult) == -1) {
+ nsIAutoCompleteResult* oldResult = mResults.SafeObjectAt(aSearchIndex);
+ if (oldResult) {
+ MOZ_ASSERT(false, "Passing new matches to OnSearchResult with a new "
+ "nsIAutoCompleteResult every time is deprecated, please "
+ "update the same result until the search is done");
+ // Build a new nsIAutocompleteSimpleResult and merge results into it.
+ RefPtr<nsAutoCompleteSimpleResult> mergedResult =
+ new nsAutoCompleteSimpleResult();
+ mergedResult->AppendResult(oldResult);
+ mergedResult->AppendResult(aResult);
+ mResults.ReplaceObjectAt(mergedResult, aSearchIndex);
+ } else {
+ // This inserts and grows the array if needed.
+ mResults.ReplaceObjectAt(aResult, aSearchIndex);
+ }
+ }
+ // When found the result should have the same index as the search.
+ MOZ_ASSERT_IF(mResults.IndexOf(aResult) != -1,
+ mResults.IndexOf(aResult) == aSearchIndex);
+ MOZ_ASSERT(mResults.Count() >= aSearchIndex + 1,
+ "aSearchIndex should always be valid for mResults");
+
+ uint32_t oldRowCount = mRowCount;
+ // If the search failed, increase the match count to include the error
+ // description.
+ if (searchResult == nsIAutoCompleteResult::RESULT_FAILURE) {
+ nsAutoString error;
+ aResult->GetErrorDescription(error);
+ if (!error.IsEmpty()) {
+ ++mRowCount;
+ if (mTree) {
+ mTree->RowCountChanged(oldRowCount, 1);
+ }
+ }
+ } else if (searchResult == nsIAutoCompleteResult::RESULT_SUCCESS ||
+ searchResult == nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING) {
+ // Increase the match count for all matches in this result.
+ uint32_t totalMatchCount = 0;
+ for (uint32_t i = 0; i < mResults.Length(); i++) {
+ nsIAutoCompleteResult* result = mResults.SafeObjectAt(i);
+ if (result) {
+ uint32_t matchCount = 0;
+ result->GetMatchCount(&matchCount);
+ totalMatchCount += matchCount;
+ }
+ }
+ uint32_t delta = totalMatchCount - oldRowCount;
+
+ mRowCount += delta;
+ if (mTree) {
+ mTree->RowCountChanged(oldRowCount, delta);
+ }
+ }
+
+ // Try to autocomplete the default index for this search.
+ // Do this before invalidating so the binding knows about it.
+ CompleteDefaultIndex(aSearchIndex);
+
+ // Refresh the popup view to display the new search results
+ nsCOMPtr<nsIAutoCompletePopup> popup;
+ input->GetPopup(getter_AddRefs(popup));
+ NS_ENSURE_TRUE(popup != nullptr, NS_ERROR_FAILURE);
+ popup->Invalidate(nsIAutoCompletePopup::INVALIDATE_REASON_NEW_RESULT);
+
+ uint32_t minResults;
+ input->GetMinResultsForPopup(&minResults);
+
+ // Make sure the popup is open, if necessary, since we now have at least one
+ // search result ready to display. Don't force the popup closed if we might
+ // get results in the future to avoid unnecessarily canceling searches.
+ if (mRowCount || !minResults) {
+ OpenPopup();
+ } else if (mSearchesOngoing == 0) {
+ ClosePopup();
+ }
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::PostSearchCleanup()
+{
+ NS_ENSURE_STATE(mInput);
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+
+ uint32_t minResults;
+ input->GetMinResultsForPopup(&minResults);
+
+ if (mRowCount || minResults == 0) {
+ OpenPopup();
+ if (mRowCount)
+ mSearchStatus = nsIAutoCompleteController::STATUS_COMPLETE_MATCH;
+ else
+ mSearchStatus = nsIAutoCompleteController::STATUS_COMPLETE_NO_MATCH;
+ } else {
+ mSearchStatus = nsIAutoCompleteController::STATUS_COMPLETE_NO_MATCH;
+ ClosePopup();
+ }
+
+ // notify the input that the search is complete
+ input->OnSearchComplete();
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::ClearResults()
+{
+ int32_t oldRowCount = mRowCount;
+ mRowCount = 0;
+ mResults.Clear();
+ if (oldRowCount != 0) {
+ if (mTree)
+ mTree->RowCountChanged(0, -oldRowCount);
+ else if (mInput) {
+ nsCOMPtr<nsIAutoCompletePopup> popup;
+ mInput->GetPopup(getter_AddRefs(popup));
+ NS_ENSURE_TRUE(popup != nullptr, NS_ERROR_FAILURE);
+ // if we had a tree, RowCountChanged() would have cleared the selection
+ // when the selected row was removed. But since we don't have a tree,
+ // we need to clear the selection manually.
+ popup->SetSelectedIndex(-1);
+ }
+ }
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::CompleteDefaultIndex(int32_t aResultIndex)
+{
+ if (mDefaultIndexCompleted || mProhibitAutoFill || mSearchString.Length() == 0 || !mInput)
+ return NS_OK;
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+
+ int32_t selectionStart;
+ input->GetSelectionStart(&selectionStart);
+ int32_t selectionEnd;
+ input->GetSelectionEnd(&selectionEnd);
+
+ bool isPlaceholderSelected =
+ selectionEnd == (int32_t)mPlaceholderCompletionString.Length() &&
+ selectionStart == (int32_t)mSearchString.Length() &&
+ StringBeginsWith(mPlaceholderCompletionString,
+ mSearchString, nsCaseInsensitiveStringComparator());
+
+ // Don't try to automatically complete to the first result if there's already
+ // a selection or the cursor isn't at the end of the input. In case the
+ // selection is from the current placeholder completion value, then still
+ // automatically complete.
+ if (!isPlaceholderSelected && (selectionEnd != selectionStart ||
+ selectionEnd != (int32_t)mSearchString.Length()))
+ return NS_OK;
+
+ bool shouldComplete;
+ input->GetCompleteDefaultIndex(&shouldComplete);
+ if (!shouldComplete)
+ return NS_OK;
+
+ nsAutoString resultValue;
+ if (NS_SUCCEEDED(GetDefaultCompleteValue(aResultIndex, true, resultValue))) {
+ CompleteValue(resultValue);
+
+ mDefaultIndexCompleted = true;
+ }
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::GetDefaultCompleteResult(int32_t aResultIndex,
+ nsIAutoCompleteResult** _result,
+ int32_t* _defaultIndex)
+{
+ *_defaultIndex = -1;
+ int32_t resultIndex = aResultIndex;
+
+ // If a result index was not provided, find the first defaultIndex result.
+ for (int32_t i = 0; resultIndex < 0 && i < mResults.Count(); ++i) {
+ nsIAutoCompleteResult *result = mResults.SafeObjectAt(i);
+ if (result &&
+ NS_SUCCEEDED(result->GetDefaultIndex(_defaultIndex)) &&
+ *_defaultIndex >= 0) {
+ resultIndex = i;
+ }
+ }
+ if (resultIndex < 0) {
+ return NS_ERROR_FAILURE;
+ }
+
+ *_result = mResults.SafeObjectAt(resultIndex);
+ NS_ENSURE_TRUE(*_result, NS_ERROR_FAILURE);
+
+ if (*_defaultIndex < 0) {
+ // The search must explicitly provide a default index in order
+ // for us to be able to complete.
+ (*_result)->GetDefaultIndex(_defaultIndex);
+ }
+
+ if (*_defaultIndex < 0) {
+ // We were given a result index, but that result doesn't want to
+ // be autocompleted.
+ return NS_ERROR_FAILURE;
+ }
+
+ // If the result wrongly notifies a RESULT_SUCCESS with no matches, or
+ // provides a defaultIndex greater than its matchCount, avoid trying to
+ // complete to an empty value.
+ uint32_t matchCount = 0;
+ (*_result)->GetMatchCount(&matchCount);
+ // Here defaultIndex is surely non-negative, so can be cast to unsigned.
+ if ((uint32_t)(*_defaultIndex) >= matchCount) {
+ return NS_ERROR_FAILURE;
+ }
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::GetDefaultCompleteValue(int32_t aResultIndex,
+ bool aPreserveCasing,
+ nsAString &_retval)
+{
+ nsIAutoCompleteResult *result;
+ int32_t defaultIndex = -1;
+ nsresult rv = GetDefaultCompleteResult(aResultIndex, &result, &defaultIndex);
+ if (NS_FAILED(rv)) return rv;
+
+ nsAutoString resultValue;
+ result->GetValueAt(defaultIndex, resultValue);
+ if (aPreserveCasing &&
+ StringBeginsWith(resultValue, mSearchString,
+ nsCaseInsensitiveStringComparator())) {
+ // We try to preserve user casing, otherwise we would end up changing
+ // the case of what he typed, if we have a result with a different casing.
+ // For example if we have result "Test", and user starts writing "tuna",
+ // after digiting t, we would convert it to T trying to autocomplete "Test".
+ // We will still complete to cased "Test" if the user explicitely choose
+ // that result, by either selecting it in the results popup, or with
+ // keyboard navigation or if autocompleting in the middle.
+ nsAutoString casedResultValue;
+ casedResultValue.Assign(mSearchString);
+ // Use what the user has typed so far.
+ casedResultValue.Append(Substring(resultValue,
+ mSearchString.Length(),
+ resultValue.Length()));
+ _retval = casedResultValue;
+ }
+ else
+ _retval = resultValue;
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::GetFinalDefaultCompleteValue(nsAString &_retval)
+{
+ MOZ_ASSERT(mInput, "Must have a valid input");
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+ nsIAutoCompleteResult *result;
+ int32_t defaultIndex = -1;
+ nsresult rv = GetDefaultCompleteResult(-1, &result, &defaultIndex);
+ if (NS_FAILED(rv)) return rv;
+
+ result->GetValueAt(defaultIndex, _retval);
+ nsAutoString inputValue;
+ input->GetTextValue(inputValue);
+ if (!_retval.Equals(inputValue, nsCaseInsensitiveStringComparator())) {
+ return NS_ERROR_FAILURE;
+ }
+
+ nsAutoString finalCompleteValue;
+ rv = result->GetFinalCompleteValueAt(defaultIndex, finalCompleteValue);
+ if (NS_SUCCEEDED(rv)) {
+ _retval = finalCompleteValue;
+ }
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::CompleteValue(nsString &aValue)
+/* mInput contains mSearchString, which we want to autocomplete to aValue. If
+ * selectDifference is true, select the remaining portion of aValue not
+ * contained in mSearchString. */
+{
+ MOZ_ASSERT(mInput, "Must have a valid input");
+
+ nsCOMPtr<nsIAutoCompleteInput> input(mInput);
+ const int32_t mSearchStringLength = mSearchString.Length();
+ int32_t endSelect = aValue.Length(); // By default, select all of aValue.
+
+ if (aValue.IsEmpty() ||
+ StringBeginsWith(aValue, mSearchString,
+ nsCaseInsensitiveStringComparator())) {
+ // aValue is empty (we were asked to clear mInput), or mSearchString
+ // matches the beginning of aValue. In either case we can simply
+ // autocomplete to aValue.
+ mPlaceholderCompletionString = aValue;
+ SetTextValue(input, aValue,
+ nsIAutoCompleteInput::TEXTVALUE_REASON_COMPLETEDEFAULT);
+ } else {
+ nsresult rv;
+ nsCOMPtr<nsIIOService> ios = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
+ NS_ENSURE_SUCCESS(rv, rv);
+ nsAutoCString scheme;
+ if (NS_SUCCEEDED(ios->ExtractScheme(NS_ConvertUTF16toUTF8(aValue), scheme))) {
+ // Trying to autocomplete a URI from somewhere other than the beginning.
+ // Only succeed if the missing portion is "http://"; otherwise do not
+ // autocomplete. This prevents us from "helpfully" autocompleting to a
+ // URI that isn't equivalent to what the user expected.
+ const int32_t findIndex = 7; // length of "http://"
+
+ if ((endSelect < findIndex + mSearchStringLength) ||
+ !scheme.LowerCaseEqualsLiteral("http") ||
+ !Substring(aValue, findIndex, mSearchStringLength).Equals(
+ mSearchString, nsCaseInsensitiveStringComparator())) {
+ return NS_OK;
+ }
+
+ mPlaceholderCompletionString = mSearchString +
+ Substring(aValue, mSearchStringLength + findIndex, endSelect);
+ SetTextValue(input, mPlaceholderCompletionString,
+ nsIAutoCompleteInput::TEXTVALUE_REASON_COMPLETEDEFAULT);
+
+ endSelect -= findIndex; // We're skipping this many characters of aValue.
+ } else {
+ // Autocompleting something other than a URI from the middle.
+ // Use the format "searchstring >> full string" to indicate to the user
+ // what we are going to replace their search string with.
+ SetTextValue(input, mSearchString + NS_LITERAL_STRING(" >> ") + aValue,
+ nsIAutoCompleteInput::TEXTVALUE_REASON_COMPLETEDEFAULT);
+
+ endSelect = mSearchString.Length() + 4 + aValue.Length();
+
+ // Reset the last search completion.
+ mPlaceholderCompletionString.Truncate();
+ }
+ }
+
+ input->SelectTextRange(mSearchStringLength, endSelect);
+
+ return NS_OK;
+}
+
+nsresult
+nsAutoCompleteController::GetResultLabelAt(int32_t aIndex, nsAString & _retval)
+{
+ return GetResultValueLabelAt(aIndex, false, false, _retval);
+}
+
+nsresult
+nsAutoCompleteController::GetResultValueAt(int32_t aIndex, bool aGetFinalValue,
+ nsAString & _retval)
+{
+ return GetResultValueLabelAt(aIndex, aGetFinalValue, true, _retval);
+}
+
+nsresult
+nsAutoCompleteController::GetResultValueLabelAt(int32_t aIndex,
+ bool aGetFinalValue,
+ bool aGetValue,
+ nsAString & _retval)
+{
+ NS_ENSURE_TRUE(aIndex >= 0 && (uint32_t) aIndex < mRowCount, NS_ERROR_ILLEGAL_VALUE);
+
+ int32_t rowIndex;
+ nsIAutoCompleteResult *result;
+ nsresult rv = GetResultAt(aIndex, &result, &rowIndex);
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ uint16_t searchResult;
+ result->GetSearchResult(&searchResult);
+
+ if (searchResult == nsIAutoCompleteResult::RESULT_FAILURE) {
+ if (aGetValue)
+ return NS_ERROR_FAILURE;
+ result->GetErrorDescription(_retval);
+ } else if (searchResult == nsIAutoCompleteResult::RESULT_SUCCESS ||
+ searchResult == nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING) {
+ if (aGetFinalValue) {
+ // Some implementations may miss finalCompleteValue, try to be backwards
+ // compatible.
+ if (NS_FAILED(result->GetFinalCompleteValueAt(rowIndex, _retval))) {
+ result->GetValueAt(rowIndex, _retval);
+ }
+ } else if (aGetValue) {
+ result->GetValueAt(rowIndex, _retval);
+ } else {
+ result->GetLabelAt(rowIndex, _retval);
+ }
+ }
+
+ return NS_OK;
+}
+
+/**
+ * Given the index of a row in the autocomplete popup, find the
+ * corresponding nsIAutoCompleteSearch index, and sub-index into
+ * the search's results list.
+ */
+nsresult
+nsAutoCompleteController::RowIndexToSearch(int32_t aRowIndex, int32_t *aSearchIndex, int32_t *aItemIndex)
+{
+ *aSearchIndex = -1;
+ *aItemIndex = -1;
+
+ uint32_t index = 0;
+
+ // Move index through the results of each registered nsIAutoCompleteSearch
+ // until we find the given row
+ for (uint32_t i = 0; i < mSearches.Length(); ++i) {
+ nsIAutoCompleteResult *result = mResults.SafeObjectAt(i);
+ if (!result)
+ continue;
+
+ uint32_t rowCount = 0;
+
+ uint16_t searchResult;
+ result->GetSearchResult(&searchResult);
+
+ // Find out how many results were provided by the
+ // current nsIAutoCompleteSearch.
+ if (searchResult == nsIAutoCompleteResult::RESULT_SUCCESS ||
+ searchResult == nsIAutoCompleteResult::RESULT_SUCCESS_ONGOING) {
+ result->GetMatchCount(&rowCount);
+ }
+
+ // If the given row index is within the results range
+ // of the current nsIAutoCompleteSearch then return the
+ // search index and sub-index into the results array
+ if ((rowCount != 0) && (index + rowCount-1 >= (uint32_t) aRowIndex)) {
+ *aSearchIndex = i;
+ *aItemIndex = aRowIndex - index;
+ return NS_OK;
+ }
+
+ // Advance the popup table index cursor past the
+ // results of the current search.
+ index += rowCount;
+ }
+
+ return NS_OK;
+}
+
+NS_GENERIC_FACTORY_CONSTRUCTOR(nsAutoCompleteController)
+NS_GENERIC_FACTORY_CONSTRUCTOR(nsAutoCompleteSimpleResult)
+
+NS_DEFINE_NAMED_CID(NS_AUTOCOMPLETECONTROLLER_CID);
+NS_DEFINE_NAMED_CID(NS_AUTOCOMPLETESIMPLERESULT_CID);
+
+static const mozilla::Module::CIDEntry kAutoCompleteCIDs[] = {
+ { &kNS_AUTOCOMPLETECONTROLLER_CID, false, nullptr, nsAutoCompleteControllerConstructor },
+ { &kNS_AUTOCOMPLETESIMPLERESULT_CID, false, nullptr, nsAutoCompleteSimpleResultConstructor },
+ { nullptr }
+};
+
+static const mozilla::Module::ContractIDEntry kAutoCompleteContracts[] = {
+ { NS_AUTOCOMPLETECONTROLLER_CONTRACTID, &kNS_AUTOCOMPLETECONTROLLER_CID },
+ { NS_AUTOCOMPLETESIMPLERESULT_CONTRACTID, &kNS_AUTOCOMPLETESIMPLERESULT_CID },
+ { nullptr }
+};
+
+static const mozilla::Module kAutoCompleteModule = {
+ mozilla::Module::kVersion,
+ kAutoCompleteCIDs,
+ kAutoCompleteContracts
+};
+
+NSMODULE_DEFN(tkAutoCompleteModule) = &kAutoCompleteModule;
diff --git a/toolkit/components/autocomplete/nsAutoCompleteController.h b/toolkit/components/autocomplete/nsAutoCompleteController.h
new file mode 100644
index 000000000..62aa980f6
--- /dev/null
+++ b/toolkit/components/autocomplete/nsAutoCompleteController.h
@@ -0,0 +1,176 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __nsAutoCompleteController__
+#define __nsAutoCompleteController__
+
+#include "nsIAutoCompleteController.h"
+
+#include "nsCOMPtr.h"
+#include "nsIAutoCompleteInput.h"
+#include "nsIAutoCompletePopup.h"
+#include "nsIAutoCompleteResult.h"
+#include "nsIAutoCompleteSearch.h"
+#include "nsString.h"
+#include "nsITreeView.h"
+#include "nsITreeSelection.h"
+#include "nsITimer.h"
+#include "nsTArray.h"
+#include "nsCOMArray.h"
+#include "nsCycleCollectionParticipant.h"
+
+class nsAutoCompleteController final : public nsIAutoCompleteController,
+ public nsIAutoCompleteObserver,
+ public nsITimerCallback,
+ public nsITreeView
+{
+public:
+ NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+ NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsAutoCompleteController,
+ nsIAutoCompleteController)
+ NS_DECL_NSIAUTOCOMPLETECONTROLLER
+ NS_DECL_NSIAUTOCOMPLETEOBSERVER
+ NS_DECL_NSITREEVIEW
+ NS_DECL_NSITIMERCALLBACK
+
+ nsAutoCompleteController();
+
+protected:
+ virtual ~nsAutoCompleteController();
+
+ nsresult OpenPopup();
+ nsresult ClosePopup();
+
+ nsresult StartSearch(uint16_t aSearchType);
+
+ nsresult BeforeSearches();
+ nsresult StartSearches();
+ void AfterSearches();
+ nsresult ClearSearchTimer();
+ void MaybeCompletePlaceholder();
+
+ void HandleSearchResult(nsIAutoCompleteSearch *aSearch,
+ nsIAutoCompleteResult *aResult);
+ nsresult ProcessResult(int32_t aSearchIndex, nsIAutoCompleteResult *aResult);
+ nsresult PostSearchCleanup();
+
+ nsresult EnterMatch(bool aIsPopupSelection,
+ nsIDOMEvent *aEvent);
+ nsresult RevertTextValue();
+
+ nsresult CompleteDefaultIndex(int32_t aResultIndex);
+ nsresult CompleteValue(nsString &aValue);
+
+ nsresult GetResultAt(int32_t aIndex, nsIAutoCompleteResult** aResult,
+ int32_t* aRowIndex);
+ nsresult GetResultValueAt(int32_t aIndex, bool aGetFinalValue,
+ nsAString & _retval);
+ nsresult GetResultLabelAt(int32_t aIndex, nsAString & _retval);
+private:
+ nsresult GetResultValueLabelAt(int32_t aIndex, bool aGetFinalValue,
+ bool aGetValue, nsAString & _retval);
+protected:
+
+ /**
+ * Gets and validates the defaultComplete result and the relative
+ * defaultIndex value.
+ *
+ * @param aResultIndex
+ * Index of the defaultComplete result to be used. Pass -1 to search
+ * for the first result providing a valid defaultIndex.
+ * @param _result
+ * The found result.
+ * @param _defaultIndex
+ * The defaultIndex relative to _result.
+ */
+ nsresult GetDefaultCompleteResult(int32_t aResultIndex,
+ nsIAutoCompleteResult** _result,
+ int32_t* _defaultIndex);
+
+ /**
+ * Gets the defaultComplete value to be suggested to the user.
+ *
+ * @param aResultIndex
+ * Index of the defaultComplete result to be used.
+ * @param aPreserveCasing
+ * Whether user casing should be preserved.
+ * @param _retval
+ * The value to be completed.
+ */
+ nsresult GetDefaultCompleteValue(int32_t aResultIndex, bool aPreserveCasing,
+ nsAString &_retval);
+
+ /**
+ * Gets the defaultComplete value to be used when the user confirms the
+ * current match.
+ * The value is returned only if it case-insensitively matches the current
+ * input text, otherwise the method returns NS_ERROR_FAILURE.
+ * This happens because we don't want to replace text if the user backspaces
+ * just before Enter.
+ *
+ * @param _retval
+ * The value to be completed.
+ */
+ nsresult GetFinalDefaultCompleteValue(nsAString &_retval);
+
+ nsresult ClearResults();
+
+ nsresult RowIndexToSearch(int32_t aRowIndex,
+ int32_t *aSearchIndex, int32_t *aItemIndex);
+
+ // members //////////////////////////////////////////
+
+ nsCOMPtr<nsIAutoCompleteInput> mInput;
+
+ nsCOMArray<nsIAutoCompleteSearch> mSearches;
+ // This is used as a sparse array, always use SafeObjectAt to access it.
+ nsCOMArray<nsIAutoCompleteResult> mResults;
+ // Temporarily keeps the results alive while invoking startSearch() for each
+ // search. This is needed to allow the searches to reuse the previous result,
+ // since otherwise the first search clears mResults.
+ nsCOMArray<nsIAutoCompleteResult> mResultCache;
+
+ nsCOMPtr<nsITimer> mTimer;
+ nsCOMPtr<nsITreeSelection> mSelection;
+ nsCOMPtr<nsITreeBoxObject> mTree;
+
+ nsString mSearchString;
+ nsString mPlaceholderCompletionString;
+ bool mDefaultIndexCompleted;
+ bool mPopupClosedByCompositionStart;
+
+ // Whether autofill is allowed for the next search. May be retrieved by the
+ // search through the "prohibit-autofill" searchParam.
+ bool mProhibitAutoFill;
+
+ // Indicates whether the user cleared the autofilled part, returning to the
+ // originally entered search string.
+ bool mUserClearedAutoFill;
+
+ // Indicates whether clearing the autofilled string should issue a new search.
+ bool mClearingAutoFillSearchesAgain;
+
+ enum CompositionState {
+ eCompositionState_None,
+ eCompositionState_Composing,
+ eCompositionState_Committing
+ };
+ CompositionState mCompositionState;
+ uint16_t mSearchStatus;
+ uint32_t mRowCount;
+ uint32_t mSearchesOngoing;
+ uint32_t mSearchesFailed;
+ bool mFirstSearchResult;
+ uint32_t mImmediateSearchesCount;
+ // The index of the match on the popup that was selected using the keyboard,
+ // if the completeselectedindex attribute is set.
+ // This is used to distinguish that selection (which would have been put in
+ // the input on being selected) from a moused-over selectedIndex value. This
+ // distinction is used to prevent mouse moves from inadvertently changing
+ // what happens once the user hits Enter on the keyboard.
+ // See bug 1043584 for more details.
+ int32_t mCompletedSelectionIndex;
+};
+
+#endif /* __nsAutoCompleteController__ */
diff --git a/toolkit/components/autocomplete/nsAutoCompleteSimpleResult.cpp b/toolkit/components/autocomplete/nsAutoCompleteSimpleResult.cpp
new file mode 100644
index 000000000..9fd2c0022
--- /dev/null
+++ b/toolkit/components/autocomplete/nsAutoCompleteSimpleResult.cpp
@@ -0,0 +1,292 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsAutoCompleteSimpleResult.h"
+
+#define CHECK_MATCH_INDEX(_index, _insert) \
+ if (_index < 0 || \
+ static_cast<MatchesArray::size_type>(_index) > mMatches.Length() || \
+ (!_insert && static_cast<MatchesArray::size_type>(_index) == mMatches.Length())) { \
+ MOZ_ASSERT(false, "Trying to use an invalid index on mMatches"); \
+ return NS_ERROR_ILLEGAL_VALUE; \
+ } \
+
+NS_IMPL_ISUPPORTS(nsAutoCompleteSimpleResult,
+ nsIAutoCompleteResult,
+ nsIAutoCompleteSimpleResult)
+
+struct AutoCompleteSimpleResultMatch
+{
+ AutoCompleteSimpleResultMatch(const nsAString& aValue,
+ const nsAString& aComment,
+ const nsAString& aImage,
+ const nsAString& aStyle,
+ const nsAString& aFinalCompleteValue,
+ const nsAString& aLabel)
+ : mValue(aValue)
+ , mComment(aComment)
+ , mImage(aImage)
+ , mStyle(aStyle)
+ , mFinalCompleteValue(aFinalCompleteValue)
+ , mLabel(aLabel)
+ {
+ }
+
+ nsString mValue;
+ nsString mComment;
+ nsString mImage;
+ nsString mStyle;
+ nsString mFinalCompleteValue;
+ nsString mLabel;
+};
+
+nsAutoCompleteSimpleResult::nsAutoCompleteSimpleResult() :
+ mDefaultIndex(-1),
+ mSearchResult(RESULT_NOMATCH)
+{
+}
+
+nsresult
+nsAutoCompleteSimpleResult::AppendResult(nsIAutoCompleteResult* aResult)
+{
+ nsAutoString searchString;
+ nsresult rv = aResult->GetSearchString(searchString);
+ NS_ENSURE_SUCCESS(rv, rv);
+ mSearchString = searchString;
+
+ uint16_t searchResult;
+ rv = aResult->GetSearchResult(&searchResult);
+ NS_ENSURE_SUCCESS(rv, rv);
+ mSearchResult = searchResult;
+
+ nsAutoString errorDescription;
+ if (NS_SUCCEEDED(aResult->GetErrorDescription(errorDescription)) &&
+ !errorDescription.IsEmpty()) {
+ mErrorDescription = errorDescription;
+ }
+
+ int32_t defaultIndex = -1;
+ if (NS_SUCCEEDED(aResult->GetDefaultIndex(&defaultIndex)) &&
+ defaultIndex >= 0) {
+ mDefaultIndex = defaultIndex;
+ }
+
+ nsCOMPtr<nsIAutoCompleteSimpleResult> simpleResult =
+ do_QueryInterface(aResult);
+ if (simpleResult) {
+ nsCOMPtr<nsIAutoCompleteSimpleResultListener> listener;
+ if (NS_SUCCEEDED(simpleResult->GetListener(getter_AddRefs(listener))) &&
+ listener) {
+ listener.swap(mListener);
+ }
+ }
+
+ // Copy matches.
+ uint32_t matchCount = 0;
+ rv = aResult->GetMatchCount(&matchCount);
+ NS_ENSURE_SUCCESS(rv, rv);
+ for (size_t i = 0; i < matchCount; ++i) {
+ nsAutoString value, comment, image, style, finalCompleteValue, label;
+
+ rv = aResult->GetValueAt(i, value);
+ NS_ENSURE_SUCCESS(rv, rv);
+ rv = aResult->GetCommentAt(i, comment);
+ NS_ENSURE_SUCCESS(rv, rv);
+ rv = aResult->GetImageAt(i, image);
+ NS_ENSURE_SUCCESS(rv, rv);
+ rv = aResult->GetStyleAt(i, style);
+ NS_ENSURE_SUCCESS(rv, rv);
+ rv = aResult->GetFinalCompleteValueAt(i, finalCompleteValue);
+ NS_ENSURE_SUCCESS(rv, rv);
+ rv = aResult->GetLabelAt(i, label);
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = AppendMatch(value, comment, image, style, finalCompleteValue, label);
+ NS_ENSURE_SUCCESS(rv, rv);
+ }
+
+ return NS_OK;
+}
+
+// searchString
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetSearchString(nsAString &aSearchString)
+{
+ aSearchString = mSearchString;
+ return NS_OK;
+}
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::SetSearchString(const nsAString &aSearchString)
+{
+ mSearchString.Assign(aSearchString);
+ return NS_OK;
+}
+
+// searchResult
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetSearchResult(uint16_t *aSearchResult)
+{
+ *aSearchResult = mSearchResult;
+ return NS_OK;
+}
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::SetSearchResult(uint16_t aSearchResult)
+{
+ mSearchResult = aSearchResult;
+ return NS_OK;
+}
+
+// defaultIndex
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetDefaultIndex(int32_t *aDefaultIndex)
+{
+ *aDefaultIndex = mDefaultIndex;
+ return NS_OK;
+}
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::SetDefaultIndex(int32_t aDefaultIndex)
+{
+ mDefaultIndex = aDefaultIndex;
+ return NS_OK;
+}
+
+// errorDescription
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetErrorDescription(nsAString & aErrorDescription)
+{
+ aErrorDescription = mErrorDescription;
+ return NS_OK;
+}
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::SetErrorDescription(
+ const nsAString &aErrorDescription)
+{
+ mErrorDescription.Assign(aErrorDescription);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::InsertMatchAt(int32_t aIndex,
+ const nsAString& aValue,
+ const nsAString& aComment,
+ const nsAString& aImage,
+ const nsAString& aStyle,
+ const nsAString& aFinalCompleteValue,
+ const nsAString& aLabel)
+{
+ CHECK_MATCH_INDEX(aIndex, true);
+
+ AutoCompleteSimpleResultMatch match(aValue, aComment, aImage, aStyle, aFinalCompleteValue, aLabel);
+
+ if (!mMatches.InsertElementAt(aIndex, match)) {
+ return NS_ERROR_OUT_OF_MEMORY;
+ }
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::AppendMatch(const nsAString& aValue,
+ const nsAString& aComment,
+ const nsAString& aImage,
+ const nsAString& aStyle,
+ const nsAString& aFinalCompleteValue,
+ const nsAString& aLabel)
+{
+ return InsertMatchAt(mMatches.Length(), aValue, aComment, aImage, aStyle,
+ aFinalCompleteValue, aLabel);
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetMatchCount(uint32_t *aMatchCount)
+{
+ *aMatchCount = mMatches.Length();
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetValueAt(int32_t aIndex, nsAString& _retval)
+{
+ CHECK_MATCH_INDEX(aIndex, false);
+ _retval = mMatches[aIndex].mValue;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetLabelAt(int32_t aIndex, nsAString& _retval)
+{
+ CHECK_MATCH_INDEX(aIndex, false);
+ _retval = mMatches[aIndex].mLabel;
+ if (_retval.IsEmpty()) {
+ _retval = mMatches[aIndex].mValue;
+ }
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetCommentAt(int32_t aIndex, nsAString& _retval)
+{
+ CHECK_MATCH_INDEX(aIndex, false);
+ _retval = mMatches[aIndex].mComment;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetImageAt(int32_t aIndex, nsAString& _retval)
+{
+ CHECK_MATCH_INDEX(aIndex, false);
+ _retval = mMatches[aIndex].mImage;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetStyleAt(int32_t aIndex, nsAString& _retval)
+{
+ CHECK_MATCH_INDEX(aIndex, false);
+ _retval = mMatches[aIndex].mStyle;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetFinalCompleteValueAt(int32_t aIndex,
+ nsAString& _retval)
+{
+ CHECK_MATCH_INDEX(aIndex, false);
+ _retval = mMatches[aIndex].mFinalCompleteValue;
+ if (_retval.IsEmpty()) {
+ _retval = mMatches[aIndex].mValue;
+ }
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::SetListener(nsIAutoCompleteSimpleResultListener* aListener)
+{
+ mListener = aListener;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::GetListener(nsIAutoCompleteSimpleResultListener** aListener)
+{
+ nsCOMPtr<nsIAutoCompleteSimpleResultListener> listener(mListener);
+ listener.forget(aListener);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+nsAutoCompleteSimpleResult::RemoveValueAt(int32_t aRowIndex,
+ bool aRemoveFromDb)
+{
+ CHECK_MATCH_INDEX(aRowIndex, false);
+
+ nsString value = mMatches[aRowIndex].mValue;
+ mMatches.RemoveElementAt(aRowIndex);
+
+ if (mListener) {
+ mListener->OnValueRemoved(this, value, aRemoveFromDb);
+ }
+
+ return NS_OK;
+}
diff --git a/toolkit/components/autocomplete/nsAutoCompleteSimpleResult.h b/toolkit/components/autocomplete/nsAutoCompleteSimpleResult.h
new file mode 100644
index 000000000..28968aa57
--- /dev/null
+++ b/toolkit/components/autocomplete/nsAutoCompleteSimpleResult.h
@@ -0,0 +1,44 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __nsAutoCompleteSimpleResult__
+#define __nsAutoCompleteSimpleResult__
+
+#include "nsIAutoCompleteResult.h"
+#include "nsIAutoCompleteSimpleResult.h"
+
+#include "nsString.h"
+#include "nsCOMPtr.h"
+#include "nsTArray.h"
+#include "mozilla/Attributes.h"
+
+struct AutoCompleteSimpleResultMatch;
+
+class nsAutoCompleteSimpleResult final : public nsIAutoCompleteSimpleResult
+{
+public:
+ nsAutoCompleteSimpleResult();
+
+ NS_DECL_ISUPPORTS
+ NS_DECL_NSIAUTOCOMPLETERESULT
+ NS_DECL_NSIAUTOCOMPLETESIMPLERESULT
+
+ nsresult AppendResult(nsIAutoCompleteResult* aResult);
+
+private:
+ ~nsAutoCompleteSimpleResult() {}
+
+protected:
+ typedef nsTArray<AutoCompleteSimpleResultMatch> MatchesArray;
+ MatchesArray mMatches;
+
+ nsString mSearchString;
+ nsString mErrorDescription;
+ int32_t mDefaultIndex;
+ uint32_t mSearchResult;
+
+ nsCOMPtr<nsIAutoCompleteSimpleResultListener> mListener;
+};
+
+#endif // __nsAutoCompleteSimpleResult__
diff --git a/toolkit/components/autocomplete/nsIAutoCompleteController.idl b/toolkit/components/autocomplete/nsIAutoCompleteController.idl
new file mode 100644
index 000000000..0b68032dc
--- /dev/null
+++ b/toolkit/components/autocomplete/nsIAutoCompleteController.idl
@@ -0,0 +1,173 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+interface nsIAutoCompleteInput;
+interface nsIDOMEvent;
+
+[scriptable, uuid(ff9f8465-204a-47a6-b3c9-0628b3856684)]
+interface nsIAutoCompleteController : nsISupports
+{
+ /*
+ * Possible values for the searchStatus attribute
+ */
+ const unsigned short STATUS_NONE = 1;
+ const unsigned short STATUS_SEARCHING = 2;
+ const unsigned short STATUS_COMPLETE_NO_MATCH = 3;
+ const unsigned short STATUS_COMPLETE_MATCH = 4;
+
+ /*
+ * The input widget that is currently being controlled.
+ */
+ attribute nsIAutoCompleteInput input;
+
+ /*
+ * State which indicates the status of possible ongoing searches
+ */
+ readonly attribute unsigned short searchStatus;
+
+ /*
+ * The number of matches
+ */
+ readonly attribute unsigned long matchCount;
+
+ /*
+ * Start a search on a string, assuming the input property is already set.
+ */
+ void startSearch(in AString searchString);
+
+ /*
+ * Stop all asynchronous searches
+ */
+ void stopSearch();
+
+ /*
+ * Notify the controller that the user has changed text in the textbox.
+ * This includes all means of changing the text value, including typing a
+ * character, backspacing, deleting, pasting, committing composition or
+ * canceling composition.
+ *
+ * NOTE: handleText() must be called after composition actually ends, even if
+ * the composition is canceled and the textbox value isn't changed.
+ * Then, implementation of handleText() can access the editor when
+ * it's not in composing mode. DOM compositionend event is not good
+ * timing for calling handleText(). DOM input event immediately after
+ * DOM compositionend event is the best timing to call this.
+ *
+ * @return whether this handler started a new search.
+ */
+ boolean handleText();
+
+ /*
+ * Notify the controller that the user wishes to enter the current text. If
+ * aIsPopupSelection is true, then a selection was made from the popup, so
+ * fill this value into the input field before continuing. If false, just
+ * use the current value of the input field.
+ *
+ * @param aIsPopupSelection
+ * Pass true if the selection was made from the popup.
+ * @param aEvent
+ * The event that triggered the enter, like a key event if the user
+ * pressed the Return key or a click event if the user clicked a popup
+ * item.
+ * @return Whether the controller wishes to prevent event propagation and
+ * default event.
+ */
+ boolean handleEnter(in boolean aIsPopupSelection,
+ [optional] in nsIDOMEvent aEvent);
+
+ /*
+ * Notify the controller that the user wishes to revert autocomplete
+ *
+ * @return Whether the controller wishes to prevent event propagation and
+ * default event.
+ */
+ boolean handleEscape();
+
+ /*
+ * Notify the controller that the user wishes to start composition
+ *
+ * NOTE: nsIAutoCompleteController implementation expects that this is called
+ * by DOM compositionstart handler.
+ */
+ void handleStartComposition();
+
+ /*
+ * Notify the controller that the user wishes to end composition
+ *
+ * NOTE: nsIAutoCompleteController implementation expects that this is called
+ * by DOM compositionend handler.
+ */
+ void handleEndComposition();
+
+ /*
+ * Handle tab. Just closes up.
+ */
+ void handleTab();
+
+ /*
+ * Notify the controller of the following key navigation events:
+ * up, down, left, right, page up, page down
+ *
+ * @return Whether the controller wishes to prevent event propagation and
+ * default event
+ */
+ boolean handleKeyNavigation(in unsigned long key);
+
+ /*
+ * Notify the controller that the user chose to delete the current
+ * auto-complete result.
+ *
+ * @return Whether the controller removed a result item.
+ */
+ boolean handleDelete();
+
+ /*
+ * Get the value of the result at a given index in the last completed search
+ */
+ AString getValueAt(in long index);
+
+ /*
+ * Get the label of the result at a given index in the last completed search
+ */
+ AString getLabelAt(in long index);
+
+ /*
+ * Get the comment of the result at a given index in the last completed search
+ */
+ AString getCommentAt(in long index);
+
+ /*
+ * Get the style hint for the result at a given index in the last completed search
+ */
+ AString getStyleAt(in long index);
+
+ /*
+ * Get the url of the image of the result at a given index in the last completed search
+ */
+ AString getImageAt(in long index);
+
+ /*
+ * For the last completed search, get the final value that should be completed
+ * when the user confirms the match at the given index
+ */
+ AString getFinalCompleteValueAt(in long index);
+
+ /*
+ * Get / set the current search string. Note, setting will not start searching
+ */
+ attribute AString searchString;
+
+ /*
+ * Set the index of the result item that should be initially selected.
+ * This should be used when a search wants to pre-select an element before
+ * the user starts using results.
+ *
+ * @note Setting this is not the same as just setting selectedIndex in
+ * nsIAutocompletePopup, since this will take care of updating any internal
+ * tracking variables of features like completeSelectedIndex.
+ */
+ void setInitiallySelectedIndex(in long index);
+};
diff --git a/toolkit/components/autocomplete/nsIAutoCompleteInput.idl b/toolkit/components/autocomplete/nsIAutoCompleteInput.idl
new file mode 100644
index 000000000..26a75ea77
--- /dev/null
+++ b/toolkit/components/autocomplete/nsIAutoCompleteInput.idl
@@ -0,0 +1,181 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+#include "nsIAutoCompleteController.idl"
+
+interface nsIAutoCompletePopup;
+
+[scriptable, uuid(B068E70F-F82C-4C12-AD87-82E271C5C180)]
+interface nsIAutoCompleteInput : nsISupports
+{
+ /*
+ * The result view that will be used to display results
+ */
+ readonly attribute nsIAutoCompletePopup popup;
+
+ /*
+ * The controller.
+ */
+ readonly attribute nsIAutoCompleteController controller;
+
+ /*
+ * Indicates if the popup is currently open
+ */
+ attribute boolean popupOpen;
+
+ /*
+ * Option to disable autocomplete functionality
+ */
+ attribute boolean disableAutoComplete;
+
+ /*
+ * If a search result has its defaultIndex set, this will optionally
+ * try to complete the text in the textbox to the entire text of the
+ * result at the default index as the user types
+ */
+ attribute boolean completeDefaultIndex;
+
+ /*
+ * complete text in the textbox as the user selects from the dropdown
+ * options if set to true
+ */
+ attribute boolean completeSelectedIndex;
+
+ /*
+ * Option for completing to the default result whenever the user hits
+ * enter or the textbox loses focus
+ */
+ attribute boolean forceComplete;
+
+ /*
+ * Option to open the popup only after a certain number of results are available
+ */
+ attribute unsigned long minResultsForPopup;
+
+ /*
+ * The maximum number of rows to show in the autocomplete popup.
+ */
+ attribute unsigned long maxRows;
+
+ /*
+ * Option to show a second column in the popup which contains
+ * the comment for each autocomplete result
+ */
+ attribute boolean showCommentColumn;
+
+ /*
+ * Option to show a third column in the popup which contains
+ * an additional image for each autocomplete result
+ */
+ attribute boolean showImageColumn;
+
+ /*
+ * Number of milliseconds after a keystroke before a search begins
+ */
+ attribute unsigned long timeout;
+
+ /*
+ * An extra parameter to configure searches with.
+ */
+ attribute AString searchParam;
+
+ /*
+ * The number of autocomplete session to search
+ */
+ readonly attribute unsigned long searchCount;
+
+ /*
+ * Get the name of one of the autocomplete search session objects
+ */
+ ACString getSearchAt(in unsigned long index);
+
+ /*
+ * The value of text in the autocomplete textbox.
+ *
+ * @note when setting a new value, the controller always first tries to use
+ * setTextboxValueWithReason, and only if that throws (unimplemented),
+ * fallbacks to the textValue's setter. If a reason is not provided,
+ * the implementation should assume TEXTVALUE_REASON_UNKNOWN, but it
+ * should only happen in testing code.
+ */
+ attribute AString textValue;
+
+ /*
+ * Set the value of text in the autocomplete textbox, providing a reason to
+ * the autocomplete view.
+ */
+ const unsigned short TEXTVALUE_REASON_UNKNOWN = 0;
+ const unsigned short TEXTVALUE_REASON_COMPLETEDEFAULT = 1;
+ const unsigned short TEXTVALUE_REASON_COMPLETESELECTED = 2;
+ const unsigned short TEXTVALUE_REASON_REVERT = 3;
+ const unsigned short TEXTVALUE_REASON_ENTERMATCH = 4;
+
+ void setTextValueWithReason(in AString aValue,
+ in unsigned short aReason);
+
+ /*
+ * Report the starting index of the cursor in the textbox
+ */
+ readonly attribute long selectionStart;
+
+ /*
+ * Report the ending index of the cursor in the textbox
+ */
+ readonly attribute long selectionEnd;
+
+ /*
+ * Select a range of text in the autocomplete textbox
+ */
+ void selectTextRange(in long startIndex, in long endIndex);
+
+ /*
+ * Notification that the search has started
+ */
+ void onSearchBegin();
+
+ /*
+ * Notification that the search concluded successfully
+ */
+ void onSearchComplete();
+
+ /*
+ * Notification that the user selected and entered a result item
+ *
+ * @param aEvent
+ * The event that triggered the enter.
+ * @return True if the user wishes to prevent the enter
+ */
+ boolean onTextEntered([optional] in nsIDOMEvent aEvent);
+
+ /*
+ * Notification that the user cancelled the autocomplete session
+ *
+ * @return True if the user wishes to prevent the revert
+ */
+ boolean onTextReverted();
+
+ /*
+ * This popup should consume or dispatch the rollup event.
+ * TRUE: should consume; FALSE: should dispatch.
+ */
+ readonly attribute boolean consumeRollupEvent;
+
+ /*
+ * Indicates whether this input is in a "private browsing" context.
+ * nsIAutoCompleteSearches for these inputs should not persist any data to disk
+ * (such as a history database).
+ */
+ readonly attribute boolean inPrivateContext;
+
+ /*
+ * Don't rollup the popup when the caret is moved.
+ */
+ readonly attribute boolean noRollupOnCaretMove;
+
+ /**
+ * The userContextId of the current browser.
+ */
+ readonly attribute unsigned long userContextId;
+};
diff --git a/toolkit/components/autocomplete/nsIAutoCompletePopup.idl b/toolkit/components/autocomplete/nsIAutoCompletePopup.idl
new file mode 100644
index 000000000..cb5dda6f2
--- /dev/null
+++ b/toolkit/components/autocomplete/nsIAutoCompletePopup.idl
@@ -0,0 +1,71 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+interface nsIDOMElement;
+interface nsIAutoCompleteInput;
+
+[scriptable, uuid(bd3c2662-a988-41ab-8c94-c15ed0e6ac7d)]
+interface nsIAutoCompletePopup : nsISupports
+{
+ /*
+ * The input object that the popup is currently bound to
+ */
+ readonly attribute nsIAutoCompleteInput input;
+
+ /*
+ * An alternative value to be used when text is entered, rather than the
+ * value of the selected item
+ */
+ readonly attribute AString overrideValue;
+
+ /*
+ * The index of the result item that is currently selected
+ */
+ attribute long selectedIndex;
+
+ /*
+ * Indicates if the popup is currently open
+ */
+ readonly attribute boolean popupOpen;
+
+ /*
+ * Bind the popup to an input object and display it with the given coordinates
+ *
+ * @param input - The input object that the popup will be bound to
+ * @param element - The element that the popup will be aligned with
+ */
+ void openAutocompletePopup(in nsIAutoCompleteInput input, in nsIDOMElement element);
+
+ /*
+ * Close the popup and detach from the bound input
+ */
+ void closePopup();
+
+ /*
+ * Instruct the result view to repaint itself to reflect the most current
+ * underlying data
+ *
+ * @param reason - The reason the popup needs to be invalidated, one of the
+ * INVALIDATE_REASON consts.
+ */
+ void invalidate(in unsigned short reason);
+
+ /*
+ * Possible values of invalidate()'s 'reason' argument.
+ */
+ const unsigned short INVALIDATE_REASON_NEW_RESULT = 0;
+ const unsigned short INVALIDATE_REASON_DELETE = 1;
+
+ /*
+ * Change the selection relative to the current selection and make sure
+ * the newly selected row is visible
+ *
+ * @param reverse - Select a row above the current selection
+ * @param page - Select a row that is a full visible page from the current selection
+ * @return The currently selected result item index
+ */
+ void selectBy(in boolean reverse, in boolean page);
+};
diff --git a/toolkit/components/autocomplete/nsIAutoCompleteResult.idl b/toolkit/components/autocomplete/nsIAutoCompleteResult.idl
new file mode 100644
index 000000000..c719d9427
--- /dev/null
+++ b/toolkit/components/autocomplete/nsIAutoCompleteResult.idl
@@ -0,0 +1,89 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+[scriptable, uuid(9203c031-c4e7-4537-a4ec-81443d623d5a)]
+interface nsIAutoCompleteResult : nsISupports
+{
+ /**
+ * Possible values for the searchResult attribute
+ */
+ const unsigned short RESULT_IGNORED = 1; /* indicates invalid searchString */
+ const unsigned short RESULT_FAILURE = 2; /* indicates failure */
+ const unsigned short RESULT_NOMATCH = 3; /* indicates success with no matches
+ and that the search is complete */
+ const unsigned short RESULT_SUCCESS = 4; /* indicates success with matches
+ and that the search is complete */
+ const unsigned short RESULT_NOMATCH_ONGOING = 5; /* indicates success
+ with no matches
+ and that the search
+ is still ongoing */
+ const unsigned short RESULT_SUCCESS_ONGOING = 6; /* indicates success
+ with matches
+ and that the search
+ is still ongoing */
+ /**
+ * The original search string
+ */
+ readonly attribute AString searchString;
+
+ /**
+ * The result of the search
+ */
+ readonly attribute unsigned short searchResult;
+
+ /**
+ * Index of the default item that should be entered if none is selected
+ */
+ readonly attribute long defaultIndex;
+
+ /**
+ * A string describing the cause of a search failure
+ */
+ readonly attribute AString errorDescription;
+
+ /**
+ * The number of matches
+ */
+ readonly attribute unsigned long matchCount;
+
+ /**
+ * Get the value of the result at the given index
+ */
+ AString getValueAt(in long index);
+
+ /**
+ * This returns the string that is displayed in the dropdown
+ */
+ AString getLabelAt(in long index);
+
+ /**
+ * Get the comment of the result at the given index
+ */
+ AString getCommentAt(in long index);
+
+ /**
+ * Get the style hint for the result at the given index
+ */
+ AString getStyleAt(in long index);
+
+ /**
+ * Get the image of the result at the given index
+ */
+ AString getImageAt(in long index);
+
+ /**
+ * Get the final value that should be completed when the user confirms
+ * the match at the given index.
+ */
+ AString getFinalCompleteValueAt(in long index);
+
+ /**
+ * Remove the value at the given index from the autocomplete results.
+ * If removeFromDb is set to true, the value should be removed from
+ * persistent storage as well.
+ */
+ void removeValueAt(in long rowIndex, in boolean removeFromDb);
+};
diff --git a/toolkit/components/autocomplete/nsIAutoCompleteSearch.idl b/toolkit/components/autocomplete/nsIAutoCompleteSearch.idl
new file mode 100644
index 000000000..188c333ac
--- /dev/null
+++ b/toolkit/components/autocomplete/nsIAutoCompleteSearch.idl
@@ -0,0 +1,74 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+interface nsIAutoCompleteResult;
+interface nsIAutoCompleteObserver;
+
+[scriptable, uuid(DE8DB85F-C1DE-4d87-94BA-7844890F91FE)]
+interface nsIAutoCompleteSearch : nsISupports
+{
+ /*
+ * Search for a given string and notify a listener (either synchronously
+ * or asynchronously) of the result
+ *
+ * @param searchString - The string to search for
+ * @param searchParam - An extra parameter
+ * @param previousResult - A previous result to use for faster searching
+ * @param listener - A listener to notify when the search is complete
+ */
+ void startSearch(in AString searchString,
+ in AString searchParam,
+ in nsIAutoCompleteResult previousResult,
+ in nsIAutoCompleteObserver listener);
+
+ /*
+ * Stop all searches that are in progress
+ */
+ void stopSearch();
+};
+
+[scriptable, uuid(8bd1dbbc-dcce-4007-9afa-b551eb687b61)]
+interface nsIAutoCompleteObserver : nsISupports
+{
+ /*
+ * Called when a search is complete and the results are ready
+ *
+ * @param search - The search object that processed this search
+ * @param result - The search result object
+ */
+ void onSearchResult(in nsIAutoCompleteSearch search, in nsIAutoCompleteResult result);
+
+ /*
+ * Called to update with new results
+ *
+ * @param search - The search object that processed this search
+ * @param result - The search result object
+ */
+ void onUpdateSearchResult(in nsIAutoCompleteSearch search, in nsIAutoCompleteResult result);
+};
+
+[scriptable, uuid(4c3e7462-fbfb-4310-8f4b-239238392b75)]
+interface nsIAutoCompleteSearchDescriptor : nsISupports
+{
+ // The search is started after the timeout specified by the corresponding
+ // nsIAutoCompleteInput implementation.
+ const unsigned short SEARCH_TYPE_DELAYED = 0;
+ // The search is started synchronously, before any delayed searches.
+ const unsigned short SEARCH_TYPE_IMMEDIATE = 1;
+
+ /**
+ * Identifies the search behavior.
+ * Should be one of the SEARCH_TYPE_* constants above.
+ * Defaults to SEARCH_TYPE_DELAYED.
+ */
+ readonly attribute unsigned short searchType;
+
+ /*
+ * Whether a new search should be triggered when the user deletes the
+ * autofilled part.
+ */
+ readonly attribute boolean clearingAutoFillSearchesAgain;
+};
diff --git a/toolkit/components/autocomplete/nsIAutoCompleteSimpleResult.idl b/toolkit/components/autocomplete/nsIAutoCompleteSimpleResult.idl
new file mode 100644
index 000000000..5e92e037a
--- /dev/null
+++ b/toolkit/components/autocomplete/nsIAutoCompleteSimpleResult.idl
@@ -0,0 +1,116 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+#include "nsIAutoCompleteResult.idl"
+
+interface nsIAutoCompleteSimpleResultListener;
+
+/**
+ * This class implements nsIAutoCompleteResult and provides simple methods
+ * for setting the value and result items. It can be used whenever some basic
+ * auto complete results are needed that can be pre-generated and filled into
+ * an array.
+ */
+
+[scriptable, uuid(23de9c96-becb-4d0d-a9bb-1d131ce361b5)]
+interface nsIAutoCompleteSimpleResult : nsIAutoCompleteResult
+{
+ /**
+ * A writer for the readonly attribute 'searchString' which should contain
+ * the string that the user typed.
+ */
+ void setSearchString(in AString aSearchString);
+
+ /**
+ * A writer for the readonly attribute 'errorDescription'.
+ */
+ void setErrorDescription(in AString aErrorDescription);
+
+ /**
+ * A writer for the readonly attribute 'defaultIndex' which should contain
+ * the index of the list that will be selected by default (normally 0).
+ */
+ void setDefaultIndex(in long aDefaultIndex);
+
+ /**
+ * A writer for the readonly attribute 'searchResult' which should contain
+ * one of the constants nsIAutoCompleteResult.RESULT_* indicating the success
+ * of the search.
+ */
+ void setSearchResult(in unsigned short aSearchResult);
+
+ /**
+ * Inserts a match consisting of the given value, comment, image, style and
+ * the value to use for defaultIndex completion at a given position.
+ * @param aIndex
+ * The index to insert at
+ * @param aValue
+ * The value to autocomplete to
+ * @param aComment
+ * Comment shown in the autocomplete widget to describe this match
+ * @param aImage
+ * Image shown in the autocomplete widget for this match.
+ * @param aStyle
+ * Describes how to style the match in the autocomplete widget
+ * @param aFinalCompleteValue
+ * Value used when the user confirms selecting this match. If not
+ * provided, aValue will be used.
+ */
+ void insertMatchAt(in long aIndex,
+ in AString aValue,
+ in AString aComment,
+ [optional] in AString aImage,
+ [optional] in AString aStyle,
+ [optional] in AString aFinalCompleteValue,
+ [optional] in AString aLabel);
+
+ /**
+ * Appends a match consisting of the given value, comment, image, style and
+ * the value to use for defaultIndex completion.
+ * @param aValue
+ * The value to autocomplete to
+ * @param aComment
+ * Comment shown in the autocomplete widget to describe this match
+ * @param aImage
+ * Image shown in the autocomplete widget for this match.
+ * @param aStyle
+ * Describes how to style the match in the autocomplete widget
+ * @param aFinalCompleteValue
+ * Value used when the user confirms selecting this match. If not
+ * provided, aValue will be used.
+ */
+ void appendMatch(in AString aValue,
+ in AString aComment,
+ [optional] in AString aImage,
+ [optional] in AString aStyle,
+ [optional] in AString aFinalCompleteValue,
+ [optional] in AString aLabel);
+
+ /**
+ * Gets the listener for changes in the result.
+ */
+ nsIAutoCompleteSimpleResultListener getListener();
+
+ /**
+ * Sets a listener for changes in the result.
+ */
+ void setListener(in nsIAutoCompleteSimpleResultListener aListener);
+};
+
+[scriptable, uuid(004efdc5-1989-4874-8a7a-345bf2fa33af)]
+interface nsIAutoCompleteSimpleResultListener : nsISupports
+{
+ /**
+ * Dispatched after a value is removed from the result.
+ * @param aResult
+ * The result from which aValue has been removed.
+ * @param aValue
+ * The removed value.
+ * @param aRemoveFromDb
+ * Whether the value should be removed from persistent storage as well.
+ */
+ void onValueRemoved(in nsIAutoCompleteSimpleResult aResult, in AString aValue,
+ in boolean aRemoveFromDb);
+};
diff --git a/toolkit/components/autocomplete/tests/unit/.eslintrc.js b/toolkit/components/autocomplete/tests/unit/.eslintrc.js
new file mode 100644
index 000000000..d35787cd2
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/.eslintrc.js
@@ -0,0 +1,7 @@
+"use strict";
+
+module.exports = {
+ "extends": [
+ "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
+ ]
+};
diff --git a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js
new file mode 100644
index 000000000..1443879f0
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js
@@ -0,0 +1,206 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+
+var Cc = Components.classes;
+var Ci = Components.interfaces;
+var Cu = Components.utils;
+
+/**
+ * Dummy nsIAutoCompleteInput source that returns
+ * the given list of AutoCompleteSearch names.
+ *
+ * Implements only the methods needed for this test.
+ */
+function AutoCompleteInputBase(aSearches) {
+ this.searches = aSearches;
+}
+AutoCompleteInputBase.prototype = {
+
+ // Array of AutoCompleteSearch names
+ searches: null,
+
+ minResultsForPopup: 0,
+ timeout: 10,
+ searchParam: "",
+ textValue: "",
+ disableAutoComplete: false,
+ completeDefaultIndex: false,
+
+ // Text selection range
+ _selStart: 0,
+ _selEnd: 0,
+ get selectionStart() {
+ return this._selStart;
+ },
+ get selectionEnd() {
+ return this._selEnd;
+ },
+ selectTextRange: function(aStart, aEnd) {
+ this._selStart = aStart;
+ this._selEnd = aEnd;
+ },
+
+ get searchCount() {
+ return this.searches.length;
+ },
+
+ getSearchAt: function(aIndex) {
+ return this.searches[aIndex];
+ },
+
+ onSearchBegin: function() {},
+ onSearchComplete: function() {},
+
+ popupOpen: false,
+
+ get popup() {
+ if (!this._popup) {
+ this._popup = new AutocompletePopupBase(this);
+ }
+ return this._popup;
+ },
+
+ // nsISupports implementation
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput])
+}
+
+/**
+ * nsIAutoCompleteResult implementation
+ */
+function AutoCompleteResultBase(aValues) {
+ this._values = aValues;
+}
+AutoCompleteResultBase.prototype = {
+
+ // Arrays
+ _values: null,
+ _comments: [],
+ _styles: [],
+ _finalCompleteValues: [],
+
+ searchString: "",
+ searchResult: null,
+
+ defaultIndex: -1,
+
+ get matchCount() {
+ return this._values.length;
+ },
+
+ getValueAt: function(aIndex) {
+ return this._values[aIndex];
+ },
+
+ getLabelAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ getCommentAt: function(aIndex) {
+ return this._comments[aIndex];
+ },
+
+ getStyleAt: function(aIndex) {
+ return this._styles[aIndex];
+ },
+
+ getImageAt: function(aIndex) {
+ return "";
+ },
+
+ getFinalCompleteValueAt: function(aIndex) {
+ return this._finalCompleteValues[aIndex] || this._values[aIndex];
+ },
+
+ removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+
+ // nsISupports implementation
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteResult])
+}
+
+/**
+ * nsIAutoCompleteSearch implementation that always returns
+ * the same result set.
+ */
+function AutoCompleteSearchBase(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteSearchBase.prototype = {
+
+ // Search name. Used by AutoCompleteController
+ name: null,
+
+ // AutoCompleteResult
+ _result: null,
+
+ startSearch: function(aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener) {
+ var result = this._result;
+
+ result.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
+ aListener.onSearchResult(this, result);
+ },
+
+ stopSearch: function() {},
+
+ // nsISupports implementation
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory,
+ Ci.nsIAutoCompleteSearch]),
+
+ // nsIFactory implementation
+ createInstance: function(outer, iid) {
+ return this.QueryInterface(iid);
+ }
+}
+
+function AutocompletePopupBase(input) {
+ this.input = input;
+}
+AutocompletePopupBase.prototype = {
+ selectedIndex: 0,
+ invalidate() {},
+ selectBy(reverse, page) {
+ let numRows = this.input.controller.matchCount;
+ if (numRows > 0) {
+ let delta = reverse ? -1 : 1;
+ this.selectedIndex = (this.selectedIndex + delta) % numRows;
+ if (this.selectedIndex < 0) {
+ this.selectedIndex = numRows - 1;
+ }
+ }
+ },
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup]),
+};
+
+/**
+ * Helper to register an AutoCompleteSearch with the given name.
+ * Allows the AutoCompleteController to find the search.
+ */
+function registerAutoCompleteSearch(aSearch) {
+ var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
+ var cid = Cc["@mozilla.org/uuid-generator;1"].
+ getService(Ci.nsIUUIDGenerator).
+ generateUUID();
+
+ var desc = "Test AutoCompleteSearch";
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.registerFactory(cid, desc, name, aSearch);
+
+ // Keep the id on the object so we can unregister later
+ aSearch.cid = cid;
+}
+
+/**
+ * Helper to unregister an AutoCompleteSearch.
+ */
+function unregisterAutoCompleteSearch(aSearch) {
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.unregisterFactory(aSearch.cid, aSearch);
+}
+
diff --git a/toolkit/components/autocomplete/tests/unit/test_330578.js b/toolkit/components/autocomplete/tests/unit/test_330578.js
new file mode 100644
index 000000000..c422dbb6a
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_330578.js
@@ -0,0 +1,45 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+var gResultListener = {
+ _lastResult: null,
+ _lastValue: "",
+ _lastRemoveFromDb: false,
+
+ onValueRemoved: function(aResult, aValue, aRemoveFromDb) {
+ this._lastResult = aResult;
+ this._lastValue = aValue;
+ this._lastRemoveFromDb = aRemoveFromDb;
+ }
+};
+
+
+// main
+function run_test() {
+ var result = Cc["@mozilla.org/autocomplete/simple-result;1"].
+ createInstance(Ci.nsIAutoCompleteSimpleResult);
+ result.appendMatch("a", "");
+ result.appendMatch("b", "");
+ result.appendMatch("c", "");
+ result.setListener(gResultListener);
+ do_check_eq(result.matchCount, 3);
+ result.removeValueAt(0, true);
+ do_check_eq(result.matchCount, 2);
+ do_check_eq(gResultListener._lastResult, result);
+ do_check_eq(gResultListener._lastValue, "a");
+ do_check_eq(gResultListener._lastRemoveFromDb, true);
+
+ result.removeValueAt(0, false);
+ do_check_eq(result.matchCount, 1);
+ do_check_eq(gResultListener._lastValue, "b");
+ do_check_eq(gResultListener._lastRemoveFromDb, false);
+
+ // check that we don't get notified if the listener is unset
+ result.setListener(null);
+ result.removeValueAt(0, true); // "c"
+ do_check_eq(result.matchCount, 0);
+ do_check_eq(gResultListener._lastValue, "b");
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_378079.js b/toolkit/components/autocomplete/tests/unit/test_378079.js
new file mode 100644
index 000000000..ad7e5590f
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_378079.js
@@ -0,0 +1,285 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Unit test for Bug 378079 - AutoComplete returns invalid rows when
+ * more than one AutoCompleteSearch is used.
+ */
+
+
+
+/**
+ * Dummy nsIAutoCompleteInput source that returns
+ * the given list of AutoCompleteSearch names.
+ *
+ * Implements only the methods needed for this test.
+ */
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+}
+AutoCompleteInput.prototype = {
+ constructor: AutoCompleteInput,
+
+ // Array of AutoCompleteSearch names
+ searches: null,
+
+ minResultsForPopup: 0,
+ timeout: 10,
+ searchParam: "",
+ textValue: "",
+ disableAutoComplete: false,
+ completeDefaultIndex: false,
+
+ get searchCount() {
+ return this.searches.length;
+ },
+
+ getSearchAt: function(aIndex) {
+ return this.searches[aIndex];
+ },
+
+ onSearchBegin: function() {},
+ onSearchComplete: function() {},
+
+ popupOpen: false,
+
+ popup: {
+ setSelectedIndex: function(aIndex) {},
+ invalidate: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompletePopup))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+ },
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteInput))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+
+/**
+ * nsIAutoCompleteResult implementation
+ */
+function AutoCompleteResult(aValues, aComments, aStyles) {
+ this._values = aValues;
+ this._comments = aComments;
+ this._styles = aStyles;
+
+ if (this._values.length > 0) {
+ this.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
+ } else {
+ this.searchResult = Ci.nsIAutoCompleteResult.NOMATCH;
+ }
+}
+AutoCompleteResult.prototype = {
+ constructor: AutoCompleteResult,
+
+ // Arrays
+ _values: null,
+ _comments: null,
+ _styles: null,
+
+ searchString: "",
+ searchResult: null,
+
+ defaultIndex: 0,
+
+ get matchCount() {
+ return this._values.length;
+ },
+
+ getValueAt: function(aIndex) {
+ return this._values[aIndex];
+ },
+
+ getLabelAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ getCommentAt: function(aIndex) {
+ return this._comments[aIndex];
+ },
+
+ getStyleAt: function(aIndex) {
+ return this._styles[aIndex];
+ },
+
+ getImageAt: function(aIndex) {
+ return "";
+ },
+
+ getFinalCompleteValueAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteResult))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+
+/**
+ * nsIAutoCompleteSearch implementation that always returns
+ * the same result set.
+ */
+function AutoCompleteSearch(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteSearch.prototype = {
+ constructor: AutoCompleteSearch,
+
+ // Search name. Used by AutoCompleteController
+ name: null,
+
+ // AutoCompleteResult
+ _result:null,
+
+
+ /**
+ * Return the same result set for every search
+ */
+ startSearch: function(aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener)
+ {
+ aListener.onSearchResult(this, this._result);
+ },
+
+ stopSearch: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIFactory) ||
+ iid.equals(Ci.nsIAutoCompleteSearch))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ },
+
+ // nsIFactory implementation
+ createInstance: function(outer, iid) {
+ return this.QueryInterface(iid);
+ }
+}
+
+
+
+/**
+ * Helper to register an AutoCompleteSearch with the given name.
+ * Allows the AutoCompleteController to find the search.
+ */
+function registerAutoCompleteSearch(aSearch) {
+ var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
+
+ var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
+ getService(Ci.nsIUUIDGenerator);
+ var cid = uuidGenerator.generateUUID();
+
+ var desc = "Test AutoCompleteSearch";
+
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.registerFactory(cid, desc, name, aSearch);
+
+ // Keep the id on the object so we can unregister later
+ aSearch.cid = cid;
+}
+
+
+
+/**
+ * Helper to unregister an AutoCompleteSearch.
+ */
+function unregisterAutoCompleteSearch(aSearch) {
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.unregisterFactory(aSearch.cid, aSearch);
+}
+
+
+
+/**
+ * Test AutoComplete with multiple AutoCompleteSearch sources.
+ */
+function run_test() {
+
+ // Make an AutoCompleteSearch that always returns nothing
+ var emptySearch = new AutoCompleteSearch("test-empty-search",
+ new AutoCompleteResult([], [], []));
+
+ // Make an AutoCompleteSearch that returns two values
+ var expectedValues = ["test1", "test2"];
+ var regularSearch = new AutoCompleteSearch("test-regular-search",
+ new AutoCompleteResult(expectedValues, [], []));
+
+ // Register searches so AutoCompleteController can find them
+ registerAutoCompleteSearch(emptySearch);
+ registerAutoCompleteSearch(regularSearch);
+
+ var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
+ getService(Components.interfaces.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our searches
+ // and confirms results on search complete
+ var input = new AutoCompleteInput([emptySearch.name, regularSearch.name]);
+ var numSearchesStarted = 0;
+
+ input.onSearchBegin = function() {
+ numSearchesStarted++;
+ do_check_eq(numSearchesStarted, 1);
+ };
+
+ input.onSearchComplete = function() {
+
+ do_check_eq(numSearchesStarted, 1);
+
+ do_check_eq(controller.searchStatus,
+ Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
+ do_check_eq(controller.matchCount, 2);
+
+ // Confirm expected result values
+ for (var i = 0; i < expectedValues.length; i++) {
+ do_check_eq(expectedValues[i], controller.getValueAt(i));
+ }
+
+ // Unregister searches
+ unregisterAutoCompleteSearch(emptySearch);
+ unregisterAutoCompleteSearch(regularSearch);
+
+ do_test_finished();
+ };
+
+ controller.input = input;
+
+ // Search is asynchronous, so don't let the test finish immediately
+ do_test_pending();
+
+ controller.startSearch("test");
+}
+
diff --git a/toolkit/components/autocomplete/tests/unit/test_393191.js b/toolkit/components/autocomplete/tests/unit/test_393191.js
new file mode 100644
index 000000000..6fb57e6c4
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_393191.js
@@ -0,0 +1,272 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Unit test for Bug 393191 - AutoComplete crashes if result is null
+ */
+
+
+
+/**
+ * Dummy nsIAutoCompleteInput source that returns
+ * the given list of AutoCompleteSearch names.
+ *
+ * Implements only the methods needed for this test.
+ */
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+}
+AutoCompleteInput.prototype = {
+ constructor: AutoCompleteInput,
+
+ // Array of AutoCompleteSearch names
+ searches: null,
+
+ minResultsForPopup: 0,
+ timeout: 10,
+ searchParam: "",
+ textValue: "",
+ disableAutoComplete: false,
+ completeDefaultIndex: false,
+
+ get searchCount() {
+ return this.searches.length;
+ },
+
+ getSearchAt: function(aIndex) {
+ return this.searches[aIndex];
+ },
+
+ onSearchBegin: function() {},
+ onSearchComplete: function() {},
+
+ popupOpen: false,
+
+ popup: {
+ setSelectedIndex: function(aIndex) {},
+ invalidate: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompletePopup))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+ },
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteInput))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+
+/**
+ * nsIAutoCompleteResult implementation
+ */
+function AutoCompleteResult(aValues, aComments, aStyles) {
+ this._values = aValues;
+ this._comments = aComments;
+ this._styles = aStyles;
+
+ if (this._values.length > 0) {
+ this.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
+ } else {
+ this.searchResult = Ci.nsIAutoCompleteResult.NOMATCH;
+ }
+}
+AutoCompleteResult.prototype = {
+ constructor: AutoCompleteResult,
+
+ // Arrays
+ _values: null,
+ _comments: null,
+ _styles: null,
+
+ searchString: "",
+ searchResult: null,
+
+ defaultIndex: 0,
+
+ get matchCount() {
+ return this._values.length;
+ },
+
+ getValueAt: function(aIndex) {
+ return this._values[aIndex];
+ },
+
+ getLabelAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ getCommentAt: function(aIndex) {
+ return this._comments[aIndex];
+ },
+
+ getStyleAt: function(aIndex) {
+ return this._styles[aIndex];
+ },
+
+ getImageAt: function(aIndex) {
+ return "";
+ },
+
+ getFinalCompleteValueAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteResult))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+
+/**
+ * nsIAutoCompleteSearch implementation that always returns
+ * the same result set.
+ */
+function AutoCompleteSearch(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteSearch.prototype = {
+ constructor: AutoCompleteSearch,
+
+ // Search name. Used by AutoCompleteController
+ name: null,
+
+ // AutoCompleteResult
+ _result: null,
+
+
+ /**
+ * Return the same result set for every search
+ */
+ startSearch: function(aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener)
+ {
+ aListener.onSearchResult(this, this._result);
+ },
+
+ stopSearch: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIFactory) ||
+ iid.equals(Ci.nsIAutoCompleteSearch))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ },
+
+ // nsIFactory implementation
+ createInstance: function(outer, iid) {
+ return this.QueryInterface(iid);
+ }
+}
+
+
+
+/**
+ * Helper to register an AutoCompleteSearch with the given name.
+ * Allows the AutoCompleteController to find the search.
+ */
+function registerAutoCompleteSearch(aSearch) {
+ var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
+
+ var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
+ getService(Ci.nsIUUIDGenerator);
+ var cid = uuidGenerator.generateUUID();
+
+ var desc = "Test AutoCompleteSearch";
+
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.registerFactory(cid, desc, name, aSearch);
+
+ // Keep the id on the object so we can unregister later
+ aSearch.cid = cid;
+}
+
+
+
+/**
+ * Helper to unregister an AutoCompleteSearch.
+ */
+function unregisterAutoCompleteSearch(aSearch) {
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.unregisterFactory(aSearch.cid, aSearch);
+}
+
+
+
+/**
+ * Test AutoComplete with a search that returns a null result
+ */
+function run_test() {
+
+ // Make an AutoCompleteSearch that always returns nothing
+ var emptySearch = new AutoCompleteSearch("test-empty-search",
+ new AutoCompleteResult([], [], []));
+
+ // Register search so AutoCompleteController can find them
+ registerAutoCompleteSearch(emptySearch);
+
+ var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
+ getService(Components.interfaces.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our search
+ // and confirms results on search complete
+ var input = new AutoCompleteInput([emptySearch.name]);
+ var numSearchesStarted = 0;
+
+ input.onSearchBegin = function() {
+ numSearchesStarted++;
+ do_check_eq(numSearchesStarted, 1);
+ };
+
+ input.onSearchComplete = function() {
+
+ do_check_eq(numSearchesStarted, 1);
+
+ do_check_eq(controller.searchStatus,
+ Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH);
+ do_check_eq(controller.matchCount, 0);
+
+ // Unregister searches
+ unregisterAutoCompleteSearch(emptySearch);
+
+ do_test_finished();
+ };
+
+ controller.input = input;
+
+ // Search is asynchronous, so don't let the test finish immediately
+ do_test_pending();
+
+ controller.startSearch("test");
+}
+
diff --git a/toolkit/components/autocomplete/tests/unit/test_440866.js b/toolkit/components/autocomplete/tests/unit/test_440866.js
new file mode 100644
index 000000000..e450aebbf
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_440866.js
@@ -0,0 +1,285 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Unit test for Bug 440866 - First AutoCompleteSearch that returns
+ * RESULT_NOMATCH cancels all other searches when popup is open
+ */
+
+
+
+/**
+ * Dummy nsIAutoCompleteInput source that returns
+ * the given list of AutoCompleteSearch names.
+ *
+ * Implements only the methods needed for this test.
+ */
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+}
+AutoCompleteInput.prototype = {
+ constructor: AutoCompleteInput,
+
+ // Array of AutoCompleteSearch names
+ searches: null,
+
+ minResultsForPopup: 0,
+ timeout: 10,
+ searchParam: "",
+ textValue: "",
+ disableAutoComplete: false,
+ completeDefaultIndex: false,
+
+ get searchCount() {
+ return this.searches.length;
+ },
+
+ getSearchAt: function(aIndex) {
+ return this.searches[aIndex];
+ },
+
+ onSearchBegin: function() {},
+ onSearchComplete: function() {},
+
+ popupOpen: false,
+
+ popup: {
+ setSelectedIndex: function(aIndex) {},
+ invalidate: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompletePopup))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+ },
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteInput))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+
+/**
+ * nsIAutoCompleteResult implementation
+ */
+function AutoCompleteResult(aValues, aComments, aStyles) {
+ this._values = aValues;
+ this._comments = aComments;
+ this._styles = aStyles;
+
+ if (this._values.length > 0) {
+ this.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
+ } else {
+ this.searchResult = Ci.nsIAutoCompleteResult.NOMATCH;
+ }
+}
+AutoCompleteResult.prototype = {
+ constructor: AutoCompleteResult,
+
+ // Arrays
+ _values: null,
+ _comments: null,
+ _styles: null,
+
+ searchString: "",
+ searchResult: null,
+
+ defaultIndex: 0,
+
+ get matchCount() {
+ return this._values.length;
+ },
+
+ getValueAt: function(aIndex) {
+ return this._values[aIndex];
+ },
+
+ getLabelAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ getCommentAt: function(aIndex) {
+ return this._comments[aIndex];
+ },
+
+ getStyleAt: function(aIndex) {
+ return this._styles[aIndex];
+ },
+
+ getImageAt: function(aIndex) {
+ return "";
+ },
+
+ getFinalCompleteValueAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteResult))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+
+/**
+ * nsIAutoCompleteSearch implementation that always returns
+ * the same result set.
+ */
+function AutoCompleteSearch(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteSearch.prototype = {
+ constructor: AutoCompleteSearch,
+
+ // Search name. Used by AutoCompleteController
+ name: null,
+
+ // AutoCompleteResult
+ _result:null,
+
+
+ /**
+ * Return the same result set for every search
+ */
+ startSearch: function(aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener)
+ {
+ aListener.onSearchResult(this, this._result);
+ },
+
+ stopSearch: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIFactory) ||
+ iid.equals(Ci.nsIAutoCompleteSearch))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ },
+
+ // nsIFactory implementation
+ createInstance: function(outer, iid) {
+ return this.QueryInterface(iid);
+ }
+}
+
+
+
+/**
+ * Helper to register an AutoCompleteSearch with the given name.
+ * Allows the AutoCompleteController to find the search.
+ */
+function registerAutoCompleteSearch(aSearch) {
+ var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
+
+ var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
+ getService(Ci.nsIUUIDGenerator);
+ var cid = uuidGenerator.generateUUID();
+
+ var desc = "Test AutoCompleteSearch";
+
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.registerFactory(cid, desc, name, aSearch);
+
+ // Keep the id on the object so we can unregister later
+ aSearch.cid = cid;
+}
+
+
+
+/**
+ * Helper to unregister an AutoCompleteSearch.
+ */
+function unregisterAutoCompleteSearch(aSearch) {
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.unregisterFactory(aSearch.cid, aSearch);
+}
+
+
+
+/**
+ * Test AutoComplete with multiple AutoCompleteSearch sources.
+ */
+function run_test() {
+
+ // Make an AutoCompleteSearch that always returns nothing
+ var emptySearch = new AutoCompleteSearch("test-empty-search",
+ new AutoCompleteResult([], [], []));
+
+ // Make an AutoCompleteSearch that returns two values
+ var expectedValues = ["test1", "test2"];
+ var regularSearch = new AutoCompleteSearch("test-regular-search",
+ new AutoCompleteResult(expectedValues, [], []));
+
+ // Register searches so AutoCompleteController can find them
+ registerAutoCompleteSearch(emptySearch);
+ registerAutoCompleteSearch(regularSearch);
+
+ var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
+ getService(Components.interfaces.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our searches
+ // and confirms results on search complete
+ var input = new AutoCompleteInput([emptySearch.name, regularSearch.name]);
+ var numSearchesStarted = 0;
+
+ input.onSearchBegin = function() {
+ numSearchesStarted++;
+ do_check_eq(numSearchesStarted, 1);
+ do_check_eq(input.searchCount, 2);
+ };
+
+ input.onSearchComplete = function() {
+ do_check_eq(numSearchesStarted, 1);
+
+ do_check_eq(controller.searchStatus,
+ Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
+ do_check_eq(controller.matchCount, 2);
+
+ // Confirm expected result values
+ for (var i = 0; i < expectedValues.length; i++) {
+ do_check_eq(expectedValues[i], controller.getValueAt(i));
+ }
+
+ do_check_true(input.popupOpen);
+
+ // Unregister searches
+ unregisterAutoCompleteSearch(emptySearch);
+ unregisterAutoCompleteSearch(regularSearch);
+
+ do_test_finished();
+ };
+
+ controller.input = input;
+
+ // Search is asynchronous, so don't let the test finish immediately
+ do_test_pending();
+
+ controller.startSearch("test");
+}
+
diff --git a/toolkit/components/autocomplete/tests/unit/test_463023.js b/toolkit/components/autocomplete/tests/unit/test_463023.js
new file mode 100644
index 000000000..a2639fd03
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_463023.js
@@ -0,0 +1,12 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// main
+function run_test() {
+ var result = Cc["@mozilla.org/autocomplete/controller;1"].
+ createInstance(Ci.nsIAutoCompleteController);
+ do_check_eq(result.searchStatus, Ci.nsIAutoCompleteController.STATUS_NONE);
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_660156.js b/toolkit/components/autocomplete/tests/unit/test_660156.js
new file mode 100644
index 000000000..98acb243e
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_660156.js
@@ -0,0 +1,101 @@
+/**
+ * Search object that returns results at different times.
+ * First, the search that returns results asynchronously.
+ */
+function AutoCompleteAsyncSearch(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteAsyncSearch.prototype = Object.create(AutoCompleteSearchBase.prototype);
+AutoCompleteAsyncSearch.prototype.startSearch = function(aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener) {
+ this._result.searchResult = Ci.nsIAutoCompleteResult.RESULT_NOMATCH_ONGOING;
+ aListener.onSearchResult(this, this._result);
+
+ do_timeout(500, () => {
+ this._returnResults(aListener);
+ });
+};
+
+AutoCompleteAsyncSearch.prototype._returnResults = function(aListener) {
+ var result = this._result;
+
+ result.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
+ aListener.onSearchResult(this, result);
+};
+
+/**
+ * The synchronous version
+ */
+function AutoCompleteSyncSearch(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteSyncSearch.prototype = Object.create(AutoCompleteAsyncSearch.prototype);
+AutoCompleteSyncSearch.prototype.startSearch = function(aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener) {
+ this._returnResults(aListener);
+};
+
+/**
+ * Results object
+ */
+function AutoCompleteResult(aValues, aDefaultIndex) {
+ this._values = aValues;
+ this.defaultIndex = aDefaultIndex;
+}
+AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+
+/**
+ * Test AutoComplete with multiple AutoCompleteSearch sources, with one of them
+ * (index != 0) returning before the rest.
+ */
+function run_test() {
+ do_test_pending();
+
+ var results = ["mozillaTest"];
+ var inputStr = "moz";
+
+ // Async search
+ var asyncSearch = new AutoCompleteAsyncSearch("Async",
+ new AutoCompleteResult(results, -1));
+ // Sync search
+ var syncSearch = new AutoCompleteSyncSearch("Sync",
+ new AutoCompleteResult(results, 0));
+
+ // Register searches so AutoCompleteController can find them
+ registerAutoCompleteSearch(asyncSearch);
+ registerAutoCompleteSearch(syncSearch);
+
+ var controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our searches
+ // and confirms results on search complete.
+ // Async search MUST be FIRST to trigger the bug this tests.
+ var input = new AutoCompleteInputBase([asyncSearch.name, syncSearch.name]);
+ input.completeDefaultIndex = true;
+ input.textValue = inputStr;
+
+ // Caret must be at the end. Autofill doesn't happen unless you're typing
+ // characters at the end.
+ var strLen = inputStr.length;
+ input.selectTextRange(strLen, strLen);
+
+ controller.input = input;
+ controller.startSearch(inputStr);
+
+ input.onSearchComplete = function() {
+ do_check_eq(input.textValue, results[0]);
+
+ // Unregister searches
+ unregisterAutoCompleteSearch(asyncSearch);
+ unregisterAutoCompleteSearch(syncSearch);
+ do_test_finished();
+ };
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js
new file mode 100644
index 000000000..7fee48d55
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js
@@ -0,0 +1,276 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Dummy nsIAutoCompleteInput source that returns
+ * the given list of AutoCompleteSearch names.
+ *
+ * Implements only the methods needed for this test.
+ */
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+}
+AutoCompleteInput.prototype = {
+ constructor: AutoCompleteInput,
+
+ // Array of AutoCompleteSearch names
+ searches: null,
+
+ minResultsForPopup: 0,
+ timeout: 10,
+ searchParam: "",
+ textValue: "",
+ disableAutoComplete: false,
+ completeDefaultIndex: false,
+
+ get searchCount() {
+ return this.searches.length;
+ },
+
+ getSearchAt: function(aIndex) {
+ return this.searches[aIndex];
+ },
+
+ onSearchBegin: function() {},
+ onSearchComplete: function() {},
+
+ popupOpen: false,
+
+ popup: {
+ setSelectedIndex: function(aIndex) {},
+ invalidate: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompletePopup))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+ },
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteInput))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+
+/**
+ * nsIAutoCompleteResult implementation
+ */
+function AutoCompleteResult(aValues, aComments, aStyles) {
+ this._values = aValues;
+ this._comments = aComments;
+ this._styles = aStyles;
+}
+AutoCompleteResult.prototype = {
+ constructor: AutoCompleteResult,
+
+ // Arrays
+ _values: null,
+ _comments: null,
+ _styles: null,
+
+ searchString: "",
+ searchResult: null,
+
+ defaultIndex: 0,
+
+ get matchCount() {
+ return this._values.length;
+ },
+
+ getValueAt: function(aIndex) {
+ return this._values[aIndex];
+ },
+
+ getLabelAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ getCommentAt: function(aIndex) {
+ return this._comments[aIndex];
+ },
+
+ getStyleAt: function(aIndex) {
+ return this._styles[aIndex];
+ },
+
+ getImageAt: function(aIndex) {
+ return "";
+ },
+
+ getFinalCompleteValueAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteResult))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+
+/**
+ * nsIAutoCompleteSearch implementation that always returns
+ * the same result set.
+ */
+function AutoCompleteSearch(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteSearch.prototype = {
+ constructor: AutoCompleteSearch,
+
+ // Search name. Used by AutoCompleteController
+ name: null,
+
+ // AutoCompleteResult
+ _result:null,
+
+
+ /**
+ * Return the same result set for every search
+ */
+ startSearch: function(aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener)
+ {
+ var result = this._result;
+ if (result._values.length > 0) {
+ result.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS_ONGOING;
+ } else {
+ result.searchResult = Ci.nsIAutoCompleteResult.RESULT_NOMATCH_ONGOING;
+ }
+ aListener.onSearchResult(this, result);
+
+ if (result._values.length > 0) {
+ result.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
+ } else {
+ result.searchResult = Ci.nsIAutoCompleteResult.RESULT_NOMATCH;
+ }
+ aListener.onSearchResult(this, result);
+ },
+
+ stopSearch: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIFactory) ||
+ iid.equals(Ci.nsIAutoCompleteSearch))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ },
+
+ // nsIFactory implementation
+ createInstance: function(outer, iid) {
+ return this.QueryInterface(iid);
+ }
+}
+
+
+
+/**
+ * Helper to register an AutoCompleteSearch with the given name.
+ * Allows the AutoCompleteController to find the search.
+ */
+function registerAutoCompleteSearch(aSearch) {
+ var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
+
+ var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
+ getService(Ci.nsIUUIDGenerator);
+ var cid = uuidGenerator.generateUUID();
+
+ var desc = "Test AutoCompleteSearch";
+
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.registerFactory(cid, desc, name, aSearch);
+
+ // Keep the id on the object so we can unregister later
+ aSearch.cid = cid;
+}
+
+
+
+/**
+ * Helper to unregister an AutoCompleteSearch.
+ */
+function unregisterAutoCompleteSearch(aSearch) {
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.unregisterFactory(aSearch.cid, aSearch);
+}
+
+
+
+/**
+ * Test AutoComplete with multiple AutoCompleteSearch sources.
+ */
+function run_test() {
+ var expected1 = ["1", "2", "3"];
+ var expected2 = ["a", "b", "c"];
+ var search1 = new AutoCompleteSearch("search1",
+ new AutoCompleteResult(expected1, [], []));
+ var search2 = new AutoCompleteSearch("search2",
+ new AutoCompleteResult(expected2, [], []));
+
+ // Register searches so AutoCompleteController can find them
+ registerAutoCompleteSearch(search1);
+ registerAutoCompleteSearch(search2);
+
+ var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
+ getService(Components.interfaces.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our searches
+ // and confirms results on search complete
+ var input = new AutoCompleteInput([search1.name, search2.name]);
+ var numSearchesStarted = 0;
+
+ input.onSearchBegin = function() {
+ numSearchesStarted++;
+ do_check_eq(numSearchesStarted, 1);
+ };
+
+ input.onSearchComplete = function() {
+
+ do_check_eq(numSearchesStarted, 1);
+
+ do_check_eq(controller.searchStatus,
+ Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
+ do_check_eq(controller.matchCount, expected1.length + expected2.length);
+
+ // Unregister searches
+ unregisterAutoCompleteSearch(search1);
+ unregisterAutoCompleteSearch(search2);
+
+ do_test_finished();
+ };
+
+ controller.input = input;
+
+ // Search is asynchronous, so don't let the test finish immediately
+ do_test_pending();
+
+ controller.startSearch("test");
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js b/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js
new file mode 100644
index 000000000..c98db7f8f
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js
@@ -0,0 +1,45 @@
+"use strict";
+
+Cu.import("resource://gre/modules/Promise.jsm");
+
+function AutoCompleteInput(aSearches, aUserContextId) {
+ this.searches = aSearches;
+ this.userContextId = aUserContextId;
+ this.popup.selectedIndex = -1;
+}
+AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
+
+function AutoCompleteSearch(aName) {
+ this.name = aName;
+}
+AutoCompleteSearch.prototype = Object.create(AutoCompleteSearchBase.prototype);
+
+add_task(function *test_userContextId() {
+ let searchParam = yield doSearch("test", 1);
+ Assert.equal(searchParam, " user-context-id:1");
+});
+
+function doSearch(aString, aUserContextId) {
+ let deferred = Promise.defer();
+ let search = new AutoCompleteSearch("test");
+
+ search.startSearch = function (aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener) {
+ unregisterAutoCompleteSearch(search);
+ deferred.resolve(aSearchParam);
+ };
+
+ registerAutoCompleteSearch(search);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ let input = new AutoCompleteInput([ search.name ], aUserContextId);
+ controller.input = input;
+ controller.startSearch(aString);
+
+ return deferred.promise;
+ }
+
diff --git a/toolkit/components/autocomplete/tests/unit/test_autofillSelectedPopupIndex.js b/toolkit/components/autocomplete/tests/unit/test_autofillSelectedPopupIndex.js
new file mode 100644
index 000000000..5fb93abc1
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_autofillSelectedPopupIndex.js
@@ -0,0 +1,78 @@
+"use strict";
+
+add_task(function* sameCaseAsMatch() {
+ yield runTest("moz");
+});
+
+add_task(function* differentCaseFromMatch() {
+ yield runTest("MOZ");
+});
+
+function* runTest(searchStr) {
+ let matches = [
+ "mozilla.org",
+ "example.com",
+ ];
+ let result = new AutoCompleteResultBase(matches);
+ result.defaultIndex = 0;
+
+ let search = new AutoCompleteSearchBase("search", result);
+ registerAutoCompleteSearch(search);
+
+ let input = new AutoCompleteInputBase([search.name]);
+ input.completeSelectedIndex = true;
+ input.completeDefaultIndex = true;
+
+ // Start off with the search string in the input. The selection must be
+ // collapsed and the caret must be at the end to trigger autofill below.
+ input.textValue = searchStr;
+ input.selectTextRange(searchStr.length, searchStr.length);
+ Assert.equal(input.selectionStart, searchStr.length,
+ "Selection should start at the end of the input");
+ Assert.equal(input.selectionEnd, searchStr.length,
+ "Selection should end at the end of the input");
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ createInstance(Ci.nsIAutoCompleteController);
+ controller.input = input;
+ input.controller = controller;
+
+ // Start a search.
+ yield new Promise(resolve => {
+ controller.startSearch(searchStr);
+ input.onSearchComplete = () => {
+ // The first match should have autofilled, but the case of the search
+ // string should be preserved.
+ let expectedValue = searchStr + matches[0].substr(searchStr.length);
+ Assert.equal(input.textValue, expectedValue,
+ "Should have autofilled");
+ Assert.equal(input.selectionStart, searchStr.length,
+ "Selection should start after search string");
+ Assert.equal(input.selectionEnd, expectedValue.length,
+ "Selection should end at the end of the input");
+ resolve();
+ };
+ });
+
+ // Key down to select the second match in the popup.
+ controller.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_DOWN);
+ let expectedValue = matches[1];
+ Assert.equal(input.textValue, expectedValue,
+ "Should have filled second match");
+ Assert.equal(input.selectionStart, expectedValue.length,
+ "Selection should start at the end of the input");
+ Assert.equal(input.selectionEnd, expectedValue.length,
+ "Selection should end at the end of the input");
+
+ // Key up to select the first match again. The input should be restored
+ // exactly as it was when the first match was autofilled above: the search
+ // string's case should be preserved, and the selection should be preserved.
+ controller.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_UP);
+ expectedValue = searchStr + matches[0].substr(searchStr.length);
+ Assert.equal(input.textValue, expectedValue,
+ "Should have filled first match again");
+ Assert.equal(input.selectionStart, searchStr.length,
+ "Selection should start after search string again");
+ Assert.equal(input.selectionEnd, expectedValue.length,
+ "Selection should end at the end of the input again");
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js b/toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js
new file mode 100644
index 000000000..17f735388
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js
@@ -0,0 +1,96 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * A results that wants to defaultComplete to 0, but it has no matches,
+ * though it notifies SUCCESS to the controller.
+ */
+function AutoCompleteNoMatchResult() {
+ this.defaultIndex = 0;
+}
+AutoCompleteNoMatchResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+/**
+ * A results that wants to defaultComplete to an index greater than the number
+ * of matches.
+ */
+function AutoCompleteBadIndexResult(aValues, aDefaultIndex) {
+ do_check_true(aValues.length <= aDefaultIndex);
+ this._values = aValues;
+ this.defaultIndex = aDefaultIndex;
+}
+AutoCompleteBadIndexResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+add_test(function autocomplete_noMatch_success() {
+ const INPUT_STR = "moz";
+
+ let searchNoMatch =
+ new AutoCompleteSearchBase("searchNoMatch",
+ new AutoCompleteNoMatchResult());
+ registerAutoCompleteSearch(searchNoMatch);
+
+ // Make an AutoCompleteInput that uses our search and confirms results.
+ let input = new AutoCompleteInputBase([searchNoMatch.name]);
+ input.completeDefaultIndex = true;
+ input.textValue = INPUT_STR;
+
+ // Caret must be at the end for autoFill to happen.
+ let strLen = INPUT_STR.length;
+ input.selectTextRange(strLen, strLen);
+ do_check_eq(input.selectionStart, strLen);
+ do_check_eq(input.selectionEnd, strLen);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+ controller.input = input;
+ controller.startSearch(INPUT_STR);
+
+ input.onSearchComplete = function () {
+ // Should not try to autoFill to an empty value.
+ do_check_eq(input.textValue, "moz");
+
+ // Clean up.
+ unregisterAutoCompleteSearch(searchNoMatch);
+ run_next_test();
+ };
+});
+
+add_test(function autocomplete_defaultIndex_exceeds_matchCount() {
+ const INPUT_STR = "moz";
+
+ // Result returning matches, but a bad defaultIndex.
+ let searchBadIndex =
+ new AutoCompleteSearchBase("searchBadIndex",
+ new AutoCompleteBadIndexResult(["mozillaTest"], 1));
+ registerAutoCompleteSearch(searchBadIndex);
+
+ // Make an AutoCompleteInput that uses our search and confirms results.
+ let input = new AutoCompleteInputBase([searchBadIndex.name]);
+ input.completeDefaultIndex = true;
+ input.textValue = INPUT_STR;
+
+ // Caret must be at the end for autoFill to happen.
+ let strLen = INPUT_STR.length;
+ input.selectTextRange(strLen, strLen);
+ do_check_eq(input.selectionStart, strLen);
+ do_check_eq(input.selectionEnd, strLen);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+ controller.input = input;
+ controller.startSearch(INPUT_STR);
+
+ input.onSearchComplete = function () {
+ // Should not try to autoFill to an empty value.
+ do_check_eq(input.textValue, "moz");
+
+ // Clean up.
+ unregisterAutoCompleteSearch(searchBadIndex);
+ run_next_test();
+ };
+});
+
+function run_test() {
+ run_next_test();
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_completeDefaultIndex_casing.js b/toolkit/components/autocomplete/tests/unit/test_completeDefaultIndex_casing.js
new file mode 100644
index 000000000..c25b00907
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_completeDefaultIndex_casing.js
@@ -0,0 +1,63 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+function AutoCompleteResult(aValues) {
+ this._values = aValues;
+ this.defaultIndex = 0;
+}
+AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+ this.popup.selectedIndex = -1;
+ this.completeDefaultIndex = true;
+}
+AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
+
+function run_test() {
+ run_next_test();
+}
+
+add_test(function test_keyNavigation() {
+ doSearch("MOZ", "mozilla", function(aController) {
+ do_check_eq(aController.input.textValue, "MOZilla");
+ aController.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_RIGHT);
+ do_check_eq(aController.input.textValue, "mozilla");
+ });
+});
+
+add_test(function test_handleEnter() {
+ doSearch("MOZ", "mozilla", function(aController) {
+ do_check_eq(aController.input.textValue, "MOZilla");
+ aController.handleEnter(false);
+ do_check_eq(aController.input.textValue, "mozilla");
+ });
+});
+
+function doSearch(aSearchString, aResultValue, aOnCompleteCallback) {
+ let search = new AutoCompleteSearchBase("search",
+ new AutoCompleteResult([ "mozilla", "toolkit" ], 0));
+ registerAutoCompleteSearch(search);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our searches and confirms results.
+ let input = new AutoCompleteInput([ search.name ]);
+ input.textValue = aSearchString;
+
+ // Caret must be at the end for autofill to happen.
+ let strLen = aSearchString.length;
+ input.selectTextRange(strLen, strLen);
+ controller.input = input;
+ controller.startSearch(aSearchString);
+
+ input.onSearchComplete = function onSearchComplete() {
+ aOnCompleteCallback(controller);
+
+ // Clean up.
+ unregisterAutoCompleteSearch(search);
+ run_next_test();
+ };
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue.js b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue.js
new file mode 100644
index 000000000..fcac8ae43
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue.js
@@ -0,0 +1,48 @@
+function AutoCompleteResult(aValues, aFinalCompleteValues) {
+ this._values = aValues;
+ this._finalCompleteValues = aFinalCompleteValues;
+}
+AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+ this.popup.selectedIndex = 0;
+}
+AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
+
+add_test(function test_handleEnter_mouse() {
+ doSearch("moz", "mozilla.com", "http://www.mozilla.com", function(aController) {
+ do_check_eq(aController.input.textValue, "moz");
+ do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
+ // Keyboard interaction is tested by test_finalCompleteValueSelectedIndex.js
+ // so here just test popup selection.
+ aController.handleEnter(true);
+ do_check_eq(aController.input.textValue, "http://www.mozilla.com");
+ });
+});
+
+function doSearch(aSearchString, aResultValue, aFinalCompleteValue, aOnCompleteCallback) {
+ let search = new AutoCompleteSearchBase(
+ "search",
+ new AutoCompleteResult([ aResultValue ], [ aFinalCompleteValue ])
+ );
+ registerAutoCompleteSearch(search);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our searches and confirms results.
+ let input = new AutoCompleteInput([ search.name ]);
+ input.textValue = aSearchString;
+
+ controller.input = input;
+ controller.startSearch(aSearchString);
+
+ input.onSearchComplete = function onSearchComplete() {
+ aOnCompleteCallback(controller);
+
+ // Clean up.
+ unregisterAutoCompleteSearch(search);
+ run_next_test();
+ };
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValueSelectedIndex.js b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValueSelectedIndex.js
new file mode 100644
index 000000000..6556a26dc
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValueSelectedIndex.js
@@ -0,0 +1,119 @@
+function AutoCompleteResult(aResultValues) {
+ this._values = aResultValues.map(x => x[0]);
+ this._finalCompleteValues = aResultValues.map(x => x[1]);
+}
+AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+var selectByWasCalled = false;
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+ this.popup.selectedIndex = 0;
+ this.popup.selectBy = function(reverse, page) {
+ Assert.equal(selectByWasCalled, false);
+ selectByWasCalled = true;
+ Assert.equal(reverse, false);
+ Assert.equal(page, false);
+ this.selectedIndex += (reverse ? -1 : 1) * (page ? 100 : 1);
+ };
+ this.completeSelectedIndex = true;
+}
+AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
+
+add_test(function test_handleEnter_key() {
+ let results = [
+ ["mozilla.com", "http://www.mozilla.com"],
+ ["mozilla.org", "http://www.mozilla.org"],
+ ];
+ // First check the case where we do select a value with the keyboard:
+ doSearch("moz", results, function(aController) {
+ Assert.equal(aController.input.textValue, "moz");
+ Assert.equal(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
+ Assert.equal(aController.getFinalCompleteValueAt(1), "http://www.mozilla.org");
+
+ Assert.equal(aController.input.popup.selectedIndex, 0);
+ aController.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_DOWN);
+ Assert.equal(aController.input.popup.selectedIndex, 1);
+ // Simulate mouse interaction changing selectedIndex
+ // ie NOT keyboard interaction:
+ aController.input.popup.selectedIndex = 0;
+
+ aController.handleEnter(false);
+ // Verify that the keyboard-selected thing got inserted,
+ // and not the mouse selection:
+ Assert.equal(aController.input.textValue, "http://www.mozilla.org");
+ });
+});
+
+add_test(function test_handleEnter_mouse() {
+ let results = [
+ ["mozilla.com", "http://www.mozilla.com"],
+ ["mozilla.org", "http://www.mozilla.org"],
+ ];
+ // Then the case where we do not:
+ doSearch("moz", results, function(aController) {
+ Assert.equal(aController.input.textValue, "moz");
+ Assert.equal(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
+ Assert.equal(aController.getFinalCompleteValueAt(1), "http://www.mozilla.org");
+
+ Assert.equal(aController.input.popup.selectedIndex, 0);
+ aController.input.popupOpen = true;
+ // Simulate mouse interaction changing selectedIndex
+ // ie NOT keyboard interaction:
+ aController.input.popup.selectedIndex = 1;
+ Assert.equal(selectByWasCalled, false);
+ Assert.equal(aController.input.popup.selectedIndex, 1);
+
+ aController.handleEnter(false);
+ // Verify that the input stayed the same, because no selection was made
+ // with the keyboard:
+ Assert.equal(aController.input.textValue, "moz");
+ });
+});
+
+add_test(function test_handleEnter_preselected() {
+ let results = [
+ ["mozilla.com", "http://www.mozilla.com"],
+ ["mozilla.org", "http://www.mozilla.org"],
+ ];
+ // Then test a preselection.
+ doSearch("moz", results, function(aController) {
+ Assert.equal(aController.input.textValue, "moz");
+ Assert.equal(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
+ Assert.equal(aController.getFinalCompleteValueAt(1), "http://www.mozilla.org");
+
+ aController.setInitiallySelectedIndex(0);
+
+ aController.handleEnter(false);
+ // Verify that the input stayed the same, because no selection was made
+ // with the keyboard:
+ Assert.equal(aController.input.textValue, "http://www.mozilla.com");
+ });
+});
+
+function doSearch(aSearchString, aResults, aOnCompleteCallback) {
+ selectByWasCalled = false;
+ let search = new AutoCompleteSearchBase(
+ "search",
+ new AutoCompleteResult(aResults)
+ );
+ registerAutoCompleteSearch(search);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our searches and confirms results.
+ let input = new AutoCompleteInput([ search.name ]);
+ input.textValue = aSearchString;
+
+ controller.input = input;
+ controller.startSearch(aSearchString);
+
+ input.onSearchComplete = function onSearchComplete() {
+ aOnCompleteCallback(controller);
+
+ // Clean up.
+ unregisterAutoCompleteSearch(search);
+ run_next_test();
+ };
+}
+
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_defaultIndex.js b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_defaultIndex.js
new file mode 100644
index 000000000..4942e7a9f
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_defaultIndex.js
@@ -0,0 +1,107 @@
+function AutoCompleteResult(aResultValues) {
+ this.defaultIndex = 0;
+ this._values = aResultValues.map(x => x[0]);
+ this._finalCompleteValues = aResultValues.map(x => x[1]);
+}
+AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+ this.popup.selectedIndex = 0;
+ this.completeSelectedIndex = true;
+ this.completeDefaultIndex = true;
+}
+AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
+
+add_test(function test_handleEnter() {
+ let results = [
+ ["mozilla.com", "https://www.mozilla.com"],
+ ["gomozilla.org", "http://www.gomozilla.org"],
+ ];
+ doSearch("moz", results, { selectedIndex: 0 }, controller => {
+ let input = controller.input;
+ Assert.equal(input.textValue, "mozilla.com");
+ Assert.equal(controller.getFinalCompleteValueAt(0), results[0][1]);
+ Assert.equal(controller.getFinalCompleteValueAt(1), results[1][1]);
+ Assert.equal(input.popup.selectedIndex, 0);
+
+ controller.handleEnter(false);
+ // Verify that the keyboard-selected thing got inserted,
+ // and not the mouse selection:
+ Assert.equal(controller.input.textValue, "https://www.mozilla.com");
+ });
+});
+
+add_test(function test_handleEnter_otherSelected() {
+ // The popup selection may not coincide with what is filled into the input
+ // field, for example if the user changed it with the mouse and then pressed
+ // Enter. In such a case we should still use the inputField value and not the
+ // popup selected value.
+ let results = [
+ ["mozilla.com", "https://www.mozilla.com"],
+ ["gomozilla.org", "http://www.gomozilla.org"],
+ ];
+ doSearch("moz", results, { selectedIndex: 1 }, controller => {
+ let input = controller.input;
+ Assert.equal(input.textValue, "mozilla.com");
+ Assert.equal(controller.getFinalCompleteValueAt(0), results[0][1]);
+ Assert.equal(controller.getFinalCompleteValueAt(1), results[1][1]);
+ Assert.equal(input.popup.selectedIndex, 1);
+
+ controller.handleEnter(false);
+ // Verify that the keyboard-selected thing got inserted,
+ // and not the mouse selection:
+ Assert.equal(controller.input.textValue, "https://www.mozilla.com");
+ });
+});
+
+add_test(function test_handleEnter_otherSelected_nocompleteselectedindex() {
+ let results = [
+ ["mozilla.com", "https://www.mozilla.com"],
+ ["gomozilla.org", "http://www.gomozilla.org"],
+ ];
+ doSearch("moz", results, { selectedIndex: 1,
+ completeSelectedIndex: false }, controller => {
+ let input = controller.input;
+ Assert.equal(input.textValue, "mozilla.com");
+ Assert.equal(controller.getFinalCompleteValueAt(0), results[0][1]);
+ Assert.equal(controller.getFinalCompleteValueAt(1), results[1][1]);
+ Assert.equal(input.popup.selectedIndex, 1);
+
+ controller.handleEnter(false);
+ // Verify that the keyboard-selected result is inserted, not the
+ // defaultComplete.
+ Assert.equal(controller.input.textValue, "http://www.gomozilla.org");
+ });
+});
+
+function doSearch(aSearchString, aResults, aOptions, aOnCompleteCallback) {
+ let search = new AutoCompleteSearchBase(
+ "search",
+ new AutoCompleteResult(aResults)
+ );
+ registerAutoCompleteSearch(search);
+
+ let input = new AutoCompleteInput([ search.name ]);
+ input.textValue = aSearchString;
+ if ("selectedIndex" in aOptions) {
+ input.popup.selectedIndex = aOptions.selectedIndex;
+ }
+ if ("completeSelectedIndex" in aOptions) {
+ input.completeSelectedIndex = aOptions.completeSelectedIndex;
+ }
+ // Needed for defaultIndex completion.
+ input.selectTextRange(aSearchString.length, aSearchString.length);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+ controller.input = input;
+ controller.startSearch(aSearchString);
+
+ input.onSearchComplete = function onSearchComplete() {
+ aOnCompleteCallback(controller);
+
+ unregisterAutoCompleteSearch(search);
+ run_next_test();
+ };
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_forceComplete.js b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_forceComplete.js
new file mode 100644
index 000000000..5642d3e3e
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_forceComplete.js
@@ -0,0 +1,104 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+function AutoCompleteResult(aValues, aFinalCompleteValues) {
+ this._values = aValues;
+ this._finalCompleteValues = aFinalCompleteValues;
+ this.defaultIndex = 0;
+}
+AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+ this.popup.selectedIndex = -1;
+}
+AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
+
+function run_test() {
+ run_next_test();
+}
+
+add_test(function test_handleEnterWithDirectMatchCompleteSelectedIndex() {
+ doSearch("moz", "mozilla.com", "http://www.mozilla.com",
+ { forceComplete: true, completeSelectedIndex: true }, function(aController) {
+ do_check_eq(aController.input.textValue, "moz");
+ do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
+ aController.handleEnter(false);
+ // After enter the final complete value should be shown in the input.
+ do_check_eq(aController.input.textValue, "http://www.mozilla.com");
+ });
+});
+
+add_test(function test_handleEnterWithDirectMatch() {
+ doSearch("mozilla", "mozilla.com", "http://www.mozilla.com",
+ { forceComplete: true, completeDefaultIndex: true }, function(aController) {
+ // Should autocomplete the search string to a suggestion.
+ do_check_eq(aController.input.textValue, "mozilla.com");
+ do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
+ aController.handleEnter(false);
+ // After enter the final complete value should be shown in the input.
+ do_check_eq(aController.input.textValue, "http://www.mozilla.com");
+ });
+});
+
+add_test(function test_handleEnterWithNoMatch() {
+ doSearch("mozilla", "mozilla.com", "http://www.mozilla.com",
+ { forceComplete: true, completeDefaultIndex: true }, function(aController) {
+ // Should autocomplete the search string to a suggestion.
+ do_check_eq(aController.input.textValue, "mozilla.com");
+ do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
+ // Now input something that does not match...
+ aController.input.textValue = "mozillax";
+ // ... and confirm. We don't want one of the values from the previous
+ // results to be taken, since what's now in the input field doesn't match.
+ aController.handleEnter(false);
+ do_check_eq(aController.input.textValue, "mozillax");
+ });
+});
+
+add_test(function test_handleEnterWithIndirectMatch() {
+ doSearch("com", "mozilla.com", "http://www.mozilla.com",
+ { forceComplete: true, completeDefaultIndex: true }, function(aController) {
+ // Should autocomplete the search string to a suggestion.
+ do_check_eq(aController.input.textValue, "com >> mozilla.com");
+ do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
+ aController.handleEnter(false);
+ // After enter the final complete value from the suggestion should be shown
+ // in the input.
+ do_check_eq(aController.input.textValue, "http://www.mozilla.com");
+ });
+});
+
+function doSearch(aSearchString, aResultValue, aFinalCompleteValue,
+ aInputProps, aOnCompleteCallback) {
+ let search = new AutoCompleteSearchBase(
+ "search",
+ new AutoCompleteResult([ aResultValue ], [ aFinalCompleteValue ])
+ );
+ registerAutoCompleteSearch(search);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our searches and confirms results.
+ let input = new AutoCompleteInput([ search.name ]);
+ for (var p in aInputProps) {
+ input[p] = aInputProps[p];
+ }
+ input.textValue = aSearchString;
+ // Place the cursor at the end of the input so that completion to
+ // default index will kick in.
+ input.selectTextRange(aSearchString.length, aSearchString.length);
+
+ controller.input = input;
+ controller.startSearch(aSearchString);
+
+ input.onSearchComplete = function onSearchComplete() {
+ aOnCompleteCallback(controller);
+
+ // Clean up.
+ unregisterAutoCompleteSearch(search);
+ run_next_test();
+ };
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalDefaultCompleteValue.js b/toolkit/components/autocomplete/tests/unit/test_finalDefaultCompleteValue.js
new file mode 100644
index 000000000..c983d969b
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_finalDefaultCompleteValue.js
@@ -0,0 +1,66 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+function AutoCompleteResult(aValues, aFinalCompleteValues) {
+ this._values = aValues;
+ this._finalCompleteValues = aFinalCompleteValues;
+ this.defaultIndex = 0;
+}
+AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+ this.popup.selectedIndex = -1;
+ this.completeDefaultIndex = true;
+}
+AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
+
+function run_test() {
+ run_next_test();
+}
+
+add_test(function test_keyNavigation() {
+ doSearch("moz", "mozilla.com", "http://www.mozilla.com", function(aController) {
+ do_check_eq(aController.input.textValue, "mozilla.com");
+ aController.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_RIGHT);
+ do_check_eq(aController.input.textValue, "mozilla.com");
+ });
+});
+
+add_test(function test_handleEnter() {
+ doSearch("moz", "mozilla.com", "http://www.mozilla.com", function(aController) {
+ do_check_eq(aController.input.textValue, "mozilla.com");
+ aController.handleEnter(false);
+ do_check_eq(aController.input.textValue, "http://www.mozilla.com");
+ });
+});
+
+function doSearch(aSearchString, aResultValue, aFinalCompleteValue, aOnCompleteCallback) {
+ let search = new AutoCompleteSearchBase(
+ "search",
+ new AutoCompleteResult([ aResultValue ], [ aFinalCompleteValue ])
+ );
+ registerAutoCompleteSearch(search);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our searches and confirms results.
+ let input = new AutoCompleteInput([ search.name ]);
+ input.textValue = aSearchString;
+
+ // Caret must be at the end for autofill to happen.
+ let strLen = aSearchString.length;
+ input.selectTextRange(strLen, strLen);
+ controller.input = input;
+ controller.startSearch(aSearchString);
+
+ input.onSearchComplete = function onSearchComplete() {
+ aOnCompleteCallback(controller);
+
+ // Clean up.
+ unregisterAutoCompleteSearch(search);
+ run_next_test();
+ };
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_immediate_search.js b/toolkit/components/autocomplete/tests/unit/test_immediate_search.js
new file mode 100644
index 000000000..0579f5dcb
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_immediate_search.js
@@ -0,0 +1,157 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+function AutoCompleteImmediateSearch(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteImmediateSearch.prototype = Object.create(AutoCompleteSearchBase.prototype);
+AutoCompleteImmediateSearch.prototype.searchType =
+ Ci.nsIAutoCompleteSearchDescriptor.SEARCH_TYPE_IMMEDIATE;
+AutoCompleteImmediateSearch.prototype.QueryInterface =
+ XPCOMUtils.generateQI([Ci.nsIFactory,
+ Ci.nsIAutoCompleteSearch,
+ Ci.nsIAutoCompleteSearchDescriptor]);
+
+function AutoCompleteDelayedSearch(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteDelayedSearch.prototype = Object.create(AutoCompleteSearchBase.prototype);
+
+function AutoCompleteResult(aValues, aDefaultIndex) {
+ this._values = aValues;
+ this.defaultIndex = aDefaultIndex;
+}
+AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
+
+function run_test() {
+ run_next_test();
+}
+
+/**
+ * An immediate search should be executed synchronously.
+ */
+add_test(function test_immediate_search() {
+ let inputStr = "moz";
+
+ let immediateSearch = new AutoCompleteImmediateSearch(
+ "immediate", new AutoCompleteResult(["moz-immediate"], 0));
+ registerAutoCompleteSearch(immediateSearch);
+ let delayedSearch = new AutoCompleteDelayedSearch(
+ "delayed", new AutoCompleteResult(["moz-delayed"], 0));
+ registerAutoCompleteSearch(delayedSearch);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ let input = new AutoCompleteInputBase([delayedSearch.name,
+ immediateSearch.name]);
+ input.completeDefaultIndex = true;
+ input.textValue = inputStr;
+
+ // Caret must be at the end. Autofill doesn't happen unless you're typing
+ // characters at the end.
+ let strLen = inputStr.length;
+ input.selectTextRange(strLen, strLen);
+
+ controller.input = input;
+ controller.startSearch(inputStr);
+
+ // Immediately check the result, the immediate search should have finished.
+ do_check_eq(input.textValue, "moz-immediate");
+
+ // Wait for both queries to finish.
+ input.onSearchComplete = function() {
+ // Sanity check.
+ do_check_eq(input.textValue, "moz-immediate");
+
+ unregisterAutoCompleteSearch(immediateSearch);
+ unregisterAutoCompleteSearch(delayedSearch);
+ run_next_test();
+ };
+});
+
+/**
+ * An immediate search should be executed before any delayed search.
+ */
+add_test(function test_immediate_search_notimeout() {
+ let inputStr = "moz";
+
+ let immediateSearch = new AutoCompleteImmediateSearch(
+ "immediate", new AutoCompleteResult(["moz-immediate"], 0));
+ registerAutoCompleteSearch(immediateSearch);
+
+ let delayedSearch = new AutoCompleteDelayedSearch(
+ "delayed", new AutoCompleteResult(["moz-delayed"], 0));
+ registerAutoCompleteSearch(delayedSearch);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ let input = new AutoCompleteInputBase([delayedSearch.name,
+ immediateSearch.name]);
+ input.completeDefaultIndex = true;
+ input.textValue = inputStr;
+ input.timeout = 0;
+
+ // Caret must be at the end. Autofill doesn't happen unless you're typing
+ // characters at the end.
+ let strLen = inputStr.length;
+ input.selectTextRange(strLen, strLen);
+
+ controller.input = input;
+ let complete = false;
+ input.onSearchComplete = function() {
+ complete = true;
+ };
+ controller.startSearch(inputStr);
+ do_check_true(complete);
+
+ // Immediately check the result, the immediate search should have finished.
+ do_check_eq(input.textValue, "moz-immediate");
+
+ unregisterAutoCompleteSearch(immediateSearch);
+ unregisterAutoCompleteSearch(delayedSearch);
+ run_next_test();
+});
+
+/**
+ * A delayed search should be executed synchronously with a zero timeout.
+ */
+add_test(function test_delayed_search_notimeout() {
+ let inputStr = "moz";
+
+ let delayedSearch = new AutoCompleteDelayedSearch(
+ "delayed", new AutoCompleteResult(["moz-delayed"], 0));
+ registerAutoCompleteSearch(delayedSearch);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ let input = new AutoCompleteInputBase([delayedSearch.name]);
+ input.completeDefaultIndex = true;
+ input.textValue = inputStr;
+ input.timeout = 0;
+
+ // Caret must be at the end. Autofill doesn't happen unless you're typing
+ // characters at the end.
+ let strLen = inputStr.length;
+ input.selectTextRange(strLen, strLen);
+
+ controller.input = input;
+ let complete = false;
+ input.onSearchComplete = function() {
+ complete = true;
+ };
+ controller.startSearch(inputStr);
+ do_check_true(complete);
+
+ // Immediately check the result, the delayed search should have finished.
+ do_check_eq(input.textValue, "moz-delayed");
+
+ unregisterAutoCompleteSearch(delayedSearch);
+ run_next_test();
+});
diff --git a/toolkit/components/autocomplete/tests/unit/test_insertMatchAt.js b/toolkit/components/autocomplete/tests/unit/test_insertMatchAt.js
new file mode 100644
index 000000000..14ee388b8
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_insertMatchAt.js
@@ -0,0 +1,14 @@
+function run_test() {
+ let result = Cc["@mozilla.org/autocomplete/simple-result;1"]
+ .createInstance(Ci.nsIAutoCompleteSimpleResult);
+ result.appendMatch("a", "");
+ result.appendMatch("c", "");
+ result.insertMatchAt(1, "b", "");
+ result.insertMatchAt(3, "d", "");
+
+ Assert.equal(result.matchCount, 4);
+ Assert.equal(result.getValueAt(0), "a");
+ Assert.equal(result.getValueAt(1), "b");
+ Assert.equal(result.getValueAt(2), "c");
+ Assert.equal(result.getValueAt(3), "d");
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_previousResult.js b/toolkit/components/autocomplete/tests/unit/test_previousResult.js
new file mode 100644
index 000000000..bfe6c7aae
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_previousResult.js
@@ -0,0 +1,280 @@
+/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Unit test for Bug 438861 - Previous search results not returned to multiple
+ * searches.
+ */
+
+
+/**
+ * Dummy nsIAutoCompleteInput source that returns
+ * the given list of AutoCompleteSearch names.
+ *
+ * Implements only the methods needed for this test.
+ */
+function AutoCompleteInput(aSearches) {
+ this.searches = aSearches;
+}
+AutoCompleteInput.prototype = {
+ constructor: AutoCompleteInput,
+
+ // Array of AutoCompleteSearch names
+ searches: null,
+
+ minResultsForPopup: 0,
+ timeout: 10,
+ searchParam: "",
+ textValue: "",
+ disableAutoComplete: false,
+ completeDefaultIndex: false,
+
+ get searchCount() {
+ return this.searches.length;
+ },
+
+ getSearchAt: function(aIndex) {
+ return this.searches[aIndex];
+ },
+
+ onSearchBegin: function() {},
+ onSearchComplete: function() {},
+
+ popupOpen: false,
+
+ popup: {
+ setSelectedIndex: function(aIndex) {},
+ invalidate: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompletePopup))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+ },
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteInput))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+
+/**
+ * nsIAutoCompleteResult implementation
+ */
+function AutoCompleteResult(aValues, aComments, aStyles) {
+ this._values = aValues;
+ this._comments = aComments;
+ this._styles = aStyles;
+ if (this._values.length > 0) {
+ this.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
+ } else {
+ this.searchResult = Ci.nsIAutoCompleteResult.NOMATCH;
+ }
+}
+AutoCompleteResult.prototype = {
+ constructor: AutoCompleteResult,
+
+ // Arrays
+ _values: null,
+ _comments: null,
+ _styles: null,
+
+ searchString: "",
+ searchResult: null,
+
+ defaultIndex: 0,
+
+ get matchCount() {
+ return this._values.length;
+ },
+
+ getValueAt: function(aIndex) {
+ return this._values[aIndex];
+ },
+
+ getLabelAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ getCommentAt: function(aIndex) {
+ return this._comments[aIndex];
+ },
+
+ getStyleAt: function(aIndex) {
+ return this._styles[aIndex];
+ },
+
+ getImageAt: function(aIndex) {
+ return "";
+ },
+
+ getFinalCompleteValueAt: function(aIndex) {
+ return this.getValueAt(aIndex);
+ },
+
+ removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIAutoCompleteResult))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ }
+}
+
+
+/**
+ * nsIAutoCompleteSearch implementation that always returns
+ * the same result set.
+ */
+function AutoCompleteSearch(aName, aResult) {
+ this.name = aName;
+ this._result = aResult;
+}
+AutoCompleteSearch.prototype = {
+ constructor: AutoCompleteSearch,
+
+ // Search name. Used by AutoCompleteController
+ name: null,
+
+ // AutoCompleteResult
+ _result: null,
+
+ _previousResult: null,
+
+
+ /**
+ * Return the same result set for every search
+ */
+ startSearch: function(aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener)
+ {
+ this._previousResult = aPreviousResult;
+ aListener.onSearchResult(this, this._result);
+ },
+
+ stopSearch: function() {},
+
+ // nsISupports implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIFactory) ||
+ iid.equals(Ci.nsIAutoCompleteSearch))
+ return this;
+
+ throw Components.results.NS_ERROR_NO_INTERFACE;
+ },
+
+ // nsIFactory implementation
+ createInstance: function(outer, iid) {
+ return this.QueryInterface(iid);
+ }
+}
+
+
+/**
+ * Helper to register an AutoCompleteSearch with the given name.
+ * Allows the AutoCompleteController to find the search.
+ */
+function registerAutoCompleteSearch(aSearch) {
+ var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
+
+ var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
+ getService(Ci.nsIUUIDGenerator);
+ var cid = uuidGenerator.generateUUID();
+
+ var desc = "Test AutoCompleteSearch";
+
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.registerFactory(cid, desc, name, aSearch);
+
+ // Keep the id on the object so we can unregister later
+ aSearch.cid = cid;
+}
+
+
+/**
+ * Helper to unregister an AutoCompleteSearch.
+ */
+function unregisterAutoCompleteSearch(aSearch) {
+ var componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.unregisterFactory(aSearch.cid, aSearch);
+}
+
+
+/**
+ */
+function run_test() {
+ // Make an AutoCompleteSearch that always returns nothing
+ var search1 = new AutoCompleteSearch("test-previous-result1",
+ new AutoCompleteResult(["hello1"], [""], [""]));
+
+ var search2 = new AutoCompleteSearch("test-previous-result2",
+ new AutoCompleteResult(["hello2"], [""], [""]));
+
+ // Register search so AutoCompleteController can find them
+ registerAutoCompleteSearch(search1);
+ registerAutoCompleteSearch(search2);
+
+ var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
+ getService(Components.interfaces.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our search
+ // and confirms results on search complete
+ var input = new AutoCompleteInput([search1.name,
+ search2.name]);
+ var numSearchesStarted = 0;
+
+ input.onSearchBegin = function() {
+ numSearchesStarted++;
+ };
+
+ input.onSearchComplete = function() {
+ do_check_eq(controller.searchStatus,
+ Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
+ do_check_eq(controller.matchCount, 2);
+
+ if (numSearchesStarted == 1) {
+ do_check_eq(search1._previousResult, null);
+ do_check_eq(search2._previousResult, null);
+
+ // Now start it again
+ controller.startSearch("test");
+ return;
+ }
+ do_check_neq(search1._previousResult, null);
+ do_check_neq(search2._previousResult, null);
+
+ // Unregister searches
+ unregisterAutoCompleteSearch(search1);
+ unregisterAutoCompleteSearch(search2);
+
+ do_test_finished();
+ };
+
+ controller.input = input;
+
+ // Search is asynchronous, so don't let the test finish immediately
+ do_test_pending();
+
+ controller.startSearch("test");
+}
diff --git a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js
new file mode 100644
index 000000000..5ef3454b4
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js
@@ -0,0 +1,187 @@
+/*
+ * Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+/**
+ * Purpose of the test is to check that a stopSearch call comes always before a
+ * startSearch call.
+ */
+
+Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+
+
+/**
+ * Dummy nsIAutoCompleteInput source that returns
+ * the given list of AutoCompleteSearch names.
+ *
+ * Implements only the methods needed for this test.
+ */
+function AutoCompleteInput(aSearches)
+{
+ this.searches = aSearches;
+}
+AutoCompleteInput.prototype = {
+ constructor: AutoCompleteInput,
+ minResultsForPopup: 0,
+ timeout: 10,
+ searchParam: "",
+ textValue: "hello",
+ disableAutoComplete: false,
+ completeDefaultIndex: false,
+ set popupOpen(val) { return val; }, // ignore
+ get popupOpen() { return false; },
+ get searchCount() { return this.searches.length; },
+ getSearchAt: function(aIndex) { return this.searches[aIndex]; },
+ onSearchBegin: function() {},
+ onSearchComplete: function() {},
+ onTextReverted: function () {},
+ onTextEntered: function () {},
+ popup: {
+ selectBy: function() {},
+ invalidate: function() {},
+ set selectedIndex(val) { return val; }, // ignore
+ get selectedIndex() { return -1 },
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup])
+ },
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput])
+}
+
+
+/**
+ * nsIAutoCompleteSearch implementation.
+ */
+function AutoCompleteSearch(aName)
+{
+ this.name = aName;
+}
+AutoCompleteSearch.prototype = {
+ constructor: AutoCompleteSearch,
+ stopSearchInvoked: true,
+ startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener)
+ {
+ print("Check stop search has been called");
+ do_check_true(this.stopSearchInvoked);
+ this.stopSearchInvoked = false;
+ },
+ stopSearch: function()
+ {
+ this.stopSearchInvoked = true;
+ },
+ QueryInterface: XPCOMUtils.generateQI([
+ Ci.nsIFactory
+ , Ci.nsIAutoCompleteSearch
+ ]),
+ createInstance: function(outer, iid)
+ {
+ return this.QueryInterface(iid);
+ }
+}
+
+
+/**
+ * Helper to register an AutoCompleteSearch with the given name.
+ * Allows the AutoCompleteController to find the search.
+ */
+function registerAutoCompleteSearch(aSearch)
+{
+ let name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
+ let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
+ getService(Ci.nsIUUIDGenerator);
+ let cid = uuidGenerator.generateUUID();
+ let desc = "Test AutoCompleteSearch";
+ let componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.registerFactory(cid, desc, name, aSearch);
+ // Keep the id on the object so we can unregister later
+ aSearch.cid = cid;
+}
+
+
+/**
+ * Helper to unregister an AutoCompleteSearch.
+ */
+function unregisterAutoCompleteSearch(aSearch) {
+ let componentManager = Components.manager
+ .QueryInterface(Ci.nsIComponentRegistrar);
+ componentManager.unregisterFactory(aSearch.cid, aSearch);
+}
+
+
+var gTests = [
+ function(controller) {
+ print("handleText");
+ controller.input.textValue = "hel";
+ controller.handleText();
+ },
+ function(controller) {
+ print("handleStartComposition");
+ controller.handleStartComposition();
+ },
+ function(controller) {
+ print("handleEndComposition");
+ controller.handleEndComposition();
+ // an input event always follows compositionend event.
+ controller.handleText();
+ },
+ function(controller) {
+ print("handleEscape");
+ controller.handleEscape();
+ },
+ function(controller) {
+ print("handleEnter");
+ controller.handleEnter(false);
+ },
+ function(controller) {
+ print("handleTab");
+ controller.handleTab();
+ },
+
+ function(controller) {
+ print("handleKeyNavigation");
+ controller.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_UP);
+ },
+];
+
+
+var gSearch;
+var gCurrentTest;
+function run_test() {
+ // Make an AutoCompleteSearch that always returns nothing
+ gSearch = new AutoCompleteSearch("test");
+ registerAutoCompleteSearch(gSearch);
+
+ let controller = Cc["@mozilla.org/autocomplete/controller;1"].
+ getService(Ci.nsIAutoCompleteController);
+
+ // Make an AutoCompleteInput that uses our search.
+ let input = new AutoCompleteInput([gSearch.name]);
+ controller.input = input;
+
+ input.onSearchBegin = function() {
+ do_execute_soon(function() {
+ gCurrentTest(controller);
+ });
+ };
+ input.onSearchComplete = function() {
+ run_next_test(controller);
+ }
+
+ // Search is asynchronous, so don't let the test finish immediately
+ do_test_pending();
+
+ run_next_test(controller);
+}
+
+function run_next_test(controller) {
+ if (gTests.length == 0) {
+ unregisterAutoCompleteSearch(gSearch);
+ controller.stopSearch();
+ controller.input = null;
+ do_test_finished();
+ return;
+ }
+
+ gCurrentTest = gTests.shift();
+ controller.startSearch("hello");
+}
diff --git a/toolkit/components/autocomplete/tests/unit/xpcshell.ini b/toolkit/components/autocomplete/tests/unit/xpcshell.ini
new file mode 100644
index 000000000..4d193965c
--- /dev/null
+++ b/toolkit/components/autocomplete/tests/unit/xpcshell.ini
@@ -0,0 +1,24 @@
+[DEFAULT]
+head = head_autocomplete.js
+tail =
+
+[test_330578.js]
+[test_378079.js]
+[test_393191.js]
+[test_440866.js]
+[test_463023.js]
+[test_660156.js]
+[test_autocomplete_multiple.js]
+[test_autocomplete_userContextId.js]
+[test_autofillSelectedPopupIndex.js]
+[test_badDefaultIndex.js]
+[test_completeDefaultIndex_casing.js]
+[test_finalCompleteValue.js]
+[test_finalCompleteValue_defaultIndex.js]
+[test_finalCompleteValue_forceComplete.js]
+[test_finalCompleteValueSelectedIndex.js]
+[test_finalDefaultCompleteValue.js]
+[test_immediate_search.js]
+[test_insertMatchAt.js]
+[test_previousResult.js]
+[test_stopSearch.js]