Merge remote-tracking branch 'origin/master' into custom

This commit is contained in:
Roy Tam 2019-04-27 09:01:02 +08:00
commit 2cb30a238c
4110 changed files with 343 additions and 435849 deletions

View file

@ -79,12 +79,8 @@ const DELAY_WARNING_MS = 10 * 1000;
// Crash the process if shutdown is really too long
// (allowing for sleep).
const PREF_DELAY_CRASH_MS = "toolkit.asyncshutdown.crash_timeout";
var DELAY_CRASH_MS = 60 * 1000; // One minute
try {
DELAY_CRASH_MS = Services.prefs.getIntPref(PREF_DELAY_CRASH_MS);
} catch (ex) {
// Ignore errors
}
var DELAY_CRASH_MS = Services.prefs.getIntPref(PREF_DELAY_CRASH_MS,
60 * 1000); // One minute
Services.prefs.addObserver(PREF_DELAY_CRASH_MS, function() {
DELAY_CRASH_MS = Services.prefs.getIntPref(PREF_DELAY_CRASH_MS);
}, false);
@ -207,12 +203,7 @@ function log(msg, prefix = "", error = null) {
}
}
const PREF_DEBUG_LOG = "toolkit.asyncshutdown.log";
var DEBUG_LOG = false;
try {
DEBUG_LOG = Services.prefs.getBoolPref(PREF_DEBUG_LOG);
} catch (ex) {
// Ignore errors
}
var DEBUG_LOG = Services.prefs.getBoolPref(PREF_DEBUG_LOG, false);
Services.prefs.addObserver(PREF_DEBUG_LOG, function() {
DEBUG_LOG = Services.prefs.getBoolPref(PREF_DEBUG_LOG);
}, false);
@ -360,12 +351,7 @@ this.AsyncShutdown = {
* Access function getPhase. For testing purposes only.
*/
get _getPhase() {
let accepted = false;
try {
accepted = Services.prefs.getBoolPref("toolkit.asyncshutdown.testing");
} catch (ex) {
// Ignore errors
}
let accepted = Services.prefs.getBoolPref("toolkit.asyncshutdown.testing", false);
if (accepted) {
return getPhase;
}
@ -464,12 +450,7 @@ function getPhase(topic) {
* notification. For testing purposes only.
*/
get _trigger() {
let accepted = false;
try {
accepted = Services.prefs.getBoolPref("toolkit.asyncshutdown.testing");
} catch (ex) {
// Ignore errors
}
let accepted = Services.prefs.getBoolPref("toolkit.asyncshutdown.testing", false);
if (accepted) {
return () => spinner.observe();
}

View file

@ -4,6 +4,8 @@
* 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/. */
#filter substitution
"use strict";
const Cc = Components.classes;
@ -27,9 +29,6 @@ XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
#ifdef MOZ_WEBEXTENSIONS
XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils",
"resource://gre/modules/UpdateUtils.jsm");
#else
XPCOMUtils.defineLazyModuleGetter(this, "UpdateChannel",
"resource://gre/modules/UpdateChannel.jsm");
#endif
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
@ -243,16 +242,7 @@ function getLocale() {
/* Get the distribution pref values, from defaults only */
function getDistributionPrefValue(aPrefName) {
var prefValue = "default";
var defaults = gPref.getDefaultBranch(null);
try {
prefValue = defaults.getCharPref(aPrefName);
} catch (e) {
// use default when pref not found
}
return prefValue;
return gPref.getDefaultBranch(null).getCharPref(aPrefName, "default");
}
/**
@ -539,13 +529,14 @@ Blocklist.prototype = {
pingCountTotal = 1;
dsURI = dsURI.replace(/%APP_ID%/g, gApp.ID);
// Not all applications implement nsIXULAppInfo (e.g. xpcshell doesn't).
if (gApp.version)
if (gApp.version) {
dsURI = dsURI.replace(/%APP_VERSION%/g, gApp.version);
dsURI = dsURI.replace(/%PRODUCT%/g, gApp.name);
// Not all applications implement nsIXULAppInfo (e.g. xpcshell doesn't).
if (gApp.version)
dsURI = dsURI.replace(/%VERSION%/g, gApp.version);
}
dsURI = dsURI.replace(/%PRODUCT%/g, gApp.name);
dsURI = dsURI.replace(/%BUILD_ID%/g, gApp.appBuildID);
dsURI = dsURI.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI);
dsURI = dsURI.replace(/%OS_VERSION%/g, gOSVersion);
@ -553,7 +544,7 @@ Blocklist.prototype = {
#ifdef MOZ_WEBEXTENSIONS
dsURI = dsURI.replace(/%CHANNEL%/g, UpdateUtils.UpdateChannel);
#else
dsURI = dsURI.replace(/%CHANNEL%/g, UpdateChannel.get());
dsURI = dsURI.replace(/%CHANNEL%/g, "@MOZ_UPDATE_CHANNEL@");
#endif
dsURI = dsURI.replace(/%PLATFORM_VERSION%/g, gApp.platformVersion);
dsURI = dsURI.replace(/%DISTRIBUTION%/g,

View file

@ -3,8 +3,6 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
toolkit.jar:
#ifndef MOZ_FENNEC
% content cookie %content/cookie/
content/cookie/cookieAcceptDialog.xul (content/cookieAcceptDialog.xul)
content/cookie/cookieAcceptDialog.js (content/cookieAcceptDialog.js)
#endif

View file

@ -368,11 +368,7 @@ this.DownloadIntegration = {
*/
getPreferredDownloadsDirectory: Task.async(function* () {
let directoryPath = null;
let prefValue = 1;
try {
prefValue = Services.prefs.getIntPref("browser.download.folderList");
} catch(e) {}
let prefValue = Services.prefs.getIntPref("browser.download.folderList", 1);
switch(prefValue) {
case 0: // Desktop

View file

@ -89,7 +89,9 @@ if CONFIG['MOZ_XUL']:
if 'gtk' in CONFIG['MOZ_WIDGET_TOOLKIT']:
DIRS += ['filepicker']
if CONFIG['MOZ_TOOLKIT_SEARCH']:
if CONFIG['MOZ_TOOLKIT_SEARCH'] and not CONFIG['MC_BASILISK'] \
and not CONFIG['HYPE_ICEWEASEL'] \
and not CONFIG['HYPE_ICEDOVE']:
DIRS += ['search']
if CONFIG['MOZ_URL_CLASSIFIER']:

View file

@ -104,13 +104,7 @@ nsDefaultCLH.prototype = {
// if the pref is missing, ignore the exception
try {
var chromeURI = prefs.getCharPref("toolkit.defaultChromeURI");
var flags = "chrome,dialog=no,all";
try {
flags = prefs.getCharPref("toolkit.defaultChromeFeatures");
}
catch (e) { }
var flags = prefs.getCharPref("toolkit.defaultChromeFeatures", "chrome,dialog=no,all");
var wwatch = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
.getService(nsIWindowWatcher);
wwatch.openWindow(null, chromeURI, "_blank",

View file

@ -239,10 +239,9 @@ var Scheduler = this.Scheduler = {
* Prepare to kill the OS.File worker after a few seconds.
*/
restartTimer: function(arg) {
let delay;
try {
delay = Services.prefs.getIntPref("osfile.reset_worker_delay");
} catch(e) {
let delay = Services.prefs.getIntPref("osfile.reset_worker_delay", 0);
if (!delay) {
// Don't auto-shutdown if we don't have a delay preference set.
return;
}
@ -468,43 +467,25 @@ var Scheduler = this.Scheduler = {
const PREF_OSFILE_LOG = "toolkit.osfile.log";
const PREF_OSFILE_LOG_REDIRECT = "toolkit.osfile.log.redirect";
/**
* Safely read a PREF_OSFILE_LOG preference.
* Returns a value read or, in case of an error, oldPref or false.
*
* @param bool oldPref
* An optional value that the DEBUG flag was set to previously.
*/
function readDebugPref(prefName, oldPref = false) {
let pref = oldPref;
try {
pref = Services.prefs.getBoolPref(prefName);
} catch (x) {
// In case of an error when reading a pref keep it as is.
}
// If neither pref nor oldPref were set, default it to false.
return pref;
};
/**
* Listen to PREF_OSFILE_LOG changes and update gShouldLog flag
* appropriately.
*/
Services.prefs.addObserver(PREF_OSFILE_LOG,
function prefObserver(aSubject, aTopic, aData) {
SharedAll.Config.DEBUG = readDebugPref(PREF_OSFILE_LOG, SharedAll.Config.DEBUG);
SharedAll.Config.DEBUG = Services.prefs.getBoolPref(PREF_OSFILE_LOG, SharedAll.Config.DEBUG);
if (Scheduler.launched) {
// Don't start the worker just to set this preference.
Scheduler.post("SET_DEBUG", [SharedAll.Config.DEBUG]);
}
}, false);
SharedAll.Config.DEBUG = readDebugPref(PREF_OSFILE_LOG, false);
SharedAll.Config.DEBUG = Services.prefs.getBoolPref(PREF_OSFILE_LOG, false);
Services.prefs.addObserver(PREF_OSFILE_LOG_REDIRECT,
function prefObserver(aSubject, aTopic, aData) {
SharedAll.Config.TEST = readDebugPref(PREF_OSFILE_LOG_REDIRECT, OS.Shared.TEST);
SharedAll.Config.TEST = Services.prefs.getBoolPref(PREF_OSFILE_LOG_REDIRECT, OS.Shared.TEST);
}, false);
SharedAll.Config.TEST = readDebugPref(PREF_OSFILE_LOG_REDIRECT, false);
SharedAll.Config.TEST = Services.prefs.getBoolPref(PREF_OSFILE_LOG_REDIRECT, false);
/**
@ -515,7 +496,7 @@ var nativeWheneverAvailable = true;
const PREF_OSFILE_NATIVE = "toolkit.osfile.native";
Services.prefs.addObserver(PREF_OSFILE_NATIVE,
function prefObserver(aSubject, aTopic, aData) {
nativeWheneverAvailable = readDebugPref(PREF_OSFILE_NATIVE, nativeWheneverAvailable);
nativeWheneverAvailable = Services.prefs.getBoolPref(PREF_OSFILE_NATIVE, nativeWheneverAvailable);
}, false);
@ -557,12 +538,8 @@ Services.prefs.addObserver(PREF_OSFILE_TEST_SHUTDOWN_OBSERVER,
function prefObserver() {
// The temporary phase topic used to trigger the unclosed
// phase warning.
let TOPIC = null;
try {
TOPIC = Services.prefs.getCharPref(
PREF_OSFILE_TEST_SHUTDOWN_OBSERVER);
} catch (x) {
}
let TOPIC = Services.prefs.getCharPref(PREF_OSFILE_TEST_SHUTDOWN_OBSERVER,
"");
if (TOPIC) {
// Generate a phase, add a blocker.
// Note that this can work only if AsyncShutdown itself has been

View file

@ -2,11 +2,6 @@
This form triggers a MP and gets filled in.<br>
<form>
Username: <input type="text" id="userfield" name="u"><br>
Password: <input type="password" id="passfield" name="p"><br>
<script>
// Only notify when we fill in the password field.
document.getElementById("passfield").addEventListener("input", function() {
parent.postMessage("filled", "*");
});
</script>
Password: <input type="password" id="passfield" name="p"
oninput="parent.postMessage('filled', '*');"><br>
</form>

View file

@ -77,11 +77,8 @@ PlacesCategoriesStarter.prototype = {
break;
case "idle-daily":
// Once a week run places.sqlite maintenance tasks.
let lastMaintenance = 0;
try {
lastMaintenance =
Services.prefs.getIntPref("places.database.lastMaintenance");
} catch (ex) {}
let lastMaintenance =
Services.prefs.getIntPref("places.database.lastMaintenance", 0);
let nowSeconds = parseInt(Date.now() / 1000);
if (lastMaintenance < nowSeconds - MAINTENANCE_INTERVAL_SECONDS) {
PlacesDBUtils.maintenanceOnIdle();

View file

@ -95,11 +95,7 @@ function observe(subject, topic, data) {
case "nsPref:changed":
if (data == PREF_SHOW_REMOTE_ICONS) {
try {
showRemoteIcons = Services.prefs.getBoolPref(PREF_SHOW_REMOTE_ICONS);
} catch (_) {
showRemoteIcons = true; // no such pref - default is to show the icons.
}
showRemoteIcons = Services.prefs.getBoolPref(PREF_SHOW_REMOTE_ICONS, true);
}
break;

View file

@ -464,10 +464,7 @@ XPCOMUtils.defineLazyGetter(this, "Prefs", () => {
store.suggestTyped = prefs.get(...PREF_SUGGEST_HISTORY_ONLYTYPED);
store.suggestSearches = prefs.get(...PREF_SUGGEST_SEARCHES);
store.maxCharsForSearchSuggestions = prefs.get(...PREF_MAX_CHARS_FOR_SUGGEST);
store.keywordEnabled = true;
try {
store.keywordEnabled = Services.prefs.getBoolPref("keyword.enabled");
} catch (ex) {}
store.keywordEnabled = Services.prefs.getBoolPref("keyword.enabled", true);
// If history is not set, onlyTyped value should be ignored.
if (!store.suggestHistory) {

View file

@ -812,11 +812,8 @@ nsPlacesExpiration.prototype = {
_loadPrefs: Task.async(function* () {
// Get the user's limit, if it was set.
try {
// We want to silently fail since getIntPref throws if it does not exist,
// and use a default to fallback to.
this._urisLimit = this._prefBranch.getIntPref(PREF_MAX_URIS);
} catch (ex) { /* User limit not set */ }
this._urisLimit = this._prefBranch.getIntPref(PREF_MAX_URIS,
PREF_MAX_URIS_NOTSET);
if (this._urisLimit < 0) {
// Some testing code expects a pref change to be synchronous, so
@ -874,11 +871,8 @@ nsPlacesExpiration.prototype = {
this._urisLimit);
// Get the expiration interval value.
try {
// We want to silently fail since getIntPref throws if it does not exist,
// and use a default to fallback to.
this._interval = this._prefBranch.getIntPref(PREF_INTERVAL_SECONDS);
} catch (ex) { /* User interval not set */ }
this._interval = this._prefBranch.getIntPref(PREF_INTERVAL_SECONDS,
PREF_INTERVAL_SECONDS_NOTSET);
if (this._interval <= 0) {
this._interval = PREF_INTERVAL_SECONDS_NOTSET;
}

View file

@ -56,14 +56,8 @@ var prefPrefix = "places.frecency.";
function* task_initializeBucket(bucket) {
let [cutoffName, weightName] = bucket;
// get pref values
var weight = 0, cutoff = 0;
try {
weight = prefs.getIntPref(prefPrefix + weightName);
} catch (ex) {}
try {
cutoff = prefs.getIntPref(prefPrefix + cutoffName);
} catch (ex) {}
var weight = prefs.getIntPref(prefPrefix + weightName, 0);
var cutoff = prefs.getIntPref(prefPrefix + cutoffName, 0);
if (cutoff < 1)
return;

View file

@ -65,14 +65,7 @@ function initDialog()
// ---------------------------------------------------
function isListOfPrinterFeaturesAvailable()
{
var has_printerfeatures = false;
try {
has_printerfeatures = gPrefs.getBoolPref("print.tmp.printerfeatures." + gPrintSettings.printerName + ".has_special_printerfeatures");
} catch (ex) {
}
return has_printerfeatures;
return gPrefs.getBoolPref("print.tmp.printerfeatures." + gPrintSettings.printerName + ".has_special_printerfeatures", false);
}
// ---------------------------------------------------

View file

@ -79,15 +79,7 @@ function stripTrailingWhitespace(element)
// ---------------------------------------------------
function getPrinterDescription(printerName)
{
var s = "";
try {
/* This may not work with non-ASCII test (see bug 235763 comment #16) */
s = gPrefs.getCharPref("print.printer_" + printerName + ".printer_description")
} catch (e) {
}
return s;
return gPrefs.getCharPref("print.printer_" + printerName + ".printer_description", "")
}
// ---------------------------------------------------

View file

@ -33,14 +33,7 @@ function checkDouble(element, maxVal)
// ---------------------------------------------------
function isListOfPrinterFeaturesAvailable()
{
var has_printerfeatures = false;
try {
has_printerfeatures = gPrefs.getBoolPref("print.tmp.printerfeatures." + gPrintSettings.printerName + ".has_special_printerfeatures");
} catch (ex) {
}
return has_printerfeatures;
return gPrefs.getBoolPref("print.tmp.printerfeatures." + gPrintSettings.printerName + ".has_special_printerfeatures", false);
}
// ---------------------------------------------------

View file

@ -1,398 +0,0 @@
/* 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/. */
"use strict";
this.EXPORTED_SYMBOLS = ["SearchSuggestionController"];
const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NS_ASSERT", "resource://gre/modules/debug.js");
const SEARCH_RESPONSE_SUGGESTION_JSON = "application/x-suggestions+json";
const DEFAULT_FORM_HISTORY_PARAM = "searchbar-history";
const HTTP_OK = 200;
const REMOTE_TIMEOUT = 500; // maximum time (ms) to wait before giving up on a remote suggestions
const BROWSER_SUGGEST_PREF = "browser.search.suggest.enabled";
/**
* Remote search suggestions will be shown if gRemoteSuggestionsEnabled
* is true. Global because only one pref observer is needed for all instances.
*/
var gRemoteSuggestionsEnabled = Services.prefs.getBoolPref(BROWSER_SUGGEST_PREF);
Services.prefs.addObserver(BROWSER_SUGGEST_PREF, function(aSubject, aTopic, aData) {
gRemoteSuggestionsEnabled = Services.prefs.getBoolPref(BROWSER_SUGGEST_PREF);
}, false);
/**
* SearchSuggestionController.jsm exists as a helper module to allow multiple consumers to request and display
* search suggestions from a given engine, regardless of the base implementation. Much of this
* code was originally in nsSearchSuggestions.js until it was refactored to separate it from the
* nsIAutoCompleteSearch dependency.
* One instance of SearchSuggestionController should be used per field since form history results are cached.
*/
/**
* @param {function} [callback] - Callback for search suggestion results. You can use the promise
* returned by the search method instead if you prefer.
* @constructor
*/
this.SearchSuggestionController = function SearchSuggestionController(callback = null) {
this._callback = callback;
};
this.SearchSuggestionController.prototype = {
/**
* The maximum number of local form history results to return. This limit is
* only enforced if remote results are also returned.
*/
maxLocalResults: 5,
/**
* The maximum number of remote search engine results to return.
* We'll actually only display at most
* maxRemoteResults - <displayed local results count> remote results.
*/
maxRemoteResults: 10,
/**
* The maximum time (ms) to wait before giving up on a remote suggestions.
*/
remoteTimeout: REMOTE_TIMEOUT,
/**
* The additional parameter used when searching form history.
*/
formHistoryParam: DEFAULT_FORM_HISTORY_PARAM,
// Private properties
/**
* The last form history result used to improve the performance of subsequent searches.
* This shouldn't be used for any other purpose as it is never cleared and therefore could be stale.
*/
_formHistoryResult: null,
/**
* The remote server timeout timer, if applicable. The timer starts when form history
* search is completed.
*/
_remoteResultTimer: null,
/**
* The deferred for the remote results before its promise is resolved.
*/
_deferredRemoteResult: null,
/**
* The optional result callback registered from the constructor.
*/
_callback: null,
/**
* The XMLHttpRequest object for remote results.
*/
_request: null,
// Public methods
/**
* Fetch search suggestions from all of the providers. Fetches in progress will be stopped and
* results from them will not be provided.
*
* @param {string} searchTerm - the term to provide suggestions for
* @param {bool} privateMode - whether the request is being made in the context of private browsing
* @param {nsISearchEngine} engine - search engine for the suggestions.
* @param {int} userContextId - the userContextId of the selected tab.
*
* @return {Promise} resolving to an object containing results or null.
*/
fetch: function(searchTerm, privateMode, engine, userContextId) {
// There is no smart filtering from previous results here (as there is when looking through
// history/form data) because the result set returned by the server is different for every typed
// value - e.g. "ocean breathes" does not return a subset of the results returned for "ocean".
this.stop();
if (!Services.search.isInitialized) {
throw new Error("Search not initialized yet (how did you get here?)");
}
if (typeof privateMode === "undefined") {
throw new Error("The privateMode argument is required to avoid unintentional privacy leaks");
}
if (!(engine instanceof Ci.nsISearchEngine)) {
throw new Error("Invalid search engine");
}
if (!this.maxLocalResults && !this.maxRemoteResults) {
throw new Error("Zero results expected, what are you trying to do?");
}
if (this.maxLocalResults < 0 || this.maxRemoteResults < 0) {
throw new Error("Number of requested results must be positive");
}
// Array of promises to resolve before returning results.
let promises = [];
this._searchString = searchTerm;
// Remote results
if (searchTerm && gRemoteSuggestionsEnabled && this.maxRemoteResults &&
engine.supportsResponseType(SEARCH_RESPONSE_SUGGESTION_JSON)) {
this._deferredRemoteResult = this._fetchRemote(searchTerm, engine, privateMode, userContextId);
promises.push(this._deferredRemoteResult.promise);
}
// Local results from form history
if (this.maxLocalResults) {
let deferredHistoryResult = this._fetchFormHistory(searchTerm);
promises.push(deferredHistoryResult.promise);
}
function handleRejection(reason) {
if (reason == "HTTP request aborted") {
// Do nothing since this is normal.
return null;
}
Cu.reportError("SearchSuggestionController rejection: " + reason);
return null;
}
return Promise.all(promises).then(this._dedupeAndReturnResults.bind(this), handleRejection);
},
/**
* Stop pending fetches so no results are returned from them.
*
* Note: If there was no remote results fetched, the fetching cannot be stopped and local results
* will still be returned because stopping relies on aborting the XMLHTTPRequest to reject the
* promise for Promise.all.
*/
stop: function() {
if (this._request) {
this._request.abort();
} else if (!this.maxRemoteResults) {
Cu.reportError("SearchSuggestionController: Cannot stop fetching if remote results were not "+
"requested");
}
this._reset();
},
// Private methods
_fetchFormHistory: function(searchTerm) {
let deferredFormHistory = Promise.defer();
let acSearchObserver = {
// Implements nsIAutoCompleteSearch
onSearchResult: (search, result) => {
this._formHistoryResult = result;
if (this._request) {
this._remoteResultTimer = Cc["@mozilla.org/timer;1"].
createInstance(Ci.nsITimer);
this._remoteResultTimer.initWithCallback(this._onRemoteTimeout.bind(this),
this.remoteTimeout || REMOTE_TIMEOUT,
Ci.nsITimer.TYPE_ONE_SHOT);
}
switch (result.searchResult) {
case Ci.nsIAutoCompleteResult.RESULT_SUCCESS:
case Ci.nsIAutoCompleteResult.RESULT_NOMATCH:
if (result.searchString !== this._searchString) {
deferredFormHistory.resolve("Unexpected response, this._searchString does not match form history response");
return;
}
let fhEntries = [];
for (let i = 0; i < result.matchCount; ++i) {
fhEntries.push(result.getValueAt(i));
}
deferredFormHistory.resolve({
result: fhEntries,
formHistoryResult: result,
});
break;
case Ci.nsIAutoCompleteResult.RESULT_FAILURE:
case Ci.nsIAutoCompleteResult.RESULT_IGNORED:
deferredFormHistory.resolve("Form History returned RESULT_FAILURE or RESULT_IGNORED");
break;
}
},
};
let formHistory = Cc["@mozilla.org/autocomplete/search;1?name=form-history"].
createInstance(Ci.nsIAutoCompleteSearch);
formHistory.startSearch(searchTerm, this.formHistoryParam || DEFAULT_FORM_HISTORY_PARAM,
this._formHistoryResult,
acSearchObserver);
return deferredFormHistory;
},
/**
* Fetch suggestions from the search engine over the network.
*/
_fetchRemote: function(searchTerm, engine, privateMode, userContextId) {
let deferredResponse = Promise.defer();
this._request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
createInstance(Ci.nsIXMLHttpRequest);
let submission = engine.getSubmission(searchTerm,
SEARCH_RESPONSE_SUGGESTION_JSON);
let method = (submission.postData ? "POST" : "GET");
this._request.open(method, submission.uri.spec, true);
this._request.setOriginAttributes({userContextId,
privateBrowsingId: privateMode ? 1 : 0});
this._request.mozBackgroundRequest = true; // suppress dialogs and fail silently
this._request.addEventListener("load", this._onRemoteLoaded.bind(this, deferredResponse));
this._request.addEventListener("error", (evt) => deferredResponse.resolve("HTTP error"));
// Reject for an abort assuming it's always from .stop() in which case we shouldn't return local
// or remote results for existing searches.
this._request.addEventListener("abort", (evt) => deferredResponse.reject("HTTP request aborted"));
this._request.send(submission.postData);
return deferredResponse;
},
/**
* Called when the request completed successfully (thought the HTTP status could be anything)
* so we can handle the response data.
* @private
*/
_onRemoteLoaded: function(deferredResponse) {
if (!this._request) {
deferredResponse.resolve("Got HTTP response after the request was cancelled");
return;
}
let status, serverResults;
try {
status = this._request.status;
} catch (e) {
// The XMLHttpRequest can throw NS_ERROR_NOT_AVAILABLE.
deferredResponse.resolve("Unknown HTTP status: " + e);
return;
}
if (status != HTTP_OK || this._request.responseText == "") {
deferredResponse.resolve("Non-200 status or empty HTTP response: " + status);
return;
}
try {
serverResults = JSON.parse(this._request.responseText);
} catch (ex) {
deferredResponse.resolve("Failed to parse suggestion JSON: " + ex);
return;
}
if (!serverResults[0] ||
this._searchString.localeCompare(serverResults[0], undefined,
{ sensitivity: "base" })) {
// something is wrong here so drop remote results
deferredResponse.resolve("Unexpected response, this._searchString does not match remote response");
return;
}
let results = serverResults[1] || [];
deferredResponse.resolve({ result: results });
},
/**
* Called when this._remoteResultTimer fires indicating the remote request took too long.
*/
_onRemoteTimeout: function () {
this._request = null;
// FIXME: bug 387341
// Need to break the cycle between us and the timer.
this._remoteResultTimer = null;
// The XMLHTTPRequest for suggest results is taking too long
// so send out the form history results and cancel the request.
if (this._deferredRemoteResult) {
this._deferredRemoteResult.resolve("HTTP Timeout");
this._deferredRemoteResult = null;
}
},
/**
* @param {Array} suggestResults - an array of result objects from different sources (local or remote)
* @return {Object}
*/
_dedupeAndReturnResults: function(suggestResults) {
if (this._searchString === null) {
// _searchString can be null if stop() was called and remote suggestions
// were disabled (stopping if we are fetching remote suggestions will
// cause a promise rejection before we reach _dedupeAndReturnResults).
return null;
}
let results = {
term: this._searchString,
remote: [],
local: [],
formHistoryResult: null,
};
for (let result of suggestResults) {
if (typeof result === "string") { // Failure message
Cu.reportError("SearchSuggestionController: " + result);
} else if (result.formHistoryResult) { // Local results have a formHistoryResult property.
results.formHistoryResult = result.formHistoryResult;
results.local = result.result || [];
} else { // Remote result
results.remote = result.result || [];
}
}
// If we have remote results, cap the number of local results
if (results.remote.length) {
results.local = results.local.slice(0, this.maxLocalResults);
}
// We don't want things to appear in both history and suggestions so remove entries from
// remote results that are already in local.
if (results.remote.length && results.local.length) {
for (let i = 0; i < results.local.length; ++i) {
let term = results.local[i];
let dupIndex = results.remote.indexOf(term);
if (dupIndex != -1) {
results.remote.splice(dupIndex, 1);
}
}
}
// Trim the number of results to the maximum requested (now that we've pruned dupes).
results.remote =
results.remote.slice(0, this.maxRemoteResults - results.local.length);
if (this._callback) {
this._callback(results);
}
this._reset();
return results;
},
_reset: function() {
this._request = null;
if (this._remoteResultTimer) {
this._remoteResultTimer.cancel();
this._remoteResultTimer = null;
}
this._deferredRemoteResult = null;
this._searchString = null;
},
};
/**
* Determines whether the given engine offers search suggestions.
*
* @param {nsISearchEngine} engine - The search engine
* @return {boolean} True if the engine offers suggestions and false otherwise.
*/
this.SearchSuggestionController.engineOffersSuggestions = function(engine) {
return engine.supportsResponseType(SEARCH_RESPONSE_SUGGESTION_JSON);
};

View file

@ -1,31 +0,0 @@
# -*- 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/.
EXTRA_COMPONENTS += [
'nsSearchSuggestions.js',
]
EXTRA_PP_COMPONENTS += [
'nsSearchService.js',
]
if CONFIG['MOZ_PHOENIX'] or CONFIG['MOZ_FENNEC'] or CONFIG['MOZ_XULRUNNER']:
DEFINES['HAVE_SIDEBAR'] = True
EXTRA_COMPONENTS += [
'nsSidebar.js',
]
EXTRA_JS_MODULES += [
'SearchSuggestionController.jsm',
]
EXTRA_PP_COMPONENTS += [
'toolkitsearch.manifest',
]
EXTRA_JS_MODULES += [
'SearchStaticData.jsm',
]

File diff suppressed because it is too large Load diff

View file

@ -1,66 +0,0 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 4 -*- */
/* 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/. */
const { interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
// File extension for Sherlock search plugin description files
const SHERLOCK_FILE_EXT_REGEXP = /\.src$/i;
function nsSidebar() {
}
nsSidebar.prototype = {
init: function(window) {
this.window = window;
try {
this.mm = window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDocShell)
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIContentFrameMessageManager);
} catch (e) {
Cu.reportError(e);
}
},
// Deprecated, only left here to avoid breaking old browser-detection scripts.
addSearchEngine: function(engineURL, iconURL, suggestedTitle, suggestedCategory) {
if (SHERLOCK_FILE_EXT_REGEXP.test(engineURL)) {
Cu.reportError("Installing Sherlock search plugins is no longer supported.");
return;
}
this.AddSearchProvider(engineURL);
},
// This function implements window.external.AddSearchProvider().
// The capitalization, although nonstandard here, is to match other browsers'
// APIs and is therefore important.
AddSearchProvider: function(engineURL) {
if (!this.mm) {
Cu.reportError(`Installing a search provider from this context is not currently supported: ${Error().stack}.`);
return;
}
this.mm.sendAsyncMessage("Search:AddEngine", {
pageURL: this.window.document.documentURIObject.spec,
engineURL
});
},
// This function exists to implement window.external.IsSearchProviderInstalled(),
// for compatibility with other browsers. The function has been deprecated
// and so will not be implemented.
IsSearchProviderInstalled: function(engineURL) {
return 0;
},
classID: Components.ID("{22117140-9c6e-11d3-aaf1-00805f8a4905}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
Ci.nsIDOMGlobalPropertyInitializer])
}
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([nsSidebar]);

View file

@ -4,12 +4,19 @@
# 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/xpcshell/xpcshell.ini']
EXTRA_COMPONENTS += ['nsSearchSuggestions.js']
if CONFIG['MC_BASILISK'] or CONFIG['HYPE_ICEWEASEL'] or CONFIG['HYPE_ICEDOVE']:
DIRS += ['current']
else:
DIRS += ['orginal']
EXTRA_PP_COMPONENTS += [
'nsSearchService.js',
'toolkitsearch.manifest',
]
if CONFIG['MOZ_PHOENIX'] or CONFIG['MOZ_XULRUNNER']:
DEFINES['HAVE_SIDEBAR'] = True
EXTRA_COMPONENTS += ['nsSidebar.js']
EXTRA_JS_MODULES += [
'SearchStaticData.jsm',
'SearchSuggestionController.jsm',
]
with Files('**'):
BUG_COMPONENT = ('Firefox', 'Search')

View file

@ -416,399 +416,6 @@ function isPartnerBuild() {
return false;
}
// Method to determine if we should be using geo-specific defaults
function geoSpecificDefaultsEnabled() {
let geoSpecificDefaults = false;
try {
geoSpecificDefaults = Services.prefs.getBoolPref("browser.search.geoSpecificDefaults");
} catch(e) {}
return geoSpecificDefaults;
}
// Some notes on countryCode and region prefs:
// * A "countryCode" pref is set via a geoip lookup. It always reflects the
// result of that geoip request.
// * A "region" pref, once set, is the region actually used for search. In
// most cases it will be identical to the countryCode pref.
// * The value of "region" and "countryCode" will only not agree in one edge
// case - 34/35 users who have previously been configured to use US defaults
// based purely on a timezone check will have "region" forced to US,
// regardless of what countryCode geoip returns.
// * We may want to know if we are in the US before we have *either*
// countryCode or region - in which case we fallback to a timezone check,
// but we don't persist that value anywhere in the expectation we will
// eventually get a countryCode/region.
// A method that "migrates" prefs if necessary.
function migrateRegionPrefs() {
// If we already have a "region" pref there's nothing to do.
if (Services.prefs.prefHasUserValue("browser.search.region")) {
return;
}
// If we have 'isUS' but no 'countryCode' then we are almost certainly
// a profile from Fx 34/35 that set 'isUS' based purely on a timezone
// check. If this said they were US, we force region to be US.
// (But if isUS was false, we leave region alone - we will do a geoip request
// and set the region accordingly)
try {
if (Services.prefs.getBoolPref("browser.search.isUS") &&
!Services.prefs.prefHasUserValue("browser.search.countryCode")) {
Services.prefs.setCharPref("browser.search.region", "US");
}
} catch (ex) {
// no isUS pref, nothing to do.
}
// If we have a countryCode pref but no region pref, just force region
// to be the countryCode.
try {
let countryCode = Services.prefs.getCharPref("browser.search.countryCode");
if (!Services.prefs.prefHasUserValue("browser.search.region")) {
Services.prefs.setCharPref("browser.search.region", countryCode);
}
} catch (ex) {
// no countryCode pref, nothing to do.
}
}
// A method to determine if we are in the United States (US) for the search
// service.
// It uses a browser.search.region pref (which typically comes from a geoip
// request) or if that doesn't exist, falls back to a hacky timezone check.
function getIsUS() {
// Regardless of the region or countryCode, non en-US builds are not
// considered to be in the US from the POV of the search service.
if (getLocale() != "en-US") {
return false;
}
// If we've got a region pref, trust it.
try {
return Services.prefs.getCharPref("browser.search.region") == "US";
} catch(e) {}
// So we are en-US but have no region pref - fallback to hacky timezone check.
let isNA = isUSTimezone();
LOG("getIsUS() fell back to a timezone check with the result=" + isNA);
return isNA;
}
// Helper method to modify preference keys with geo-specific modifiers, if needed.
function getGeoSpecificPrefName(basepref) {
if (!geoSpecificDefaultsEnabled() || isPartnerBuild())
return basepref;
if (getIsUS())
return basepref + ".US";
return basepref;
}
// A method that tries to determine if this user is in a US geography.
function isUSTimezone() {
// Timezone assumptions! We assume that if the system clock's timezone is
// between Newfoundland and Hawaii, that the user is in North America.
// This includes all of South America as well, but we have relatively few
// en-US users there, so that's OK.
// 150 minutes = 2.5 hours (UTC-2.5), which is
// Newfoundland Daylight Time (http://www.timeanddate.com/time/zones/ndt)
// 600 minutes = 10 hours (UTC-10), which is
// Hawaii-Aleutian Standard Time (http://www.timeanddate.com/time/zones/hast)
let UTCOffset = (new Date()).getTimezoneOffset();
return UTCOffset >= 150 && UTCOffset <= 600;
}
// A less hacky method that tries to determine our country-code via an XHR
// geoip lookup.
// If this succeeds and we are using an en-US locale, we set the pref used by
// the hacky method above, so isUS() can avoid the hacky timezone method.
// If it fails we don't touch that pref so isUS() does its normal thing.
var ensureKnownCountryCode = Task.async(function* () {
// If we have a country-code already stored in our prefs we trust it.
let countryCode;
try {
countryCode = Services.prefs.getCharPref("browser.search.countryCode");
} catch(e) {}
if (!countryCode) {
// We don't have it cached, so fetch it. fetchCountryCode() will call
// storeCountryCode if it gets a result (even if that happens after the
// promise resolves) and fetchRegionDefault.
yield fetchCountryCode();
} else {
// if nothing to do, return early.
if (!geoSpecificDefaultsEnabled())
return;
let expir = engineMetadataService.getGlobalAttr("searchDefaultExpir") || 0;
if (expir > Date.now()) {
// The territory default we have already fetched hasn't expired yet.
// If we have a default engine or a list of visible default engines
// saved, the hashes should be valid, verify them now so that we can
// refetch if they have been tampered with.
let defaultEngine = engineMetadataService.getGlobalAttr("searchDefault");
let visibleDefaultEngines =
engineMetadataService.getGlobalAttr("visibleDefaultEngines");
if ((!defaultEngine || engineMetadataService.getGlobalAttr("searchDefaultHash") == getVerificationHash(defaultEngine)) &&
(!visibleDefaultEngines ||
engineMetadataService.getGlobalAttr("visibleDefaultEnginesHash") == getVerificationHash(visibleDefaultEngines))) {
// No geo defaults, or valid hashes; nothing to do.
return;
}
}
yield new Promise(resolve => {
let timeoutMS = Services.prefs.getIntPref("browser.search.geoip.timeout");
let timerId = setTimeout(() => {
timerId = null;
resolve();
}, timeoutMS);
let callback = () => {
clearTimeout(timerId);
resolve();
};
fetchRegionDefault().then(callback).catch(err => {
Components.utils.reportError(err);
callback();
});
});
}
});
// Store the result of the geoip request as well as any other values and
// telemetry which depend on it.
function storeCountryCode(cc) {
// Set the country-code itself.
Services.prefs.setCharPref("browser.search.countryCode", cc);
// And set the region pref if we don't already have a value.
if (!Services.prefs.prefHasUserValue("browser.search.region")) {
Services.prefs.setCharPref("browser.search.region", cc);
}
// and telemetry...
let isTimezoneUS = isUSTimezone();
// telemetry to compare our geoip response with platform-specific country data.
// On Mac and Windows, we can get a country code via sysinfo
let platformCC = Services.sysinfo.get("countryCode");
if (platformCC) {
let probeUSMismatched, probeNonUSMismatched;
switch (Services.appinfo.OS) {
case "Darwin":
probeUSMismatched = "SEARCH_SERVICE_US_COUNTRY_MISMATCHED_PLATFORM_OSX";
probeNonUSMismatched = "SEARCH_SERVICE_NONUS_COUNTRY_MISMATCHED_PLATFORM_OSX";
break;
case "WINNT":
probeUSMismatched = "SEARCH_SERVICE_US_COUNTRY_MISMATCHED_PLATFORM_WIN";
probeNonUSMismatched = "SEARCH_SERVICE_NONUS_COUNTRY_MISMATCHED_PLATFORM_WIN";
break;
default:
Cu.reportError("Platform " + Services.appinfo.OS + " has system country code but no search service telemetry probes");
break;
}
}
}
// Get the country we are in via a XHR geoip request.
function fetchCountryCode() {
// values for the SEARCH_SERVICE_COUNTRY_FETCH_RESULT 'enum' telemetry probe.
const TELEMETRY_RESULT_ENUM = {
SUCCESS: 0,
SUCCESS_WITHOUT_DATA: 1,
XHRTIMEOUT: 2,
ERROR: 3,
// Note that we expect to add finer-grained error types here later (eg,
// dns error, network error, ssl error, etc) with .ERROR remaining as the
// generic catch-all that doesn't fit into other categories.
};
let endpoint = Services.urlFormatter.formatURLPref("browser.search.geoip.url");
LOG("_fetchCountryCode starting with endpoint " + endpoint);
// As an escape hatch, no endpoint means no geoip.
if (!endpoint) {
return Promise.resolve();
}
let startTime = Date.now();
return new Promise(resolve => {
// Instead of using a timeout on the xhr object itself, we simulate one
// using a timer and let the XHR request complete. This allows us to
// capture reliable telemetry on what timeout value should actually be
// used to ensure most users don't see one while not making it so large
// that many users end up doing a sync init of the search service and thus
// would see the jank that implies.
// (Note we do actually use a timeout on the XHR, but that's set to be a
// large value just incase the request never completes - we don't want the
// XHR object to live forever)
let timeoutMS = Services.prefs.getIntPref("browser.search.geoip.timeout");
let geoipTimeoutPossible = true;
let timerId = setTimeout(() => {
LOG("_fetchCountryCode: timeout fetching country information");
timerId = null;
resolve();
}, timeoutMS);
let resolveAndReportSuccess = (result, reason) => {
// Even if we timed out, we want to save the country code and everything
// related so next startup sees the value and doesn't retry this dance.
if (result) {
storeCountryCode(result);
}
// This notification is just for tests...
Services.obs.notifyObservers(null, SEARCH_SERVICE_TOPIC, "geoip-lookup-xhr-complete");
if (timerId) {
geoipTimeoutPossible = false;
}
let callback = () => {
// If we've already timed out then we've already resolved the promise,
// so there's nothing else to do.
if (timerId == null) {
return;
}
clearTimeout(timerId);
resolve();
};
if (result && geoSpecificDefaultsEnabled()) {
fetchRegionDefault().then(callback).catch(err => {
Components.utils.reportError(err);
callback();
});
} else {
callback();
}
};
let request = new XMLHttpRequest();
// This notification is just for tests...
Services.obs.notifyObservers(request, SEARCH_SERVICE_TOPIC, "geoip-lookup-xhr-starting");
request.timeout = 100000; // 100 seconds as the last-chance fallback
request.onload = function(event) {
let took = Date.now() - startTime;
let cc = event.target.response && event.target.response.country_code;
LOG("_fetchCountryCode got success response in " + took + "ms: " + cc);
let reason = cc ? TELEMETRY_RESULT_ENUM.SUCCESS : TELEMETRY_RESULT_ENUM.SUCCESS_WITHOUT_DATA;
resolveAndReportSuccess(cc, reason);
};
request.ontimeout = function(event) {
LOG("_fetchCountryCode: XHR finally timed-out fetching country information");
resolveAndReportSuccess(null, TELEMETRY_RESULT_ENUM.XHRTIMEOUT);
};
request.onerror = function(event) {
LOG("_fetchCountryCode: failed to retrieve country information");
resolveAndReportSuccess(null, TELEMETRY_RESULT_ENUM.ERROR);
};
request.open("POST", endpoint, true);
request.setRequestHeader("Content-Type", "application/json");
request.responseType = "json";
request.send("{}");
});
}
// This will make an HTTP request to a Mozilla server that will return
// JSON data telling us what engine should be set as the default for
// the current region, and how soon we should check again.
//
// The optional cohort value returned by the server is to be kept locally
// and sent to the server the next time we ping it. It lets the server
// identify profiles that have been part of a specific experiment.
//
// This promise may take up to 100s to resolve, it's the caller's
// responsibility to ensure with a timer that we are not going to
// block the async init for too long.
var fetchRegionDefault = () => new Promise(resolve => {
let urlTemplate = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF)
.getCharPref("geoSpecificDefaults.url");
let endpoint = Services.urlFormatter.formatURL(urlTemplate);
// As an escape hatch, no endpoint means no region specific defaults.
if (!endpoint) {
resolve();
return;
}
// Append the optional cohort value.
const cohortPref = "browser.search.cohort";
let cohort;
try {
cohort = Services.prefs.getCharPref(cohortPref);
} catch(e) {}
if (cohort)
endpoint += "/" + cohort;
LOG("fetchRegionDefault starting with endpoint " + endpoint);
let startTime = Date.now();
let request = new XMLHttpRequest();
request.timeout = 100000; // 100 seconds as the last-chance fallback
request.onload = function(event) {
let took = Date.now() - startTime;
let status = event.target.status;
if (status != 200) {
LOG("fetchRegionDefault failed with HTTP code " + status);
let retryAfter = request.getResponseHeader("retry-after");
if (retryAfter) {
engineMetadataService.setGlobalAttr("searchDefaultExpir",
Date.now() + retryAfter * 1000);
}
resolve();
return;
}
let response = event.target.response || {};
LOG("received " + response.toSource());
if (response.cohort) {
Services.prefs.setCharPref(cohortPref, response.cohort);
} else {
Services.prefs.clearUserPref(cohortPref);
}
if (response.settings && response.settings.searchDefault) {
let defaultEngine = response.settings.searchDefault;
engineMetadataService.setGlobalAttr("searchDefault", defaultEngine);
let hash = getVerificationHash(defaultEngine);
LOG("fetchRegionDefault saved searchDefault: " + defaultEngine +
" with verification hash: " + hash);
engineMetadataService.setGlobalAttr("searchDefaultHash", hash);
}
if (response.settings && response.settings.visibleDefaultEngines) {
let visibleDefaultEngines = response.settings.visibleDefaultEngines;
let string = visibleDefaultEngines.join(",");
engineMetadataService.setGlobalAttr("visibleDefaultEngines", string);
let hash = getVerificationHash(string);
LOG("fetchRegionDefault saved visibleDefaultEngines: " + string +
" with verification hash: " + hash);
engineMetadataService.setGlobalAttr("visibleDefaultEnginesHash", hash);
}
let interval = response.interval || SEARCH_GEO_DEFAULT_UPDATE_INTERVAL;
let milliseconds = interval * 1000; // |interval| is in seconds.
engineMetadataService.setGlobalAttr("searchDefaultExpir",
Date.now() + milliseconds);
LOG("fetchRegionDefault got success response in " + took + "ms");
resolve();
};
request.ontimeout = function(event) {
LOG("fetchRegionDefault: XHR finally timed-out");
resolve();
};
request.onerror = function(event) {
LOG("fetchRegionDefault: failed to retrieve territory default information");
resolve();
};
request.open("GET", endpoint, true);
request.setRequestHeader("Content-Type", "application/json");
request.responseType = "json";
request.send();
});
function getVerificationHash(aName) {
let disclaimer = "By modifying this file, I agree that I am doing so " +
"only within $appName itself, using official, user-driven search " +
@ -1034,11 +641,8 @@ function QueryParameter(aName, aValue, aPurpose) {
function ParamSubstitution(aParamValue, aSearchTerms, aEngine) {
var value = aParamValue;
var distributionID = MOZ_DISTRIBUTION_ID;
try {
distributionID = Services.prefs.getCharPref(BROWSER_SEARCH_PREF + "distributionID");
}
catch (ex) { }
var distributionID = Services.prefs.getCharPref(BROWSER_SEARCH_PREF + "distributionID",
MOZ_DISTRIBUTION_ID || "");
var official = MOZ_OFFICIAL;
try {
if (Services.prefs.getBoolPref(BROWSER_SEARCH_PREF + "official"))
@ -2925,7 +2529,6 @@ SearchService.prototype = {
_syncInit: function SRCH_SVC__syncInit() {
LOG("_syncInit start");
this._initStarted = true;
migrateRegionPrefs();
try {
this._syncLoadEngines();
} catch (ex) {
@ -2950,14 +2553,8 @@ SearchService.prototype = {
* succeeds.
*/
_asyncInit: function SRCH_SVC__asyncInit() {
migrateRegionPrefs();
return Task.spawn(function() {
LOG("_asyncInit start");
try {
yield checkForSyncCompletion(ensureKnownCountryCode());
} catch (ex if ex.result != Cr.NS_ERROR_ALREADY_INITIALIZED) {
LOG("_asyncInit: failure determining country code: " + ex);
}
try {
yield checkForSyncCompletion(this._asyncLoadEngines());
} catch (ex if ex.result != Cr.NS_ERROR_ALREADY_INITIALIZED) {
@ -2997,9 +2594,8 @@ SearchService.prototype = {
let defaultPrefB = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF);
let nsIPLS = Ci.nsIPrefLocalizedString;
let defPref = getGeoSpecificPrefName("defaultenginename");
try {
defaultEngine = defaultPrefB.getComplexValue(defPref, nsIPLS).data;
defaultEngine = defaultPrefB.getComplexValue("defaultenginename", nsIPLS).data;
} catch (ex) {
// If the default pref is invalid (e.g. an add-on set it to a bogus value)
// getEngineByName will just return null, which is the best we can do.
@ -3344,12 +2940,7 @@ SearchService.prototype = {
try {
LOG("Restarting engineMetadataService");
yield engineMetadataService.init();
yield ensureKnownCountryCode();
// Due to the HTTP requests done by ensureKnownCountryCode, it's possible that
// at this point a synchronous init has been forced by other code.
if (!gInitialized)
yield this._asyncLoadEngines();
yield this._asyncLoadEngines();
// Typically we'll re-init as a result of a pref observer,
// so signal to 'callers' that we're done.
@ -3856,10 +3447,8 @@ SearchService.prototype = {
}
catch (e) { }
let prefNameBase = getGeoSpecificPrefName(BROWSER_SEARCH_PREF + "order");
while (true) {
prefName = prefNameBase + "." + (++i);
engineName = getLocalizedPref(prefName);
engineName = getLocalizedPref(BROWSER_SEARCH_PREF + "order." + (++i));
if (!engineName)
break;
@ -3992,10 +3581,8 @@ SearchService.prototype = {
}
// Now look through the "browser.search.order" branch.
let prefNameBase = getGeoSpecificPrefName(BROWSER_SEARCH_PREF + "order");
for (var j = 1; ; j++) {
let prefName = prefNameBase + "." + j;
engineName = getLocalizedPref(prefName);
engineName = getLocalizedPref(BROWSER_SEARCH_PREF + "order." + j);
if (!engineName)
break;
@ -4208,8 +3795,7 @@ SearchService.prototype = {
get defaultEngine() {
this._ensureInitialized();
if (!this._defaultEngine) {
let defPref = getGeoSpecificPrefName(BROWSER_SEARCH_PREF + "defaultenginename");
let defaultEngine = this.getEngineByName(getLocalizedPref(defPref, ""))
let defaultEngine = this.getEngineByName(getLocalizedPref(BROWSER_SEARCH_PREF + "defaultenginename", ""))
if (!defaultEngine)
defaultEngine = this._getSortedEngines(false)[0] || null;
this._defaultEngine = defaultEngine;
@ -4236,18 +3822,16 @@ SearchService.prototype = {
this._defaultEngine = newDefaultEngine;
let defPref = getGeoSpecificPrefName(BROWSER_SEARCH_PREF + "defaultenginename");
// If we change the default engine in the future, that change should impact
// users who have switched away from and then back to the build's "default"
// engine. So clear the user pref when the defaultEngine is set to the
// build's default engine, so that the defaultEngine getter falls back to
// whatever the default is.
if (this._defaultEngine == this._originalDefaultEngine) {
Services.prefs.clearUserPref(defPref);
Services.prefs.clearUserPref(BROWSER_SEARCH_PREF + "defaultenginename");
}
else {
setLocalizedPref(defPref, this._defaultEngine.name);
setLocalizedPref(BROWSER_SEARCH_PREF + "defaultenginename", this._defaultEngine.name);
}
notifyAction(this._defaultEngine, SEARCH_ENGINE_DEFAULT);
@ -4350,11 +3934,9 @@ SearchService.prototype = {
} catch(e) {}
}
let prefNameBase = getGeoSpecificPrefName(BROWSER_SEARCH_PREF + "order");
let i = 0;
while (!sendSubmissionURL) {
let prefName = prefNameBase + "." + (++i);
let engineName = getLocalizedPref(prefName);
let engineName = getLocalizedPref(BROWSER_SEARCH_PREF + "order." + (++i));
if (!engineName)
break;
if (result.name == engineName) {
@ -4622,10 +4204,6 @@ SearchService.prototype = {
Services.obs.addObserver(this, SEARCH_ENGINE_TOPIC, false);
Services.obs.addObserver(this, QUIT_APPLICATION_TOPIC, false);
#ifdef MOZ_FENNEC
Services.prefs.addObserver(LOCALE_PREF, this, false);
#endif
// The current stage of shutdown. Used to help analyze crash
// signatures in case of shutdown timeout.
let shutdownState = {
@ -4670,10 +4248,6 @@ SearchService.prototype = {
_removeObservers: function SRCH_SVC_removeObservers() {
Services.obs.removeObserver(this, SEARCH_ENGINE_TOPIC);
Services.obs.removeObserver(this, QUIT_APPLICATION_TOPIC);
#ifdef MOZ_FENNEC
Services.prefs.removeObserver(LOCALE_PREF, this);
#endif
},
QueryInterface: function SRCH_SVC_QI(aIID) {
@ -4974,4 +4548,4 @@ var engineUpdateService = {
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SearchService]);
#include ../../../../toolkit/modules/debug.js
#include ../../../toolkit/modules/debug.js

View file

@ -1,43 +0,0 @@
/* 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/. */
/*
* This module contains additional data about default search engines that is the
* same across all languages. This information is defined outside of the actual
* search engine definition files, so that localizers don't need to update them
* when a change is made.
*
* This separate module is also easily overridable, in case a hotfix is needed.
* No high-level processing logic is applied here.
*/
"use strict";
this.EXPORTED_SYMBOLS = [
"SearchStaticData",
];
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
// To update this list of known alternate domains, just cut-and-paste from
// https://www.google.com/supported_domains
const gGoogleDomainsSource = ".google.com .google.ad .google.ae .google.com.af .google.com.ag .google.com.ai .google.al .google.am .google.co.ao .google.com.ar .google.as .google.at .google.com.au .google.az .google.ba .google.com.bd .google.be .google.bf .google.bg .google.com.bh .google.bi .google.bj .google.com.bn .google.com.bo .google.com.br .google.bs .google.bt .google.co.bw .google.by .google.com.bz .google.ca .google.cd .google.cf .google.cg .google.ch .google.ci .google.co.ck .google.cl .google.cm .google.cn .google.com.co .google.co.cr .google.com.cu .google.cv .google.com.cy .google.cz .google.de .google.dj .google.dk .google.dm .google.com.do .google.dz .google.com.ec .google.ee .google.com.eg .google.es .google.com.et .google.fi .google.com.fj .google.fm .google.fr .google.ga .google.ge .google.gg .google.com.gh .google.com.gi .google.gl .google.gm .google.gp .google.gr .google.com.gt .google.gy .google.com.hk .google.hn .google.hr .google.ht .google.hu .google.co.id .google.ie .google.co.il .google.im .google.co.in .google.iq .google.is .google.it .google.je .google.com.jm .google.jo .google.co.jp .google.co.ke .google.com.kh .google.ki .google.kg .google.co.kr .google.com.kw .google.kz .google.la .google.com.lb .google.li .google.lk .google.co.ls .google.lt .google.lu .google.lv .google.com.ly .google.co.ma .google.md .google.me .google.mg .google.mk .google.ml .google.com.mm .google.mn .google.ms .google.com.mt .google.mu .google.mv .google.mw .google.com.mx .google.com.my .google.co.mz .google.com.na .google.com.nf .google.com.ng .google.com.ni .google.ne .google.nl .google.no .google.com.np .google.nr .google.nu .google.co.nz .google.com.om .google.com.pa .google.com.pe .google.com.pg .google.com.ph .google.com.pk .google.pl .google.pn .google.com.pr .google.ps .google.pt .google.com.py .google.com.qa .google.ro .google.ru .google.rw .google.com.sa .google.com.sb .google.sc .google.se .google.com.sg .google.sh .google.si .google.sk .google.com.sl .google.sn .google.so .google.sm .google.sr .google.st .google.com.sv .google.td .google.tg .google.co.th .google.com.tj .google.tk .google.tl .google.tm .google.tn .google.to .google.com.tr .google.tt .google.com.tw .google.co.tz .google.com.ua .google.co.ug .google.co.uk .google.com.uy .google.co.uz .google.com.vc .google.co.ve .google.vg .google.co.vi .google.com.vn .google.vu .google.ws .google.rs .google.co.za .google.co.zm .google.co.zw .google.cat";
const gGoogleDomains = gGoogleDomainsSource.split(" ").map(d => "www" + d);
this.SearchStaticData = {
/**
* Returns a list of alternate domains for a given search engine domain.
*
* @param aDomain
* Lowercase host name to look up. For example, if this argument is
* "www.google.com" or "www.google.co.uk", the function returns the
* full list of supported Google domains.
*
* @return Array containing one entry for each alternate host name, or empty
* array if none is known. The returned array should not be modified.
*/
getAlternateDomains: function (aDomain) {
return gGoogleDomains.indexOf(aDomain) == -1 ? [] : gGoogleDomains;
},
};

View file

@ -1,31 +0,0 @@
# -*- 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/.
EXTRA_COMPONENTS += [
'nsSearchSuggestions.js',
]
EXTRA_PP_COMPONENTS += [
'nsSearchService.js',
]
if CONFIG['MOZ_PHOENIX'] or CONFIG['MOZ_FENNEC'] or CONFIG['MOZ_XULRUNNER']:
DEFINES['HAVE_SIDEBAR'] = True
EXTRA_COMPONENTS += [
'nsSidebar.js',
]
EXTRA_JS_MODULES += [
'SearchSuggestionController.jsm',
]
EXTRA_PP_COMPONENTS += [
'toolkitsearch.manifest',
]
EXTRA_JS_MODULES += [
'SearchStaticData.jsm',
]

View file

@ -1,197 +0,0 @@
/* 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/. */
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/nsFormAutoCompleteResult.jsm");
Cu.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "SearchSuggestionController",
"resource://gre/modules/SearchSuggestionController.jsm");
/**
* SuggestAutoComplete is a base class that implements nsIAutoCompleteSearch
* and can collect results for a given search by using this._suggestionController.
* We do it this way since the AutoCompleteController in Mozilla requires a
* unique XPCOM Service for every search provider, even if the logic for two
* providers is identical.
* @constructor
*/
function SuggestAutoComplete() {
this._init();
}
SuggestAutoComplete.prototype = {
_init: function() {
this._suggestionController = new SearchSuggestionController(obj => this.onResultsReturned(obj));
this._suggestionController.maxLocalResults = this._historyLimit;
},
get _suggestionLabel() {
let bundle = Services.strings.createBundle("chrome://global/locale/search/search.properties");
let label = bundle.GetStringFromName("suggestion_label");
Object.defineProperty(SuggestAutoComplete.prototype, "_suggestionLabel", {value: label});
return label;
},
/**
* The object implementing nsIAutoCompleteObserver that we notify when
* we have found results
* @private
*/
_listener: null,
/**
* Maximum number of history items displayed. This is capped at 7
* because the primary consumer (Firefox search bar) displays 10 rows
* by default, and so we want to leave some space for suggestions
* to be visible.
*/
_historyLimit: 7,
/**
* Callback for handling results from SearchSuggestionController.jsm
* @private
*/
onResultsReturned: function(results) {
let finalResults = [];
let finalComments = [];
// If form history has results, add them to the list.
for (let i = 0; i < results.local.length; ++i) {
finalResults.push(results.local[i]);
finalComments.push("");
}
// If there are remote matches, add them.
if (results.remote.length) {
// "comments" column values for suggestions starts as empty strings
let comments = new Array(results.remote.length).fill("", 1);
comments[0] = this._suggestionLabel;
// now put the history results above the suggestions
finalResults = finalResults.concat(results.remote);
finalComments = finalComments.concat(comments);
}
// Notify the FE of our new results
this.onResultsReady(results.term, finalResults, finalComments, results.formHistoryResult);
},
/**
* Notifies the front end of new results.
* @param searchString the user's query string
* @param results an array of results to the search
* @param comments an array of metadata corresponding to the results
* @private
*/
onResultsReady: function(searchString, results, comments, formHistoryResult) {
if (this._listener) {
// Create a copy of the results array to use as labels, since
// FormAutoCompleteResult doesn't like being passed the same array
// for both.
let labels = results.slice();
let result = new FormAutoCompleteResult(
searchString,
Ci.nsIAutoCompleteResult.RESULT_SUCCESS,
0,
"",
results,
labels,
comments,
formHistoryResult);
this._listener.onSearchResult(this, result);
// Null out listener to make sure we don't notify it twice
this._listener = null;
}
},
/**
* Initiates the search result gathering process. Part of
* nsIAutoCompleteSearch implementation.
*
* @param searchString the user's query string
* @param searchParam unused, "an extra parameter"; even though
* this parameter and the next are unused, pass
* them through in case the form history
* service wants them
* @param previousResult unused, a client-cached store of the previous
* generated resultset for faster searching.
* @param listener object implementing nsIAutoCompleteObserver which
* we notify when results are ready.
*/
startSearch: function(searchString, searchParam, previousResult, listener) {
// Don't reuse a previous form history result when it no longer applies.
if (!previousResult)
this._formHistoryResult = null;
var formHistorySearchParam = searchParam.split("|")[0];
// Receive the information about the privacy mode of the window to which
// this search box belongs. The front-end's search.xml bindings passes this
// information in the searchParam parameter. The alternative would have
// been to modify nsIAutoCompleteSearch to add an argument to startSearch
// and patch all of autocomplete to be aware of this, but the searchParam
// argument is already an opaque argument, so this solution is hopefully
// less hackish (although still gross.)
var privacyMode = (searchParam.split("|")[1] == "private");
// Start search immediately if possible, otherwise once the search
// service is initialized
if (Services.search.isInitialized) {
this._triggerSearch(searchString, formHistorySearchParam, listener, privacyMode);
return;
}
Services.search.init((function startSearch_cb(aResult) {
if (!Components.isSuccessCode(aResult)) {
Cu.reportError("Could not initialize search service, bailing out: " + aResult);
return;
}
this._triggerSearch(searchString, formHistorySearchParam, listener, privacyMode);
}).bind(this));
},
/**
* Actual implementation of search.
*/
_triggerSearch: function(searchString, searchParam, listener, privacyMode) {
this._listener = listener;
this._suggestionController.fetch(searchString,
privacyMode,
Services.search.currentEngine);
},
/**
* Ends the search result gathering process. Part of nsIAutoCompleteSearch
* implementation.
*/
stopSearch: function() {
this._suggestionController.stop();
},
// nsISupports
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteSearch,
Ci.nsIAutoCompleteObserver])
};
/**
* SearchSuggestAutoComplete is a service implementation that handles suggest
* results specific to web searches.
* @constructor
*/
function SearchSuggestAutoComplete() {
// This calls _init() in the parent class (SuggestAutoComplete) via the
// prototype, below.
this._init();
}
SearchSuggestAutoComplete.prototype = {
classID: Components.ID("{aa892eb4-ffbf-477d-9f9a-06c995ae9f27}"),
__proto__: SuggestAutoComplete.prototype,
serviceURL: ""
};
var component = [SearchSuggestAutoComplete];
this.NSGetFactory = XPCOMUtils.generateNSGetFactory(component);

View file

@ -1,10 +0,0 @@
component {7319788a-fe93-4db3-9f39-818cf08f4256} nsSearchService.js process=main
contract @mozilla.org/browser/search-service;1 {7319788a-fe93-4db3-9f39-818cf08f4256} process=main
# 21600 == 6 hours
category update-timer nsSearchService @mozilla.org/browser/search-service;1,getService,search-engine-update-timer,browser.search.update.interval,21600
component {aa892eb4-ffbf-477d-9f9a-06c995ae9f27} nsSearchSuggestions.js
contract @mozilla.org/autocomplete/search;1?name=search-autocomplete {aa892eb4-ffbf-477d-9f9a-06c995ae9f27}
#ifdef HAVE_SIDEBAR
component {22117140-9c6e-11d3-aaf1-00805f8a4905} nsSidebar.js
contract @mozilla.org/sidebar;1 {22117140-9c6e-11d3-aaf1-00805f8a4905}
#endif

View file

@ -1,7 +0,0 @@
"use strict";
module.exports = {
"extends": [
"../../../../../testing/xpcshell/xpcshell.eslintrc.js"
]
};

View file

@ -1,3 +0,0 @@
locale testsearchplugin ar jar:jar:searchTest.jar!/chrome/searchTest.jar!/
content testsearchplugin ./

View file

@ -1,8 +0,0 @@
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>addon</ShortName>
<Description>addon</Description>
<InputEncoding>UTF-8</InputEncoding>
<Url type="text/html" method="GET" template="http://searchtest.local">
<Param name="search" value="{searchTerms}"/>
</Url>
</SearchPlugin>

View file

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>TestEngineApp</ShortName>
<Description>A test search engine installed in the application directory</Description>
<InputEncoding>ISO-8859-1</InputEncoding>
<Url type="text/html" method="GET" template="http://localhost/" resultdomain="localhost">
<Param name="q" value="{searchTerms}"/>
</Url>
</SearchPlugin>

View file

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>engine-chromeicon</ShortName>
<Image width="16" height="16">chrome://branding/content/icon16.png</Image>
<Image width="32" height="32">chrome://branding/content/icon32.png</Image>
<Url type="text/html" method="GET" template="http://www.google.com/search">
<Param name="q" value="{searchTerms}"/>
</Url>
</SearchPlugin>

View file

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>Test search engine (fr)</ShortName>
<Description>A test search engine (based on Google search for a different locale)</Description>
<InputEncoding>ISO-8859-1</InputEncoding>
<Url type="text/html" method="GET" template="http://www.google.fr/search" resultdomain="google.fr">
<Param name="q" value="{searchTerms}"/>
<Param name="ie" value="iso-8859-1"/>
<Param name="oe" value="iso-8859-1"/>
</Url>
<SearchForm>http://www.google.fr/</SearchForm>
</SearchPlugin>

View file

@ -1,8 +0,0 @@
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>bug645970</ShortName>
<Description>override</Description>
<InputEncoding>UTF-8</InputEncoding>
<Url type="text/html" method="GET" template="http://searchtest.local">
<Param name="search" value="{searchTerms}"/>
</Url>
</SearchPlugin>

View file

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>engine-pref</ShortName>
<Url type="text/html" method="GET" template="http://www.google.com/search">
<Param name="q" value="{searchTerms}"/>
<!-- Dynamic parameters -->
<MozParam name="code" condition="pref" pref="code"/>
</Url>
</SearchPlugin>

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>engine-rel-searchform-post.xml</ShortName>
<Url type="text/html" method="POST" template="http://engine-rel-searchform-post.xml/POST" rel="searchform"/>
<SearchForm>http://engine-rel-searchform-post.xml/?search</SearchForm>
</SearchPlugin>

View file

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>engine-rel-searchform-purpose</ShortName>
<Url type="text/html" method="GET" template="http://www.google.com/search" resultdomain="google.com" rel="searchform">
<Param name="q" value="{searchTerms}"/>
<!-- Dynamic parameters -->
<MozParam name="channel" condition="purpose" purpose="contextmenu" value="rcs"/>
<MozParam name="channel" condition="purpose" purpose="keyword" value="fflb"/>
<MozParam name="channel" condition="purpose" purpose="searchbar" value="sb"/>
</Url>
</SearchPlugin>

View file

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>engine-rel-searchform.xml</ShortName>
<Url type="text/html" method="GET" template="http://engine-rel-searchform.xml/?search" rel="searchform"/>
</SearchPlugin>

View file

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>engine-resourceicon</ShortName>
<Image width="16" height="16">resource://search-plugins/icon16.png</Image>
<Image width="32" height="32">resource://search-plugins/icon32.png</Image>
<Url type="text/html" method="GET" template="http://www.google.com/search">
<Param name="q" value="{searchTerms}"/>
</Url>
</SearchPlugin>

View file

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>engine-system-purpose</ShortName>
<Url type="text/html" method="GET" template="http://www.google.com/search">
<Param name="q" value="{searchTerms}"/>
<!-- Dynamic parameters -->
<MozParam name="channel" condition="purpose" purpose="searchbar" value="sb"/>
<MozParam name="channel" condition="purpose" purpose="system" value="sys"/>
</Url>
</SearchPlugin>

View file

@ -1,10 +0,0 @@
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>update</ShortName>
<Description>update</Description>
<InputEncoding>UTF-8</InputEncoding>
<Url type="text/html" method="GET" template="http://searchtest.local">
<Param name="search" value="{searchTerms}"/>
</Url>
<UpdateUrl>http://searchtest.local/opensearch.xml</UpdateUrl>
<IconUpdateUrl>http://searchtest.local/favicon.ico</IconUpdateUrl>
</SearchPlugin>

View file

@ -1,25 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>Test search engine</ShortName>
<Description>A test search engine (based on Google search)</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16">data:image/png;base64,AAABAAEAEBAAAAEAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs9Pt8xetPtu9FsfFNtu%2BTzvb2%2B%2Fne4dFJeBw0egA%2FfAJAfAA8ewBBegAAAAD%2B%2FPtft98Mp%2BwWsfAVsvEbs%2FQeqvF8xO7%2F%2F%2F63yqkxdgM7gwE%2FggM%2BfQA%2BegBDeQDe7PIbotgQufcMufEPtfIPsvAbs%2FQvq%2Bfz%2Bf%2F%2B%2B%2FZKhR05hgBBhQI8hgBAgAI9ewD0%2B%2Fg3pswAtO8Cxf4Kw%2FsJvvYAqupKsNv%2B%2Fv7%2F%2FP5VkSU0iQA7jQA9hgBDgQU%2BfQH%2F%2Ff%2FQ6fM4sM4KsN8AteMCruIqqdbZ7PH8%2Fv%2Fg6Nc%2Fhg05kAA8jAM9iQI%2BhQA%2BgQDQu6b97uv%2F%2F%2F7V8Pqw3eiWz97q8%2Ff%2F%2F%2F%2F7%2FPptpkkqjQE4kwA7kAA5iwI8iAA8hQCOSSKdXjiyflbAkG7u2s%2F%2B%2F%2F39%2F%2F7r8utrqEYtjQE8lgA7kwA7kwA9jwA9igA9hACiWSekVRyeSgiYSBHx6N%2F%2B%2Fv7k7OFRmiYtlAA5lwI7lwI4lAA7kgI9jwE9iwI4iQCoVhWcTxCmb0K%2BooT8%2Fv%2F7%2F%2F%2FJ2r8fdwI1mwA3mQA3mgA8lAE8lAE4jwA9iwE%2BhwGfXifWvqz%2B%2Ff%2F58u%2Fev6Dt4tr%2B%2F%2F2ZuIUsggA7mgM6mAM3lgA5lgA6kQE%2FkwBChwHt4dv%2F%2F%2F728ei1bCi7VAC5XQ7kz7n%2F%2F%2F6bsZkgcB03lQA9lgM7kwA2iQktZToPK4r9%2F%2F%2F9%2F%2F%2FSqYK5UwDKZAS9WALIkFn%2B%2F%2F3%2F%2BP8oKccGGcIRJrERILYFEMwAAuEAAdX%2F%2Ff7%2F%2FP%2B%2BfDvGXQLIZgLEWgLOjlf7%2F%2F%2F%2F%2F%2F9QU90EAPQAAf8DAP0AAfMAAOUDAtr%2F%2F%2F%2F7%2B%2Fu2bCTIYwDPZgDBWQDSr4P%2F%2Fv%2F%2F%2FP5GRuABAPkAA%2FwBAfkDAPAAAesAAN%2F%2F%2B%2Fz%2F%2F%2F64g1C5VwDMYwK8Yg7y5tz8%2Fv%2FV1PYKDOcAAP0DAf4AAf0AAfYEAOwAAuAAAAD%2F%2FPvi28ymXyChTATRrIb8%2F%2F3v8fk6P8MAAdUCAvoAAP0CAP0AAfYAAO4AAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAA</Image>
<Url type="application/x-suggestions+json" method="GET" template="http://suggestqueries.google.com/complete/search?output=firefox&amp;client=firefox&amp;hl={moz:locale}&amp;q={searchTerms}"/>
<Url type="text/html" method="GET" template="http://www.google.com/search" resultdomain="google.com">
<Param name="q" value="{searchTerms}"/>
<Param name="ie" value="utf-8"/>
<Param name="oe" value="utf-8"/>
<Param name="aq" value="t"/>
<!-- Dynamic parameters -->
<MozParam name="channel" condition="purpose" purpose="contextmenu" value="rcs"/>
<MozParam name="channel" condition="purpose" purpose="keyword" value="fflb"/>
</Url>
<Url type="application/x-moz-default-purpose" method="GET" template="http://www.google.com/search" resultdomain="purpose.google.com">
<Param name="q" value="{searchTerms}"/>
<!-- MozParam uses searchbar if purpose is not specified -->
<MozParam name="channel" condition="purpose" purpose="searchbar" value="ffsb"/>
<MozParam name="channel" condition="purpose" purpose="contextmenu" value="rcs"/>
<MozParam name="channel" condition="purpose" purpose="keyword" value="fflb"/>
</Url>
<SearchForm>http://www.google.com/</SearchForm>
</SearchPlugin>

File diff suppressed because one or more lines are too long

View file

@ -1,22 +0,0 @@
<!-- 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/. -->
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>IconsTest</ShortName>
<Description>IconsTest. Search by Test.</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16">data:image/x-icon;base64,ico16</Image>
<Image width="32" height="32">data:image/x-icon;base64,ico32</Image>
<Image width="74" height="74">data:image/png;base64,ico74</Image>
<Url type="application/x-suggestions+json" template="http://api.bing.com/osjson.aspx">
<Param name="query" value="{searchTerms}"/>
<Param name="form" value="MOZW"/>
</Url>
<Url type="text/html" method="GET" template="http://www.bing.com/search">
<Param name="q" value="{searchTerms}"/>
<MozParam name="pc" condition="pref" pref="ms-pc"/>
<Param name="form" value="MOZW"/>
</Url>
<SearchForm>http://www.bing.com/search</SearchForm>
</SearchPlugin>

View file

@ -1,54 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
/**
* Dynamically create a search engine offering search suggestions via searchSuggestions.sjs.
*
* The engine is constructed by passing a JSON object with engine datails as the query string.
*/
function handleRequest(request, response) {
let engineData = JSON.parse(unescape(request.queryString).replace("+", " "));
if (!engineData.baseURL) {
response.setStatusLine(request.httpVersion, 500, "baseURL required");
return;
}
engineData.name = engineData.name || "Generated test engine";
engineData.description = engineData.description || "Generated test engine description";
engineData.method = engineData.method || "GET";
response.setStatusLine(request.httpVersion, 200, "OK");
createOpenSearchEngine(response, engineData);
}
/**
* Create an OpenSearch engine for the given base URL.
*/
function createOpenSearchEngine(response, engineData) {
let params = "", queryString = "";
if (engineData.method == "POST") {
params = "<Param name='q' value='{searchTerms}'/>";
} else {
queryString = "?q={searchTerms}";
}
let result = "<?xml version='1.0' encoding='utf-8'?>\
<OpenSearchDescription xmlns='http://a9.com/-/spec/opensearch/1.1/'>\
<ShortName>" + engineData.name + "</ShortName>\
<Description>" + engineData.description + "</Description>\
<InputEncoding>UTF-8</InputEncoding>\
<LongName>" + engineData.name + "</LongName>\
<Url type='application/x-suggestions+json' method='" + engineData.method + "'\
template='" + engineData.baseURL + "searchSuggestions.sjs" + queryString + "'>\
" + params + "\
</Url>\
<Url type='text/html' method='" + engineData.method + "'\
template='" + engineData.baseURL + queryString + "'/>\
</OpenSearchDescription>\
";
response.write(result);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 901 B

View file

@ -1,23 +0,0 @@
<?xml version="1.0"?>
<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:em="http://www.mozilla.org/2004/em-rdf#">
<Description about="urn:mozilla:install-manifest">
<em:id>search-engine@tests.mozilla.org</em:id>
<em:unpack>true</em:unpack>
<em:version>1.0</em:version>
<em:targetApplication>
<Description>
<em:id>toolkit@mozilla.org</em:id>
<em:minVersion>0</em:minVersion>
<em:maxVersion>*</em:maxVersion>
</Description>
</em:targetApplication>
<!-- Front End MetaData -->
<em:name>Search Engine</em:name>
</Description>
</RDF>

View file

@ -1 +0,0 @@
# An invalid xml engine file.

View file

@ -1,5 +0,0 @@
{
"[app]/bug645970.xml": {
"alias": "lp"
}
}

View file

@ -1,7 +0,0 @@
{
"default": {
"visibleDefaultEngines": [
"engine", "engine-pref", "engine-rel-searchform-purpose", "engine-system-purpose", "engine-chromeicon", "engine-resourceicon"
]
}
}

View file

@ -1,30 +0,0 @@
{
"[global]": {
"searchdefaultexpir": 1471013469846
},
"[profile]\/engine.xml": {
"order": 1,
"alias": "foo"
},
"[app]\/google.xml": {
"order": 2
},
"[app]\/yahoo.xml": {
"order": 3
},
"[app]\/bing.xml": {
"order": 4
},
"[app]\/amazondotcom.xml": {
"order": 5
},
"[app]\/ddg.xml": {
"order": 6
},
"[app]\/twitter.xml": {
"order": 7
},
"[app]\/wikipedia.xml": {
"order": 8
}
}

View file

@ -1,86 +0,0 @@
{
"version": 1,
"buildID": "20121106",
"locale": "en-US",
"metaData": {},
"engines": [
{
"_name": "Test search engine",
"_shortName": "test-search-engine",
"description": "A test search engine (based on Google search)",
"extensionID": "test-addon-id@mozilla.org",
"__searchForm": "http://www.google.com/",
"_iconURL": "data:image/png;base64,AAABAAEAEBAAAAEAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs9Pt8xetPtu9FsfFNtu%2BTzvb2%2B%2Fne4dFJeBw0egA%2FfAJAfAA8ewBBegAAAAD%2B%2FPtft98Mp%2BwWsfAVsvEbs%2FQeqvF8xO7%2F%2F%2F63yqkxdgM7gwE%2FggM%2BfQA%2BegBDeQDe7PIbotgQufcMufEPtfIPsvAbs%2FQvq%2Bfz%2Bf%2F%2B%2B%2FZKhR05hgBBhQI8hgBAgAI9ewD0%2B%2Fg3pswAtO8Cxf4Kw%2FsJvvYAqupKsNv%2B%2Fv7%2F%2FP5VkSU0iQA7jQA9hgBDgQU%2BfQH%2F%2Ff%2FQ6fM4sM4KsN8AteMCruIqqdbZ7PH8%2Fv%2Fg6Nc%2Fhg05kAA8jAM9iQI%2BhQA%2BgQDQu6b97uv%2F%2F%2F7V8Pqw3eiWz97q8%2Ff%2F%2F%2F%2F7%2FPptpkkqjQE4kwA7kAA5iwI8iAA8hQCOSSKdXjiyflbAkG7u2s%2F%2B%2F%2F39%2F%2F7r8utrqEYtjQE8lgA7kwA7kwA9jwA9igA9hACiWSekVRyeSgiYSBHx6N%2F%2B%2Fv7k7OFRmiYtlAA5lwI7lwI4lAA7kgI9jwE9iwI4iQCoVhWcTxCmb0K%2BooT8%2Fv%2F7%2F%2F%2FJ2r8fdwI1mwA3mQA3mgA8lAE8lAE4jwA9iwE%2BhwGfXifWvqz%2B%2Ff%2F58u%2Fev6Dt4tr%2B%2F%2F2ZuIUsggA7mgM6mAM3lgA5lgA6kQE%2FkwBChwHt4dv%2F%2F%2F728ei1bCi7VAC5XQ7kz7n%2F%2F%2F6bsZkgcB03lQA9lgM7kwA2iQktZToPK4r9%2F%2F%2F9%2F%2F%2FSqYK5UwDKZAS9WALIkFn%2B%2F%2F3%2F%2BP8oKccGGcIRJrERILYFEMwAAuEAAdX%2F%2Ff7%2F%2FP%2B%2BfDvGXQLIZgLEWgLOjlf7%2F%2F%2F%2F%2F%2F9QU90EAPQAAf8DAP0AAfMAAOUDAtr%2F%2F%2F%2F7%2B%2Fu2bCTIYwDPZgDBWQDSr4P%2F%2Fv%2F%2F%2FP5GRuABAPkAA%2FwBAfkDAPAAAesAAN%2F%2F%2B%2Fz%2F%2F%2F64g1C5VwDMYwK8Yg7y5tz8%2Fv%2FV1PYKDOcAAP0DAf4AAf0AAfYEAOwAAuAAAAD%2F%2FPvi28ymXyChTATRrIb8%2F%2F3v8fk6P8MAAdUCAvoAAP0CAP0AAfYAAO4AAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAA",
"_metaData": {},
"_urls": [
{
"template": "http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl={moz:locale}&q={searchTerms}",
"rels": [
],
"type": "application/x-suggestions+json",
"params": [
]
},
{
"template": "http://www.google.com/search",
"resultDomain": "google.com",
"rels": [
],
"params": [
{
"name": "q",
"value": "{searchTerms}"
},
{
"name": "ie",
"value": "utf-8"
},
{
"name": "oe",
"value": "utf-8"
},
{
"name": "aq",
"value": "t"
},
{
"name": "channel",
"value": "fflb",
"purpose": "keyword"
},
{
"name": "channel",
"value": "rcs",
"purpose": "contextmenu"
}
]
},
{
"template": "http://www.google.com/search",
"resultDomain": "purpose.google.com",
"rels": [
],
"type": "application/x-moz-default-purpose",
"params": [
{
"name": "q",
"value": "{searchTerms}"
},
{
"name": "channel",
"value": "fflb",
"purpose": "keyword"
},
{
"name": "channel",
"value": "rcs",
"purpose": "contextmenu"
}
]
}
],
"queryCharset": "UTF-8",
"_readOnly": false
}
]
}

View file

@ -1,78 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/Timer.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
/**
* Provide search suggestions in the OpenSearch JSON format.
*/
function handleRequest(request, response) {
// Get the query parameters from the query string.
let query = parseQueryString(request.queryString);
function writeSuggestions(query, completions = []) {
let result = [query, completions];
response.write(JSON.stringify(result));
return result;
}
response.setStatusLine(request.httpVersion, 200, "OK");
let q = request.method == "GET" ? query.q : undefined;
if (q == "no remote" || q == "no results") {
writeSuggestions(q);
} else if (q == "Query Mismatch") {
writeSuggestions("This is an incorrect query string", ["some result"]);
} else if (q == "Query Case Mismatch") {
writeSuggestions(q.toUpperCase(), [q]);
} else if (q == "") {
writeSuggestions("", ["The server should never be sent an empty query"]);
} else if (q && q.startsWith("mo")) {
writeSuggestions(q, ["Mozilla", "modern", "mom"]);
} else if (q && q.startsWith("I ❤️")) {
writeSuggestions(q, ["I ❤️ Mozilla"]);
} else if (q && q.startsWith("letter ")) {
let letters = [];
for (let charCode = "A".charCodeAt(); charCode <= "Z".charCodeAt(); charCode++) {
letters.push("letter " + String.fromCharCode(charCode));
}
writeSuggestions(q, letters);
} else if (q && q.startsWith("HTTP ")) {
response.setStatusLine(request.httpVersion, q.replace("HTTP ", ""), q);
writeSuggestions(q, [q]);
} else if (q && q.startsWith("delay")) {
// Delay the response by 200 milliseconds (less than the timeout but hopefully enough to abort
// before completion).
response.processAsync();
writeSuggestions(q, [q]);
setTimeout(() => response.finish(), 200);
} else if (q && q.startsWith("slow ")) {
// Delay the response by 10 seconds so the client timeout is reached.
response.processAsync();
writeSuggestions(q, [q]);
setTimeout(() => response.finish(), 10000);
} else if (request.method == "POST") {
// This includes headers, not just the body
let requestText = NetUtil.readInputStreamToString(request.bodyInputStream,
request.bodyInputStream.available());
// Only use the last line which contains the encoded params
let requestLines = requestText.split("\n");
let postParams = parseQueryString(requestLines[requestLines.length - 1]);
writeSuggestions(postParams.q, ["Mozilla", "modern", "mom"]);
} else {
response.setStatusLine(request.httpVersion, 404, "Not Found");
}
}
function parseQueryString(queryString) {
let query = {};
queryString.split('&').forEach(function (val) {
let [name, value] = val.split('=');
query[name] = unescape(value).replace(/[+]/g, " ");
});
return query;
}

View file

@ -1,544 +0,0 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et: */
var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/osfile.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://testing-common/AppInfo.jsm");
Cu.import("resource://testing-common/httpd.js");
const BROWSER_SEARCH_PREF = "browser.search.";
const NS_APP_SEARCH_DIR = "SrchPlugns";
const MODE_RDONLY = FileUtils.MODE_RDONLY;
const MODE_WRONLY = FileUtils.MODE_WRONLY;
const MODE_CREATE = FileUtils.MODE_CREATE;
const MODE_TRUNCATE = FileUtils.MODE_TRUNCATE;
const CACHE_FILENAME = "search.json.mozlz4";
// nsSearchService.js uses Services.appinfo.name to build a salt for a hash.
var XULRuntime = Components.classesByID["{95d89e3e-a169-41a3-8e56-719978e15b12}"]
.getService(Ci.nsIXULRuntime);
var isChild = XULRuntime.processType == XULRuntime.PROCESS_TYPE_CONTENT;
updateAppInfo({
name: "XPCShell",
ID: "xpcshell@test.mozilla.org",
version: "5",
platformVersion: "1.9",
// mirror OS from the base impl as some of the "location" tests rely on it
OS: XULRuntime.OS,
// mirror processType from the base implementation
extraProps: {
processType: XULRuntime.processType,
},
});
var gProfD;
if (!isChild) {
// Need to create and register a profile folder.
gProfD = do_get_profile();
}
function dumpn(text)
{
dump("search test: " + text + "\n");
}
/**
* Configure preferences to load engines from
* chrome://testsearchplugin/locale/searchplugins/
*/
function configureToLoadJarEngines()
{
let url = "chrome://testsearchplugin/locale/searchplugins/";
let resProt = Services.io.getProtocolHandler("resource")
.QueryInterface(Ci.nsIResProtocolHandler);
resProt.setSubstitution("search-plugins",
Services.io.newURI(url, null, null));
// Ensure a test engine exists in the app dir anyway.
let dir = Services.dirsvc.get(NS_APP_SEARCH_DIR, Ci.nsIFile);
if (!dir.exists())
dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
do_get_file("data/engine-app.xml").copyTo(dir, "app.xml");
}
/**
* Fake the installation of an add-on in the profile, by creating the
* directory and registering it with the directory service.
*/
function installAddonEngine(name = "engine-addon")
{
const XRE_EXTENSIONS_DIR_LIST = "XREExtDL";
const profD = do_get_profile().QueryInterface(Ci.nsILocalFile);
let dir = profD.clone();
dir.append("extensions");
if (!dir.exists())
dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
dir.append("search-engine@tests.mozilla.org");
dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
do_get_file("data/install.rdf").copyTo(dir, "install.rdf");
let addonDir = dir.clone();
dir.append("searchplugins");
dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
do_get_file("data/" + name + ".xml").copyTo(dir, "bug645970.xml");
Services.dirsvc.registerProvider({
QueryInterface: XPCOMUtils.generateQI([Ci.nsIDirectoryServiceProvider,
Ci.nsIDirectoryServiceProvider2]),
getFile: function (prop, persistant) {
throw Cr.NS_ERROR_FAILURE;
},
getFiles: function (prop) {
let result = [];
switch (prop) {
case XRE_EXTENSIONS_DIR_LIST:
result.push(addonDir);
break;
default:
throw Cr.NS_ERROR_FAILURE;
}
return {
QueryInterface: XPCOMUtils.generateQI([Ci.nsISimpleEnumerator]),
hasMoreElements: () => result.length > 0,
getNext: () => result.shift()
};
}
});
}
/**
* Copy the engine-distribution.xml engine to a fake distribution
* created in the profile, and registered with the directory service.
*/
function installDistributionEngine()
{
const XRE_APP_DISTRIBUTION_DIR = "XREAppDist";
const profD = do_get_profile().QueryInterface(Ci.nsILocalFile);
let dir = profD.clone();
dir.append("distribution");
dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
let distDir = dir.clone();
dir.append("searchplugins");
dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
dir.append("common");
dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
do_get_file("data/engine-override.xml").copyTo(dir, "bug645970.xml");
Services.dirsvc.registerProvider({
getFile: function(aProp, aPersistent) {
aPersistent.value = true;
if (aProp == XRE_APP_DISTRIBUTION_DIR)
return distDir.clone();
return null;
}
});
}
/**
* Clean the profile of any metadata files left from a previous run.
*/
function removeMetadata()
{
let file = gProfD.clone();
file.append("search-metadata.json");
if (file.exists()) {
file.remove(false);
}
file = gProfD.clone();
file.append("search.sqlite");
if (file.exists()) {
file.remove(false);
}
}
function promiseCacheData() {
return new Promise(resolve => Task.spawn(function* () {
let path = OS.Path.join(OS.Constants.Path.profileDir, CACHE_FILENAME);
let bytes = yield OS.File.read(path, {compression: "lz4"});
resolve(JSON.parse(new TextDecoder().decode(bytes)));
}));
}
function promiseSaveCacheData(data) {
return OS.File.writeAtomic(OS.Path.join(OS.Constants.Path.profileDir, CACHE_FILENAME),
new TextEncoder().encode(JSON.stringify(data)),
{compression: "lz4"});
}
function promiseEngineMetadata() {
return new Promise(resolve => Task.spawn(function* () {
let cache = yield promiseCacheData();
let data = {};
for (let engine of cache.engines) {
data[engine._shortName] = engine._metaData;
}
resolve(data);
}));
}
function promiseGlobalMetadata() {
return new Promise(resolve => Task.spawn(function* () {
let cache = yield promiseCacheData();
resolve(cache.metaData);
}));
}
function promiseSaveGlobalMetadata(globalData) {
return new Promise(resolve => Task.spawn(function* () {
let data = yield promiseCacheData();
data.metaData = globalData;
yield promiseSaveCacheData(data);
resolve();
}));
}
var forceExpiration = Task.async(function* () {
let metadata = yield promiseGlobalMetadata();
// Make the current geodefaults expire 1s ago.
metadata.searchDefaultExpir = Date.now() - 1000;
yield promiseSaveGlobalMetadata(metadata);
});
/**
* Clean the profile of any cache file left from a previous run.
* Returns a boolean indicating if the cache file existed.
*/
function removeCacheFile()
{
let file = gProfD.clone();
file.append(CACHE_FILENAME);
if (file.exists()) {
file.remove(false);
return true;
}
return false;
}
/**
* isUSTimezone taken from nsSearchService.js
*/
function isUSTimezone() {
// Timezone assumptions! We assume that if the system clock's timezone is
// between Newfoundland and Hawaii, that the user is in North America.
// This includes all of South America as well, but we have relatively few
// en-US users there, so that's OK.
// 150 minutes = 2.5 hours (UTC-2.5), which is
// Newfoundland Daylight Time (http://www.timeanddate.com/time/zones/ndt)
// 600 minutes = 10 hours (UTC-10), which is
// Hawaii-Aleutian Standard Time (http://www.timeanddate.com/time/zones/hast)
let UTCOffset = (new Date()).getTimezoneOffset();
return UTCOffset >= 150 && UTCOffset <= 600;
}
const kDefaultenginenamePref = "browser.search.defaultenginename";
const kTestEngineName = "Test search engine";
const kLocalePref = "general.useragent.locale";
function getDefaultEngineName(isUS) {
const nsIPLS = Ci.nsIPrefLocalizedString;
// Copy the logic from nsSearchService
let pref = kDefaultenginenamePref;
if (isUS === undefined)
isUS = Services.prefs.getCharPref(kLocalePref) == "en-US" && isUSTimezone();
if (isUS) {
pref += ".US";
}
return Services.prefs.getComplexValue(pref, nsIPLS).data;
}
/**
* Waits for the cache file to be saved.
* @return {Promise} Resolved when the cache file is saved.
*/
function promiseAfterCache() {
return waitForSearchNotification("write-cache-to-disk-complete");
}
function parseJsonFromStream(aInputStream) {
const json = Cc["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON);
const data = json.decodeFromStream(aInputStream, aInputStream.available());
return data;
}
/**
* Read a JSON file and return the JS object
*/
function readJSONFile(aFile) {
let stream = Cc["@mozilla.org/network/file-input-stream;1"].
createInstance(Ci.nsIFileInputStream);
try {
stream.init(aFile, MODE_RDONLY, FileUtils.PERMS_FILE, 0);
return parseJsonFromStream(stream, stream.available());
} catch (ex) {
dumpn("readJSONFile: Error reading JSON file: " + ex);
} finally {
stream.close();
}
return false;
}
/**
* Recursively compare two objects and check that every property of expectedObj has the same value
* on actualObj.
*/
function isSubObjectOf(expectedObj, actualObj) {
for (let prop in expectedObj) {
if (expectedObj[prop] instanceof Object) {
do_check_eq(expectedObj[prop].length, actualObj[prop].length);
isSubObjectOf(expectedObj[prop], actualObj[prop]);
} else {
if (expectedObj[prop] != actualObj[prop])
do_print("comparing property " + prop);
do_check_eq(expectedObj[prop], actualObj[prop]);
}
}
}
// Can't set prefs if we're running in a child process, but the search service
// doesn't run in child processes anyways.
if (!isChild) {
// Expand the amount of information available in error logs
Services.prefs.setBoolPref("browser.search.log", true);
// The geo-specific search tests assume certain prefs are already setup, which
// might not be true when run in comm-central etc. So create them here.
Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", true);
Services.prefs.setIntPref("browser.search.geoip.timeout", 3000);
// But still disable geoip lookups - tests that need it will re-configure this.
Services.prefs.setCharPref("browser.search.geoip.url", "");
// Also disable region defaults - tests using it will also re-configure it.
Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref("geoSpecificDefaults.url", "");
}
/**
* After useHttpServer() is called, this string contains the URL of the "data"
* directory, including the final slash.
*/
var gDataUrl;
/**
* Initializes the HTTP server and ensures that it is terminated when tests end.
*
* @return The HttpServer object in case further customization is needed.
*/
function useHttpServer() {
let httpServer = new HttpServer();
httpServer.start(-1);
httpServer.registerDirectory("/", do_get_cwd());
gDataUrl = "http://localhost:" + httpServer.identity.primaryPort + "/data/";
do_register_cleanup(() => httpServer.stop(() => {}));
return httpServer;
}
/**
* Adds test engines and returns a promise resolved when they are installed.
*
* The engines are added in the given order.
*
* @param aItems
* Array of objects with the following properties:
* {
* name: Engine name, used to wait for it to be loaded.
* xmlFileName: Name of the XML file in the "data" folder.
* details: Array containing the parameters of addEngineWithDetails,
* except for the engine name. Alternative to xmlFileName.
* }
*/
var addTestEngines = Task.async(function* (aItems) {
if (!gDataUrl) {
do_throw("useHttpServer must be called before addTestEngines.");
}
let engines = [];
for (let item of aItems) {
do_print("Adding engine: " + item.name);
yield new Promise((resolve, reject) => {
Services.obs.addObserver(function obs(subject, topic, data) {
try {
let engine = subject.QueryInterface(Ci.nsISearchEngine);
do_print("Observed " + data + " for " + engine.name);
if (data != "engine-added" || engine.name != item.name) {
return;
}
Services.obs.removeObserver(obs, "browser-search-engine-modified");
engines.push(engine);
resolve();
} catch (ex) {
reject(ex);
}
}, "browser-search-engine-modified", false);
if (item.xmlFileName) {
Services.search.addEngine(gDataUrl + item.xmlFileName,
null, null, false);
} else {
Services.search.addEngineWithDetails(item.name, ...item.details);
}
});
}
return engines;
});
/**
* Installs a test engine into the test profile.
*/
function installTestEngine() {
removeMetadata();
removeCacheFile();
do_check_false(Services.search.isInitialized);
let engineDummyFile = gProfD.clone();
engineDummyFile.append("searchplugins");
engineDummyFile.append("test-search-engine.xml");
let engineDir = engineDummyFile.parent;
engineDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
do_get_file("data/engine.xml").copyTo(engineDir, "engine.xml");
do_register_cleanup(function() {
removeMetadata();
removeCacheFile();
});
}
/**
* Set a localized preference on the default branch
* @param aPrefName
* The name of the pref to set.
*/
function setLocalizedDefaultPref(aPrefName, aValue) {
let value = "data:text/plain," + BROWSER_SEARCH_PREF + aPrefName + "=" + aValue;
Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF)
.setCharPref(aPrefName, value);
}
/**
* Installs two test engines, sets them as default for US vs. general.
*/
function setUpGeoDefaults() {
removeMetadata();
removeCacheFile();
do_check_false(Services.search.isInitialized);
let engineDummyFile = gProfD.clone();
engineDummyFile.append("searchplugins");
engineDummyFile.append("test-search-engine.xml");
let engineDir = engineDummyFile.parent;
engineDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
do_get_file("data/engine.xml").copyTo(engineDir, "engine.xml");
engineDummyFile = gProfD.clone();
engineDummyFile.append("searchplugins");
engineDummyFile.append("test-search-engine2.xml");
do_get_file("data/engine2.xml").copyTo(engineDir, "engine2.xml");
setLocalizedDefaultPref("defaultenginename", "Test search engine");
setLocalizedDefaultPref("defaultenginename.US", "A second test engine");
do_register_cleanup(function() {
removeMetadata();
removeCacheFile();
});
}
/**
* Returns a promise that is resolved when an observer notification from the
* search service fires with the specified data.
*
* @param aExpectedData
* The value the observer notification sends that causes us to resolve
* the promise.
*/
function waitForSearchNotification(aExpectedData) {
return new Promise(resolve => {
const SEARCH_SERVICE_TOPIC = "browser-search-service";
Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
if (aData != aExpectedData)
return;
Services.obs.removeObserver(observer, SEARCH_SERVICE_TOPIC);
resolve(aSubject);
}, SEARCH_SERVICE_TOPIC, false);
});
}
function asyncInit() {
return new Promise(resolve => {
Services.search.init(function() {
do_check_true(Services.search.isInitialized);
resolve();
});
});
}
function asyncReInit() {
let promise = waitForSearchNotification("reinit-complete");
Services.search.QueryInterface(Ci.nsIObserver)
.observe(null, "nsPref:changed", kLocalePref);
return promise;
}
// This "enum" from nsSearchService.js
const TELEMETRY_RESULT_ENUM = {
SUCCESS: 0,
SUCCESS_WITHOUT_DATA: 1,
XHRTIMEOUT: 2,
ERROR: 3,
};
/**
* Checks the value of the SEARCH_SERVICE_COUNTRY_FETCH_RESULT probe.
*
* @param aExpectedValue
* If a value from TELEMETRY_RESULT_ENUM, we expect to see this value
* recorded exactly once in the probe. If |null|, we expect to see
* nothing recorded in the probe at all.
*/
function checkCountryResultTelemetry(aExpectedValue) {
let histogram = Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_FETCH_RESULT");
let snapshot = histogram.snapshot();
// The probe is declared with 8 values, but we get 9 back from .counts
let expectedCounts = [0, 0, 0, 0, 0, 0, 0, 0, 0];
if (aExpectedValue != null) {
expectedCounts[aExpectedValue] = 1;
}
deepEqual(snapshot.counts, expectedCounts);
}

View file

@ -1,22 +0,0 @@
/* -*- 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/. */
/**
* Test nsSearchService with nested jar: uris, without async initialization
*/
function run_test() {
updateAppInfo();
do_load_manifest("data/chrome.manifest");
configureToLoadJarEngines();
// The search service needs to be started after the jarURIs pref has been
// set in order to initiate it correctly
let engine = Services.search.getEngineByName("bug645970");
do_check_neq(engine, null);
Services.obs.notifyObservers(null, "quit-application", null);
}

View file

@ -1,27 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* Tests the SearchStaticData module.
*/
"use strict";
Cu.import("resource://gre/modules/SearchStaticData.jsm", this);
function run_test() {
do_check_true(SearchStaticData.getAlternateDomains("www.google.com")
.indexOf("www.google.fr") != -1);
do_check_true(SearchStaticData.getAlternateDomains("www.google.fr")
.indexOf("www.google.com") != -1);
do_check_true(SearchStaticData.getAlternateDomains("www.google.com")
.every(d => d.startsWith("www.google.")));
do_check_true(SearchStaticData.getAlternateDomains("google.com").length == 0);
// Test that methods from SearchStaticData module can be overwritten,
// needed for hotfixing.
let backup = SearchStaticData.getAlternateDomains;
SearchStaticData.getAlternateDomains = () => ["www.bing.fr"];
do_check_matches(SearchStaticData.getAlternateDomains("www.bing.com"), ["www.bing.fr"]);
SearchStaticData.getAlternateDomains = backup;
}

View file

@ -1,34 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
const kSearchEngineID = "addEngineWithDetails_test_engine";
const kSearchEngineURL = "http://example.com/?search={searchTerms}";
const kSearchTerm = "foo";
add_task(function* test_addEngineWithDetails() {
do_check_false(Services.search.isInitialized);
Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF)
.setBoolPref("reset.enabled", true);
yield asyncInit();
Services.search.addEngineWithDetails(kSearchEngineID, "", "", "", "get",
kSearchEngineURL);
// An engine added with addEngineWithDetails should have a load path, even
// though we can't point to a specific file.
let engine = Services.search.getEngineByName(kSearchEngineID);
do_check_eq(engine.wrappedJSObject._loadPath, "[other]addEngineWithDetails");
// Set the engine as default; this should set a loadPath verification hash,
// which should ensure we don't show the search reset prompt.
Services.search.currentEngine = engine;
let expectedURL = kSearchEngineURL.replace("{searchTerms}", kSearchTerm);
let submission =
Services.search.currentEngine.getSubmission(kSearchTerm, null, "searchbar");
do_check_eq(submission.uri.spec, expectedURL);
});

View file

@ -1,95 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* Tests covering nsIBrowserSearchService::addEngine's optional callback.
*/
Components.utils.import("resource://testing-common/MockRegistrar.jsm");
"use strict";
// Only need to stub the methods actually called by nsSearchService
var promptService = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptService]),
confirmEx: function() {}
};
var prompt = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIPrompt]),
alert: function() {}
};
// Override the prompt service and nsIPrompt, since the search service currently
// prompts in response to certain installation failures we test here
// XXX this should disappear once bug 863474 is fixed
MockRegistrar.register("@mozilla.org/embedcomp/prompt-service;1", promptService);
MockRegistrar.register("@mozilla.org/prompter;1", prompt);
// First test inits the search service
add_test(function init_search_service() {
Services.search.init(function (status) {
if (!Components.isSuccessCode(status))
do_throw("Failed to initialize search service");
run_next_test();
});
});
// Simple test of the search callback
add_test(function simple_callback_test() {
let searchCallback = {
onSuccess: function (engine) {
do_check_true(!!engine);
do_check_neq(engine.name, Services.search.defaultEngine.name);
do_check_eq(engine.wrappedJSObject._loadPath,
"[http]localhost/test-search-engine.xml");
run_next_test();
},
onError: function (errorCode) {
do_throw("search callback returned error: " + errorCode);
}
}
Services.search.addEngine(gDataUrl + "engine.xml", null,
null, false, searchCallback);
});
// Test of the search callback on duplicate engine failures
add_test(function duplicate_failure_test() {
let searchCallback = {
onSuccess: function (engine) {
do_throw("this addition should not have succeeded");
},
onError: function (errorCode) {
do_check_true(!!errorCode);
do_check_eq(errorCode, Ci.nsISearchInstallCallback.ERROR_DUPLICATE_ENGINE);
run_next_test();
}
}
// Re-add the same engine added in the previous test
Services.search.addEngine(gDataUrl + "engine.xml", null,
null, false, searchCallback);
});
// Test of the search callback on failure to load the engine failures
add_test(function load_failure_test() {
let searchCallback = {
onSuccess: function (engine) {
do_throw("this addition should not have succeeded");
},
onError: function (errorCode) {
do_check_true(!!errorCode);
do_check_eq(errorCode, Ci.nsISearchInstallCallback.ERROR_UNKNOWN_FAILURE);
run_next_test();
}
}
// Try adding an engine that doesn't exist
Services.search.addEngine("http://invalid/data/engine.xml", null,
null, false, searchCallback);
});
function run_test() {
updateAppInfo();
useHttpServer();
run_next_test();
}

View file

@ -1,34 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
do_test_pending();
removeMetadata();
removeCacheFile();
do_load_manifest("data/chrome.manifest");
configureToLoadJarEngines();
do_check_false(Services.search.isInitialized);
Services.search.init(function search_initialized(aStatus) {
do_check_true(Components.isSuccessCode(aStatus));
do_check_true(Services.search.isInitialized);
// test engines from dir are not loaded.
let engines = Services.search.getEngines();
do_check_eq(engines.length, 1);
// test jar engine is loaded ok.
let engine = Services.search.getEngineByName("bug645970");
do_check_neq(engine, null);
// Check the hidden engine is not loaded.
engine = Services.search.getEngineByName("hidden");
do_check_eq(engine, null);
do_test_finished();
});
}

View file

@ -1,33 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
do_test_pending();
removeMetadata();
removeCacheFile();
do_load_manifest("data/chrome.manifest");
configureToLoadJarEngines();
installAddonEngine();
do_check_false(Services.search.isInitialized);
Services.search.init(function search_initialized(aStatus) {
do_check_true(Components.isSuccessCode(aStatus));
do_check_true(Services.search.isInitialized);
// test the add-on engine is loaded in addition to our jar engine
let engines = Services.search.getEngines();
do_check_eq(engines.length, 2);
// test jar engine is loaded ok.
let engine = Services.search.getEngineByName("addon");
do_check_neq(engine, null);
do_check_eq(engine.description, "addon");
do_test_finished();
});
}

View file

@ -1,33 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
do_test_pending();
removeMetadata();
removeCacheFile();
do_load_manifest("data/chrome.manifest");
configureToLoadJarEngines();
installAddonEngine("engine-override");
do_check_false(Services.search.isInitialized);
Services.search.init(function search_initialized(aStatus) {
do_check_true(Components.isSuccessCode(aStatus));
do_check_true(Services.search.isInitialized);
// test the add-on engine isn't overriding our jar engine
let engines = Services.search.getEngines();
do_check_eq(engines.length, 1);
// test jar engine is loaded ok.
let engine = Services.search.getEngineByName("bug645970");
do_check_neq(engine, null);
do_check_eq(engine.description, "bug645970");
do_test_finished();
});
}

View file

@ -1,33 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
do_test_pending();
removeMetadata();
removeCacheFile();
do_load_manifest("data/chrome.manifest");
configureToLoadJarEngines();
installDistributionEngine();
do_check_false(Services.search.isInitialized);
Services.search.init(function search_initialized(aStatus) {
do_check_true(Components.isSuccessCode(aStatus));
do_check_true(Services.search.isInitialized);
// test that the engine from the distribution overrides our jar engine
let engines = Services.search.getEngines();
do_check_eq(engines.length, 1);
let engine = Services.search.getEngineByName("bug645970");
do_check_neq(engine, null);
// check the engine we have is actually the one from the distribution
do_check_eq(engine.description, "override");
do_test_finished();
});
}

View file

@ -1,27 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/* Test that legacy metadata from search-metadata.json is correctly
* transferred to the new metadata storage. */
function run_test() {
updateAppInfo();
installTestEngine();
do_get_file("data/metadata.json").copyTo(gProfD, "search-metadata.json");
run_next_test();
}
add_task(function* test_async_metadata_migration() {
yield asyncInit();
yield promiseAfterCache();
// Check that the entries are placed as specified correctly
let metadata = yield promiseEngineMetadata();
do_check_eq(metadata["engine"].order, 1);
do_check_eq(metadata["engine"].alias, "foo");
metadata = yield promiseGlobalMetadata();
do_check_eq(metadata["searchDefaultExpir"], 1471013469846);
});

View file

@ -1,42 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
const NS_APP_USER_SEARCH_DIR = "UsrSrchPlugns";
function run_test() {
do_test_pending();
removeMetadata();
removeCacheFile();
do_load_manifest("data/chrome.manifest");
configureToLoadJarEngines();
// Copy an engine in [profile]/searchplugin/ and ensure it's not
// overriding the same file from a jar.
// The description in the file we are copying is 'profile'.
let dir = Services.dirsvc.get(NS_APP_USER_SEARCH_DIR, Ci.nsIFile);
if (!dir.exists())
dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
do_get_file("data/engine-override.xml").copyTo(dir, "bug645970.xml");
do_check_false(Services.search.isInitialized);
Services.search.init(function search_initialized(aStatus) {
do_check_true(Components.isSuccessCode(aStatus));
do_check_true(Services.search.isInitialized);
// test engines from dir are not loaded.
let engines = Services.search.getEngines();
do_check_eq(engines.length, 1);
// test jar engine is loaded ok.
let engine = Services.search.getEngineByName("bug645970");
do_check_neq(engine, null);
do_check_eq(engine.description, "bug645970");
do_test_finished();
});
}

View file

@ -1,11 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test()
{
if (isChild) {
do_check_false("@mozilla.org/browser/search-service;1" in Cc);
} else {
do_check_true("@mozilla.org/browser/search-service;1" in Cc);
}
}

View file

@ -1,3 +0,0 @@
function run_test() {
run_test_in_child("test_bug930456.js");
}

View file

@ -1,31 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
/* Test that resource URLs can be used in default engines */
"use strict";
function run_test() {
updateAppInfo();
// The test engines used in this test need to be recognized as 'default'
// engines or the resource URL won't be used
let url = "resource://test/data/";
let resProt = Services.io.getProtocolHandler("resource")
.QueryInterface(Ci.nsIResProtocolHandler);
resProt.setSubstitution("search-plugins",
Services.io.newURI(url, null, null));
run_next_test();
}
add_task(function* test_defaultresourceicon() {
yield asyncInit();
let engine1 = Services.search.getEngineByName("engine-resourceicon");
do_check_eq(engine1.iconURI.spec, "resource://search-plugins/icon16.png");
do_check_eq(engine1.getIconURLBySize(32, 32), "resource://search-plugins/icon32.png");
let engine2 = Services.search.getEngineByName("engine-chromeicon");
do_check_eq(engine2.iconURI.spec, "chrome://branding/content/icon16.png");
do_check_eq(engine2.getIconURLBySize(32, 32), "chrome://branding/content/icon32.png");
});

View file

@ -1,23 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
/* Test that an installed engine can't use a resource URL for an icon */
"use strict";
function run_test() {
removeMetadata();
updateAppInfo();
useHttpServer();
run_next_test();
}
add_task(function* test_installedresourceicon() {
let [engine1, engine2] = yield addTestEngines([
{ name: "engine-resourceicon", xmlFileName: "engine-resourceicon.xml" },
{ name: "engine-chromeicon", xmlFileName: "engine-chromeicon.xml" },
]);
do_check_null(engine1.iconURI);
do_check_null(engine2.iconURI);
});

View file

@ -1,25 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
do_check_true(Services.search.getVisibleEngines().length > 1);
do_check_true(Services.search.isInitialized);
// Remove the current engine...
let currentEngine = Services.search.currentEngine;
Services.search.removeEngine(currentEngine);
// ... and verify a new current engine has been set.
do_check_neq(Services.search.currentEngine.name, currentEngine.name);
do_check_true(currentEngine.hidden);
// Remove all the other engines.
Services.search.getVisibleEngines().forEach(Services.search.removeEngine);
do_check_eq(Services.search.getVisibleEngines().length, 0);
// Verify the original default engine is used as a fallback and no
// longer hidden.
do_check_eq(Services.search.currentEngine.name, currentEngine.name);
do_check_false(currentEngine.hidden);
do_check_eq(Services.search.getVisibleEngines().length, 1);
}

View file

@ -1,51 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* Test that currentEngine and defaultEngine properties can be set and yield the
* proper events and behavior (search results)
*/
"use strict";
function run_test() {
removeMetadata();
updateAppInfo();
useHttpServer();
run_next_test();
}
add_task(function* test_defaultEngine() {
let search = Services.search;
let originalDefault = search.defaultEngine;
let [engine1, engine2] = yield addTestEngines([
{ name: "Test search engine", xmlFileName: "engine.xml" },
{ name: "A second test engine", xmlFileName: "engine2.xml" },
]);
search.defaultEngine = engine1;
do_check_eq(search.defaultEngine, engine1);
search.defaultEngine = engine2
do_check_eq(search.defaultEngine, engine2);
search.defaultEngine = engine1;
do_check_eq(search.defaultEngine, engine1);
// Test that hiding the currently-default engine affects the defaultEngine getter
// We fallback first to the original default...
engine1.hidden = true;
do_check_eq(search.defaultEngine, originalDefault);
// ... and then to the first visible engine in the list, so move our second
// engine to that position.
search.moveEngine(engine2, 0);
originalDefault.hidden = true;
do_check_eq(search.defaultEngine, engine2);
// Test that setting defaultEngine to an already-hidden engine works, but
// doesn't change the return value of the getter
search.defaultEngine = engine1;
do_check_eq(search.defaultEngine, engine2);
});

View file

@ -1,50 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/* Test that user-set metadata isn't lost on engine update */
"use strict";
function run_test() {
updateAppInfo();
useHttpServer();
run_next_test();
}
add_task(function* test_engineUpdate() {
const KEYWORD = "keyword";
const FILENAME = "engine.xml"
const TOPIC = "browser-search-engine-modified";
const ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;
yield asyncInit();
let [engine] = yield addTestEngines([
{ name: "Test search engine", xmlFileName: FILENAME },
]);
engine.alias = KEYWORD;
Services.search.moveEngine(engine, 0);
// can't have an accurate updateURL in the file since we can't know the test
// server origin, so manually set it
engine.wrappedJSObject._updateURL = gDataUrl + FILENAME;
yield new Promise(resolve => {
Services.obs.addObserver(function obs(subject, topic, data) {
if (data == "engine-loaded") {
let loadedEngine = subject.QueryInterface(Ci.nsISearchEngine);
let rawEngine = loadedEngine.wrappedJSObject;
equal(loadedEngine.alias, KEYWORD, "Keyword not cleared by update");
equal(rawEngine.getAttr("order"), 1, "Order not cleared by update");
Services.obs.removeObserver(obs, TOPIC, false);
resolve();
}
}, TOPIC, false);
// set last update to 8 days ago, since the default interval is 7, then
// trigger an update
engine.wrappedJSObject.setAttr("updateexpir", Date.now() - (ONE_DAY_IN_MS * 8));
Services.search.QueryInterface(Components.interfaces.nsITimerCallback).notify(null);
});
});

View file

@ -1,80 +0,0 @@
"use strict";
function run_test() {
useHttpServer();
run_next_test();
}
add_task(function* test_engine_set_alias() {
yield asyncInit();
do_print("Set engine alias");
let [engine1] = yield addTestEngines([
{
name: "bacon",
details: ["", "b", "Search Bacon", "GET", "http://www.bacon.test/find"]
}
]);
Assert.equal(engine1.alias, "b");
engine1.alias = "a";
Assert.equal(engine1.alias, "a");
Services.search.removeEngine(engine1);
});
add_task(function* test_engine_set_alias_with_left_space() {
do_print("Set engine alias with left space");
let [engine2] = yield addTestEngines([
{
name: "bacon",
details: ["", " a", "Search Bacon", "GET", "http://www.bacon.test/find"]
}
]);
Assert.equal(engine2.alias, "a");
engine2.alias = " c";
Assert.equal(engine2.alias, "c");
Services.search.removeEngine(engine2);
});
add_task(function* test_engine_set_alias_with_right_space() {
do_print("Set engine alias with right space");
let [engine3] = yield addTestEngines([
{
name: "bacon",
details: ["", "c ", "Search Bacon", "GET", "http://www.bacon.test/find"]
}
]);
Assert.equal(engine3.alias, "c");
engine3.alias = "o ";
Assert.equal(engine3.alias, "o");
Services.search.removeEngine(engine3);
});
add_task(function* test_engine_set_alias_with_right_left_space() {
do_print("Set engine alias with left and right space");
let [engine4] = yield addTestEngines([
{
name: "bacon",
details: ["", " o ", "Search Bacon", "GET", "http://www.bacon.test/find"]
}
]);
Assert.equal(engine4.alias, "o");
engine4.alias = " n ";
Assert.equal(engine4.alias, "n");
Services.search.removeEngine(engine4);
});
add_task(function* test_engine_set_alias_with_space() {
do_print("Set engine alias with space");
let [engine5] = yield addTestEngines([
{
name: "bacon",
details: ["", " ", "Search Bacon", "GET", "http://www.bacon.test/find"]
}
]);
Assert.equal(engine5.alias, null);
engine5.alias = "b";
Assert.equal(engine5.alias, "b");
engine5.alias = " ";
Assert.equal(engine5.alias, null);
Services.search.removeEngine(engine5);
});

View file

@ -1,253 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
var requests = [];
var gServerCohort = "";
const kUrlPref = "geoSpecificDefaults.url";
const kDayInSeconds = 86400;
const kYearInSeconds = kDayInSeconds * 365;
function run_test() {
updateAppInfo();
installTestEngine();
let srv = new HttpServer();
srv.registerPathHandler("/lookup_defaults", (metadata, response) => {
response.setStatusLine("1.1", 200, "OK");
let data = {interval: kYearInSeconds,
settings: {searchDefault: "Test search engine"}};
if (gServerCohort)
data.cohort = gServerCohort;
response.write(JSON.stringify(data));
requests.push(metadata);
});
srv.registerPathHandler("/lookup_fail", (metadata, response) => {
response.setStatusLine("1.1", 404, "Not Found");
requests.push(metadata);
});
srv.registerPathHandler("/lookup_unavailable", (metadata, response) => {
response.setStatusLine("1.1", 503, "Service Unavailable");
response.setHeader("Retry-After", kDayInSeconds.toString());
requests.push(metadata);
});
srv.start(-1);
do_register_cleanup(() => srv.stop(() => {}));
let url = "http://localhost:" + srv.identity.primaryPort + "/lookup_defaults?";
Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, url);
// Set a bogus user value so that running the test ensures we ignore it.
Services.prefs.setCharPref(BROWSER_SEARCH_PREF + kUrlPref, "about:blank");
Services.prefs.setCharPref("browser.search.geoip.url",
'data:application/json,{"country_code": "FR"}');
run_next_test();
}
function checkNoRequest() {
do_check_eq(requests.length, 0);
}
function checkRequest(cohort = "") {
do_check_eq(requests.length, 1);
let req = requests.pop();
do_check_eq(req._method, "GET");
do_check_eq(req._queryString, cohort ? "/" + cohort : "");
}
add_task(function* no_request_if_prefed_off() {
// Disable geoSpecificDefaults and check no HTTP request is made.
Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", false);
yield asyncInit();
checkNoRequest();
yield promiseAfterCache();
// The default engine should be set based on the prefs.
do_check_eq(Services.search.currentEngine.name, getDefaultEngineName(false));
// Ensure nothing related to geoSpecificDefaults has been written in the metadata.
let metadata = yield promiseGlobalMetadata();
do_check_eq(typeof metadata.searchDefaultExpir, "undefined");
do_check_eq(typeof metadata.searchDefault, "undefined");
do_check_eq(typeof metadata.searchDefaultHash, "undefined");
Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", true);
});
add_task(function* should_get_geo_defaults_only_once() {
// (Re)initializing the search service should trigger a request,
// and set the default engine based on it.
// Due to the previous initialization, we expect the countryCode to already be set.
do_check_true(Services.prefs.prefHasUserValue("browser.search.countryCode"));
do_check_eq(Services.prefs.getCharPref("browser.search.countryCode"), "FR");
yield asyncReInit();
checkRequest();
do_check_eq(Services.search.currentEngine.name, kTestEngineName);
yield promiseAfterCache();
// Verify the metadata was written correctly.
let metadata = yield promiseGlobalMetadata();
do_check_eq(typeof metadata.searchDefaultExpir, "number");
do_check_true(metadata.searchDefaultExpir > Date.now());
do_check_eq(typeof metadata.searchDefault, "string");
do_check_eq(metadata.searchDefault, "Test search engine");
do_check_eq(typeof metadata.searchDefaultHash, "string");
do_check_eq(metadata.searchDefaultHash.length, 44);
// The next restart shouldn't trigger a request.
yield asyncReInit();
checkNoRequest();
do_check_eq(Services.search.currentEngine.name, kTestEngineName);
});
add_task(function* should_request_when_countryCode_not_set() {
Services.prefs.clearUserPref("browser.search.countryCode");
yield asyncReInit();
checkRequest();
yield promiseAfterCache();
});
add_task(function* should_recheck_if_interval_expired() {
yield forceExpiration();
let date = Date.now();
yield asyncReInit();
checkRequest();
yield promiseAfterCache();
// Check that the expiration timestamp has been updated.
let metadata = yield promiseGlobalMetadata();
do_check_eq(typeof metadata.searchDefaultExpir, "number");
do_check_true(metadata.searchDefaultExpir >= date + kYearInSeconds * 1000);
do_check_true(metadata.searchDefaultExpir < date + (kYearInSeconds + 3600) * 1000);
});
add_task(function* should_recheck_when_broken_hash() {
// This test verifies both that we ignore saved geo-defaults if the
// hash is invalid, and that we keep the local preferences-based
// default for all of the session in case a synchronous
// initialization was triggered before our HTTP request completed.
let metadata = yield promiseGlobalMetadata();
// Break the hash.
let hash = metadata.searchDefaultHash;
metadata.searchDefaultHash = "broken";
yield promiseSaveGlobalMetadata(metadata);
let commitPromise = promiseAfterCache();
let unInitPromise = waitForSearchNotification("uninit-complete");
let reInitPromise = asyncReInit();
yield unInitPromise;
// Synchronously check the current default engine, to force a sync init.
// The hash is wrong, so we should fallback to the default engine from prefs.
do_check_false(Services.search.isInitialized)
do_check_eq(Services.search.currentEngine.name, getDefaultEngineName(false));
do_check_true(Services.search.isInitialized)
yield reInitPromise;
checkRequest();
yield commitPromise;
// Check that the hash is back to its previous value.
metadata = yield promiseGlobalMetadata();
do_check_eq(typeof metadata.searchDefaultHash, "string");
if (metadata.searchDefaultHash == "broken") {
// If the server takes more than 1000ms to return the result,
// the commitPromise was resolved by a first save of the cache
// that saved the engines, but not the request's results.
do_print("waiting for the cache to be saved a second time");
yield promiseAfterCache();
metadata = yield promiseGlobalMetadata();
}
do_check_eq(metadata.searchDefaultHash, hash);
// The current default engine shouldn't change during a session.
do_check_eq(Services.search.currentEngine.name, getDefaultEngineName(false));
// After another restart, the current engine should be back to the geo default,
// without doing yet another request.
yield asyncReInit();
checkNoRequest();
do_check_eq(Services.search.currentEngine.name, kTestEngineName);
});
add_task(function* should_remember_cohort_id() {
// Check that initially the cohort pref doesn't exist.
const cohortPref = "browser.search.cohort";
do_check_eq(Services.prefs.getPrefType(cohortPref), Services.prefs.PREF_INVALID);
// Make the server send a cohort id.
let cohort = gServerCohort = "xpcshell";
// Trigger a new request.
yield forceExpiration();
let commitPromise = promiseAfterCache();
yield asyncReInit();
checkRequest();
yield commitPromise;
// Check that the cohort was saved.
do_check_eq(Services.prefs.getPrefType(cohortPref), Services.prefs.PREF_STRING);
do_check_eq(Services.prefs.getCharPref(cohortPref), cohort);
// Make the server stop sending the cohort.
gServerCohort = "";
// Check that the next request sends the previous cohort id, and
// will remove it from the prefs due to the server no longer sending it.
yield forceExpiration();
commitPromise = promiseAfterCache();
yield asyncReInit();
checkRequest(cohort);
yield commitPromise;
do_check_eq(Services.prefs.getPrefType(cohortPref), Services.prefs.PREF_INVALID);
});
add_task(function* should_retry_after_failure() {
let defaultBranch = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF);
let originalUrl = defaultBranch.getCharPref(kUrlPref);
defaultBranch.setCharPref(kUrlPref, originalUrl.replace("defaults", "fail"));
// Trigger a new request.
yield forceExpiration();
yield asyncReInit();
checkRequest();
// After another restart, a new request should be triggered automatically without
// the test having to call forceExpiration again.
yield asyncReInit();
checkRequest();
});
add_task(function* should_honor_retry_after_header() {
let defaultBranch = Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF);
let originalUrl = defaultBranch.getCharPref(kUrlPref);
defaultBranch.setCharPref(kUrlPref, originalUrl.replace("fail", "unavailable"));
// Trigger a new request.
yield forceExpiration();
let date = Date.now();
let commitPromise = promiseAfterCache();
yield asyncReInit();
checkRequest();
yield commitPromise;
// Check that the expiration timestamp has been updated.
let metadata = yield promiseGlobalMetadata();
do_check_eq(typeof metadata.searchDefaultExpir, "number");
do_check_true(metadata.searchDefaultExpir >= date + kDayInSeconds * 1000);
do_check_true(metadata.searchDefaultExpir < date + (kDayInSeconds + 3600) * 1000);
// After another restart, a new request should not be triggered.
yield asyncReInit();
checkNoRequest();
});

View file

@ -1,135 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/**
* Tests the hasEngineWithURL() method of the nsIBrowserSearchService.
*/
function run_test() {
do_print("Setting up test");
updateAppInfo();
useHttpServer();
do_print("Test starting");
run_next_test();
}
// Return a discreet, cloned copy of an (engine) object.
function getEngineClone(engine) {
return JSON.parse(JSON.stringify(engine));
}
// Check whether and engine does or doesn't exist.
function checkEngineState(exists, engine) {
do_check_eq(exists, Services.search.hasEngineWithURL(engine.method,
engine.formURL,
engine.queryParams));
}
// Add a search engine for testing.
function addEngineWithParams(engine) {
Services.search.addEngineWithDetails(engine.name, null, null, null,
engine.method, engine.formURL);
let addedEngine = Services.search.getEngineByName(engine.name);
for (let param of engine.queryParams) {
addedEngine.addParam(param.name, param.value, null);
}
}
// Main test.
add_task(function* test_hasEngineWithURL() {
// Avoid deprecated synchronous initialization.
yield asyncInit();
// Setup various Engine definitions for method tests.
let UNSORTED_ENGINE = {
name: "mySearch Engine",
method: "GET",
formURL: "https://totallyNotRealSearchEngine.com/",
queryParams: [
{ name: "DDs", value: "38s" },
{ name: "DCs", value: "39s" },
{ name: "DDs", value: "39s" },
{ name: "DDs", value: "38s" },
{ name: "DDs", value: "37s" },
{ name: "DDs", value: "38s" },
{ name: "DEs", value: "38s" },
{ name: "DCs", value: "38s" },
{ name: "DEs", value: "37s" },
],
};
// Same as UNSORTED_ENGINE, but sorted.
let SORTED_ENGINE = {
name: "mySearch Engine",
method: "GET",
formURL: "https://totallyNotRealSearchEngine.com/",
queryParams: [
{ name: "DCs", value: "38s" },
{ name: "DCs", value: "39s" },
{ name: "DDs", value: "37s" },
{ name: "DDs", value: "38s" },
{ name: "DDs", value: "38s" },
{ name: "DDs", value: "38s" },
{ name: "DDs", value: "39s" },
{ name: "DEs", value: "37s" },
{ name: "DEs", value: "38s" },
],
};
// Unique variations of the SORTED_ENGINE.
let SORTED_ENGINE_METHOD_CHANGE = getEngineClone(SORTED_ENGINE);
SORTED_ENGINE_METHOD_CHANGE.method = "PoST";
let SORTED_ENGINE_FORMURL_CHANGE = getEngineClone(SORTED_ENGINE);
SORTED_ENGINE_FORMURL_CHANGE.formURL = "http://www.ahighrpowr.com/"
let SORTED_ENGINE_QUERYPARM_CHANGE = getEngineClone(SORTED_ENGINE);
SORTED_ENGINE_QUERYPARM_CHANGE.queryParams = [];
let SORTED_ENGINE_NAME_CHANGE = getEngineClone(SORTED_ENGINE);
SORTED_ENGINE_NAME_CHANGE.name += " 2";
// First ensure neither the unsorted engine, nor the same engine
// with a pre-sorted list of query parms matches.
checkEngineState(false, UNSORTED_ENGINE);
do_print("The unsorted version of the test engine does not exist.");
checkEngineState(false, SORTED_ENGINE);
do_print("The sorted version of the test engine does not exist.");
// Ensure variations of the engine definition do not match.
checkEngineState(false, SORTED_ENGINE_METHOD_CHANGE);
checkEngineState(false, SORTED_ENGINE_FORMURL_CHANGE);
checkEngineState(false, SORTED_ENGINE_QUERYPARM_CHANGE);
do_print("There are no modified versions of the sorted test engine.");
// Note that this method doesn't check name variations.
checkEngineState(false, SORTED_ENGINE_NAME_CHANGE);
do_print("There is no NAME modified version of the sorted test engine.");
// Add the unsorted engine and it's queryParams.
addEngineWithParams(UNSORTED_ENGINE);
do_print("The unsorted engine has been added.");
// Then, ensure we find a match for the unsorted engine, and for the
// same engine with a pre-sorted list of query parms.
checkEngineState(true, UNSORTED_ENGINE);
do_print("The unsorted version of the test engine now exists.");
checkEngineState(true, SORTED_ENGINE);
do_print("The sorted version of the same test engine also now exists.");
// Ensure variations of the engine definition still do not match.
checkEngineState(false, SORTED_ENGINE_METHOD_CHANGE);
checkEngineState(false, SORTED_ENGINE_FORMURL_CHANGE);
checkEngineState(false, SORTED_ENGINE_QUERYPARM_CHANGE);
do_print("There are still no modified versions of the sorted test engine.");
// Note that this method still doesn't check name variations.
checkEngineState(true, SORTED_ENGINE_NAME_CHANGE);
do_print("There IS now a NAME modified version of the sorted test engine.");
});

View file

@ -1,93 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
const kUrlPref = "geoSpecificDefaults.url";
function run_test() {
removeMetadata();
removeCacheFile();
do_load_manifest("data/chrome.manifest");
configureToLoadJarEngines();
// Geo specific defaults won't be fetched if there's no country code.
Services.prefs.setCharPref("browser.search.geoip.url",
'data:application/json,{"country_code": "US"}');
// Make 'hidden' the only visible engine.
let url = "data:application/json,{\"interval\": 31536000, \"settings\": {\"searchDefault\": \"hidden\", \"visibleDefaultEngines\": [\"hidden\"]}}";
Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, url);
do_check_false(Services.search.isInitialized);
run_next_test();
}
add_task(function* async_init() {
let commitPromise = promiseAfterCache()
yield asyncInit();
let engines = Services.search.getEngines();
do_check_eq(engines.length, 1);
// The default test jar engine has been hidden.
let engine = Services.search.getEngineByName("bug645970");
do_check_eq(engine, null);
// The hidden engine is visible.
engine = Services.search.getEngineByName("hidden");
do_check_neq(engine, null);
// The next test does a sync init, which won't do the geoSpecificDefaults XHR,
// so it depends on the metadata having been written to disk.
yield commitPromise;
});
add_task(function* sync_init() {
let unInitPromise = waitForSearchNotification("uninit-complete");
let reInitPromise = asyncReInit();
yield unInitPromise;
do_check_false(Services.search.isInitialized);
// Synchronously check the current default engine, to force a sync init.
do_check_eq(Services.search.currentEngine.name, "hidden");
do_check_true(Services.search.isInitialized);
let engines = Services.search.getEngines();
do_check_eq(engines.length, 1);
// The default test jar engine has been hidden.
let engine = Services.search.getEngineByName("bug645970");
do_check_eq(engine, null);
// The hidden engine is visible.
engine = Services.search.getEngineByName("hidden");
do_check_neq(engine, null);
yield reInitPromise;
});
add_task(function* invalid_engine() {
// Trigger a new request.
yield forceExpiration();
// Set the visibleDefaultEngines list to something that contains a non-existent engine.
// This should cause the search service to ignore the list altogether and fallback to
// local defaults.
let url = "data:application/json,{\"interval\": 31536000, \"settings\": {\"searchDefault\": \"hidden\", \"visibleDefaultEngines\": [\"hidden\", \"bogus\"]}}";
Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, url);
yield asyncReInit();
let engines = Services.search.getEngines();
do_check_eq(engines.length, 1);
// The default test jar engine is visible.
let engine = Services.search.getEngineByName("bug645970");
do_check_neq(engine, null);
// The hidden engine is... hidden.
engine = Services.search.getEngineByName("hidden");
do_check_eq(engine, null);
});

View file

@ -1,56 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* Test that a search engine's identifier can be extracted from the filename.
*/
"use strict";
const SEARCH_APP_DIR = 1;
function run_test() {
removeMetadata();
removeCacheFile();
do_load_manifest("data/chrome.manifest");
configureToLoadJarEngines();
updateAppInfo();
run_next_test();
}
add_test(function test_identifier() {
let engineFile = gProfD.clone();
engineFile.append("searchplugins");
engineFile.append("test-search-engine.xml");
engineFile.parent.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
// Copy the test engine to the test profile.
let engineTemplateFile = do_get_file("data/engine.xml");
engineTemplateFile.copyTo(engineFile.parent, "test-search-engine.xml");
Services.search.init(function initComplete(aResult) {
do_print("init'd search service");
do_check_true(Components.isSuccessCode(aResult));
let profileEngine = Services.search.getEngineByName("Test search engine");
let jarEngine = Services.search.getEngineByName("bug645970");
do_check_true(profileEngine instanceof Ci.nsISearchEngine);
do_check_true(jarEngine instanceof Ci.nsISearchEngine);
// An engine loaded from the profile directory won't have an identifier,
// because it's not built-in.
do_check_eq(profileEngine.identifier, null);
// An engine loaded from a JAR will have an identifier corresponding to
// the filename inside the JAR. (In this case it's the same as the name.)
do_check_eq(jarEngine.identifier, "bug645970");
removeMetadata();
removeCacheFile();
run_next_test();
});
});

View file

@ -1,55 +0,0 @@
/* -*- 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/. */
/**
* Test nsSearchService with with the following initialization scenario:
* - launch asynchronous initialization several times;
* - all asynchronous initializations must complete.
*
* Test case comes from test_645970.js
*/
function run_test() {
do_print("Setting up test");
do_test_pending();
updateAppInfo();
do_print("Test starting");
let numberOfInitializers = 4;
let pending = [];
let numberPending = numberOfInitializers;
// Start asynchronous initializations
for (let i = 0; i < numberOfInitializers; ++i) {
let me = i;
pending[me] = true;
Services.search.init(function search_initialized_0(aStatus) {
do_check_true(Components.isSuccessCode(aStatus));
init_complete(me);
});
}
// Wait until all initializers have completed
let init_complete = function init_complete(i) {
do_check_true(pending[i]);
pending[i] = false;
numberPending--;
do_check_true(numberPending >= 0);
do_check_true(Services.search.isInitialized);
if (numberPending == 0) {
// Just check that we can access a list of engines.
let engines = Services.search.getEngines();
do_check_neq(engines, null);
// Wait a little before quitting: if some initializer is
// triggered twice, we want to catch that error.
do_timeout(1000, function() {
do_test_finished();
});
}
};
}

View file

@ -1,68 +0,0 @@
/* -*- 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/. */
/**
* Test nsSearchService with with the following initialization scenario:
* - launch asynchronous initialization several times;
* - force fallback to synchronous initialization.
* - all asynchronous initializations must complete;
* - no asynchronous initialization must complete more than once.
*
* Test case comes from test_645970.js
*/
function run_test() {
do_print("Setting up test");
do_test_pending();
updateAppInfo();
do_print("Test starting");
let numberOfInitializers = 4;
let pending = [];
let numberPending = numberOfInitializers;
// Start asynchronous initializations
for (let i = 0; i < numberOfInitializers; ++i) {
let me = i;
pending[me] = true;
Services.search.init(function search_initialized(aStatus) {
do_check_true(Components.isSuccessCode(aStatus));
init_complete(me);
});
}
// Ensure that all asynchronous initializers eventually complete
let init_complete = function init_complete(i) {
do_print("init complete " + i);
do_check_true(pending[i]);
pending[i] = false;
numberPending--;
do_check_true(numberPending >= 0);
do_check_true(Services.search.isInitialized);
if (numberPending != 0) {
do_print("Still waiting for the following initializations: " + JSON.stringify(pending));
return;
}
do_print("All initializations have completed");
// Just check that we can access a list of engines.
let engines = Services.search.getEngines();
do_check_neq(engines, null);
do_print("Waiting a second before quitting");
// Wait a little before quitting: if some initializer is
// triggered twice, we want to catch that error.
do_timeout(1000, function() {
do_print("Test is complete");
do_test_finished();
});
};
// ... but don't wait for asynchronous initializations to complete
let engines = Services.search.getEngines();
do_check_neq(engines, null);
do_print("Synchronous part of the test complete");
}

View file

@ -1,35 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* Test that invalid engine files with xml extensions will not break
* initialization. See Bug 940446.
*/
function run_test() {
do_test_pending();
removeMetadata();
removeCacheFile();
do_check_false(Services.search.isInitialized);
let engineFile = gProfD.clone();
engineFile.append("searchplugins");
engineFile.append("test-search-engine.xml");
engineFile.parent.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
// Copy the invalid engine to the test profile.
let engineTemplateFile = do_get_file("data/invalid-engine.xml");
engineTemplateFile.copyTo(engineFile.parent, "test-search-engine.xml");
Services.search.init(function search_initialized(aStatus) {
// The invalid engine should have been skipped and should not
// have caused an exception.
do_check_true(Components.isSuccessCode(aStatus));
do_check_true(Services.search.isInitialized);
removeMetadata();
removeCacheFile();
do_test_finished();
});
}

View file

@ -1,227 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* Test initializing from the search cache.
*/
"use strict";
/**
* Gets a directory from the directory service.
* @param aKey
* The directory service key indicating the directory to get.
*/
var _dirSvc = null;
function getDir(aKey, aIFace) {
if (!aKey) {
FAIL("getDir requires a directory key!");
}
if (!_dirSvc) {
_dirSvc = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties);
}
return _dirSvc.get(aKey, aIFace || Ci.nsIFile);
}
function makeURI(uri) {
return Services.io.newURI(uri, null, null);
}
var cacheTemplate, appPluginsPath, profPlugins;
/**
* Test reading from search.json.mozlz4
*/
function run_test() {
removeMetadata();
removeCacheFile();
updateAppInfo();
let cacheTemplateFile = do_get_file("data/search.json");
cacheTemplate = readJSONFile(cacheTemplateFile);
cacheTemplate.buildID = getAppInfo().platformBuildID;
let engineFile = gProfD.clone();
engineFile.append("searchplugins");
engineFile.append("test-search-engine.xml");
engineFile.parent.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
// Copy the test engine to the test profile.
let engineTemplateFile = do_get_file("data/engine.xml");
engineTemplateFile.copyTo(engineFile.parent, "test-search-engine.xml");
// The list of visibleDefaultEngines needs to match or the cache will be ignored.
let chan = NetUtil.newChannel({
uri: "resource://search-plugins/list.json",
loadUsingSystemPrincipal: true
});
let sis = Cc["@mozilla.org/scriptableinputstream;1"].
createInstance(Ci.nsIScriptableInputStream);
sis.init(chan.open2());
let list = sis.read(sis.available());
let searchSettings = JSON.parse(list);
cacheTemplate.visibleDefaultEngines = searchSettings["default"]["visibleDefaultEngines"];
run_next_test();
}
add_test(function prepare_test_data() {
OS.File.writeAtomic(OS.Path.join(OS.Constants.Path.profileDir, CACHE_FILENAME),
new TextEncoder().encode(JSON.stringify(cacheTemplate)),
{compression: "lz4"})
.then(run_next_test);
});
/**
* Start the search service and confirm the engine properties match the expected values.
*/
add_test(function test_cached_engine_properties() {
do_print("init search service");
Services.search.init(function initComplete(aResult) {
do_print("init'd search service");
do_check_true(Components.isSuccessCode(aResult));
let engines = Services.search.getEngines({});
let engine = engines[0];
do_check_true(engine instanceof Ci.nsISearchEngine);
isSubObjectOf(EXPECTED_ENGINE.engine, engine);
let engineFromSS = Services.search.getEngineByName(EXPECTED_ENGINE.engine.name);
do_check_true(!!engineFromSS);
isSubObjectOf(EXPECTED_ENGINE.engine, engineFromSS);
removeMetadata();
removeCacheFile();
run_next_test();
});
});
/**
* Test that the JSON cache written in the profile is correct.
*/
add_test(function test_cache_write() {
do_print("test cache writing");
let cache = gProfD.clone();
cache.append(CACHE_FILENAME);
do_check_false(cache.exists());
do_print("Next step is forcing flush");
do_timeout(0, function forceFlush() {
do_print("Forcing flush");
// Force flush
// Note: the timeout is needed, to avoid some reentrency
// issues in nsSearchService.
let cacheWriteObserver = {
observe: function cacheWriteObserver_observe(aEngine, aTopic, aVerb) {
if (aTopic != "browser-search-service" || aVerb != "write-cache-to-disk-complete") {
return;
}
Services.obs.removeObserver(cacheWriteObserver, "browser-search-service");
do_print("Cache write complete");
do_check_true(cache.exists());
// Check that the search.json.mozlz4 cache matches the template
promiseCacheData().then(cacheWritten => {
do_print("Check search.json.mozlz4");
isSubObjectOf(cacheTemplate, cacheWritten);
run_next_test();
});
}
};
Services.obs.addObserver(cacheWriteObserver, "browser-search-service", false);
Services.search.QueryInterface(Ci.nsIObserver).observe(null, "browser-search-engine-modified", "engine-removed");
});
});
var EXPECTED_ENGINE = {
engine: {
name: "Test search engine",
alias: null,
description: "A test search engine (based on Google search)",
searchForm: "http://www.google.com/",
wrappedJSObject: {
_extensionID: "test-addon-id@mozilla.org",
"_iconURL": "data:image/png;base64,AAABAAEAEBAAAAEAGABoAwAAFgAAACgAAAAQAAAAIAAAAAEAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs9Pt8xetPtu9FsfFNtu%2BTzvb2%2B%2Fne4dFJeBw0egA%2FfAJAfAA8ewBBegAAAAD%2B%2FPtft98Mp%2BwWsfAVsvEbs%2FQeqvF8xO7%2F%2F%2F63yqkxdgM7gwE%2FggM%2BfQA%2BegBDeQDe7PIbotgQufcMufEPtfIPsvAbs%2FQvq%2Bfz%2Bf%2F%2B%2B%2FZKhR05hgBBhQI8hgBAgAI9ewD0%2B%2Fg3pswAtO8Cxf4Kw%2FsJvvYAqupKsNv%2B%2Fv7%2F%2FP5VkSU0iQA7jQA9hgBDgQU%2BfQH%2F%2Ff%2FQ6fM4sM4KsN8AteMCruIqqdbZ7PH8%2Fv%2Fg6Nc%2Fhg05kAA8jAM9iQI%2BhQA%2BgQDQu6b97uv%2F%2F%2F7V8Pqw3eiWz97q8%2Ff%2F%2F%2F%2F7%2FPptpkkqjQE4kwA7kAA5iwI8iAA8hQCOSSKdXjiyflbAkG7u2s%2F%2B%2F%2F39%2F%2F7r8utrqEYtjQE8lgA7kwA7kwA9jwA9igA9hACiWSekVRyeSgiYSBHx6N%2F%2B%2Fv7k7OFRmiYtlAA5lwI7lwI4lAA7kgI9jwE9iwI4iQCoVhWcTxCmb0K%2BooT8%2Fv%2F7%2F%2F%2FJ2r8fdwI1mwA3mQA3mgA8lAE8lAE4jwA9iwE%2BhwGfXifWvqz%2B%2Ff%2F58u%2Fev6Dt4tr%2B%2F%2F2ZuIUsggA7mgM6mAM3lgA5lgA6kQE%2FkwBChwHt4dv%2F%2F%2F728ei1bCi7VAC5XQ7kz7n%2F%2F%2F6bsZkgcB03lQA9lgM7kwA2iQktZToPK4r9%2F%2F%2F9%2F%2F%2FSqYK5UwDKZAS9WALIkFn%2B%2F%2F3%2F%2BP8oKccGGcIRJrERILYFEMwAAuEAAdX%2F%2Ff7%2F%2FP%2B%2BfDvGXQLIZgLEWgLOjlf7%2F%2F%2F%2F%2F%2F9QU90EAPQAAf8DAP0AAfMAAOUDAtr%2F%2F%2F%2F7%2B%2Fu2bCTIYwDPZgDBWQDSr4P%2F%2Fv%2F%2F%2FP5GRuABAPkAA%2FwBAfkDAPAAAesAAN%2F%2F%2B%2Fz%2F%2F%2F64g1C5VwDMYwK8Yg7y5tz8%2Fv%2FV1PYKDOcAAP0DAf4AAf0AAfYEAOwAAuAAAAD%2F%2FPvi28ymXyChTATRrIb8%2F%2F3v8fk6P8MAAdUCAvoAAP0CAP0AAfYAAO4AAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAA",
_urls : [
{
type: "application/x-suggestions+json",
method: "GET",
template: "http://suggestqueries.google.com/complete/search?output=firefox&client=firefox" +
"&hl={moz:locale}&q={searchTerms}",
params: "",
},
{
type: "text/html",
method: "GET",
template: "http://www.google.com/search",
resultDomain: "google.com",
params: [
{
"name": "q",
"value": "{searchTerms}",
"purpose": undefined,
},
{
"name": "ie",
"value": "utf-8",
"purpose": undefined,
},
{
"name": "oe",
"value": "utf-8",
"purpose": undefined,
},
{
"name": "aq",
"value": "t",
"purpose": undefined,
},
{
"name": "channel",
"value": "fflb",
"purpose": "keyword",
},
{
"name": "channel",
"value": "rcs",
"purpose": "contextmenu",
},
],
},
{
type: "application/x-moz-default-purpose",
method: "GET",
template: "http://www.google.com/search",
resultDomain: "purpose.google.com",
params: [
{
"name": "q",
"value": "{searchTerms}",
"purpose": undefined,
},
{
"name": "channel",
"value": "fflb",
"purpose": "keyword",
},
{
"name": "channel",
"value": "rcs",
"purpose": "contextmenu",
},
],
},
],
},
},
};

View file

@ -1,66 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
installTestEngine();
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "AU"}');
Services.search.init(() => {
equal(Services.prefs.getCharPref("browser.search.countryCode"), "AU", "got the correct country code.");
equal(Services.prefs.getCharPref("browser.search.region"), "AU", "region pref also set to the countryCode.")
// No isUS pref is ever written
ok(!Services.prefs.prefHasUserValue("browser.search.isUS"), "no isUS pref")
// check we have "success" recorded in telemetry
checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS);
// a false value for each of SEARCH_SERVICE_COUNTRY_TIMEOUT and SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT
for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
"SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
let histogram = Services.telemetry.getHistogramById(hid);
let snapshot = histogram.snapshot();
deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
}
// simple checks for our platform-specific telemetry. We can't influence
// what they return (as we can't influence the countryCode the platform
// thinks we are in), but we can check the values are correct given reality.
let probeUSMismatched, probeNonUSMismatched;
switch (Services.appinfo.OS) {
case "Darwin":
probeUSMismatched = "SEARCH_SERVICE_US_COUNTRY_MISMATCHED_PLATFORM_OSX";
probeNonUSMismatched = "SEARCH_SERVICE_NONUS_COUNTRY_MISMATCHED_PLATFORM_OSX";
break;
case "WINNT":
probeUSMismatched = "SEARCH_SERVICE_US_COUNTRY_MISMATCHED_PLATFORM_WIN";
probeNonUSMismatched = "SEARCH_SERVICE_NONUS_COUNTRY_MISMATCHED_PLATFORM_WIN";
break;
default:
break;
}
if (probeUSMismatched && probeNonUSMismatched) {
let countryCode = Services.sysinfo.get("countryCode");
print("Platform says the country-code is", countryCode);
let expectedResult;
let hid;
// We know geoip said AU - if the platform thinks US then we expect
// probeUSMismatched with true (ie, a mismatch)
if (countryCode == "US") {
hid = probeUSMismatched;
expectedResult = [0, 1, 0]; // boolean probe so 3 buckets, expect 1 result for |1|.
} else {
// We are expecting probeNonUSMismatched with false if the platform
// says AU (not a mismatch) and true otherwise.
hid = probeNonUSMismatched;
expectedResult = countryCode == "AU" ? [1, 0, 0] : [0, 1, 0];
}
let histogram = Services.telemetry.getHistogramById(hid);
let snapshot = histogram.snapshot();
deepEqual(snapshot.counts, expectedResult);
}
do_test_finished();
run_next_test();
});
do_test_pending();
}

View file

@ -1,30 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
installTestEngine();
// We use an invalid port that parses but won't open
let url = "http://localhost:0";
Services.prefs.setCharPref("browser.search.geoip.url", url);
Services.search.init(() => {
try {
Services.prefs.getCharPref("browser.search.countryCode");
ok(false, "not expecting countryCode to be set");
} catch (ex) {}
// should have an error recorded.
checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.ERROR);
// but false values for timeout and forced-sync-init.
for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
"SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
let histogram = Services.telemetry.getHistogramById(hid);
let snapshot = histogram.snapshot();
deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
}
do_test_finished();
run_next_test();
});
do_test_pending();
}

View file

@ -1,17 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "US"}');
// funnelcake builds start with "mozilla"
Services.prefs.setCharPref("distribution.id", 'mozilla38');
setUpGeoDefaults();
Services.search.init(() => {
equal(Services.search.defaultEngine.name, "A second test engine");
do_test_finished();
run_next_test();
});
do_test_pending();
}

View file

@ -1,57 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
// A console listener so we can listen for a log message from nsSearchService.
function promiseTimezoneMessage() {
return new Promise(resolve => {
let listener = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIConsoleListener]),
observe : function (msg) {
if (msg.message.startsWith("getIsUS() fell back to a timezone check with the result=")) {
Services.console.unregisterListener(listener);
resolve(msg);
}
}
};
Services.console.registerListener(listener);
});
}
function run_test() {
installTestEngine();
// setup a console listener for the timezone fallback message.
let promiseTzMessage = promiseTimezoneMessage();
// Here we have malformed JSON
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code"');
Services.search.init(() => {
ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
ok(!Services.prefs.prefHasUserValue("browser.search.isUS"), "should never be an isUS pref");
// fetch the engines - this should force the timezone check, but still
// doesn't persist any prefs.
Services.search.getEngines();
ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
ok(!Services.prefs.prefHasUserValue("browser.search.isUS"), "should never be an isUS pref");
// should have recorded SUCCESS_WITHOUT_DATA
checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS_WITHOUT_DATA);
// and false values for timeout and forced-sync-init.
for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
"SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
let histogram = Services.telemetry.getHistogramById(hid);
let snapshot = histogram.snapshot();
deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
}
// Check we saw the timezone fallback message.
promiseTzMessage.then(msg => {
print("Timezone message:", msg.message);
ok(msg.message.endsWith(isUSTimezone().toString()), "fell back to timezone and it matches our timezone");
do_test_finished();
run_next_test();
});
});
do_test_pending();
}

View file

@ -1,24 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
// Here we are testing the "migration" when both isUS and countryCode are
// set.
function run_test() {
installTestEngine();
// Set the prefs we care about.
Services.prefs.setBoolPref("browser.search.isUS", true);
Services.prefs.setCharPref("browser.search.countryCode", "US");
// And the geoip request that will return AU - it shouldn't be used.
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "AU"}');
Services.search.init(() => {
// "region" and countryCode should still reflect US.
equal(Services.prefs.getCharPref("browser.search.region"), "US", "got the correct region.");
equal(Services.prefs.getCharPref("browser.search.countryCode"), "US", "got the correct country code.");
// should be no geoip evidence.
checkCountryResultTelemetry(null);
do_test_finished();
run_next_test();
});
do_test_pending();
}

View file

@ -1,30 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
// Here we are testing the "migration" from the isUS pref being true but when
// no country-code exists.
function run_test() {
installTestEngine();
// Set the pref we care about.
Services.prefs.setBoolPref("browser.search.isUS", true);
// And the geoip request that will return *not* US.
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "AU"}');
Services.search.init(() => {
// "region" should be set to US, but countryCode to AU.
equal(Services.prefs.getCharPref("browser.search.region"), "US", "got the correct region.");
equal(Services.prefs.getCharPref("browser.search.countryCode"), "AU", "got the correct country code.");
// check we have "success" recorded in telemetry
checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS);
// a false value for each of SEARCH_SERVICE_COUNTRY_TIMEOUT and SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT
for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
"SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
let histogram = Services.telemetry.getHistogramById(hid);
let snapshot = histogram.snapshot();
deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
}
do_test_finished();
run_next_test();
});
do_test_pending();
}

View file

@ -1,30 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
// Here we are testing the "migration" from the isUS pref being false but when
// no country-code exists.
function run_test() {
installTestEngine();
// Set the pref we care about.
Services.prefs.setBoolPref("browser.search.isUS", false);
// And the geoip request that will return US.
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "US"}');
Services.search.init(() => {
// "region" and countryCode should reflect US.
equal(Services.prefs.getCharPref("browser.search.region"), "US", "got the correct region.");
equal(Services.prefs.getCharPref("browser.search.countryCode"), "US", "got the correct country code.");
// check we have "success" recorded in telemetry
checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS);
// a false value for each of SEARCH_SERVICE_COUNTRY_TIMEOUT and SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT
for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT",
"SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) {
let histogram = Services.telemetry.getHistogramById(hid);
let snapshot = histogram.snapshot();
deepEqual(snapshot.counts, [1, 0, 0]); // boolean probe so 3 buckets, expect 1 result for |0|.
}
do_test_finished();
run_next_test();
});
do_test_pending();
}

View file

@ -1,16 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "US"}');
Services.prefs.setCharPref("distribution.id", 'partner-1');
setUpGeoDefaults();
Services.search.init(() => {
equal(Services.search.defaultEngine.name, "Test search engine");
do_test_finished();
run_next_test();
});
do_test_pending();
}

View file

@ -1,101 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function getCountryCodePref() {
try {
return Services.prefs.getCharPref("browser.search.countryCode");
} catch (_) {
return undefined;
}
}
function getIsUSPref() {
try {
return Services.prefs.getBoolPref("browser.search.isUS");
} catch (_) {
return undefined;
}
}
// A console listener so we can listen for a log message from nsSearchService.
function promiseTimezoneMessage() {
return new Promise(resolve => {
let listener = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIConsoleListener]),
observe : function (msg) {
if (msg.message.startsWith("getIsUS() fell back to a timezone check with the result=")) {
Services.console.unregisterListener(listener);
resolve(msg);
}
}
};
Services.console.registerListener(listener);
});
}
function run_test() {
installTestEngine();
run_next_test();
}
// Force a sync init and ensure the right thing happens (ie, that no xhr
// request is made and we fall back to the timezone-only trick)
add_task(function* test_simple() {
deepEqual(getCountryCodePref(), undefined, "no countryCode pref");
deepEqual(getIsUSPref(), undefined, "no isUS pref");
// Still set a geoip pref so we can (indirectly) check it wasn't used.
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "AU"}');
ok(!Services.search.isInitialized);
// setup a console listener for the timezone fallback message.
let promiseTzMessage = promiseTimezoneMessage();
// fetching the engines forces a sync init, and should have caused us to
// check the timezone.
Services.search.getEngines();
ok(Services.search.isInitialized);
// a little wait to check we didn't do the xhr thang.
yield new Promise(resolve => {
do_timeout(500, resolve);
});
let msg = yield promiseTzMessage;
print("Timezone message:", msg.message);
ok(msg.message.endsWith(isUSTimezone().toString()), "fell back to timezone and it matches our timezone");
deepEqual(getCountryCodePref(), undefined, "didn't do the geoip xhr");
// and no telemetry evidence of geoip.
for (let hid of [
"SEARCH_SERVICE_COUNTRY_FETCH_RESULT",
"SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS",
"SEARCH_SERVICE_COUNTRY_TIMEOUT",
"SEARCH_SERVICE_US_COUNTRY_MISMATCHED_TIMEZONE",
"SEARCH_SERVICE_US_TIMEZONE_MISMATCHED_COUNTRY",
"SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT",
]) {
let histogram = Services.telemetry.getHistogramById(hid);
let snapshot = histogram.snapshot();
equal(snapshot.sum, 0, hid);
switch (snapshot.histogram_type) {
case Ci.nsITelemetry.HISTOGRAM_FLAG:
// flags are a special case in that they are initialized with a default
// of one |0|.
deepEqual(snapshot.counts, [1, 0, 0], hid);
break;
case Ci.nsITelemetry.HISTOGRAM_BOOLEAN:
// booleans aren't initialized at all, so should have all zeros.
deepEqual(snapshot.counts, [0, 0, 0], hid);
break;
case Ci.nsITelemetry.HISTOGRAM_EXPONENTIAL:
case Ci.nsITelemetry.HISTOGRAM_LINEAR:
equal(snapshot.counts.reduce((a, b) => a+b), 0, hid);
break;
default:
ok(false, "unknown histogram type " + snapshot.histogram_type + " for " + hid);
}
}
});

View file

@ -1,78 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
// This is testing the "normal" timer-based timeout for the location search.
function startServer(continuePromise) {
let srv = new HttpServer();
function lookupCountry(metadata, response) {
response.processAsync();
// wait for our continuePromise to resolve before writing a valid
// response.
// This will be resolved after the timeout period, so we can check
// the behaviour in that case.
continuePromise.then(() => {
response.setStatusLine("1.1", 200, "OK");
response.write('{"country_code" : "AU"}');
response.finish();
});
}
srv.registerPathHandler("/lookup_country", lookupCountry);
srv.start(-1);
return srv;
}
function getProbeSum(probe, sum) {
let histogram = Services.telemetry.getHistogramById(probe);
return histogram.snapshot().sum;
}
function run_test() {
installTestEngine();
let resolveContinuePromise;
let continuePromise = new Promise(resolve => {
resolveContinuePromise = resolve;
});
let server = startServer(continuePromise);
let url = "http://localhost:" + server.identity.primaryPort + "/lookup_country";
Services.prefs.setCharPref("browser.search.geoip.url", url);
Services.prefs.setIntPref("browser.search.geoip.timeout", 50);
Services.search.init(() => {
ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
// should be no result recorded at all.
checkCountryResultTelemetry(null);
// should have set the flag indicating we saw a timeout.
let histogram = Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_TIMEOUT");
let snapshot = histogram.snapshot();
deepEqual(snapshot.counts, [0, 1, 0]);
// should not yet have SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS recorded as our
// test server is still blocked on our promise.
equal(getProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS"), 0);
waitForSearchNotification("geoip-lookup-xhr-complete").then(() => {
// now we *should* have a report of how long the response took even though
// it timed out.
// The telemetry "sum" will be the actual time in ms - just check it's non-zero.
ok(getProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS") != 0);
// should have reported the fetch ended up being successful
checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS);
// and should have the result of the response that finally came in, and
// everything dependent should also be updated.
equal(Services.prefs.getCharPref("browser.search.countryCode"), "AU");
equal(Services.prefs.getCharPref("browser.search.region"), "AU");
ok(!Services.prefs.prefHasUserValue("browser.search.isUS"), "should never have an isUS pref");
do_test_finished();
server.stop(run_next_test);
});
// now tell the server to send its response. That will end up causing the
// search service to notify of that the response was received.
resolveContinuePromise();
});
do_test_pending();
}

View file

@ -1,85 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
// This is testing the long, last-resort XHR-based timeout for the location
// search.
function startServer(continuePromise) {
let srv = new HttpServer();
function lookupCountry(metadata, response) {
response.processAsync();
// wait for our continuePromise to resolve before writing a valid
// response.
// This will be resolved after the timeout period, so we can check
// the behaviour in that case.
continuePromise.then(() => {
response.setStatusLine("1.1", 200, "OK");
response.write('{"country_code" : "AU"}');
response.finish();
});
}
srv.registerPathHandler("/lookup_country", lookupCountry);
srv.start(-1);
return srv;
}
function verifyProbeSum(probe, sum) {
let histogram = Services.telemetry.getHistogramById(probe);
let snapshot = histogram.snapshot();
equal(snapshot.sum, sum, probe);
}
function run_test() {
installTestEngine();
let resolveContinuePromise;
let continuePromise = new Promise(resolve => {
resolveContinuePromise = resolve;
});
let server = startServer(continuePromise);
let url = "http://localhost:" + server.identity.primaryPort + "/lookup_country";
Services.prefs.setCharPref("browser.search.geoip.url", url);
// The timeout for the timer.
Services.prefs.setIntPref("browser.search.geoip.timeout", 10);
let promiseXHRStarted = waitForSearchNotification("geoip-lookup-xhr-starting");
Services.search.init(() => {
ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
// should be no result recorded at all.
checkCountryResultTelemetry(null);
// should have set the flag indicating we saw a timeout.
let histogram = Services.telemetry.getHistogramById("SEARCH_SERVICE_COUNTRY_TIMEOUT");
let snapshot = histogram.snapshot();
deepEqual(snapshot.counts, [0, 1, 0]);
// should not have SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS recorded as our
// test server is still blocked on our promise.
verifyProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS", 0);
promiseXHRStarted.then(xhr => {
// Set the timeout on the xhr object to an extremely low value, so it
// should timeout immediately.
xhr.timeout = 10;
// wait for the xhr timeout to fire.
waitForSearchNotification("geoip-lookup-xhr-complete").then(() => {
// should have the XHR timeout recorded.
checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.XHRTIMEOUT);
// still should not have a report of how long the response took as we
// only record that on success responses.
verifyProbeSum("SEARCH_SERVICE_COUNTRY_FETCH_TIME_MS", 0);
// and we still don't know the country code or region.
ok(!Services.prefs.prefHasUserValue("browser.search.countryCode"), "should be no countryCode pref");
ok(!Services.prefs.prefHasUserValue("browser.search.region"), "should be no region pref");
// unblock the server even though nothing is listening.
resolveContinuePromise();
do_test_finished();
server.stop(run_next_test);
});
});
});
do_test_pending();
}

View file

@ -1,37 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
removeMetadata();
removeCacheFile();
do_load_manifest("data/chrome.manifest");
configureToLoadJarEngines();
// Unless we unset the XPCSHELL_TEST_PROFILE_DIR environment variable,
// engine._isDefault will be true for engines from the resource:// scheme,
// bypassing the codepath we want to test.
let env = Cc["@mozilla.org/process/environment;1"]
.getService(Ci.nsIEnvironment);
env.set("XPCSHELL_TEST_PROFILE_DIR", "");
do_get_file("data/langpack-metadata.json").copyTo(gProfD, "search-metadata.json");
do_check_false(Services.search.isInitialized);
run_next_test();
}
add_task(function* async_init() {
let commitPromise = promiseAfterCache()
yield asyncInit();
let engine = Services.search.getEngineByName("bug645970");
do_check_neq(engine, null);
do_check_eq(engine.wrappedJSObject._id, "[app]/bug645970.xml");
yield commitPromise;
let metadata = yield promiseEngineMetadata();
do_check_eq(metadata["bug645970"].alias, "lp");
});

View file

@ -1,61 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* Tests getIcons() and getIconURLBySize() on engine with multiple icons.
*/
"use strict";
function run_test() {
removeMetadata();
updateAppInfo();
useHttpServer();
run_next_test();
}
add_task(function* test_multipleIcons() {
let [engine] = yield addTestEngines([
{ name: "IconsTest", xmlFileName: "engineImages.xml" },
]);
do_print("The default should be the 16x16 icon");
do_check_true(engine.iconURI.spec.includes("ico16"));
do_check_true(engine.getIconURLBySize(16, 16).includes("ico16"));
do_check_true(engine.getIconURLBySize(32, 32).includes("ico32"));
do_check_true(engine.getIconURLBySize(74, 74).includes("ico74"));
do_print("Invalid dimensions should return null.");
do_check_null(engine.getIconURLBySize(50, 50));
let allIcons = engine.getIcons();
do_print("Check that allIcons contains expected icon sizes");
do_check_eq(allIcons.length, 3);
let expectedWidths = [16, 32, 74];
do_check_true(allIcons.every((item) => {
let width = item.width;
do_check_neq(expectedWidths.indexOf(width), -1);
do_check_eq(width, item.height);
let icon = item.url.split(",").pop();
do_check_eq(icon, "ico" + width);
return true;
}));
});
add_task(function* test_icon_not_in_file() {
let engineUrl = gDataUrl + "engine-fr.xml";
let engine = yield new Promise((resolve, reject) => {
Services.search.addEngine(engineUrl, null, "data:image/x-icon;base64,ico16",
false, {onSuccess: resolve, onError: reject});
});
// Even though the icon wasn't specified inside the XML file, it should be
// available both in the iconURI attribute and with getIconURLBySize.
do_check_true(engine.iconURI.spec.includes("ico16"));
do_check_true(engine.getIconURLBySize(16, 16).includes("ico16"));
});

View file

@ -1,60 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* test_nocache: Start search engine
* - without search.json.mozlz4
*
* Ensure that :
* - nothing explodes;
* - search.json.mozlz4 is created.
*/
function run_test()
{
removeCacheFile();
updateAppInfo();
do_load_manifest("data/chrome.manifest");
useHttpServer();
run_next_test();
}
add_task(function* test_nocache() {
let search = Services.search;
let afterCachePromise = promiseAfterCache();
yield new Promise((resolve, reject) => search.init(rv => {
Components.isSuccessCode(rv) ? resolve() : reject();
}));
// Check that the cache is created at startup
yield afterCachePromise;
// Check that search.json has been created.
let cacheFile = gProfD.clone();
cacheFile.append(CACHE_FILENAME);
do_check_true(cacheFile.exists());
// Add engine and wait for cache update
yield addTestEngines([
{ name: "Test search engine", xmlFileName: "engine.xml" },
]);
do_print("Engine has been added, let's wait for the cache to be built");
yield promiseAfterCache();
do_print("Searching test engine in cache");
let cache = yield promiseCacheData();
let found = false;
for (let engine of cache.engines) {
if (engine._shortName == "test-search-engine") {
found = true;
break;
}
}
do_check_true(found);
removeCacheFile();
});

View file

@ -1,37 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/*
* test_nodb: Start search engine
* - without search-metadata.json
* - without search.sqlite
*
* Ensure that :
* - nothing explodes;
* - no search-metadata.json is created.
*/
function run_test()
{
removeMetadata();
updateAppInfo();
let search = Services.search;
do_test_pending();
search.init(function ss_initialized(rv) {
do_check_true(Components.isSuccessCode(rv));
do_timeout(500, function() {
// Check that search-metadata.json has not been
// created. Note that we cannot do much better
// than a timeout for checking a non-event.
let metadata = gProfD.clone();
metadata.append("search-metadata.json");
do_check_true(!metadata.exists());
removeMetadata();
do_test_finished();
});
});
}

Some files were not shown because too many files have changed in this diff Show more