--- a/toolkit/.eslintrc.js
+++ b/toolkit/.eslintrc.js
@@ -167,17 +167,17 @@ module.exports = {
// Always require semicolon at end of statement
// "semi": ["error", "always"],
// Require space before blocks
"space-before-blocks": "error",
// Never use spaces before function parentheses
- // "space-before-function-paren": ["error", { "anonymous": "always", "named": "never" }],
+ "space-before-function-paren": ["error", "never"],
// No space padding in parentheses
// "space-in-parens": ["error", "never"],
// Require spaces around operators
"space-infix-ops": ["error", { "int32Hint": false }],
// ++ and -- should not need spacing
--- a/toolkit/components/addoncompat/RemoteAddonsParent.jsm
+++ b/toolkit/components/addoncompat/RemoteAddonsParent.jsm
@@ -119,17 +119,17 @@ var ContentPolicyParent = {
NotificationTracker.add(["content-policy", addon]);
},
removeContentPolicy: function(addon, name) {
this._policies.delete(name);
NotificationTracker.remove(["content-policy", addon]);
},
- receiveMessage: function (aMessage) {
+ receiveMessage: function(aMessage) {
switch (aMessage.name) {
case "Addons:ContentPolicy:Run":
return this.shouldLoad(aMessage.data, aMessage.objects);
}
return undefined;
},
shouldLoad: function(aData, aObjects) {
@@ -214,17 +214,17 @@ var AboutProtocolParent = {
if (this._protocols[i].factory == factory) {
NotificationTracker.remove(["about-protocol", this._protocols[i].contractID, addon]);
this._protocols.splice(i, 1);
break;
}
}
},
- receiveMessage: function (msg) {
+ receiveMessage: function(msg) {
switch (msg.name) {
case "Addons:AboutProtocol:GetURIFlags":
return this.getURIFlags(msg);
case "Addons:AboutProtocol:OpenChannel":
return this.openChannel(msg);
}
return undefined;
},
--- a/toolkit/components/alerts/test/test_alerts.html
+++ b/toolkit/components/alerts/test/test_alerts.html
@@ -16,17 +16,17 @@
<br>Did a notification appear anywhere?
<br>If so, the test will finish once the notification disappears.
<pre id="test">
<script class="testbody" type="text/javascript">
var observer = {
alertShow: false,
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
is(aData, "foobarcookie", "Checking whether the alert cookie was passed correctly");
if (aTopic == "alertclickcallback") {
todo(false, "Did someone click the notification while running mochitests? (Please don't.)");
} else if (aTopic == "alertshow") {
ok(!this.alertShow, "Alert should not be shown more than once");
this.alertShow = true;
} else {
is(aTopic, "alertfinished", "Checking the topic for a finished notification");
--- a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js
+++ b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js
@@ -108,17 +108,17 @@ AutoCompleteResultBase.prototype = {
getImageAt: function(aIndex) {
return "";
},
getFinalCompleteValueAt: function(aIndex) {
return this._finalCompleteValues[aIndex] || this._values[aIndex];
},
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+ removeValueAt: function(aRowIndex, aRemoveFromDb) {},
// nsISupports implementation
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteResult])
}
/**
* nsIAutoCompleteSearch implementation that always returns
* the same result set.
--- a/toolkit/components/autocomplete/tests/unit/test_378079.js
+++ b/toolkit/components/autocomplete/tests/unit/test_378079.js
@@ -122,17 +122,17 @@ AutoCompleteResult.prototype = {
getImageAt: function(aIndex) {
return "";
},
getFinalCompleteValueAt: function(aIndex) {
return this.getValueAt(aIndex);
},
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+ removeValueAt: function(aRowIndex, aRemoveFromDb) {},
// nsISupports implementation
QueryInterface: function(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIAutoCompleteResult))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
--- a/toolkit/components/autocomplete/tests/unit/test_393191.js
+++ b/toolkit/components/autocomplete/tests/unit/test_393191.js
@@ -121,17 +121,17 @@ AutoCompleteResult.prototype = {
getImageAt: function(aIndex) {
return "";
},
getFinalCompleteValueAt: function(aIndex) {
return this.getValueAt(aIndex);
},
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+ removeValueAt: function(aRowIndex, aRemoveFromDb) {},
// nsISupports implementation
QueryInterface: function(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIAutoCompleteResult))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
--- a/toolkit/components/autocomplete/tests/unit/test_440866.js
+++ b/toolkit/components/autocomplete/tests/unit/test_440866.js
@@ -120,17 +120,17 @@ AutoCompleteResult.prototype = {
getImageAt: function(aIndex) {
return "";
},
getFinalCompleteValueAt: function(aIndex) {
return this.getValueAt(aIndex);
},
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+ removeValueAt: function(aRowIndex, aRemoveFromDb) {},
// nsISupports implementation
QueryInterface: function(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIAutoCompleteResult))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
--- a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js
+++ b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js
@@ -109,17 +109,17 @@ AutoCompleteResult.prototype = {
getImageAt: function(aIndex) {
return "";
},
getFinalCompleteValueAt: function(aIndex) {
return this.getValueAt(aIndex);
},
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+ removeValueAt: function(aRowIndex, aRemoveFromDb) {},
// nsISupports implementation
QueryInterface: function(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIAutoCompleteResult))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
--- a/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js
+++ b/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js
@@ -18,20 +18,20 @@ add_task(function *test_userContextId()
let searchParam = yield doSearch("test", 1);
Assert.equal(searchParam, " user-context-id:1");
});
function doSearch(aString, aUserContextId) {
let deferred = Promise.defer();
let search = new AutoCompleteSearch("test");
- search.startSearch = function (aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener) {
+ search.startSearch = function(aSearchString,
+ aSearchParam,
+ aPreviousResult,
+ aListener) {
unregisterAutoCompleteSearch(search);
deferred.resolve(aSearchParam);
};
registerAutoCompleteSearch(search);
let controller = Cc["@mozilla.org/autocomplete/controller;1"].
getService(Ci.nsIAutoCompleteController);
--- a/toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js
+++ b/toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js
@@ -41,17 +41,17 @@ add_test(function autocomplete_noMatch_s
do_check_eq(input.selectionStart, strLen);
do_check_eq(input.selectionEnd, strLen);
let controller = Cc["@mozilla.org/autocomplete/controller;1"].
getService(Ci.nsIAutoCompleteController);
controller.input = input;
controller.startSearch(INPUT_STR);
- input.onSearchComplete = function () {
+ input.onSearchComplete = function() {
// Should not try to autoFill to an empty value.
do_check_eq(input.textValue, "moz");
// Clean up.
unregisterAutoCompleteSearch(searchNoMatch);
run_next_test();
};
});
@@ -76,17 +76,17 @@ add_test(function autocomplete_defaultIn
do_check_eq(input.selectionStart, strLen);
do_check_eq(input.selectionEnd, strLen);
let controller = Cc["@mozilla.org/autocomplete/controller;1"].
getService(Ci.nsIAutoCompleteController);
controller.input = input;
controller.startSearch(INPUT_STR);
- input.onSearchComplete = function () {
+ input.onSearchComplete = function() {
// Should not try to autoFill to an empty value.
do_check_eq(input.textValue, "moz");
// Clean up.
unregisterAutoCompleteSearch(searchBadIndex);
run_next_test();
};
});
--- a/toolkit/components/autocomplete/tests/unit/test_previousResult.js
+++ b/toolkit/components/autocomplete/tests/unit/test_previousResult.js
@@ -120,17 +120,17 @@ AutoCompleteResult.prototype = {
getImageAt: function(aIndex) {
return "";
},
getFinalCompleteValueAt: function(aIndex) {
return this.getValueAt(aIndex);
},
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
+ removeValueAt: function(aRowIndex, aRemoveFromDb) {},
// nsISupports implementation
QueryInterface: function(iid) {
if (iid.equals(Ci.nsISupports) ||
iid.equals(Ci.nsIAutoCompleteResult))
return this;
throw Components.results.NS_ERROR_NO_INTERFACE;
--- a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js
+++ b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js
@@ -30,18 +30,18 @@ AutoCompleteInput.prototype = {
disableAutoComplete: false,
completeDefaultIndex: false,
set popupOpen(val) { return val; }, // ignore
get popupOpen() { return false; },
get searchCount() { return this.searches.length; },
getSearchAt: function(aIndex) { return this.searches[aIndex]; },
onSearchBegin: function() {},
onSearchComplete: function() {},
- onTextReverted: function () {},
- onTextEntered: function () {},
+ onTextReverted: function() {},
+ onTextEntered: function() {},
popup: {
selectBy: function() {},
invalidate: function() {},
set selectedIndex(val) { return val; }, // ignore
get selectedIndex() { return -1 },
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup])
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput])
--- a/toolkit/components/captivedetect/captivedetect.js
+++ b/toolkit/components/captivedetect/captivedetect.js
@@ -41,18 +41,18 @@ function URLFetcher(url, timeout) {
// final destination. It does not help if a resource is already
// cached locally.
xhr.setRequestHeader("Cache-Control", "no-cache");
// HTTP/1.0 servers might not implement Cache-Control and
// might only implement Pragma: no-cache
xhr.setRequestHeader("Pragma", "no-cache");
xhr.timeout = timeout;
- xhr.ontimeout = function () { self.ontimeout(); };
- xhr.onerror = function () { self.onerror(); };
+ xhr.ontimeout = function() { self.ontimeout(); };
+ xhr.onerror = function() { self.onerror(); };
xhr.onreadystatechange = function(oEvent) {
if (xhr.readyState === 4) {
if (self._isAborted) {
return;
}
if (xhr.status === 200) {
self.onsuccess(xhr.responseText);
} else if (xhr.status) {
@@ -106,17 +106,17 @@ function LoginObserver(captivePortalDete
let checkPageContent = function checkPageContent() {
debug("checking if public network is available after the login procedure");
urlFetcher = new URLFetcher(captivePortalDetector._canonicalSiteURL,
captivePortalDetector._maxWaitingTime);
urlFetcher.ontimeout = pageCheckingDone;
urlFetcher.onerror = pageCheckingDone;
- urlFetcher.onsuccess = function (content) {
+ urlFetcher.onsuccess = function(content) {
if (captivePortalDetector.validateContent(content)) {
urlFetcher = null;
captivePortalDetector.executeCallback(true);
} else {
pageCheckingDone();
}
};
urlFetcher.onredirectorerror = pageCheckingDone;
@@ -310,25 +310,25 @@ CaptivePortalDetector.prototype = {
let self = this;
let urlFetcher = new URLFetcher(this._canonicalSiteURL, this._maxWaitingTime);
let mayRetry = this._mayRetry.bind(this);
urlFetcher.ontimeout = mayRetry;
urlFetcher.onerror = mayRetry;
- urlFetcher.onsuccess = function (content) {
+ urlFetcher.onsuccess = function(content) {
if (self.validateContent(content)) {
self.executeCallback(true);
} else {
// Content of the canonical website has been overwrite
self._startLogin();
}
};
- urlFetcher.onredirectorerror = function (status) {
+ urlFetcher.onredirectorerror = function(status) {
if (status >= 300 && status <= 399) {
// The canonical website has been redirected to an unknown location
self._startLogin();
} else {
mayRetry();
}
};
@@ -461,16 +461,16 @@ CaptivePortalDetector.prototype = {
break;
}
}
},
};
var debug;
if (DEBUG) {
- debug = function (s) {
+ debug = function(s) {
dump('-*- CaptivePortalDetector component: ' + s + '\n');
};
} else {
- debug = function (s) {};
+ debug = function(s) {};
}
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([CaptivePortalDetector]);
--- a/toolkit/components/captivedetect/test/unit/test_captive_portal_found_303.js
+++ b/toolkit/components/captivedetect/test/unit/test_captive_portal_found_303.js
@@ -35,17 +35,17 @@ function fakeUIResponse() {
loginFinished = true;
do_check_eq(++step, 2);
}
}, 'captive-portal-login', false);
Services.obs.addObserver(function observe(subject, topic, data) {
if (topic === 'captive-portal-login-success') {
do_check_eq(++step, 4);
- gServer.stop(function () {
+ gServer.stop(function() {
gRedirectServer.stop(do_test_finished);
});
}
}, 'captive-portal-login-success', false);
}
function test_portal_found() {
do_test_pending();
--- a/toolkit/components/contentprefs/ContentPrefService2.jsm
+++ b/toolkit/components/contentprefs/ContentPrefService2.jsm
@@ -217,17 +217,17 @@ ContentPrefService2.prototype = {
group = this._parseGroup(group);
checkNameArg(name);
let storesToCheck = [this._cache];
if (context && context.usePrivateBrowsing)
storesToCheck.push(this._pbStore);
let outStore = new ContentPrefStore();
- storesToCheck.forEach(function (store) {
+ storesToCheck.forEach(function(store) {
for (let [sgroup, val] of store.match(group, name, includeSubdomains)) {
outStore.set(sgroup, name, val);
}
});
let prefs = [];
for (let [sgroup, sname, val] of outStore) {
prefs.push(new ContentPref(sgroup, sname, val));
@@ -247,17 +247,17 @@ ContentPrefService2.prototype = {
_set: function CPS2__set(group, name, value, context, callback) {
group = this._parseGroup(group);
checkNameArg(name);
checkValueArg(value);
checkCallbackArg(callback, false);
if (context && context.usePrivateBrowsing) {
this._pbStore.set(group, name, value);
- this._schedule(function () {
+ this._schedule(function() {
cbHandleCompletion(callback, Ci.nsIContentPrefCallback2.COMPLETE_OK);
this._cps._notifyPrefSet(group, name, value, context.usePrivateBrowsing);
});
return;
}
// Invalidate the cached value so consumers accessing the cache between now
// and when the operation finishes don't get old data.
--- a/toolkit/components/contentprefs/tests/unit/test_bug503971.js
+++ b/toolkit/components/contentprefs/tests/unit/test_bug503971.js
@@ -2,32 +2,32 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function run_test() {
var cps = new ContentPrefInstance(null);
var uri = ContentPrefTest.getURI("http://www.example.com/");
- do_check_thrown(function () { cps.setPref(uri, null, 8); });
- do_check_thrown(function () { cps.hasPref(uri, null); });
- do_check_thrown(function () { cps.getPref(uri, null); });
- do_check_thrown(function () { cps.removePref(uri, null); });
- do_check_thrown(function () { cps.getPrefsByName(null); });
- do_check_thrown(function () { cps.removePrefsByName(null); });
+ do_check_thrown(function() { cps.setPref(uri, null, 8); });
+ do_check_thrown(function() { cps.hasPref(uri, null); });
+ do_check_thrown(function() { cps.getPref(uri, null); });
+ do_check_thrown(function() { cps.removePref(uri, null); });
+ do_check_thrown(function() { cps.getPrefsByName(null); });
+ do_check_thrown(function() { cps.removePrefsByName(null); });
- do_check_thrown(function () { cps.setPref(uri, "", 21); });
- do_check_thrown(function () { cps.hasPref(uri, ""); });
- do_check_thrown(function () { cps.getPref(uri, ""); });
- do_check_thrown(function () { cps.removePref(uri, ""); });
- do_check_thrown(function () { cps.getPrefsByName(""); });
- do_check_thrown(function () { cps.removePrefsByName(""); });
+ do_check_thrown(function() { cps.setPref(uri, "", 21); });
+ do_check_thrown(function() { cps.hasPref(uri, ""); });
+ do_check_thrown(function() { cps.getPref(uri, ""); });
+ do_check_thrown(function() { cps.removePref(uri, ""); });
+ do_check_thrown(function() { cps.getPrefsByName(""); });
+ do_check_thrown(function() { cps.removePrefsByName(""); });
}
-function do_check_thrown (aCallback) {
+function do_check_thrown(aCallback) {
var exThrown = false;
try {
aCallback();
do_throw("NS_ERROR_ILLEGAL_VALUE should have been thrown here");
} catch (e) {
do_check_eq(e.result, Cr.NS_ERROR_ILLEGAL_VALUE);
exThrown = true;
}
--- a/toolkit/components/contentprefs/tests/unit/test_contentPrefsCache.js
+++ b/toolkit/components/contentprefs/tests/unit/test_contentPrefsCache.js
@@ -39,17 +39,17 @@ function testCacheWorks(uri, prefName) {
let dbValue = selectValue("SELECT value FROM prefs WHERE id = :param1", "value", prefId);
let cacheValue = cps.getPref(uri, prefName);
do_check_eq(dbValue, NEW_VALUE);
do_check_eq(cacheValue, CACHED_VALUE);
do_check_neq(cacheValue, dbValue);
do_test_pending();
- cps.getPref(uri, prefName, function (value) {
+ cps.getPref(uri, prefName, function(value) {
do_check_eq(dbValue, NEW_VALUE);
do_check_eq(value, CACHED_VALUE);
do_check_neq(value, dbValue);
do_test_finished();
});
}
function testHasCachedPrefFunction(uri, prefName) {
--- a/toolkit/components/contentprefs/tests/unit/test_stringGroups.js
+++ b/toolkit/components/contentprefs/tests/unit/test_stringGroups.js
@@ -19,21 +19,21 @@ function run_test() {
{
// First check that all the methods work or don't work.
function simple_test_methods(aGroup, shouldThrow) {
var prefName = "test.pref.0";
var prefValue = Math.floor(Math.random() * 100);
if (shouldThrow) {
- do_check_thrown(function () { cps.getPref(aGroup, prefName); });
- do_check_thrown(function () { cps.setPref(aGroup, prefName, prefValue); });
- do_check_thrown(function () { cps.hasPref(aGroup, prefName); });
- do_check_thrown(function () { cps.removePref(aGroup, prefName); });
- do_check_thrown(function () { cps.getPrefs(aGroup); });
+ do_check_thrown(function() { cps.getPref(aGroup, prefName); });
+ do_check_thrown(function() { cps.setPref(aGroup, prefName, prefValue); });
+ do_check_thrown(function() { cps.hasPref(aGroup, prefName); });
+ do_check_thrown(function() { cps.removePref(aGroup, prefName); });
+ do_check_thrown(function() { cps.getPrefs(aGroup); });
} else {
do_check_eq(cps.setPref(aGroup, prefName, prefValue), undefined);
do_check_true(cps.hasPref(aGroup, prefName));
do_check_eq(cps.getPref(aGroup, prefName), prefValue);
do_check_eq(cps.removePref(aGroup, prefName), undefined);
do_check_false(cps.hasPref(aGroup, prefName));
}
}
@@ -93,17 +93,17 @@ function run_test() {
do_check_eq(cps.setPref(stringURI, "test.3", 3), undefined);
enumerateAndCheck(cps.getPrefs(uri), 15, ["test.0", "test.1", "test.2", "test.3", "test.4", "test.5"]);
enumerateAndCheck(cps.getPrefs(stringURI), 15, ["test.0", "test.1", "test.2", "test.3", "test.4", "test.5"]);
enumerateAndCheck(cps.getPrefs(stringObjectURI), 15, ["test.0", "test.1", "test.2", "test.3", "test.4", "test.5"]);
}
}
-function do_check_thrown (aCallback) {
+function do_check_thrown(aCallback) {
var exThrown = false;
try {
aCallback();
do_throw("NS_ERROR_ILLEGAL_VALUE should have been thrown here");
} catch (e) {
do_check_eq(e.result, Cr.NS_ERROR_ILLEGAL_VALUE);
exThrown = true;
}
--- a/toolkit/components/contentprefs/tests/unit_cps2/head.js
+++ b/toolkit/components/contentprefs/tests/unit_cps2/head.js
@@ -20,28 +20,28 @@ function runAsyncTests(tests, dontResetB
cps = Cc["@mozilla.org/content-pref/service;1"].
getService(Ci.nsIContentPrefService2);
let s = {};
Cu.import("resource://test/AsyncRunner.jsm", s);
asyncRunner = new s.AsyncRunner({
done: do_test_finished,
- error: function (err) {
+ error: function(err) {
// xpcshell test functions like equal throw NS_ERROR_ABORT on
// failure. Ignore those and catch only uncaught exceptions.
if (err !== Cr.NS_ERROR_ABORT) {
if (err.stack) {
err = err + "\n\nTraceback (most recent call first):\n" + err.stack +
"\nUseless do_throw stack:";
}
do_throw(err);
}
},
- consoleError: function (scriptErr) {
+ consoleError: function(scriptErr) {
// Previously, this code checked for console errors related to the test,
// and treated them as failures. This was problematic, because our current
// very-broken exception reporting machinery in XPCWrappedJSClass reports
// errors to the console even if there's actually JS on the stack above
// that will catch them. And a lot of the tests here intentionally trigger
// error conditions on the JS-implemented XPCOM component (see erroneous()
// in test_getSubdomains.js, for example). In the old world, we got lucky,
// and the errors were never reported to the console due to happenstantial
@@ -51,22 +51,22 @@ function runAsyncTests(tests, dontResetB
// don't turn them into duplicate failures of the exception that was already
// propagated to the caller.
dump("AsyncRunner.jsm observed console error: " + scriptErr + "\n");
}
});
next = asyncRunner.next.bind(asyncRunner);
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
asyncRunner.destroy();
asyncRunner = null;
});
- tests.forEach(function (test) {
+ tests.forEach(function(test) {
function* gen() {
do_print("Running " + test.name);
yield test();
yield reset();
}
asyncRunner.appendIterator(gen());
});
@@ -76,27 +76,27 @@ function runAsyncTests(tests, dontResetB
} else {
reset();
}
}
function makeCallback(callbacks, success = null) {
callbacks = callbacks || {};
if (!callbacks.handleError) {
- callbacks.handleError = function (error) {
+ callbacks.handleError = function(error) {
do_throw("handleError call was not expected, error: " + error);
};
}
if (!callbacks.handleResult) {
callbacks.handleResult = function() {
do_throw("handleResult call was not expected");
};
}
if (!callbacks.handleCompletion)
- callbacks.handleCompletion = function (reason) {
+ callbacks.handleCompletion = function(reason) {
equal(reason, Ci.nsIContentPrefCallback2.COMPLETE_OK);
if (success) {
success();
} else {
next();
}
};
return callbacks;
@@ -133,20 +133,20 @@ function setWithDate(group, name, val, t
settingID = (SELECT id FROM settings WHERE name = :name)
AND groupID = (SELECT id FROM groups WHERE name = :group)
`);
stmt.params.timestamp = timestamp / 1000;
stmt.params.name = name;
stmt.params.group = group;
stmt.executeAsync({
- handleCompletion: function (reason) {
+ handleCompletion: function(reason) {
next();
},
- handleError: function (err) {
+ handleError: function(err) {
do_throw(err);
}
});
stmt.finalize();
}
cps.set(group, name, val, context, makeCallback(null, updateDate));
}
@@ -159,24 +159,24 @@ function getDate(group, name, context) {
settingID = (SELECT id FROM settings WHERE name = :name)
AND groupID = (SELECT id FROM groups WHERE name = :group)
`);
stmt.params.name = name;
stmt.params.group = group;
let res;
stmt.executeAsync({
- handleResult: function (results) {
+ handleResult: function(results) {
let row = results.getNextRow();
res = row.getResultByName("timestamp");
},
- handleCompletion: function (reason) {
+ handleCompletion: function(reason) {
next(res * 1000);
},
- handleError: function (err) {
+ handleError: function(err) {
do_throw(err);
}
});
stmt.finalize();
}
function set(group, name, val, context) {
cps.set(group, name, val, context, makeCallback());
@@ -204,17 +204,17 @@ function* getOK(args, expectedVal, expec
name: args[1],
value: expectedVal }];
yield getOKEx("getByDomainAndName", args, expectedPrefs, strict);
}
function* getSubdomainsOK(args, expectedGroupValPairs) {
if (args.length == 2)
args.push(undefined);
- let expectedPrefs = expectedGroupValPairs.map(function ([group, val]) {
+ let expectedPrefs = expectedGroupValPairs.map(function([group, val]) {
return { domain: group, name: args[1], value: val };
});
yield getOKEx("getBySubdomainAndName", args, expectedPrefs);
}
function* getGlobalOK(args, expectedVal) {
if (args.length == 1)
args.push(undefined);
@@ -224,17 +224,17 @@ function* getGlobalOK(args, expectedVal)
}
function* getOKEx(methodName, args, expectedPrefs, strict, context) {
let actualPrefs = [];
args.push(makeCallback({
handleResult: pref => actualPrefs.push(pref)
}));
yield cps[methodName].apply(cps, args);
- arraysOfArraysOK([actualPrefs], [expectedPrefs], function (actual, expected) {
+ arraysOfArraysOK([actualPrefs], [expectedPrefs], function(actual, expected) {
prefOK(actual, expected, strict);
});
}
function getCachedOK(args, expectedIsCached, expectedVal, expectedGroup,
strict) {
if (args.length == 2)
args.push(undefined);
@@ -247,21 +247,21 @@ function getCachedOK(args, expectedIsCac
}
function getCachedSubdomainsOK(args, expectedGroupValPairs) {
if (args.length == 2)
args.push(undefined);
let len = {};
args.push(len);
let actualPrefs = cps.getCachedBySubdomainAndName.apply(cps, args);
- actualPrefs = actualPrefs.sort(function (a, b) {
+ actualPrefs = actualPrefs.sort(function(a, b) {
return a.domain.localeCompare(b.domain);
});
equal(actualPrefs.length, len.value);
- let expectedPrefs = expectedGroupValPairs.map(function ([group, val]) {
+ let expectedPrefs = expectedGroupValPairs.map(function([group, val]) {
return { domain: group, name: args[1], value: val };
});
arraysOfArraysOK([actualPrefs], [expectedPrefs], prefOK);
}
function getCachedGlobalOK(args, expectedIsCached, expectedVal) {
if (args.length == 1)
args.push(undefined);
@@ -280,26 +280,26 @@ function getCachedOKEx(methodName, args,
else
strictEqual(actualPref, null);
}
function arraysOK(actual, expected, cmp) {
if (actual.length != expected.length) {
do_throw("Length is not equal: " + JSON.stringify(actual) + "==" + JSON.stringify(expected));
} else {
- actual.forEach(function (actualElt, j) {
+ actual.forEach(function(actualElt, j) {
let expectedElt = expected[j];
cmp(actualElt, expectedElt);
});
}
}
function arraysOfArraysOK(actual, expected, cmp) {
cmp = cmp || equal;
- arraysOK(actual, expected, function (act, exp) {
+ arraysOK(actual, expected, function(act, exp) {
arraysOK(act, exp, cmp)
});
}
function dbOK(expectedRows) {
let db = sendMessage("db");
let stmt = db.createAsyncStatement(`
SELECT groups.name AS grp, settings.name AS name, prefs.value AS value
@@ -331,60 +331,60 @@ function dbOK(expectedRows) {
ORDER BY value ASC, grp ASC, name ASC
`);
let actualRows = [];
let cols = ["grp", "name", "value"];
db.executeAsync([stmt], 1, {
- handleCompletion: function (reason) {
+ handleCompletion: function(reason) {
arraysOfArraysOK(actualRows, expectedRows);
next();
},
- handleResult: function (results) {
+ handleResult: function(results) {
let row = null;
while (row = results.getNextRow()) {
actualRows.push(cols.map(c => row.getResultByName(c)));
}
},
- handleError: function (err) {
+ handleError: function(err) {
do_throw(err);
}
});
stmt.finalize();
}
function on(event, names, dontRemove) {
let args = {
- reset: function () {
+ reset: function() {
for (let prop in this) {
if (Array.isArray(this[prop]))
this[prop].splice(0, this[prop].length);
}
},
};
let observers = {};
- names.forEach(function (name) {
+ names.forEach(function(name) {
let obs = {};
- ["onContentPrefSet", "onContentPrefRemoved"].forEach(function (meth) {
+ ["onContentPrefSet", "onContentPrefRemoved"].forEach(function(meth) {
obs[meth] = () => do_throw(meth + " should not be called");
});
- obs["onContentPref" + event] = function () {
+ obs["onContentPref" + event] = function() {
args[name].push(Array.slice(arguments));
};
observers[name] = obs;
args[name] = [];
args[name].observer = obs;
cps.addObserverForName(name, obs);
});
- do_execute_soon(function () {
+ do_execute_soon(function() {
if (!dontRemove)
names.forEach(n => cps.removeObserverForName(n, observers[n]));
next(args);
});
}
function schemaVersionIs(expectedVersion) {
let db = sendMessage("db");
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js
+++ b/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js
@@ -138,32 +138,32 @@ var tests = [
// (1) Set a pref and wait for it to finish.
yield set("a.com", "foo", 1);
// (2) It should be cached.
getCachedOK(["a.com", "foo"], true, 1);
// (3) Set the pref to a new value but don't wait for it to finish.
cps.set("a.com", "foo", 2, null, {
- handleCompletion: function () {
+ handleCompletion: function() {
// (6) The pref should be cached after setting it.
getCachedOK(["a.com", "foo"], true, 2);
},
});
// (4) Group "a.com" and name "foo" should no longer be cached.
getCachedOK(["a.com", "foo"], false);
// (5) Call getByDomainAndName.
var fetchedPref;
cps.getByDomainAndName("a.com", "foo", null, {
- handleResult: function (pref) {
+ handleResult: function(pref) {
fetchedPref = pref;
},
- handleCompletion: function () {
+ handleCompletion: function() {
// (7) Finally, this callback should be called after set's above.
do_check_true(!!fetchedPref);
do_check_eq(fetchedPref.value, 2);
next();
},
});
yield;
--- a/toolkit/components/contextualidentity/ContextualIdentityService.jsm
+++ b/toolkit/components/contextualidentity/ContextualIdentityService.jsm
@@ -11,21 +11,21 @@ Cu.import("resource://gre/modules/Servic
const DEFAULT_TAB_COLOR = "#909090";
const SAVE_DELAY_MS = 1500;
XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
return Services.strings.createBundle("chrome://browser/locale/browser.properties");
});
-XPCOMUtils.defineLazyGetter(this, "gTextDecoder", function () {
+XPCOMUtils.defineLazyGetter(this, "gTextDecoder", function() {
return new TextDecoder();
});
-XPCOMUtils.defineLazyGetter(this, "gTextEncoder", function () {
+XPCOMUtils.defineLazyGetter(this, "gTextEncoder", function() {
return new TextEncoder();
});
XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown",
"resource://gre/modules/AsyncShutdown.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "DeferredTask",
--- a/toolkit/components/crashes/CrashManager.jsm
+++ b/toolkit/components/crashes/CrashManager.jsm
@@ -63,17 +63,17 @@ function dateToDays(date) {
*
* storeDir (string)
* Directory we will use for our data store. This instance will write
* data files into the directory specified.
*
* telemetryStoreSizeKey (string)
* Telemetry histogram to report store size under.
*/
-this.CrashManager = function (options) {
+this.CrashManager = function(options) {
for (let k of ["pendingDumpsDir", "submittedDumpsDir", "eventsDirs",
"storeDir"]) {
if (!(k in options)) {
throw new Error("Required key not present in options: " + k);
}
}
this._log = Log.repository.getLogger("Crashes.CrashManager");
@@ -186,17 +186,17 @@ this.CrashManager.prototype = Object.fre
* date (Date)
* When this dump was created
*
* The returned arry is sorted by the modified time of the file backing
* the entry, oldest to newest.
*
* @return Promise<Array>
*/
- pendingDumps: function () {
+ pendingDumps: function() {
return this._getDirectoryEntries(this._pendingDumpsDir, this.DUMP_REGEX);
},
/**
* Obtain a list of all dump files corresponding to submitted crashes.
*
* The returned value is a promise that resolves to an Array of
* objects. Each object has the following properties:
@@ -210,17 +210,17 @@ this.CrashManager.prototype = Object.fre
* date (Date)
* The (estimated) date this crash was submitted.
*
* The returned array is sorted by the modified time of the file backing
* the entry, oldest to newest.
*
* @return Promise<Array>
*/
- submittedDumps: function () {
+ submittedDumps: function() {
return this._getDirectoryEntries(this._submittedDumpsDir,
this.SUBMITTED_REGEX);
},
/**
* Aggregates "loose" events files into the unified "database."
*
* This function should be called periodically to collect metadata from
@@ -230,17 +230,17 @@ this.CrashManager.prototype = Object.fre
* source files are deleted.
*
* Only one aggregation operation is allowed to occur at a time. If this
* is called when an existing aggregation is in progress, the promise for
* the original call will be returned.
*
* @return promise<int> The number of event files that were examined.
*/
- aggregateEventsFiles: function () {
+ aggregateEventsFiles: function() {
if (this._aggregatePromise) {
return this._aggregatePromise;
}
return this._aggregatePromise = Task.spawn(function* () {
if (this._aggregatePromise) {
return this._aggregatePromise;
}
@@ -313,43 +313,43 @@ this.CrashManager.prototype = Object.fre
/**
* Prune old crash data.
*
* @param date
* (Date) The cutoff point for pruning. Crashes without data newer
* than this will be pruned.
*/
- pruneOldCrashes: function (date) {
+ pruneOldCrashes: function(date) {
return Task.spawn(function* () {
let store = yield this._getStore();
store.pruneOldCrashes(date);
yield store.save();
}.bind(this));
},
/**
* Run tasks that should be periodically performed.
*/
- runMaintenanceTasks: function () {
+ runMaintenanceTasks: function() {
return Task.spawn(function* () {
yield this.aggregateEventsFiles();
let offset = this.PURGE_OLDER_THAN_DAYS * MILLISECONDS_IN_DAY;
yield this.pruneOldCrashes(new Date(Date.now() - offset));
}.bind(this));
},
/**
* Schedule maintenance tasks for some point in the future.
*
* @param delay
* (integer) Delay in milliseconds when maintenance should occur.
*/
- scheduleMaintenance: function (delay) {
+ scheduleMaintenance: function(delay) {
let deferred = Promise.defer();
setTimeout(() => {
this.runMaintenanceTasks().then(deferred.resolve, deferred.reject);
}, delay);
return deferred.promise;
},
@@ -363,17 +363,17 @@ this.CrashManager.prototype = Object.fre
* @param processType (string) One of the PROCESS_TYPE constants.
* @param crashType (string) One of the CRASH_TYPE constants.
* @param id (string) Crash ID. Likely a UUID.
* @param date (Date) When the crash occurred.
* @param metadata (dictionary) Crash metadata, may be empty.
*
* @return promise<null> Resolved when the store has been saved.
*/
- addCrash: function (processType, crashType, id, date, metadata) {
+ addCrash: function(processType, crashType, id, date, metadata) {
return Task.spawn(function* () {
let store = yield this._getStore();
if (store.addCrash(processType, crashType, id, date, metadata)) {
yield store.save();
}
}.bind(this));
},
@@ -449,34 +449,34 @@ this.CrashManager.prototype = Object.fre
}
}),
/**
* Obtain the paths of all unprocessed events files.
*
* The promise-resolved array is sorted by file mtime, oldest to newest.
*/
- _getUnprocessedEventsFiles: function () {
+ _getUnprocessedEventsFiles: function() {
return Task.spawn(function* () {
let entries = [];
for (let dir of this._eventsDirs) {
for (let e of yield this._getDirectoryEntries(dir, this.ALL_REGEX)) {
entries.push(e);
}
}
entries.sort((a, b) => { return a.date - b.date; });
return entries;
}.bind(this));
},
// See docs/crash-events.rst for the file format specification.
- _processEventFile: function (entry) {
+ _processEventFile: function(entry) {
return Task.spawn(function* () {
let data = yield OS.File.read(entry.path);
let store = yield this._getStore();
let decoder = new TextDecoder();
data = decoder.decode(data);
let type, time;
@@ -505,17 +505,17 @@ this.CrashManager.prototype = Object.fre
}
let date = new Date(time * 1000);
let payload = data.substring(start);
return this._handleEventFilePayload(store, entry, type, date, payload);
}.bind(this));
},
- _handleEventFilePayload: function (store, entry, type, date, payload) {
+ _handleEventFilePayload: function(store, entry, type, date, payload) {
// The payload types and formats are documented in docs/crash-events.rst.
// Do not change the format of an existing type. Instead, invent a new
// type.
// DO NOT ADD NEW TYPES WITHOUT DOCUMENTING!
let lines = payload.split("\n");
switch (type) {
case "crash.main.1":
@@ -604,17 +604,17 @@ this.CrashManager.prototype = Object.fre
/**
* The resolved promise is an array of objects with the properties:
*
* path -- String filename
* id -- regexp.match()[1] (likely the crash ID)
* date -- Date mtime of the file
*/
- _getDirectoryEntries: function (path, re) {
+ _getDirectoryEntries: function(path, re) {
return Task.spawn(function* () {
try {
yield OS.File.stat(path);
} catch (ex) {
if (!(ex instanceof OS.File.Error) || !ex.becauseNoSuchFile) {
throw ex;
}
return [];
@@ -647,17 +647,17 @@ this.CrashManager.prototype = Object.fre
}
entries.sort((a, b) => { return a.date - b.date; });
return entries;
}.bind(this));
},
- _getStore: function () {
+ _getStore: function() {
if (this._getStoreTask) {
return this._getStoreTask;
}
return this._getStoreTask = Task.spawn(function* () {
try {
if (!this._store) {
yield OS.File.makeDir(this._storeDir, {
@@ -678,17 +678,17 @@ this.CrashManager.prototype = Object.fre
// store. Since the store takes up resources, we automatically "free"
// the store after inactivity so resources can be returned to the
// system. We do this via a timer and a mechanism that tracks when the
// store is being accessed.
this._storeTimer.cancel();
// This callback frees resources from the store unless the store
// is protected from freeing by some other process.
- let timerCB = function () {
+ let timerCB = function() {
if (this._storeProtectedCount) {
this._storeTimer.initWithCallback(timerCB, this.STORE_EXPIRATION_MS,
this._storeTimer.TYPE_ONE_SHOT);
return;
}
// We kill the reference that we hold. GC will kill it later. If
// someone else holds a reference, that will prevent GC until that
@@ -707,25 +707,25 @@ this.CrashManager.prototype = Object.fre
}.bind(this));
},
/**
* Obtain information about all known crashes.
*
* Returns an array of CrashRecord instances. Instances are read-only.
*/
- getCrashes: function () {
+ getCrashes: function() {
return Task.spawn(function* () {
let store = yield this._getStore();
return store.crashes;
}.bind(this));
},
- getCrashCountsByDay: function () {
+ getCrashCountsByDay: function() {
return Task.spawn(function* () {
let store = yield this._getStore();
return store._countsByDay;
}.bind(this));
},
});
@@ -792,17 +792,17 @@ CrashStore.prototype = Object.freeze({
this._countsByDay = new Map();
},
/**
* Load data from disk.
*
* @return Promise
*/
- load: function () {
+ load: function() {
return Task.spawn(function* () {
// Loading replaces data.
this.reset();
try {
let decoder = new TextDecoder();
let data = yield OS.File.read(this._storePath, {compression: "lz4"});
data = JSON.parse(decoder.decode(data));
@@ -892,17 +892,17 @@ CrashStore.prototype = Object.freeze({
}.bind(this));
},
/**
* Save data to disk.
*
* @return Promise<null>
*/
- save: function () {
+ save: function() {
return Task.spawn(function* () {
if (!this._data) {
return;
}
let normalized = {
// The version should be incremented whenever the format
// changes.
@@ -962,17 +962,17 @@ CrashStore.prototype = Object.freeze({
* This function along with _denormalize() serve to hack around the
* default handling of Date JSON serialization because Date serialization
* is undefined by JSON.
*
* Fields ending with "Date" are assumed to contain Date instances.
* We convert these to milliseconds since epoch on output and back to
* Date on input.
*/
- _normalize: function (o) {
+ _normalize: function(o) {
let normalized = {};
for (let k in o) {
let v = o[k];
if (v && k.endsWith("Date")) {
normalized[k] = v.getTime();
} else {
normalized[k] = v;
@@ -980,17 +980,17 @@ CrashStore.prototype = Object.freeze({
}
return normalized;
},
/**
* Convert a serialized object back to its native form.
*/
- _denormalize: function (o) {
+ _denormalize: function(o) {
let n = {};
for (let k in o) {
let v = o[k];
if (v && k.endsWith("Date")) {
n[k] = new Date(parseInt(v, 10));
} else {
n[k] = v;
@@ -1006,17 +1006,17 @@ CrashStore.prototype = Object.freeze({
* Crashes without recent activity are pruned from the store so the
* size of the store is not unbounded. If there is activity on a crash,
* that activity will keep the crash and all its data around for longer.
*
* @param date
* (Date) The cutoff at which data will be pruned. If an entry
* doesn't have data newer than this, it will be pruned.
*/
- pruneOldCrashes: function (date) {
+ pruneOldCrashes: function(date) {
for (let crash of this.crashes) {
let newest = crash.newestDate;
if (!newest || newest.getTime() < date.getTime()) {
this._data.crashes.delete(crash.id);
}
}
},
@@ -1051,27 +1051,27 @@ CrashStore.prototype = Object.freeze({
},
/**
* Obtain a particular crash from its ID.
*
* A CrashRecord will be returned if the crash exists. null will be returned
* if the crash is unknown.
*/
- getCrash: function (id) {
+ getCrash: function(id) {
for (let crash of this.crashes) {
if (crash.id == id) {
return crash;
}
}
return null;
},
- _ensureCountsForDay: function (day) {
+ _ensureCountsForDay: function(day) {
if (!this._countsByDay.has(day)) {
this._countsByDay.set(day, new Map());
}
},
/**
* Ensure the crash record is present in storage.
*
@@ -1086,17 +1086,17 @@ CrashStore.prototype = Object.freeze({
* (string) The crash ID.
* @param date
* (Date) When this crash occurred.
* @param metadata
* (dictionary) Crash metadata, may be empty.
*
* @return null | object crash record
*/
- _ensureCrashRecord: function (processType, crashType, id, date, metadata) {
+ _ensureCrashRecord: function(processType, crashType, id, date, metadata) {
if (!id) {
// Crashes are keyed on ID, so it's not really helpful to store crashes
// without IDs.
return null;
}
let type = processType + "-" + crashType;
@@ -1144,49 +1144,49 @@ CrashStore.prototype = Object.freeze({
* @param processType (string) One of the PROCESS_TYPE constants.
* @param crashType (string) One of the CRASH_TYPE constants.
* @param id (string) Crash ID. Likely a UUID.
* @param date (Date) When the crash occurred.
* @param metadata (dictionary) Crash metadata, may be empty.
*
* @return boolean True if the crash was recorded and false if not.
*/
- addCrash: function (processType, crashType, id, date, metadata) {
+ addCrash: function(processType, crashType, id, date, metadata) {
return !!this._ensureCrashRecord(processType, crashType, id, date, metadata);
},
/**
* @return boolean True if the remote ID was recorded and false if not.
*/
- setRemoteCrashID: function (crashID, remoteID) {
+ setRemoteCrashID: function(crashID, remoteID) {
let crash = this._data.crashes.get(crashID);
if (!crash || !remoteID) {
return false;
}
crash.remoteID = remoteID;
return true;
},
- getCrashesOfType: function (processType, crashType) {
+ getCrashesOfType: function(processType, crashType) {
let crashes = [];
for (let crash of this.crashes) {
if (crash.isOfType(processType, crashType)) {
crashes.push(crash);
}
}
return crashes;
},
/**
* Ensure the submission record is present in storage.
* @returns [submission, crash]
*/
- _ensureSubmissionRecord: function (crashID, submissionID) {
+ _ensureSubmissionRecord: function(crashID, submissionID) {
let crash = this._data.crashes.get(crashID);
if (!crash || !submissionID) {
return null;
}
if (!crash.submissions.has(submissionID)) {
crash.submissions.set(submissionID, {
requestDate: null,
@@ -1196,33 +1196,33 @@ CrashStore.prototype = Object.freeze({
}
return [crash.submissions.get(submissionID), crash];
},
/**
* @return boolean True if the attempt was recorded.
*/
- addSubmissionAttempt: function (crashID, submissionID, date) {
+ addSubmissionAttempt: function(crashID, submissionID, date) {
let [submission, crash] =
this._ensureSubmissionRecord(crashID, submissionID);
if (!submission) {
return false;
}
submission.requestDate = date;
Services.telemetry.getKeyedHistogramById("PROCESS_CRASH_SUBMIT_ATTEMPT")
.add(crash.type, 1);
return true;
},
/**
* @return boolean True if the response was recorded.
*/
- addSubmissionResult: function (crashID, submissionID, date, result) {
+ addSubmissionResult: function(crashID, submissionID, date, result) {
let crash = this._data.crashes.get(crashID);
if (!crash || !submissionID) {
return false;
}
let submission = crash.submissions.get(submissionID);
if (!submission) {
return false;
}
@@ -1232,17 +1232,17 @@ CrashStore.prototype = Object.freeze({
Services.telemetry.getKeyedHistogramById("PROCESS_CRASH_SUBMIT_SUCCESS")
.add(crash.type, result == "ok");
return true;
},
/**
* @return boolean True if the classifications were set.
*/
- setCrashClassifications: function (crashID, classifications) {
+ setCrashClassifications: function(crashID, classifications) {
let crash = this._data.crashes.get(crashID);
if (!crash) {
return false;
}
crash.classifications = classifications;
return true;
},
@@ -1291,17 +1291,17 @@ CrashRecord.prototype = Object.freeze({
get oldestDate() {
return this._o.crashDate;
},
get type() {
return this._o.type;
},
- isOfType: function (processType, crashType) {
+ isOfType: function(processType, crashType) {
return processType + "-" + crashType == this.type;
},
get submissions() {
return this._o.submissions;
},
get classifications() {
@@ -1314,17 +1314,17 @@ CrashRecord.prototype = Object.freeze({
});
/**
* Obtain the global CrashManager instance used by the running application.
*
* CrashManager is likely only ever instantiated once per application lifetime.
* The main reason it's implemented as a reusable type is to facilitate testing.
*/
-XPCOMUtils.defineLazyGetter(this.CrashManager, "Singleton", function () {
+XPCOMUtils.defineLazyGetter(this.CrashManager, "Singleton", function() {
if (gCrashManager) {
return gCrashManager;
}
let crPath = OS.Path.join(OS.Constants.Path.userApplicationDataDir,
"Crash Reports");
let storePath = OS.Path.join(OS.Constants.Path.profileDir, "crashes");
--- a/toolkit/components/crashes/CrashManagerTest.jsm
+++ b/toolkit/components/crashes/CrashManagerTest.jsm
@@ -22,47 +22,47 @@ Cu.import("resource://gre/modules/CrashM
Cu.import("resource://gre/modules/Log.jsm", this);
Cu.import("resource://gre/modules/osfile.jsm", this);
Cu.import("resource://gre/modules/Promise.jsm", this);
Cu.import("resource://gre/modules/Task.jsm", this);
Cu.import("resource://gre/modules/Timer.jsm", this);
var loggingConfigured = false;
-this.configureLogging = function () {
+this.configureLogging = function() {
if (loggingConfigured) {
return;
}
let log = Log.repository.getLogger("Crashes.CrashManager");
log.level = Log.Level.All;
let appender = new Log.DumpAppender();
appender.level = Log.Level.All;
log.addAppender(appender);
loggingConfigured = true;
};
-this.sleep = function (wait) {
+this.sleep = function(wait) {
let deferred = Promise.defer();
setTimeout(() => {
deferred.resolve();
}, wait);
return deferred.promise;
};
-this.TestingCrashManager = function (options) {
+this.TestingCrashManager = function(options) {
CrashManager.call(this, options);
}
this.TestingCrashManager.prototype = {
__proto__: CrashManager.prototype,
- createDummyDump: function (submitted = false, date = new Date(), hr = false) {
+ createDummyDump: function(submitted = false, date = new Date(), hr = false) {
let uuid = Cc["@mozilla.org/uuid-generator;1"]
.getService(Ci.nsIUUIDGenerator)
.generateUUID()
.toString();
uuid = uuid.substring(1, uuid.length - 1);
let path;
let mode;
@@ -84,32 +84,32 @@ this.TestingCrashManager.prototype = {
yield f.setDates(date, date);
yield f.close();
dump("Created fake crash: " + path + "\n");
return uuid;
});
},
- createIgnoredDumpFile: function (filename, submitted = false) {
+ createIgnoredDumpFile: function(filename, submitted = false) {
let path;
if (submitted) {
path = OS.Path.join(this._submittedDumpsDir, filename);
} else {
path = OS.Path.join(this._pendingDumpsDir, filename);
}
return Task.spawn(function* () {
let mode = OS.Constants.libc.S_IRUSR | OS.Constants.libc.S_IWUSR;
yield OS.File.open(path, {create: true}, {unixMode: mode});
dump("Create ignored dump file: " + path + "\n");
});
},
- createEventsFile: function (filename, type, date, content, index = 0) {
+ createEventsFile: function(filename, type, date, content, index = 0) {
let path = OS.Path.join(this._eventsDirs[index], filename);
let data = type + "\n" +
Math.floor(date.getTime() / 1000) + "\n" +
content;
let encoder = new TextEncoder();
let array = encoder.encode(data);
@@ -119,17 +119,17 @@ this.TestingCrashManager.prototype = {
});
},
/**
* Overwrite event file handling to process our test file type.
*
* We can probably delete this once we have actual events defined.
*/
- _handleEventFilePayload: function (store, entry, type, date, payload) {
+ _handleEventFilePayload: function(store, entry, type, date, payload) {
if (type == "test.1") {
if (payload == "malformed") {
return this.EVENT_FILE_ERROR_MALFORMED;
} else if (payload == "success") {
return this.EVENT_FILE_SUCCESS;
}
return this.EVENT_FILE_ERROR_UNKNOWN_EVENT;
}
@@ -140,17 +140,17 @@ this.TestingCrashManager.prototype = {
type,
date,
payload);
},
};
var DUMMY_DIR_COUNT = 0;
-this.getManager = function () {
+this.getManager = function() {
return Task.spawn(function* () {
const dirMode = OS.Constants.libc.S_IRWXU;
let baseFile = OS.Constants.Path.profileDir;
function makeDir(create = true) {
return Task.spawn(function* () {
let path = OS.Path.join(baseFile, "dummy-dir-" + DUMMY_DIR_COUNT++);
--- a/toolkit/components/crashes/CrashService.js
+++ b/toolkit/components/crashes/CrashService.js
@@ -9,26 +9,26 @@ const {classes: Cc, interfaces: Ci, util
Cu.import("resource://gre/modules/Services.jsm", this);
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
/**
* This component makes crash data available throughout the application.
*
* It is a service because some background activity will eventually occur.
*/
-this.CrashService = function () {};
+this.CrashService = function() {};
CrashService.prototype = Object.freeze({
classID: Components.ID("{92668367-1b17-4190-86b2-1061b2179744}"),
QueryInterface: XPCOMUtils.generateQI([
Ci.nsICrashService,
Ci.nsIObserver,
]),
- addCrash: function (processType, crashType, id) {
+ addCrash: function(processType, crashType, id) {
switch (processType) {
case Ci.nsICrashService.PROCESS_TYPE_MAIN:
processType = Services.crashmanager.PROCESS_TYPE_MAIN;
break;
case Ci.nsICrashService.PROCESS_TYPE_CONTENT:
processType = Services.crashmanager.PROCESS_TYPE_CONTENT;
break;
case Ci.nsICrashService.PROCESS_TYPE_PLUGIN:
@@ -53,17 +53,17 @@ CrashService.prototype = Object.freeze({
break;
default:
throw new Error("Unrecognized CRASH_TYPE: " + crashType);
}
Services.crashmanager.addCrash(processType, crashType, id, new Date());
},
- observe: function (subject, topic, data) {
+ observe: function(subject, topic, data) {
switch (topic) {
case "profile-after-change":
// Side-effect is the singleton is instantiated.
let m = Services.crashmanager;
break;
}
},
});
--- a/toolkit/components/crashmonitor/CrashMonitor.jsm
+++ b/toolkit/components/crashmonitor/CrashMonitor.jsm
@@ -88,17 +88,17 @@ var CrashMonitorInternal = {
*/
path: OS.Path.join(OS.Constants.Path.profileDir, "sessionCheckpoints.json"),
/**
* Load checkpoints from previous session asynchronously.
*
* @return {Promise} A promise that resolves/rejects once loading is complete
*/
- loadPreviousCheckpoints: function () {
+ loadPreviousCheckpoints: function() {
this.previousCheckpoints = Task.spawn(function*() {
let data;
try {
data = yield OS.File.read(CrashMonitorInternal.path, { encoding: "utf-8" });
} catch (ex) {
if (!(ex instanceof OS.File.Error)) {
throw ex;
}
@@ -150,27 +150,27 @@ this.CrashMonitor = {
/**
* Initialize CrashMonitor.
*
* Should only be called from the CrashMonitor XPCOM component.
*
* @return {Promise}
*/
- init: function () {
+ init: function() {
if (CrashMonitorInternal.initialized) {
throw new Error("CrashMonitor.init() must only be called once!");
}
let promise = CrashMonitorInternal.loadPreviousCheckpoints();
// Add "profile-after-change" to checkpoint as this method is
// called after receiving it
CrashMonitorInternal.checkpoints["profile-after-change"] = true;
- NOTIFICATIONS.forEach(function (aTopic) {
+ NOTIFICATIONS.forEach(function(aTopic) {
Services.obs.addObserver(this, aTopic, false);
}, this);
// Add shutdown blocker for profile-before-change
OS.File.profileBeforeChange.addBlocker(
"CrashMonitor: Writing notifications to file after receiving profile-before-change",
CrashMonitorInternal.profileBeforeChangeDeferred.promise,
() => this.checkpoints
@@ -180,17 +180,17 @@ this.CrashMonitor = {
return promise;
},
/**
* Handle registered notifications.
*
* Update checkpoint file for every new notification received.
*/
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
if (!(aTopic in CrashMonitorInternal.checkpoints)) {
// If this is the first time this notification is received,
// remember it and write it to file
CrashMonitorInternal.checkpoints[aTopic] = true;
Task.spawn(function* () {
try {
let data = JSON.stringify(CrashMonitorInternal.checkpoints);
@@ -210,15 +210,15 @@ this.CrashMonitor = {
CrashMonitorInternal.profileBeforeChangeDeferred.resolve();
}
}
});
}
if (NOTIFICATIONS.every(elem => elem in CrashMonitorInternal.checkpoints)) {
// All notifications received, unregister observers
- NOTIFICATIONS.forEach(function (aTopic) {
+ NOTIFICATIONS.forEach(function(aTopic) {
Services.obs.removeObserver(this, aTopic);
}, this);
}
}
};
Object.freeze(this.CrashMonitor);
--- a/toolkit/components/crashmonitor/nsCrashMonitor.js
+++ b/toolkit/components/crashmonitor/nsCrashMonitor.js
@@ -13,17 +13,17 @@ function CrashMonitor() {}
CrashMonitor.prototype = {
classID: Components.ID("{d9d75e86-8f17-4c57-993e-f738f0d86d42}"),
contractID: "@mozilla.org/toolkit/crashmonitor;1",
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]),
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
switch (aTopic) {
case "profile-after-change":
MonitorAPI.init();
}
},
};
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([CrashMonitor]);
--- a/toolkit/components/ctypes/tests/unit/test_jsctypes.js
+++ b/toolkit/components/ctypes/tests/unit/test_jsctypes.js
@@ -183,28 +183,28 @@ function run_test()
do_check_throws(function() {
library.declare("test_void_t_cdecl", ctypes.default_abi, ctypes.void_t);
}, Error);
// test that library functions throw when bound to other objects
library = ctypes.open(libfile.path);
let obj = {};
obj.declare = library.declare;
- do_check_throws(function () { run_void_tests(obj); }, Error);
+ do_check_throws(function() { run_void_tests(obj); }, Error);
obj.close = library.close;
- do_check_throws(function () { obj.close(); }, Error);
+ do_check_throws(function() { obj.close(); }, Error);
// test that functions work as properties of other objects
let getter = library.declare("get_int8_t_cdecl", ctypes.default_abi, ctypes.int8_t);
do_check_eq(getter(), 109);
obj.t = getter;
do_check_eq(obj.t(), 109);
// bug 521937
- do_check_throws(function () { let nolib = ctypes.open("notfoundlibrary.dll"); nolib.close(); }, Error);
+ do_check_throws(function() { let nolib = ctypes.open("notfoundlibrary.dll"); nolib.close(); }, Error);
// bug 522360
do_check_eq(run_load_system_library(), true);
// Test loading a library with a unicode name (bug 589413). Note that nsIFile
// implementations are not available in some harnesses; if not, the harness
// should take care of the copy for us.
let unicodefile = do_get_file(CTYPES_UNICODE_LIB, true);
@@ -408,24 +408,24 @@ function run_Int64_tests() {
do_check_eq(i.toString(10), "9223372036854775807");
do_check_eq(i.toString(16), "7fffffffffffffff");
do_check_eq(i.toString(2), "111111111111111111111111111111111111111111111111111111111111111");
let vals = [-0x8000000000001000, 0x8000000000000000,
ctypes.UInt64("0x8000000000000000"),
Infinity, -Infinity, NaN, 0.1,
5.68e21, null, undefined, "", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
+ {toString: function() { return 7; }},
+ {valueOf: function() { return 7; }}];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { ctypes.Int64(vals[i]); }, TypeError);
+ do_check_throws(function() { ctypes.Int64(vals[i]); }, TypeError);
vals = ["-0x8000000000000001", "0x8000000000000000"];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { ctypes.Int64(vals[i]); }, RangeError);
+ do_check_throws(function() { ctypes.Int64(vals[i]); }, RangeError);
// Test ctypes.Int64.compare.
do_check_eq(ctypes.Int64.compare(ctypes.Int64(5), ctypes.Int64(5)), 0);
do_check_eq(ctypes.Int64.compare(ctypes.Int64(5), ctypes.Int64(4)), 1);
do_check_eq(ctypes.Int64.compare(ctypes.Int64(4), ctypes.Int64(5)), -1);
do_check_eq(ctypes.Int64.compare(ctypes.Int64(-5), ctypes.Int64(-5)), 0);
do_check_eq(ctypes.Int64.compare(ctypes.Int64(-5), ctypes.Int64(-4)), -1);
do_check_eq(ctypes.Int64.compare(ctypes.Int64(-4), ctypes.Int64(-5)), 1);
@@ -558,24 +558,24 @@ function run_UInt64_tests() {
do_check_eq(i.toString(), i.toString(10));
do_check_eq(i.toString(10), "9223372036854775807");
do_check_eq(i.toString(16), "7fffffffffffffff");
do_check_eq(i.toString(2), "111111111111111111111111111111111111111111111111111111111111111");
let vals = [-1, 0x10000000000000000, "-1", "-0x1",
ctypes.Int64("-1"), Infinity, -Infinity, NaN, 0.1,
5.68e21, null, undefined, "", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
+ {toString: function() { return 7; }},
+ {valueOf: function() { return 7; }}];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { ctypes.UInt64(vals[i]); }, TypeError);
+ do_check_throws(function() { ctypes.UInt64(vals[i]); }, TypeError);
vals = ["0x10000000000000000"];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { ctypes.UInt64(vals[i]); }, RangeError);
+ do_check_throws(function() { ctypes.UInt64(vals[i]); }, RangeError);
// Test ctypes.UInt64.compare.
do_check_eq(ctypes.UInt64.compare(ctypes.UInt64(5), ctypes.UInt64(5)), 0);
do_check_eq(ctypes.UInt64.compare(ctypes.UInt64(5), ctypes.UInt64(4)), 1);
do_check_eq(ctypes.UInt64.compare(ctypes.UInt64(4), ctypes.UInt64(5)), -1);
do_check_throws(function() { ctypes.UInt64.compare(ctypes.UInt64(4), ctypes.Int64(4)); }, TypeError);
do_check_throws(function() { ctypes.UInt64.compare(4, 5); }, TypeError);
@@ -773,20 +773,20 @@ function run_bool_tests(library) {
do_check_eq(d.value, 1);
d = new t(1);
do_check_eq(d.value, 1);
// don't convert anything else
let vals = [-1, 2, Infinity, -Infinity, NaN, 0.1,
ctypes.Int64(0), ctypes.UInt64(0),
null, undefined, "", "0", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
+ {toString: function() { return 7; }},
+ {valueOf: function() { return 7; }}];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
+ do_check_throws(function() { d.value = vals[i]; }, TypeError);
do_check_true(d.address().constructor === t.ptr);
do_check_eq(d.address().contents, d.value);
do_check_eq(d.toSource(), "ctypes." + name + "(" + d.value + ")");
do_check_eq(d.toSource(), d.toString());
// Test the function call ABI for calls involving the type,
// and check the alignment of the type against what C says.
@@ -853,20 +853,20 @@ function run_integer_tests(library, t, n
d.value = false;
do_check_eq(d.value, 0);
d.value = true;
do_check_eq(d.value, 1);
// don't convert anything else
let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1,
null, undefined, "", "0", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
+ {toString: function() { return 7; }},
+ {valueOf: function() { return 7; }}];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
+ do_check_throws(function() { d.value = vals[i]; }, TypeError);
do_check_true(d.address().constructor === t.ptr);
do_check_eq(d.address().contents, d.value);
do_check_eq(d.toSource(), "ctypes." + name + "(" + d.value + ")");
do_check_eq(d.toSource(), d.toString());
// Test the function call ABI for calls involving the type,
// and check the alignment of the type against what C says.
@@ -940,20 +940,20 @@ function run_float_tests(library, t, nam
do_check_true(isNaN(d.value));
d.value = 0;
do_check_eq(d.value, 0);
d.value = -0;
do_check_eq(1 / d.value, 1 / -0);
// don't convert anything else
let vals = [true, false, null, undefined, "", "0", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
+ {toString: function() { return 7; }},
+ {valueOf: function() { return 7; }}];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
+ do_check_throws(function() { d.value = vals[i]; }, TypeError);
// Check that values roundtrip through toSource() correctly.
function test_roundtrip(t, val)
{
let f1 = t(val);
eval("var f2 = " + f1.toSource());
do_check_eq(f1.value, f2.value);
}
@@ -1040,20 +1040,20 @@ function run_wrapped_integer_tests(libra
d.value = false;
do_check_eq(d.value, 0);
d.value = true;
do_check_eq(d.value, 1);
// don't convert anything else
let vals = [limits[2], limits[3], Infinity, -Infinity, NaN, 0.1,
null, undefined, "", "0", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
+ {toString: function() { return 7; }},
+ {valueOf: function() { return 7; }}];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
+ do_check_throws(function() { d.value = vals[i]; }, TypeError);
do_check_true(d.address().constructor === t.ptr);
do_check_eq(d.address().contents.toString(), d.value.toString());
do_check_eq(d.toSource(), "ctypes." + name + "(" + wname + "(\"" + d.value + "\"))");
do_check_eq(d.toSource(), d.toString());
// Test the function call ABI for calls involving the type,
// and check the alignment of the type against what C says.
@@ -1123,20 +1123,20 @@ function run_char_tests(library, t, name
d.value = true;
do_check_eq(d.value, 1);
do_check_throws(function() { d.value = "5"; }, TypeError);
// don't convert anything else
let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1,
null, undefined, "", "aa", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
+ {toString: function() { return 7; }},
+ {valueOf: function() { return 7; }}];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
+ do_check_throws(function() { d.value = vals[i]; }, TypeError);
do_check_true(d.address().constructor === t.ptr);
do_check_eq(d.address().contents, 1);
do_check_eq(d.toSource(), "ctypes." + name + "(" + d.value + ")");
do_check_eq(d.toSource(), d.toString());
// Test string autoconversion (and lack thereof).
let literal = "autoconverted";
@@ -1215,20 +1215,20 @@ function run_char16_tests(library, t, na
d.value = "\0";
do_check_eq(toprimitive(d.value), 0);
d.value = "a";
do_check_eq(d.value, "a");
// don't convert anything else
let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1,
null, undefined, "", "aa", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
+ {toString: function() { return 7; }},
+ {valueOf: function() { return 7; }}];
for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
+ do_check_throws(function() { d.value = vals[i]; }, TypeError);
do_check_true(d.address().constructor === t.ptr);
do_check_eq(d.address().contents, "a");
do_check_eq(d.toSource(), "ctypes." + name + "(\"" + d.value + "\")");
do_check_eq(d.toSource(), d.toString());
// Test string autoconversion (and lack thereof).
let literal = "autoconverted";
@@ -2222,17 +2222,17 @@ function run_void_tests(library) {
}
function run_string_tests(library) {
let test_ansi_len = library.declare("test_ansi_len", ctypes.default_abi, ctypes.int32_t, ctypes.char.ptr);
do_check_eq(test_ansi_len(""), 0);
do_check_eq(test_ansi_len("hello world"), 11);
// don't convert anything else to a string
- let vals = [true, 0, 1 / 3, undefined, {}, {toString: function () { return "bad"; }}, []];
+ let vals = [true, 0, 1 / 3, undefined, {}, {toString: function() { return "bad"; }}, []];
for (let i = 0; i < vals.length; i++)
do_check_throws(function() { test_ansi_len(vals[i]); }, TypeError);
let test_wide_len = library.declare("test_wide_len", ctypes.default_abi, ctypes.int32_t, ctypes.char16_t.ptr);
do_check_eq(test_wide_len("hello world"), 11);
let test_ansi_ret = library.declare("test_ansi_ret", ctypes.default_abi, ctypes.char.ptr);
do_check_eq(test_ansi_ret().readString(), "success");
--- a/toolkit/components/downloads/test/unit/test_app_rep_windows.js
+++ b/toolkit/components/downloads/test/unit/test_app_rep_windows.js
@@ -114,18 +114,18 @@ function promiseSaverComplete(aSaver, aO
function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) {
let deferred = Promise.defer();
let inputStream = new StringInputStream(aSourceString, aSourceString.length);
let copier = Cc["@mozilla.org/network/async-stream-copier;1"]
.createInstance(Ci.nsIAsyncStreamCopier);
copier.init(inputStream, aSaverOutputStream, null, false, true, 0x8000, true,
aCloseWhenDone);
copier.asyncCopy({
- onStartRequest: function () { },
- onStopRequest: function (aRequest, aContext, aStatusCode)
+ onStartRequest: function() { },
+ onStopRequest: function(aRequest, aContext, aStatusCode)
{
if (Components.isSuccessCode(aStatusCode)) {
deferred.resolve();
} else {
deferred.reject(new Components.Exception(aResult));
}
},
}, null);
--- a/toolkit/components/exthelper/extApplication.js
+++ b/toolkit/components/exthelper/extApplication.js
@@ -545,17 +545,17 @@ Extension.prototype = {
};
// =================================================
// Extensions constructor
function Extensions(addons) {
this._cache = {};
- addons.forEach(function (addon) {
+ addons.forEach(function(addon) {
this._cache[addon.id] = new Extension(addon);
}, this);
}
// =================================================
// Extensions implementation
Extensions.prototype = {
get all() {
@@ -659,17 +659,17 @@ extApplication.prototype = {
get prefs() {
let prefs = new PreferenceBranch("");
this.__defineGetter__("prefs", () => prefs);
return this.prefs;
},
getExtensions: function(callback) {
- AddonManager.getAddonsByTypes(["extension"], function (addons) {
+ AddonManager.getAddonsByTypes(["extension"], function(addons) {
callback.callback(new Extensions(addons));
});
},
get events() {
// This ensures that FUEL only registers for notifications as needed
// by callers. Note that the unload (xpcom-shutdown) event is listened
--- a/toolkit/components/filepicker/nsFilePicker.js
+++ b/toolkit/components/filepicker/nsFilePicker.js
@@ -294,19 +294,19 @@ nsFilePicker.prototype = {
return o.retvals.buttonStatus;
} catch (ex) { dump("unable to open file picker\n" + ex + "\n"); }
return null;
}
}
if (DEBUG)
- debug = function (s) { dump("-*- filepicker: " + s + "\n"); };
+ debug = function(s) { dump("-*- filepicker: " + s + "\n"); };
else
- debug = function (s) {};
+ debug = function(s) {};
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([nsFilePicker]);
/* crap from strres.js that I want to use for string bundles since I can't include another .js file.... */
var strBundleService = null;
function srGetStrBundle(path)
--- a/toolkit/components/formautofill/FormAutofillContentService.js
+++ b/toolkit/components/formautofill/FormAutofillContentService.js
@@ -138,17 +138,17 @@ FormHandler.prototype = {
/**
* Returns information from the form about fields that can be autofilled, and
* populates the fieldDetails array on this object accordingly.
*
* @returns Serializable data structure that can be sent to the user
* interface, or null if the operation failed because the constraints
* on the allowed fields were not honored.
*/
- collectFormFields: function () {
+ collectFormFields: function() {
let autofillData = {
sections: [],
};
for (let element of this.form.elements) {
// Query the interface and exclude elements that cannot be autocompleted.
if (!(element instanceof Ci.nsIDOMHTMLInputElement)) {
continue;
@@ -220,17 +220,17 @@ FormHandler.prototype = {
* section: Value originally provided to the user interface.
* addressType: Value originally provided to the user interface.
* contactType: Value originally provided to the user interface.
* fieldName: Value originally provided to the user interface.
* value: String with which the field should be updated.
* ],
* }
*/
- autofillFormFields: function (aAutofillResult) {
+ autofillFormFields: function(aAutofillResult) {
for (let field of aAutofillResult.fields) {
// Get the field details, if it was processed by the user interface.
let fieldDetail = this.fieldDetails
.find(f => f.section == field.section &&
f.addressType == field.addressType &&
f.contactType == field.contactType &&
f.fieldName == field.fieldName);
if (!fieldDetail) {
@@ -239,18 +239,18 @@ FormHandler.prototype = {
fieldDetail.element.value = field.value;
}
},
/**
* Waits for one tick of the event loop before resolving the returned promise.
*/
- waitForTick: function () {
- return new Promise(function (resolve) {
+ waitForTick: function() {
+ return new Promise(function(resolve) {
Services.tm.currentThread.dispatch(resolve, Ci.nsIThread.DISPATCH_NORMAL);
});
},
};
/**
* Implements a service used by DOM content to request Form Autofill, in
* particular when the requestAutocomplete method of Form objects is invoked.
@@ -258,15 +258,15 @@ FormHandler.prototype = {
function FormAutofillContentService() {
}
FormAutofillContentService.prototype = {
classID: Components.ID("{ed9c2c3c-3f86-4ae5-8e31-10f71b0f19e6}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIFormAutofillContentService]),
// nsIFormAutofillContentService
- requestAutocomplete: function (aForm, aWindow) {
+ requestAutocomplete: function(aForm, aWindow) {
new FormHandler(aForm, aWindow).handleRequestAutocomplete()
.catch(Cu.reportError);
},
};
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([FormAutofillContentService]);
--- a/toolkit/components/formautofill/FormAutofillStartup.js
+++ b/toolkit/components/formautofill/FormAutofillStartup.js
@@ -26,30 +26,30 @@ FormAutofillStartup.prototype = {
classID: Components.ID("{51c95b3d-7431-467b-8d50-383f158ce9e5}"),
QueryInterface: XPCOMUtils.generateQI([
Ci.nsIFrameMessageListener,
Ci.nsIObserver,
Ci.nsISupportsWeakReference,
]),
// nsIObserver
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
// This method is called by the "profile-after-change" category on startup,
// which is called before any web page loads. At this time, we need to
// register a global message listener in the parent process preemptively,
// because we can receive requests from child processes at any time. For
// performance reasons, we use this object as a message listener, so that we
// don't have to load the FormAutoFill module at startup.
let globalMM = Cc["@mozilla.org/globalmessagemanager;1"]
.getService(Ci.nsIMessageListenerManager);
globalMM.addMessageListener("FormAutofill:RequestAutocomplete", this);
},
// nsIFrameMessageListener
- receiveMessage: function (aMessage) {
+ receiveMessage: function(aMessage) {
// Process the "FormAutofill:RequestAutocomplete" message. Any exception
// raised in the parent process is caught and serialized into the reply
// message that is sent to the requesting child process.
FormAutofill.processRequestAutocomplete(aMessage.data)
.catch(ex => { return { exception: ex } })
.then(result => {
// The browser message manager in the parent will send the reply to the
// associated frame message manager in the child.
--- a/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm
+++ b/toolkit/components/formautofill/content/RequestAutocompleteUI.jsm
@@ -20,17 +20,17 @@ Cu.import("resource://gre/modules/Servic
XPCOMUtils.defineLazyModuleGetter(this, "Promise",
"resource://gre/modules/Promise.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
/**
* Handles the requestAutocomplete user interface.
*/
-this.RequestAutocompleteUI = function (aAutofillData) {
+this.RequestAutocompleteUI = function(aAutofillData) {
this._autofillData = aAutofillData;
}
this.RequestAutocompleteUI.prototype = {
_autofillData: null,
show: Task.async(function* () {
// Create a new promise and store the function that will resolve it. This
--- a/toolkit/components/formautofill/content/requestAutocomplete.js
+++ b/toolkit/components/formautofill/content/requestAutocomplete.js
@@ -17,30 +17,30 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/Promise.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
const RequestAutocompleteDialog = {
resolveFn: null,
autofillData: null,
- onLoad: function () {
+ onLoad: function() {
Task.spawn(function* () {
let args = window.arguments[0].wrappedJSObject;
this.resolveFn = args.resolveFn;
this.autofillData = args.autofillData;
window.sizeToContent();
Services.obs.notifyObservers(window,
"formautofill-window-initialized", "");
}.bind(this)).catch(Cu.reportError);
},
- onAccept: function () {
+ onAccept: function() {
// TODO: Replace with autofill storage module (bug 1018304).
const dummyDB = {
"": {
"name": "Mozzy La",
"street-address": "331 E Evelyn Ave",
"address-level2": "Mountain View",
"address-level1": "CA",
"country": "US",
@@ -73,13 +73,13 @@ const RequestAutocompleteDialog = {
}
}
}
window.close();
this.resolveFn(result);
},
- onCancel: function () {
+ onCancel: function() {
window.close();
this.resolveFn({ canceled: true });
},
};
--- a/toolkit/components/formautofill/test/browser/loader.js
+++ b/toolkit/components/formautofill/test/browser/loader.js
@@ -23,16 +23,16 @@ var Output = {
// Define assertion functions so they look the same across all frameworks.
var Assert = {
ok: _mochitestAssert.ok,
equal: _mochitestAssert.equal,
};
// Define task registration functions, see description in "loader_common.js".
var add_task_in_parent_process = add_task;
-var add_task_in_child_process = function () {};
+var add_task_in_child_process = function() {};
var add_task_in_both_processes = add_task;
Services.scriptloader.loadSubScript(getRootDirectory(gTestPath) +
"head_common.js", this);
// Reminder: unless you are adding new features to the framework, you shouldn't
// have to modify this file. Use "head_common.js" or "head.js" for shared code.
--- a/toolkit/components/formautofill/test/chrome/loader.js
+++ b/toolkit/components/formautofill/test/chrome/loader.js
@@ -25,17 +25,17 @@ Services.scriptloader.loadSubScript(shar
var parentScript = SpecialPowers.loadChromeScript(
SimpleTest.getTestFileURL("loader_parent.js"));
// Replace the extension of the loaded HTML file with ".js"
var testUrl = location.href.replace(/\.\w+$/, ".js");
// Start loading the test script in the parent process.
-var promiseParentInitFinished = new Promise(function (resolve) {
+var promiseParentInitFinished = new Promise(function(resolve) {
parentScript.addMessageListener("finish_load_in_parent", resolve);
});
parentScript.sendAsyncMessage("start_load_in_parent", { testUrl: testUrl });
// Define output functions so they look the same across all frameworks.
var Output = {
print: info,
};
@@ -73,17 +73,17 @@ window.addEventListener("load", function
for (let [taskFn, taskType, taskId] of gTestTasks) {
if (taskType == "content") {
// This is a normal task executed in the current process.
info("Running " + taskFn.name);
yield Task.spawn(taskFn);
} else {
// This is a task executed in the parent process.
info("Running task in parent process: " + taskFn.name);
- let promiseFinished = new Promise(function (resolve) {
+ let promiseFinished = new Promise(function(resolve) {
parentScript.addMessageListener("finish_task_" + taskId, resolve);
});
parentScript.sendAsyncMessage("start_task_" + taskId);
yield promiseFinished;
info("Finished task in parent process: " + taskFn.name);
}
}
} catch (ex) {
--- a/toolkit/components/formautofill/test/chrome/loader_parent.js
+++ b/toolkit/components/formautofill/test/chrome/loader_parent.js
@@ -33,37 +33,37 @@ var Assert = {
ok: assert.ok,
equal: assert.equal,
};
// Define task registration functions, see description in "loader_common.js".
function add_task_in_parent_process(taskFn, taskIdOverride) {
let taskId = taskIdOverride || getTaskId(Components.stack.caller);
Output.print("Registering in the parent process: " + taskId);
- addMessageListener("start_task_" + taskId, function () {
+ addMessageListener("start_task_" + taskId, function() {
Task.spawn(function* () {
try {
Output.print("Running in the parent process " + taskId);
yield Task.spawn(taskFn);
} catch (ex) {
assert.ok(false, ex);
}
sendAsyncMessage("finish_task_" + taskId, {});
});
});
}
-var add_task = function () {};
-var add_task_in_child_process = function () {};
+var add_task = function() {};
+var add_task_in_child_process = function() {};
var add_task_in_both_processes = add_task_in_parent_process;
// We need to wait for the child process to send us the path of the test file
// to load before we can actually start loading it.
var context = this;
-addMessageListener("start_load_in_parent", function (message) {
+addMessageListener("start_load_in_parent", function(message) {
Output.print("Starting loading infrastructure in parent process.");
let headUrl = "chrome://mochitests/content/chrome/" +
"toolkit/components/formautofill/test/chrome/head_common.js";
Services.scriptloader.loadSubScript(headUrl, context);
Services.scriptloader.loadSubScript(message.testUrl, context);
// Register the execution of termination tasks after all other tasks.
--- a/toolkit/components/formautofill/test/head_common.js
+++ b/toolkit/components/formautofill/test/head_common.js
@@ -37,47 +37,47 @@ var TestUtils = {
* Waits for at least one tick of the event loop. This means that all pending
* events at the time of this call will have been processed. Other events may
* be processed before the returned promise is resolved.
*
* @return {Promise}
* @resolves When pending events have been processed.
* @rejects Never.
*/
- waitForTick: function () {
+ waitForTick: function() {
return new Promise(resolve => executeSoon(resolve));
},
/**
* Waits for the specified timeout.
*
* @param aTimeMs
* Minimum time to wait from the moment of this call, in milliseconds.
* The actual wait may be longer, due to system timer resolution and
* pending events being processed before the promise is resolved.
*
* @return {Promise}
* @resolves When the specified time has passed.
* @rejects Never.
*/
- waitMs: function (aTimeMs) {
+ waitMs: function(aTimeMs) {
return new Promise(resolve => setTimeout(resolve, aTimeMs));
},
/**
* Allows waiting for an observer notification once.
*
* @param aTopic
* Notification topic to observe.
*
* @return {Promise}
* @resolves The array [aSubject, aData] from the observed notification.
* @rejects Never.
*/
- waitForNotification: function (aTopic) {
+ waitForNotification: function(aTopic) {
Output.print("Waiting for notification: '" + aTopic + "'.");
return new Promise(resolve => Services.obs.addObserver(
function observe(aSubject, aTopic, aData) {
Services.obs.removeObserver(observe, aTopic);
resolve([aSubject, aData]);
}, aTopic, false));
},
@@ -91,17 +91,17 @@ var TestUtils = {
* String with the name of the event.
* @param aUseCapture
* This parameter is passed to the addEventListener call.
*
* @return {Promise}
* @resolves The arguments from the observed event.
* @rejects Never.
*/
- waitForEvent: function (aTarget, aEventName, aUseCapture = false) {
+ waitForEvent: function(aTarget, aEventName, aUseCapture = false) {
Output.print("Waiting for event: '" + aEventName + "' on " + aTarget + ".");
return new Promise(resolve => aTarget.addEventListener(aEventName,
function onEvent(...aArgs) {
aTarget.removeEventListener(aEventName, onEvent, aUseCapture);
resolve(...aArgs);
}, aUseCapture));
},
--- a/toolkit/components/formautofill/test/loader_common.js
+++ b/toolkit/components/formautofill/test/loader_common.js
@@ -99,22 +99,22 @@ function add_termination_task(taskFn) {
* between the parent and child processes.
*/
function getTaskId(stackFrame) {
return stackFrame.filename + ":" + stackFrame.lineNumber;
}
// This is a shared helper for mochitest-chrome and mochitest-browser.
var _mochitestAssert = {
- ok: function (actual) {
+ ok: function(actual) {
let stack = Components.stack.caller;
ok(actual, "[" + stack.name + " : " + stack.lineNumber + "] " + actual +
" == true");
},
- equal: function (actual, expected) {
+ equal: function(actual, expected) {
let stack = Components.stack.caller;
is(actual, expected, "[" + stack.name + " : " + stack.lineNumber + "] " +
actual + " == " + expected);
},
};
// Reminder: unless you are adding new features to the framework, you shouldn't
// have to modify this file. Use "head_common.js" or "head.js" for shared code.
--- a/toolkit/components/formautofill/test/xpcshell/loader.js
+++ b/toolkit/components/formautofill/test/xpcshell/loader.js
@@ -25,17 +25,17 @@ var Output = {
print: do_print,
};
var executeSoon = do_execute_soon;
var setTimeout = (fn, delay) => do_timeout(delay, fn);
// Define task registration functions, see description in "loader_common.js".
var add_task_in_parent_process = add_task;
-var add_task_in_child_process = function () {};
+var add_task_in_child_process = function() {};
var add_task_in_both_processes = add_task;
Services.scriptloader.loadSubScript(
Services.io.newFileURI(do_get_file("head_common.js")).spec, this);
// Tests are always run asynchronously and with the profile loaded.
function run_test() {
do_get_profile();
--- a/toolkit/components/gfx/content/gfxFrameScript.js
+++ b/toolkit/components/gfx/content/gfxFrameScript.js
@@ -30,17 +30,17 @@ const gfxFrameScript = {
isSanityTest: function(aUri) {
if (!aUri) {
return false;
}
return aUri.endsWith("/sanitytest.html");
},
- onStateChange: function (webProgress, req, flags, status) {
+ onStateChange: function(webProgress, req, flags, status) {
if (webProgress.isTopLevel &&
(flags & Ci.nsIWebProgressListener.STATE_STOP) &&
this.isSanityTest(req.name)) {
webProgress.removeProgressListener(this);
// If no paint is pending, then the test already painted
if (this.domUtils.isMozAfterPaintPending) {
--- a/toolkit/components/jsdownloads/src/DownloadCore.jsm
+++ b/toolkit/components/jsdownloads/src/DownloadCore.jsm
@@ -143,17 +143,17 @@ const kProgressUpdateIntervalMs = 400;
// Download
/**
* Represents a single download, with associated state and actions. This object
* is transient, though it can be included in a DownloadList so that it can be
* managed by the user interface and persisted across sessions.
*/
-this.Download = function ()
+this.Download = function()
{
this._deferSucceeded = Promise.defer();
}
this.Download.prototype = {
/**
* DownloadSource object associated with this download.
*/
@@ -705,17 +705,17 @@ this.Download.prototype = {
* @return {Promise}
* @resolves When the instruction to launch the file has been
* successfully given to the operating system. Note that
* the OS might still take a while until the file is actually
* launched.
* @rejects JavaScript exception if there was an error trying to launch
* the file.
*/
- launch: function () {
+ launch: function() {
if (!this.succeeded) {
return Promise.reject(
new Error("launch can only be called if the download succeeded")
);
}
return DownloadIntegration.launchDownload(this);
},
@@ -839,17 +839,17 @@ this.Download.prototype = {
* After this method has been called, if the tryToKeepPartialData property is
* still true when the download is restarted, partial data will be retained
* during the new download attempt.
*
* @return {Promise}
* @resolves When the partial data has been successfully removed.
* @rejects JavaScript exception if the operation could not be completed.
*/
- removePartialData: function ()
+ removePartialData: function()
{
if (!this.canceled && !this.error) {
return Promise.resolve();
}
let promiseRemovePartialData = this._promiseRemovePartialData;
if (!promiseRemovePartialData) {
@@ -914,17 +914,17 @@ this.Download.prototype = {
*
* This allows the properties of the download to be updated in case the user
* moved or deleted the target file or its associated ".part" file.
*
* @return {Promise}
* @resolves When the operation has completed.
* @rejects Never.
*/
- refresh: function ()
+ refresh: function()
{
return Task.spawn(function* () {
if (!this.stopped || this._finalized) {
return;
}
if (this.succeeded) {
let oldExists = this.target.exists;
@@ -993,17 +993,17 @@ this.Download.prototype = {
* Whether any partially downloaded data should be removed after the
* download has been stopped.
*
* @return {Promise}
* @resolves When the operation has finished successfully.
* @rejects JavaScript exception if an error occurred while removing the
* partially downloaded data.
*/
- finalize: function (aRemovePartialData)
+ finalize: function(aRemovePartialData)
{
// Prevents the download from starting again after having been stopped.
this._finalized = true;
if (aRemovePartialData) {
// Cancel the download, in case it is currently in progress, then remove
// any partially downloaded data. The removal operation waits for
// cancellation to be completed before resolving the promise it returns.
@@ -1090,17 +1090,17 @@ this.Download.prototype = {
}
},
/**
* Returns a static representation of the current object state.
*
* @return A JavaScript object that can be serialized to JSON.
*/
- toSerializable: function ()
+ toSerializable: function()
{
let serializable = {
source: this.source.toSerializable(),
target: this.target.toSerializable(),
};
let saver = this.saver.toSerializable();
if (!serializable.source || !saver) {
@@ -1142,17 +1142,17 @@ this.Download.prototype = {
* object that should be saved into a file also change. This excludes
* properties whose value doesn't usually change during the download lifetime.
*
* This function is used to determine whether the download should be
* serialized after a property change notification has been received.
*
* @return String representing the relevant download state.
*/
- getSerializationHash: function ()
+ getSerializationHash: function()
{
// The "succeeded", "canceled", "error", and startTime properties are not
// taken into account because they all change before the "stopped" property
// changes, and are not altered in other cases.
return this.stopped + "," + this.totalBytes + "," + this.hasPartialData +
"," + this.contentType;
},
};
@@ -1187,17 +1187,17 @@ const kPlainSerializableDownloadProperti
* See DownloadTarget.fromSerializable for details.
* saver: Serializable representation of a DownloadSaver object. See
* DownloadSaver.fromSerializable for details. If omitted,
* defaults to "copy".
* }
*
* @return The newly created Download object.
*/
-Download.fromSerializable = function (aSerializable) {
+Download.fromSerializable = function(aSerializable) {
let download = new Download();
if (aSerializable.source instanceof DownloadSource) {
download.source = aSerializable.source;
} else {
download.source = DownloadSource.fromSerializable(aSerializable.source);
}
if (aSerializable.target instanceof DownloadTarget) {
download.target = aSerializable.target;
@@ -1247,17 +1247,17 @@ Download.fromSerializable = function (aS
return download;
};
// DownloadSource
/**
* Represents the source of a download, for example a document or an URI.
*/
-this.DownloadSource = function () {}
+this.DownloadSource = function() {}
this.DownloadSource.prototype = {
/**
* String containing the URI for the download source.
*/
url: null,
/**
@@ -1290,17 +1290,17 @@ this.DownloadSource.prototype = {
*/
adjustChannel: null,
/**
* Returns a static representation of the current object state.
*
* @return A JavaScript object that can be serialized to JSON.
*/
- toSerializable: function ()
+ toSerializable: function()
{
if (this.adjustChannel) {
// If the callback was used, we can't reproduce this across sessions.
return null;
}
// Simplify the representation if we don't have other details.
if (!this.isPrivate && !this.referrer && !this._unknownProperties) {
@@ -1337,17 +1337,17 @@ this.DownloadSource.prototype = {
* adjustChannel: For downloads handled by (default) DownloadCopySaver,
* this function can adjust the network channel before
* it is opened, for example to change the HTTP headers
* or to upload a stream as POST data. Optional.
* }
*
* @return The newly created DownloadSource object.
*/
-this.DownloadSource.fromSerializable = function (aSerializable) {
+this.DownloadSource.fromSerializable = function(aSerializable) {
let source = new DownloadSource();
if (isString(aSerializable)) {
// Convert String objects to primitive strings at this point.
source.url = aSerializable.toString();
} else if (aSerializable instanceof Ci.nsIURI) {
source.url = aSerializable.spec;
} else if (aSerializable instanceof Ci.nsIDOMWindow) {
source.url = aSerializable.location.href;
@@ -1374,17 +1374,17 @@ this.DownloadSource.fromSerializable = f
};
// DownloadTarget
/**
* Represents the target of a download, for example a file in the global
* downloads directory, or a file in the system temporary directory.
*/
-this.DownloadTarget = function () {}
+this.DownloadTarget = function() {}
this.DownloadTarget.prototype = {
/**
* String containing the path of the target file.
*/
path: null,
/**
@@ -1446,17 +1446,17 @@ this.DownloadTarget.prototype = {
}
}),
/**
* Returns a static representation of the current object state.
*
* @return A JavaScript object that can be serialized to JSON.
*/
- toSerializable: function ()
+ toSerializable: function()
{
// Simplify the representation if we don't have other details.
if (!this.partFilePath && !this._unknownProperties) {
return this.path;
}
let serializable = { path: this.path,
partFilePath: this.partFilePath };
@@ -1474,17 +1474,17 @@ this.DownloadTarget.prototype = {
* object with the following properties:
* {
* path: String containing the path of the target file.
* partFilePath: optional string containing the part file path.
* }
*
* @return The newly created DownloadTarget object.
*/
-this.DownloadTarget.fromSerializable = function (aSerializable) {
+this.DownloadTarget.fromSerializable = function(aSerializable) {
let target = new DownloadTarget();
if (isString(aSerializable)) {
// Convert String objects to primitive strings at this point.
target.path = aSerializable.toString();
} else if (aSerializable instanceof Ci.nsIFile) {
// Read the "path" property of nsIFile after checking the object type.
target.path = aSerializable.path;
} else {
@@ -1516,17 +1516,17 @@ this.DownloadTarget.fromSerializable = f
* download is a network failure or a local file failure,
* based on a set of known values of the result code.
* This is useful when the error is received by a
* component that handles both aspects of the download.
* }
* The properties object may also contain any of the DownloadError's
* because properties, which will be set accordingly in the error object.
*/
-this.DownloadError = function (aProperties)
+this.DownloadError = function(aProperties)
{
const NS_ERROR_MODULE_BASE_OFFSET = 0x45;
const NS_ERROR_MODULE_NETWORK = 6;
const NS_ERROR_MODULE_FILES = 13;
// Set the error name used by the Error object prototype first.
this.name = "DownloadError";
this.result = aProperties.result || Cr.NS_ERROR_FAILURE;
@@ -1648,17 +1648,17 @@ this.DownloadError.prototype = {
*/
innerException: null,
/**
* Returns a static representation of the current object state.
*
* @return A JavaScript object that can be serialized to JSON.
*/
- toSerializable: function ()
+ toSerializable: function()
{
let serializable = {
result: this.result,
message: this.message,
becauseSourceFailed: this.becauseSourceFailed,
becauseTargetFailed: this.becauseTargetFailed,
becauseBlocked: this.becauseBlocked,
becauseBlockedByParentalControls: this.becauseBlockedByParentalControls,
@@ -1675,17 +1675,17 @@ this.DownloadError.prototype = {
/**
* Creates a new DownloadError object from its serializable representation.
*
* @param aSerializable
* Serializable representation of a DownloadError object.
*
* @return The newly created DownloadError object.
*/
-this.DownloadError.fromSerializable = function (aSerializable) {
+this.DownloadError.fromSerializable = function(aSerializable) {
let e = new DownloadError(aSerializable);
deserializeUnknownProperties(e, aSerializable, property =>
property != "result" &&
property != "message" &&
property != "becauseSourceFailed" &&
property != "becauseTargetFailed" &&
property != "becauseBlocked" &&
property != "becauseBlockedByParentalControls" &&
@@ -1696,17 +1696,17 @@ this.DownloadError.fromSerializable = fu
return e;
};
// DownloadSaver
/**
* Template for an object that actually transfers the data for the download.
*/
-this.DownloadSaver = function () {}
+this.DownloadSaver = function() {}
this.DownloadSaver.prototype = {
/**
* Download object for raising notifications and reading properties.
*
* If the tryToKeepPartialData property of the download object is false, the
* saver should never try to keep partially downloaded data if the download
* fails.
@@ -1763,17 +1763,17 @@ this.DownloadSaver.prototype = {
return Promise.resolve();
},
/**
* This can be called by the saver implementation when the download is already
* started, to add it to the browsing history. This method has no effect if
* the download is private.
*/
- addToHistory: function ()
+ addToHistory: function()
{
if (this.download.source.isPrivate) {
return;
}
let sourceUri = NetUtil.newURI(this.download.source.url);
let referrer = this.download.source.referrer;
let referrerUri = referrer ? NetUtil.newURI(referrer) : null;
@@ -1800,46 +1800,46 @@ this.DownloadSaver.prototype = {
}
},
/**
* Returns a static representation of the current object state.
*
* @return A JavaScript object that can be serialized to JSON.
*/
- toSerializable: function ()
+ toSerializable: function()
{
throw new Error("Not implemented.");
},
/**
* Returns the SHA-256 hash of the downloaded file, if it exists.
*/
- getSha256Hash: function ()
+ getSha256Hash: function()
{
throw new Error("Not implemented.");
},
- getSignatureInfo: function ()
+ getSignatureInfo: function()
{
throw new Error("Not implemented.");
},
}; // DownloadSaver
/**
* Creates a new DownloadSaver object from its serializable representation.
*
* @param aSerializable
* Serializable representation of a DownloadSaver object. If no initial
* state information for the saver object is needed, can be a string
* representing the class of the download operation, for example "copy".
*
* @return The newly created DownloadSaver object.
*/
-this.DownloadSaver.fromSerializable = function (aSerializable) {
+this.DownloadSaver.fromSerializable = function(aSerializable) {
let serializable = isString(aSerializable) ? { type: aSerializable }
: aSerializable;
let saver;
switch (serializable.type) {
case "copy":
saver = DownloadCopySaver.fromSerializable(serializable);
break;
case "legacy":
@@ -1854,17 +1854,17 @@ this.DownloadSaver.fromSerializable = fu
return saver;
};
// DownloadCopySaver
/**
* Saver object that simply copies the entire source file to the target.
*/
-this.DownloadCopySaver = function () {}
+this.DownloadCopySaver = function() {}
this.DownloadCopySaver.prototype = {
__proto__: DownloadSaver.prototype,
/**
* BackgroundFileSaver object currently handling the download.
*/
_backgroundFileSaver: null,
@@ -1962,17 +1962,17 @@ this.DownloadCopySaver.prototype = {
}
// Create the object that will save the file in a background thread.
let backgroundFileSaver = new BackgroundFileSaverStreamListener();
try {
// When the operation completes, reflect the status in the promise
// returned by this download execution function.
backgroundFileSaver.observer = {
- onTargetChange: function () { },
+ onTargetChange: function() { },
onSaveComplete: (aSaver, aStatus) => {
// Send notifications now that we can restart if needed.
if (Components.isSuccessCode(aStatus)) {
// Save the hash before freeing backgroundFileSaver.
this._sha256Hash = aSaver.sha256Hash;
this._signatureInfo = aSaver.signatureInfo;
this._redirects = aSaver.redirects;
deferSaveComplete.resolve();
@@ -2027,28 +2027,28 @@ this.DownloadCopySaver.prototype = {
aProgressMax)
{
let currentBytes = resumeFromBytes + aProgress;
let totalBytes = aProgressMax == -1 ? -1 : (resumeFromBytes +
aProgressMax);
aSetProgressBytesFn(currentBytes, totalBytes, aProgress > 0 &&
partFilePath && keepPartialData);
},
- onStatus: function () { },
+ onStatus: function() { },
};
// If the callback was set, handle it now before opening the channel.
if (download.source.adjustChannel) {
yield download.source.adjustChannel(channel);
}
// Open the channel, directing output to the background file saver.
backgroundFileSaver.QueryInterface(Ci.nsIStreamListener);
channel.asyncOpen2({
- onStartRequest: function (aRequest, aContext) {
+ onStartRequest: function(aRequest, aContext) {
backgroundFileSaver.onStartRequest(aRequest, aContext);
// Check if the request's response has been blocked by Windows
// Parental Controls with an HTTP 450 error code.
if (aRequest instanceof Ci.nsIHttpChannel &&
aRequest.responseStatus == 450) {
// Set a flag that can be retrieved later when handling the
// cancellation so that the proper error can be thrown.
@@ -2119,32 +2119,32 @@ this.DownloadCopySaver.prototype = {
keepPartialData);
} else {
// Set the final target file, and delete it on failure.
backgroundFileSaver.setTarget(new FileUtils.File(targetPath),
false);
}
}.bind(copySaver),
- onStopRequest: function (aRequest, aContext, aStatusCode) {
+ onStopRequest: function(aRequest, aContext, aStatusCode) {
try {
backgroundFileSaver.onStopRequest(aRequest, aContext,
aStatusCode);
} finally {
// If the data transfer completed successfully, indicate to the
// background file saver that the operation can finish. If the
// data transfer failed, the saver has been already stopped.
if (Components.isSuccessCode(aStatusCode)) {
backgroundFileSaver.finish(Cr.NS_OK);
}
}
}.bind(copySaver),
- onDataAvailable: function (aRequest, aContext, aInputStream,
- aOffset, aCount) {
+ onDataAvailable: function(aRequest, aContext, aInputStream,
+ aOffset, aCount) {
backgroundFileSaver.onDataAvailable(aRequest, aContext,
aInputStream, aOffset,
aCount);
}.bind(copySaver),
});
// We should check if we have been canceled in the meantime, after
// all the previous asynchronous operations have been executed and
@@ -2251,17 +2251,17 @@ this.DownloadCopySaver.prototype = {
this._backgroundFileSaver.finish(Cr.NS_ERROR_FAILURE);
this._backgroundFileSaver = null;
}
},
/**
* Implements "DownloadSaver.removePartialData".
*/
- removePartialData: function ()
+ removePartialData: function()
{
return Task.spawn(function* task_DCS_removePartialData() {
if (this.download.target.partFilePath) {
try {
yield OS.File.remove(this.download.target.partFilePath);
} catch (ex) {
if (!(ex instanceof OS.File.Error) || !ex.becauseNoSuchFile) {
throw ex;
@@ -2269,64 +2269,64 @@ this.DownloadCopySaver.prototype = {
}
}
}.bind(this));
},
/**
* Implements "DownloadSaver.toSerializable".
*/
- toSerializable: function ()
+ toSerializable: function()
{
// Simplify the representation if we don't have other details.
if (!this.entityID && !this._unknownProperties) {
return "copy";
}
let serializable = { type: "copy",
entityID: this.entityID };
serializeUnknownProperties(this, serializable);
return serializable;
},
/**
* Implements "DownloadSaver.getSha256Hash"
*/
- getSha256Hash: function ()
+ getSha256Hash: function()
{
return this._sha256Hash;
},
/*
* Implements DownloadSaver.getSignatureInfo.
*/
- getSignatureInfo: function ()
+ getSignatureInfo: function()
{
return this._signatureInfo;
},
/*
* Implements DownloadSaver.getRedirects.
*/
- getRedirects: function ()
+ getRedirects: function()
{
return this._redirects;
}
};
/**
* Creates a new DownloadCopySaver object, with its initial state derived from
* its serializable representation.
*
* @param aSerializable
* Serializable representation of a DownloadCopySaver object.
*
* @return The newly created DownloadCopySaver object.
*/
-this.DownloadCopySaver.fromSerializable = function (aSerializable) {
+this.DownloadCopySaver.fromSerializable = function(aSerializable) {
let saver = new DownloadCopySaver();
if ("entityID" in aSerializable) {
saver.entityID = aSerializable.entityID;
}
deserializeUnknownProperties(saver, aSerializable, property =>
property != "entityID" && property != "type");
@@ -2335,17 +2335,17 @@ this.DownloadCopySaver.fromSerializable
// DownloadLegacySaver
/**
* Saver object that integrates with the legacy nsITransfer interface.
*
* For more background on the process, see the DownloadLegacyTransfer object.
*/
-this.DownloadLegacySaver = function ()
+this.DownloadLegacySaver = function()
{
this.deferExecuted = Promise.defer();
this.deferCanceled = Promise.defer();
}
this.DownloadLegacySaver.prototype = {
__proto__: DownloadSaver.prototype,
@@ -2434,17 +2434,17 @@ this.DownloadLegacySaver.prototype = {
* nsIRequest associated to the status update.
* @param aAlreadyAddedToHistory
* Indicates that the nsIExternalHelperAppService component already
* added the download to the browsing history, unless it was started
* from a private browsing window. When this parameter is false, the
* download is added to the browsing history here. Private downloads
* are never added to history even if this parameter is false.
*/
- onTransferStarted: function (aRequest, aAlreadyAddedToHistory)
+ onTransferStarted: function(aRequest, aAlreadyAddedToHistory)
{
// Store the entity ID to use for resuming if required.
if (this.download.tryToKeepPartialData &&
aRequest instanceof Ci.nsIResumableChannel) {
try {
// If reading the ID succeeds, the source is resumable.
this.entityID = aRequest.entityID;
} catch (ex) {
@@ -2597,17 +2597,17 @@ this.DownloadLegacySaver.prototype = {
this.request = null;
this.deferCanceled = null;
// Allow the download to restart through a DownloadCopySaver.
this.firstExecutionFinished = true;
}
}.bind(this));
},
- _checkReputationAndMove: function () {
+ _checkReputationAndMove: function() {
return DownloadCopySaver.prototype._checkReputationAndMove
.apply(this, arguments);
},
/**
* Implements "DownloadSaver.cancel".
*/
cancel: function DLS_cancel()
@@ -2623,134 +2623,134 @@ this.DownloadLegacySaver.prototype = {
if (this.deferCanceled) {
this.deferCanceled.resolve();
}
},
/**
* Implements "DownloadSaver.removePartialData".
*/
- removePartialData: function ()
+ removePartialData: function()
{
// DownloadCopySaver and DownloadLeagcySaver use the same logic for removing
// partially downloaded data, though this implementation isn't shared by
// other saver types, thus it isn't found on their shared prototype.
return DownloadCopySaver.prototype.removePartialData.call(this);
},
/**
* Implements "DownloadSaver.toSerializable".
*/
- toSerializable: function ()
+ toSerializable: function()
{
// This object depends on legacy components that are created externally,
// thus it cannot be rebuilt during deserialization. To support resuming
// across different browser sessions, this object is transformed into a
// DownloadCopySaver for the purpose of serialization.
return DownloadCopySaver.prototype.toSerializable.call(this);
},
/**
* Implements "DownloadSaver.getSha256Hash".
*/
- getSha256Hash: function ()
+ getSha256Hash: function()
{
if (this.copySaver) {
return this.copySaver.getSha256Hash();
}
return this._sha256Hash;
},
/**
* Called by the nsITransfer implementation when the hash is available.
*/
- setSha256Hash: function (hash)
+ setSha256Hash: function(hash)
{
this._sha256Hash = hash;
},
/**
* Implements "DownloadSaver.getSignatureInfo".
*/
- getSignatureInfo: function ()
+ getSignatureInfo: function()
{
if (this.copySaver) {
return this.copySaver.getSignatureInfo();
}
return this._signatureInfo;
},
/**
* Called by the nsITransfer implementation when the hash is available.
*/
- setSignatureInfo: function (signatureInfo)
+ setSignatureInfo: function(signatureInfo)
{
this._signatureInfo = signatureInfo;
},
/**
* Implements "DownloadSaver.getRedirects".
*/
- getRedirects: function ()
+ getRedirects: function()
{
if (this.copySaver) {
return this.copySaver.getRedirects();
}
return this._redirects;
},
/**
* Called by the nsITransfer implementation when the redirect chain is
* available.
*/
- setRedirects: function (redirects)
+ setRedirects: function(redirects)
{
this._redirects = redirects;
},
};
/**
* Returns a new DownloadLegacySaver object. This saver type has a
* deserializable form only when creating a new object in memory, because it
* cannot be serialized to disk.
*/
-this.DownloadLegacySaver.fromSerializable = function () {
+this.DownloadLegacySaver.fromSerializable = function() {
return new DownloadLegacySaver();
};
// DownloadPDFSaver
/**
* This DownloadSaver type creates a PDF file from the current document in a
* given window, specified using the windowRef property of the DownloadSource
* object associated with the download.
*
* In order to prevent the download from saving a different document than the one
* originally loaded in the window, any attempt to restart the download will fail.
*
* Since this DownloadSaver type requires a live document as a source, it cannot
* be persisted across sessions, unless the download already succeeded.
*/
-this.DownloadPDFSaver = function () {
+this.DownloadPDFSaver = function() {
}
this.DownloadPDFSaver.prototype = {
__proto__: DownloadSaver.prototype,
/**
* An nsIWebBrowserPrint instance for printing this page.
* This is null when saving has not started or has completed,
* or while the operation is being canceled.
*/
_webBrowserPrint: null,
/**
* Implements "DownloadSaver.execute".
*/
- execute: function (aSetProgressBytesFn, aSetPropertiesFn)
+ execute: function(aSetProgressBytesFn, aSetPropertiesFn)
{
return Task.spawn(function* task_DCS_execute() {
if (!this.download.source.windowRef) {
throw new DownloadError({
message: "PDF saver must be passed an open window, and cannot be restarted.",
becauseSourceFailed: true,
});
}
@@ -2795,34 +2795,34 @@ this.DownloadPDFSaver.prototype = {
printSettings.footerStrRight = "";
this._webBrowserPrint = win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebBrowserPrint);
try {
yield new Promise((resolve, reject) => {
this._webBrowserPrint.print(printSettings, {
- onStateChange: function (webProgress, request, stateFlags, status) {
+ onStateChange: function(webProgress, request, stateFlags, status) {
if (stateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
if (!Components.isSuccessCode(status)) {
reject(new DownloadError({ result: status,
inferCause: true }));
} else {
resolve();
}
}
},
- onProgressChange: function (webProgress, request, curSelfProgress,
- maxSelfProgress, curTotalProgress,
- maxTotalProgress) {
+ onProgressChange: function(webProgress, request, curSelfProgress,
+ maxSelfProgress, curTotalProgress,
+ maxTotalProgress) {
aSetProgressBytesFn(curTotalProgress, maxTotalProgress, false);
},
- onLocationChange: function () {},
- onStatusChange: function () {},
- onSecurityChange: function () {},
+ onLocationChange: function() {},
+ onStatusChange: function() {},
+ onSecurityChange: function() {},
});
});
} finally {
// Remove the print object to avoid leaks
this._webBrowserPrint = null;
}
let fileInfo = yield OS.File.stat(targetPath);
@@ -2839,17 +2839,17 @@ this.DownloadPDFSaver.prototype = {
this._webBrowserPrint.cancel();
this._webBrowserPrint = null;
}
},
/**
* Implements "DownloadSaver.toSerializable".
*/
- toSerializable: function ()
+ toSerializable: function()
{
if (this.download.succeeded) {
return DownloadCopySaver.prototype.toSerializable.call(this);
}
// This object needs a window to recreate itself. If it didn't succeded
// it will not be possible to restart. Returning null here will
// prevent us from serializing it at all.
@@ -2861,11 +2861,11 @@ this.DownloadPDFSaver.prototype = {
* Creates a new DownloadPDFSaver object, with its initial state derived from
* its serializable representation.
*
* @param aSerializable
* Serializable representation of a DownloadPDFSaver object.
*
* @return The newly created DownloadPDFSaver object.
*/
-this.DownloadPDFSaver.fromSerializable = function (aSerializable) {
+this.DownloadPDFSaver.fromSerializable = function(aSerializable) {
return new DownloadPDFSaver();
};
--- a/toolkit/components/jsdownloads/src/DownloadImport.jsm
+++ b/toolkit/components/jsdownloads/src/DownloadImport.jsm
@@ -46,34 +46,34 @@ const DOWNLOAD_QUEUED = 5;
/**
* Provides an object that has a method to import downloads
* from the previous SQLite storage format.
*
* @param aList A DownloadList where each successfully
* imported download will be added.
* @param aPath The path to the database file.
*/
-this.DownloadImport = function (aList, aPath)
+this.DownloadImport = function(aList, aPath)
{
this.list = aList;
this.path = aPath;
}
this.DownloadImport.prototype = {
/**
* Imports unfinished downloads from the previous SQLite storage
* format (supporting schemas 7 and up), to the new Download object
* format. Each imported download will be added to the DownloadList
*
* @return {Promise}
* @resolves When the operation has completed (i.e., every download
* from the previous database has been read and added to
* the DownloadList)
*/
- import: function () {
+ import: function() {
return Task.spawn(function* task_DI_import() {
let connection = yield Sqlite.openConnection({ path: this.path });
try {
let schemaVersion = yield connection.getSchemaVersion();
// We don't support schemas older than version 7 (from 2007)
// - Version 7 added the columns mimeType, preferredApplication
// and preferredAction in 2007
--- a/toolkit/components/jsdownloads/src/DownloadLegacy.js
+++ b/toolkit/components/jsdownloads/src/DownloadLegacy.js
@@ -161,17 +161,17 @@ DownloadLegacyTransfer.prototype = {
aCurTotalProgress,
aMaxTotalProgress)
{
this.onProgressChange64(aWebProgress, aRequest, aCurSelfProgress,
aMaxSelfProgress, aCurTotalProgress,
aMaxTotalProgress);
},
- onLocationChange: function () { },
+ onLocationChange: function() { },
onStatusChange: function DLT_onStatusChange(aWebProgress, aRequest, aStatus,
aMessage)
{
// The status change may optionally be received in addition to the state
// change, but if no network request actually started, it is possible that
// we only receive a status change with an error status code.
if (!Components.isSuccessCode(aStatus)) {
@@ -179,17 +179,17 @@ DownloadLegacyTransfer.prototype = {
// Wait for the associated Download object to be available.
this._deferDownload.promise.then(function DLT_OSC_onDownload(aDownload) {
aDownload.saver.onTransferFinished(aRequest, aStatus);
}).then(null, Cu.reportError);
}
},
- onSecurityChange: function () { },
+ onSecurityChange: function() { },
// nsIWebProgressListener2
onProgressChange64: function DLT_onProgressChange64(aWebProgress, aRequest,
aCurSelfProgress,
aMaxSelfProgress,
aCurTotalProgress,
aMaxTotalProgress)
@@ -252,27 +252,27 @@ DownloadLegacyTransfer.prototype = {
// Start processing all the other events received through nsITransfer.
this._deferDownload.resolve(aDownload);
// Add the download to the list, allowing it to be seen and canceled.
return Downloads.getList(Downloads.ALL).then(list => list.add(aDownload));
}.bind(this)).then(null, Cu.reportError);
},
- setSha256Hash: function (hash)
+ setSha256Hash: function(hash)
{
this._sha256Hash = hash;
},
- setSignatureInfo: function (signatureInfo)
+ setSignatureInfo: function(signatureInfo)
{
this._signatureInfo = signatureInfo;
},
- setRedirects: function (redirects)
+ setRedirects: function(redirects)
{
this._redirects = redirects;
},
// Private methods and properties
/**
* This deferred object contains a promise that is resolved with the Download
--- a/toolkit/components/jsdownloads/src/DownloadList.jsm
+++ b/toolkit/components/jsdownloads/src/DownloadList.jsm
@@ -41,17 +41,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/Task.jsm");
// DownloadList
/**
* Represents a collection of Download objects that can be viewed and managed by
* the user interface, and persisted across sessions.
*/
-this.DownloadList = function ()
+this.DownloadList = function()
{
this._downloads = [];
this._views = new Set();
}
this.DownloadList.prototype = {
/**
* Array of Download objects currently in the list.
@@ -199,17 +199,17 @@ this.DownloadList.prototype = {
/**
* Notifies all the views of a download addition, change, or removal.
*
* @param aMethodName
* String containing the name of the method to call on the view.
* @param aDownload
* The Download object that changed.
*/
- _notifyAllViews: function (aMethodName, aDownload) {
+ _notifyAllViews: function(aMethodName, aDownload) {
for (let view of this._views) {
try {
if (aMethodName in view) {
view[aMethodName](aDownload);
}
} catch (ex) {
Cu.reportError(ex);
}
@@ -262,17 +262,17 @@ this.DownloadList.prototype = {
* underlying lists, based on their "source.isPrivate" property. Views on this
* list will receive notifications for both public and private downloads.
*
* @param aPublicList
* Underlying DownloadList containing public downloads.
* @param aPrivateList
* Underlying DownloadList containing private downloads.
*/
-this.DownloadCombinedList = function (aPublicList, aPrivateList)
+this.DownloadCombinedList = function(aPublicList, aPrivateList)
{
DownloadList.call(this);
this._publicList = aPublicList;
this._privateList = aPrivateList;
aPublicList.addView(this).then(null, Cu.reportError);
aPrivateList.addView(this).then(null, Cu.reportError);
}
@@ -300,17 +300,17 @@ this.DownloadCombinedList.prototype = {
*
* @param aDownload
* The Download object to add.
*
* @return {Promise}
* @resolves When the download has been added.
* @rejects JavaScript exception.
*/
- add: function (aDownload)
+ add: function(aDownload)
{
if (aDownload.source.isPrivate) {
return this._privateList.add(aDownload);
}
return this._publicList.add(aDownload);
},
/**
@@ -324,53 +324,53 @@ this.DownloadCombinedList.prototype = {
*
* @param aDownload
* The Download object to remove.
*
* @return {Promise}
* @resolves When the download has been removed.
* @rejects JavaScript exception.
*/
- remove: function (aDownload)
+ remove: function(aDownload)
{
if (aDownload.source.isPrivate) {
return this._privateList.remove(aDownload);
}
return this._publicList.remove(aDownload);
},
// DownloadList view
- onDownloadAdded: function (aDownload)
+ onDownloadAdded: function(aDownload)
{
this._downloads.push(aDownload);
this._notifyAllViews("onDownloadAdded", aDownload);
},
- onDownloadChanged: function (aDownload)
+ onDownloadChanged: function(aDownload)
{
this._notifyAllViews("onDownloadChanged", aDownload);
},
- onDownloadRemoved: function (aDownload)
+ onDownloadRemoved: function(aDownload)
{
let index = this._downloads.indexOf(aDownload);
if (index != -1) {
this._downloads.splice(index, 1);
}
this._notifyAllViews("onDownloadRemoved", aDownload);
},
};
// DownloadSummary
/**
* Provides an aggregated view on the contents of a DownloadList.
*/
-this.DownloadSummary = function ()
+this.DownloadSummary = function()
{
this._downloads = [];
this._views = new Set();
}
this.DownloadSummary.prototype = {
/**
* Array of Download objects that are currently part of the summary.
@@ -391,17 +391,17 @@ this.DownloadSummary.prototype = {
*
* @param aList
* Underlying DownloadList whose contents should be summarized.
*
* @return {Promise}
* @resolves When the view on the underlying list has been registered.
* @rejects JavaScript exception.
*/
- bindToList: function (aList)
+ bindToList: function(aList)
{
if (this._list) {
throw new Error("bindToList may be called only once.");
}
return aList.addView(this).then(() => {
// Set the list reference only after addView has returned, so that we don't
// send a notification to our views for each download that is added.
@@ -427,17 +427,17 @@ this.DownloadSummary.prototype = {
* },
* }
*
* @return {Promise}
* @resolves When the view has been registered and the onSummaryChanged
* notification has been sent.
* @rejects JavaScript exception.
*/
- addView: function (aView)
+ addView: function(aView)
{
this._views.add(aView);
if ("onSummaryChanged" in aView) {
try {
aView.onSummaryChanged();
} catch (ex) {
Cu.reportError(ex);
@@ -453,17 +453,17 @@ this.DownloadSummary.prototype = {
* @param aView
* The view object to remove.
*
* @return {Promise}
* @resolves When the view has been removed. At this point, the removed view
* will not receive any more notifications.
* @rejects JavaScript exception.
*/
- removeView: function (aView)
+ removeView: function(aView)
{
this._views.delete(aView);
return Promise.resolve();
},
/**
* Indicates whether all the downloads are currently stopped.
@@ -489,17 +489,17 @@ this.DownloadSummary.prototype = {
*/
progressCurrentBytes: 0,
/**
* This function is called when any change in the list of downloads occurs,
* and will recalculate the summary and notify the views in case the
* aggregated properties are different.
*/
- _onListChanged: function () {
+ _onListChanged: function() {
let allHaveStopped = true;
let progressTotalBytes = 0;
let progressCurrentBytes = 0;
// Recalculate the aggregated state. See the description of the individual
// properties for an explanation of the summarization logic.
for (let download of this._downloads) {
if (!download.stopped) {
@@ -530,30 +530,30 @@ this.DownloadSummary.prototype = {
} catch (ex) {
Cu.reportError(ex);
}
}
},
// DownloadList view
- onDownloadAdded: function (aDownload)
+ onDownloadAdded: function(aDownload)
{
this._downloads.push(aDownload);
if (this._list) {
this._onListChanged();
}
},
- onDownloadChanged: function (aDownload)
+ onDownloadChanged: function(aDownload)
{
this._onListChanged();
},
- onDownloadRemoved: function (aDownload)
+ onDownloadRemoved: function(aDownload)
{
let index = this._downloads.indexOf(aDownload);
if (index != -1) {
this._downloads.splice(index, 1);
}
this._onListChanged();
},
};
--- a/toolkit/components/jsdownloads/src/DownloadStore.jsm
+++ b/toolkit/components/jsdownloads/src/DownloadStore.jsm
@@ -45,36 +45,36 @@ Cu.import("resource://gre/modules/XPCOMU
XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
"resource://gre/modules/Downloads.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm")
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyGetter(this, "gTextDecoder", function () {
+XPCOMUtils.defineLazyGetter(this, "gTextDecoder", function() {
return new TextDecoder();
});
-XPCOMUtils.defineLazyGetter(this, "gTextEncoder", function () {
+XPCOMUtils.defineLazyGetter(this, "gTextEncoder", function() {
return new TextEncoder();
});
// DownloadStore
/**
* Handles serialization of Download objects and persistence into a file, so
* that the state of downloads can be restored across sessions.
*
* @param aList
* DownloadList object to be populated or serialized.
* @param aPath
* String containing the file path where data should be saved.
*/
-this.DownloadStore = function (aList, aPath)
+this.DownloadStore = function(aList, aPath)
{
this.list = aList;
this.path = aPath;
}
this.DownloadStore.prototype = {
/**
* DownloadList object to be populated or serialized.
--- a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm
+++ b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm
@@ -58,36 +58,36 @@ this.DownloadUIHelper = {
*
* @param aParent
* If specified, should reference the nsIDOMWindow to which the prompts
* should be attached. If omitted, the prompts will be attached to the
* most recently active window.
*
* @return A DownloadPrompter object.
*/
- getPrompter: function (aParent)
+ getPrompter: function(aParent)
{
return new DownloadPrompter(aParent || null);
},
};
/**
* Returns an object whose keys are the string names from the downloads string
* bundle, and whose values are either the translated strings or functions
* returning formatted strings.
*/
-XPCOMUtils.defineLazyGetter(DownloadUIHelper, "strings", function () {
+XPCOMUtils.defineLazyGetter(DownloadUIHelper, "strings", function() {
let strings = {};
let sb = Services.strings.createBundle(kStringBundleUrl);
let enumerator = sb.getSimpleEnumeration();
while (enumerator.hasMoreElements()) {
let string = enumerator.getNext().QueryInterface(Ci.nsIPropertyElement);
let stringName = string.key;
if (stringName in kStringsRequiringFormatting) {
- strings[stringName] = function () {
+ strings[stringName] = function() {
// Convert "arguments" to a real array before calling into XPCOM.
return sb.formatStringFromName(stringName,
Array.slice(arguments, 0),
arguments.length);
};
} else {
strings[stringName] = string.value;
}
@@ -99,17 +99,17 @@ XPCOMUtils.defineLazyGetter(DownloadUIHe
/**
* Allows displaying prompts related to downloads.
*
* @param aParent
* The nsIDOMWindow to which prompts should be attached, or null to
* attach prompts to the most recently active window.
*/
-this.DownloadPrompter = function (aParent)
+this.DownloadPrompter = function(aParent)
{
if (AppConstants.MOZ_B2G) {
// On B2G there is no prompter implementation.
this._prompter = null;
} else {
this._prompter = Services.ww.getNewPrompter(aParent);
}
}
@@ -134,17 +134,17 @@ this.DownloadPrompter.prototype = {
*
* @param aPath
* String containing the full path to the file to be opened.
*
* @return {Promise}
* @resolves Boolean indicating whether the launch operation can continue.
* @rejects JavaScript exception.
*/
- confirmLaunchExecutable: function (aPath)
+ confirmLaunchExecutable: function(aPath)
{
const kPrefAlertOnEXEOpen = "browser.download.manager.alertOnEXEOpen";
try {
// Always launch in case we have no prompter implementation.
if (!this._prompter) {
return Promise.resolve(true);
}
--- a/toolkit/components/jsdownloads/src/Downloads.jsm
+++ b/toolkit/components/jsdownloads/src/Downloads.jsm
@@ -133,17 +133,17 @@ this.Downloads = {
* isPrivate: Indicates whether the download originated from a
* private window.
* }
*
* @return {Promise}
* @resolves When the download has finished successfully.
* @rejects JavaScript exception if the download failed.
*/
- fetch: function (aSource, aTarget, aOptions) {
+ fetch: function(aSource, aTarget, aOptions) {
return this.createDownload({
source: aSource,
target: aTarget,
}).then(function D_SD_onSuccess(aDownload) {
if (aOptions && ("isPrivate" in aOptions)) {
aDownload.source.isPrivate = aOptions.isPrivate;
}
return aDownload.start();
@@ -164,17 +164,17 @@ this.Downloads = {
* are reflected in the Downloads.ALL list, and downloads added to the
* Downloads.ALL list are also added to either the Downloads.PUBLIC or
* the Downloads.PRIVATE list based on their properties.
*
* @return {Promise}
* @resolves The requested DownloadList or DownloadCombinedList object.
* @rejects JavaScript exception.
*/
- getList: function (aType)
+ getList: function(aType)
{
if (!this._promiseListsInitialized) {
this._promiseListsInitialized = Task.spawn(function* () {
let publicList = new DownloadList();
let privateList = new DownloadList();
let combinedList = new DownloadCombinedList(publicList, privateList);
try {
@@ -226,17 +226,17 @@ this.Downloads = {
*
* @param aType
* This can be Downloads.PUBLIC, Downloads.PRIVATE, or Downloads.ALL.
*
* @return {Promise}
* @resolves The requested DownloadList or DownloadCombinedList object.
* @rejects JavaScript exception.
*/
- getSummary: function (aType)
+ getSummary: function(aType)
{
if (aType != Downloads.PUBLIC && aType != Downloads.PRIVATE &&
aType != Downloads.ALL) {
throw new Error("Invalid aType argument.");
}
if (!(aType in this._summaries)) {
this._summaries[aType] = new DownloadSummary();
--- a/toolkit/components/jsdownloads/test/browser/head.js
+++ b/toolkit/components/jsdownloads/test/browser/head.js
@@ -61,17 +61,17 @@ function getTempFile(aLeafName)
let [base, ext] = DownloadPaths.splitBaseNameAndExtension(aLeafName);
let leafName = base + "-" + gFileCounter + ext;
gFileCounter++;
// Get a file reference under the temporary directory for this test file.
let file = FileUtils.getFile("TmpD", [leafName]);
ok(!file.exists(), "Temp file does not exist");
- registerCleanupFunction(function () {
+ registerCleanupFunction(function() {
if (file.exists()) {
file.remove(false);
}
});
return file;
}
--- a/toolkit/components/jsdownloads/test/unit/common_test_Download.js
+++ b/toolkit/components/jsdownloads/test/unit/common_test_Download.js
@@ -300,17 +300,17 @@ add_task(function* test_referrer()
let sourceUrl = httpUrl("test_referrer.txt");
let targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
function cleanup() {
gHttpServer.registerPathHandler(sourcePath, null);
}
do_register_cleanup(cleanup);
- gHttpServer.registerPathHandler(sourcePath, function (aRequest, aResponse) {
+ gHttpServer.registerPathHandler(sourcePath, function(aRequest, aResponse) {
aResponse.setHeader("Content-Type", "text/plain", false);
do_check_true(aRequest.hasHeader("Referer"));
do_check_eq(aRequest.getHeader("Referer"), TEST_REFERRER_URL);
});
let download = yield Downloads.createDownload({
source: { url: sourceUrl, referrer: TEST_REFERRER_URL },
target: targetPath,
@@ -435,17 +435,17 @@ add_task(function* test_final_state_noti
{
mustInterruptResponses();
let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
let onchangeNotified = false;
let lastNotifiedStopped;
let lastNotifiedProgress;
- download.onchange = function () {
+ download.onchange = function() {
onchangeNotified = true;
lastNotifiedStopped = download.stopped;
lastNotifiedProgress = download.progress;
};
// Allow the download to complete.
let promiseAttempt = download.start();
continueResponses();
@@ -567,17 +567,17 @@ add_task(function* test_empty_noprogress
mustInterruptResponses();
let download;
if (!gUseLegacySaver) {
// When testing DownloadCopySaver, we have control over the download, thus
// we can hook its onchange callback that will be notified when the
// download starts.
download = yield promiseNewDownload(sourceUrl);
- download.onchange = function () {
+ download.onchange = function() {
if (!download.stopped) {
do_check_false(download.hasProgress);
do_check_eq(download.currentBytes, 0);
do_check_eq(download.totalBytes, 0);
}
};
download.start().catch(() => {});
@@ -671,17 +671,17 @@ add_task(function* test_cancel_midway()
download = yield promiseNewDownload(httpUrl("interruptible.txt"));
} else {
download = yield promiseStartLegacyDownload(httpUrl("interruptible.txt"),
options);
}
// Cancel the download after receiving the first part of the response.
let deferCancel = Promise.defer();
- let onchange = function () {
+ let onchange = function() {
if (!download.stopped && !download.canceled && download.progress == 50) {
// Cancel the download immediately during the notification.
deferCancel.resolve(download.cancel());
// The state change happens immediately after calling "cancel", but
// temporary files or part files may still exist at this point.
do_check_true(download.canceled);
}
@@ -856,17 +856,17 @@ add_task(function* test_cancel_midway_re
do_check_eq(download.target.size, 0);
// Verify that the server sent the response from the start.
do_check_eq(gMostRecentFirstBytePos, 0);
// The second time, we'll request and obtain the second part of the response,
// but we still stop when half of the remaining progress is reached.
let deferMidway = Promise.defer();
- download.onchange = function () {
+ download.onchange = function() {
if (!download.stopped && !download.canceled &&
download.currentBytes == Math.floor(TEST_DATA_SHORT.length * 3 / 2)) {
download.onchange = null;
deferMidway.resolve();
}
};
mustInterruptResponses();
@@ -1483,17 +1483,17 @@ add_task(function* test_public_and_priva
function cleanup() {
Services.prefs.clearUserPref("network.cookie.cookieBehavior");
Services.cookies.removeAll();
gHttpServer.registerPathHandler(sourcePath, null);
}
do_register_cleanup(cleanup);
- gHttpServer.registerPathHandler(sourcePath, function (aRequest, aResponse) {
+ gHttpServer.registerPathHandler(sourcePath, function(aRequest, aResponse) {
aResponse.setHeader("Content-Type", "text/plain", false);
if (testCount == 0) {
// No cookies should exist for first public download.
do_check_false(aRequest.hasHeader("Cookie"));
aResponse.setHeader("Set-Cookie", "foobar=1", false);
testCount++;
} else if (testCount == 1) {
@@ -1554,17 +1554,17 @@ add_task(function* test_with_content_enc
let sourcePath = "/test_with_content_encoding.txt";
let sourceUrl = httpUrl("test_with_content_encoding.txt");
function cleanup() {
gHttpServer.registerPathHandler(sourcePath, null);
}
do_register_cleanup(cleanup);
- gHttpServer.registerPathHandler(sourcePath, function (aRequest, aResponse) {
+ gHttpServer.registerPathHandler(sourcePath, function(aRequest, aResponse) {
aResponse.setHeader("Content-Type", "text/plain", false);
aResponse.setHeader("Content-Encoding", "gzip", false);
aResponse.setHeader("Content-Length",
"" + TEST_DATA_SHORT_GZIP_ENCODED.length, false);
let bos = new BinaryOutputStream(aResponse.bodyOutputStream);
bos.writeByteArray(TEST_DATA_SHORT_GZIP_ENCODED,
TEST_DATA_SHORT_GZIP_ENCODED.length);
@@ -1590,17 +1590,17 @@ add_task(function* test_with_content_enc
let sourcePath = "/test_with_content_encoding_ignore_extension.gz";
let sourceUrl = httpUrl("test_with_content_encoding_ignore_extension.gz");
function cleanup() {
gHttpServer.registerPathHandler(sourcePath, null);
}
do_register_cleanup(cleanup);
- gHttpServer.registerPathHandler(sourcePath, function (aRequest, aResponse) {
+ gHttpServer.registerPathHandler(sourcePath, function(aRequest, aResponse) {
aResponse.setHeader("Content-Type", "text/plain", false);
aResponse.setHeader("Content-Encoding", "gzip", false);
aResponse.setHeader("Content-Length",
"" + TEST_DATA_SHORT_GZIP_ENCODED.length, false);
let bos = new BinaryOutputStream(aResponse.bodyOutputStream);
bos.writeByteArray(TEST_DATA_SHORT_GZIP_ENCODED,
TEST_DATA_SHORT_GZIP_ENCODED.length);
@@ -1627,17 +1627,17 @@ add_task(function* test_with_content_enc
add_task(function* test_cancel_midway_restart_with_content_encoding()
{
mustInterruptResponses();
let download = yield promiseStartDownload(httpUrl("interruptible_gzip.txt"));
// The first time, cancel the download midway.
let deferCancel = Promise.defer();
- let onchange = function () {
+ let onchange = function() {
if (!download.stopped && !download.canceled &&
download.currentBytes == TEST_DATA_SHORT_GZIP_ENCODED_FIRST.length) {
deferCancel.resolve(download.cancel());
}
};
// Register for the notification, but also call the function directly in
// case the download already reached the expected progress.
@@ -2387,17 +2387,17 @@ add_task(function* test_platform_integra
source: httpUrl("source.txt"),
target: targetFile,
});
download.start().catch(() => {});
}
// Wait for the whenSucceeded promise to be resolved first.
// downloadDone should be called before the whenSucceeded promise is resolved.
- yield download.whenSucceeded().then(function () {
+ yield download.whenSucceeded().then(function() {
do_check_true(downloadDoneCalled);
do_check_true(downloadWatcherNotified);
});
// Then, wait for the promise returned by "start" to be resolved.
yield promiseDownloadStopped(download);
yield promiseVerifyTarget(download.target, TEST_DATA_SHORT);
--- a/toolkit/components/jsdownloads/test/unit/head.js
+++ b/toolkit/components/jsdownloads/test/unit/head.js
@@ -131,17 +131,17 @@ function getTempFile(aLeafName)
let [base, ext] = DownloadPaths.splitBaseNameAndExtension(aLeafName);
let leafName = base + "-" + gFileCounter + ext;
gFileCounter++;
// Get a file reference under the temporary directory for this test file.
let file = FileUtils.getFile("TmpD", [leafName]);
do_check_false(file.exists());
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
try {
file.remove(false)
} catch (e) {
if (!(e instanceof Components.Exception &&
(e.result == Cr.NS_ERROR_FILE_ACCESS_DENIED ||
e.result == Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST ||
e.result == Cr.NS_ERROR_FILE_NOT_FOUND))) {
throw e;
@@ -197,30 +197,30 @@ function promiseTimeout(aTime)
function promiseWaitForVisit(aUrl)
{
let deferred = Promise.defer();
let uri = NetUtil.newURI(aUrl);
PlacesUtils.history.addObserver({
QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver]),
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
- aTransitionType, aGUID, aHidden) {
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID,
+ aTransitionType, aGUID, aHidden) {
if (aURI.equals(uri)) {
PlacesUtils.history.removeObserver(this);
deferred.resolve([aTime, aTransitionType]);
}
},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
+ onTitleChanged: function() {},
+ onDeleteURI: function() {},
+ onClearHistory: function() {},
+ onPageChanged: function() {},
+ onDeleteVisits: function() {},
}, false);
return deferred.promise;
}
/**
* Check browsing history to see whether the given URI has been visited.
*
@@ -230,17 +230,17 @@ function promiseWaitForVisit(aUrl)
* @return {Promise}
* @resolves Boolean indicating whether the URI has been visited.
* @rejects JavaScript exception.
*/
function promiseIsURIVisited(aUrl) {
let deferred = Promise.defer();
PlacesUtils.asyncHistory.isURIVisited(NetUtil.newURI(aUrl),
- function (aURI, aIsVisited) {
+ function(aURI, aIsVisited) {
deferred.resolve(aIsVisited);
});
return deferred.promise;
}
/**
* Creates a new Download object, setting a temporary file as the target.
@@ -332,21 +332,21 @@ function promiseStartLegacyDownload(aSou
persist.persistFlags &= ~Ci.nsIWebBrowserPersist.PERSIST_FLAGS_NO_CONVERSION;
persist.persistFlags |=
Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
let transfer = Cc["@mozilla.org/transfer;1"].createInstance(Ci.nsITransfer);
let deferred = Promise.defer();
- Downloads.getList(Downloads.ALL).then(function (aList) {
+ Downloads.getList(Downloads.ALL).then(function(aList) {
// Temporarily register a view that will get notified when the download we
// are controlling becomes visible in the list of downloads.
aList.addView({
- onDownloadAdded: function (aDownload) {
+ onDownloadAdded: function(aDownload) {
aList.removeView(this).then(null, do_report_unexpected_exception);
// Remove the download to keep the list empty for the next test. This
// also allows the caller to register the "onchange" event directly.
let promise = aList.remove(aDownload);
// When the download object is ready, make it available to the caller.
promise.then(() => deferred.resolve(aDownload),
@@ -385,21 +385,21 @@ function promiseStartLegacyDownload(aSou
* @rejects Never. The current test fails in case of exceptions.
*/
function promiseStartExternalHelperAppServiceDownload(aSourceUrl) {
let sourceURI = NetUtil.newURI(aSourceUrl ||
httpUrl("interruptible_resumable.txt"));
let deferred = Promise.defer();
- Downloads.getList(Downloads.PUBLIC).then(function (aList) {
+ Downloads.getList(Downloads.PUBLIC).then(function(aList) {
// Temporarily register a view that will get notified when the download we
// are controlling becomes visible in the list of downloads.
aList.addView({
- onDownloadAdded: function (aDownload) {
+ onDownloadAdded: function(aDownload) {
aList.removeView(this).then(null, do_report_unexpected_exception);
// Remove the download to keep the list empty for the next test. This
// also allows the caller to register the "onchange" event directly.
let promise = aList.remove(aDownload);
// When the download object is ready, make it available to the caller.
promise.then(() => deferred.resolve(aDownload),
@@ -411,31 +411,31 @@ function promiseStartExternalHelperAppSe
uri: sourceURI,
loadUsingSystemPrincipal: true
});
// Start the actual download process.
channel.asyncOpen2({
contentListener: null,
- onStartRequest: function (aRequest, aContext)
+ onStartRequest: function(aRequest, aContext)
{
let channel = aRequest.QueryInterface(Ci.nsIChannel);
this.contentListener = gExternalHelperAppService.doContent(
channel.contentType, aRequest, null, true);
this.contentListener.onStartRequest(aRequest, aContext);
},
- onStopRequest: function (aRequest, aContext, aStatusCode)
+ onStopRequest: function(aRequest, aContext, aStatusCode)
{
this.contentListener.onStopRequest(aRequest, aContext, aStatusCode);
},
- onDataAvailable: function (aRequest, aContext, aInputStream, aOffset,
- aCount)
+ onDataAvailable: function(aRequest, aContext, aInputStream, aOffset,
+ aCount)
{
this.contentListener.onDataAvailable(aRequest, aContext, aInputStream,
aOffset, aCount);
},
});
}.bind(this)).then(null, do_report_unexpected_exception);
return deferred.promise;
@@ -451,17 +451,17 @@ function promiseStartExternalHelperAppSe
* @return {Promise}
* @resolves When the download has reached half of its progress.
* @rejects Never.
*/
function promiseDownloadMidway(aDownload) {
let deferred = Promise.defer();
// Wait for the download to reach half of its progress.
- let onchange = function () {
+ let onchange = function() {
if (!aDownload.stopped && !aDownload.canceled && aDownload.progress == 50) {
aDownload.onchange = null;
deferred.resolve();
}
};
// Register for the notification, but also call the function directly in
// case the download already reached the expected progress.
@@ -571,20 +571,20 @@ function promiseVerifyContents(aPath, aE
*
* @returns nsIServerSocket that listens for connections. Call its "close"
* method to stop listening and free the server port.
*/
function startFakeServer()
{
let serverSocket = new ServerSocket(-1, true, -1);
serverSocket.asyncListen({
- onSocketAccepted: function (aServ, aTransport) {
+ onSocketAccepted: function(aServ, aTransport) {
aTransport.close(Cr.NS_BINDING_ABORTED);
},
- onStopListening: function () { },
+ onStopListening: function() { },
});
return serverSocket;
}
/**
* This is an internal reference that should not be used directly by tests.
*/
var _gDeferResponses = Promise.defer();
@@ -637,17 +637,17 @@ function continueResponses()
* This function is called when the response is received, with the
* aRequest and aResponse arguments of the server.
* @param aSecondPartFn
* This function is called with the aRequest and aResponse arguments of
* the server, when the continueResponses function is called.
*/
function registerInterruptibleHandler(aPath, aFirstPartFn, aSecondPartFn)
{
- gHttpServer.registerPathHandler(aPath, function (aRequest, aResponse) {
+ gHttpServer.registerPathHandler(aPath, function(aRequest, aResponse) {
do_print("Interruptible request started.");
// Process the first part of the response.
aResponse.processAsync();
aFirstPartFn(aRequest, aResponse);
// Wait on the current deferred object, then finish the request.
_gDeferResponses.promise.then(function RIH_onSuccess() {
@@ -690,17 +690,17 @@ add_task(function test_common_initialize
gHttpServer.stop(resolve);
});
});
// Cache locks might prevent concurrent requests to the same resource, and
// this may block tests that use the interruptible handlers.
Services.prefs.setBoolPref("browser.cache.disk.enable", false);
Services.prefs.setBoolPref("browser.cache.memory.enable", false);
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
Services.prefs.clearUserPref("browser.cache.disk.enable");
Services.prefs.clearUserPref("browser.cache.memory.enable");
});
registerInterruptibleHandler("/interruptible.txt",
function firstPart(aRequest, aResponse) {
aResponse.setHeader("Content-Type", "text/plain", false);
aResponse.setHeader("Content-Length", "" + (TEST_DATA_SHORT.length * 2),
@@ -764,29 +764,29 @@ add_task(function test_common_initialize
TEST_DATA_SHORT_GZIP_ENCODED_FIRST.length);
}, function secondPart(aRequest, aResponse) {
let bos = new BinaryOutputStream(aResponse.bodyOutputStream);
bos.writeByteArray(TEST_DATA_SHORT_GZIP_ENCODED_SECOND,
TEST_DATA_SHORT_GZIP_ENCODED_SECOND.length);
});
gHttpServer.registerPathHandler("/shorter-than-content-length-http-1-1.txt",
- function (aRequest, aResponse) {
+ function(aRequest, aResponse) {
aResponse.processAsync();
aResponse.setStatusLine("1.1", 200, "OK");
aResponse.setHeader("Content-Type", "text/plain", false);
aResponse.setHeader("Content-Length", "" + (TEST_DATA_SHORT.length * 2),
false);
aResponse.write(TEST_DATA_SHORT);
aResponse.finish();
});
// This URL will emulate being blocked by Windows Parental controls
gHttpServer.registerPathHandler("/parentalblocked.zip",
- function (aRequest, aResponse) {
+ function(aRequest, aResponse) {
aResponse.setStatusLine(aRequest.httpVersion, 450,
"Blocked by Windows Parental Controls");
});
// During unit tests, most of the functions that require profile access or
// operating system features will be disabled. Individual tests may override
// them again to check for specific behaviors.
Integration.downloads.register(base => ({
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js
+++ b/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js
@@ -164,32 +164,32 @@ function promiseEntityID(aUrl) {
let deferred = Promise.defer();
let entityID = "";
let channel = NetUtil.newChannel({
uri: NetUtil.newURI(aUrl),
loadUsingSystemPrincipal: true
});
channel.asyncOpen2({
- onStartRequest: function (aRequest) {
+ onStartRequest: function(aRequest) {
if (aRequest instanceof Ci.nsIResumableChannel) {
entityID = aRequest.entityID;
}
aRequest.cancel(Cr.NS_BINDING_ABORTED);
},
- onStopRequest: function (aRequest, aContext, aStatusCode) {
+ onStopRequest: function(aRequest, aContext, aStatusCode) {
if (aStatusCode == Cr.NS_BINDING_ABORTED) {
deferred.resolve(entityID);
} else {
deferred.reject("Unexpected status code received");
}
},
- onDataAvailable: function () {}
+ onDataAvailable: function() {}
});
return deferred.promise;
}
/**
* Gets a file path to a temporary writeable download target, in the
* correct format as expected to be stored in the downloads database,
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadIntegration.js
+++ b/toolkit/components/jsdownloads/test/unit/test_DownloadIntegration.js
@@ -210,17 +210,17 @@ add_task(function* test_getTemporaryDown
* Re-enables the default observers for the following tests.
*
* This takes effect the first time a DownloadList object is created, and lasts
* until this test file has completed.
*/
add_task(function* test_observers_setup()
{
DownloadIntegration.allowObservers = true;
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
DownloadIntegration.allowObservers = false;
});
});
/**
* Tests notifications prompts when observers are notified if there are public
* and private active downloads.
*/
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadList.js
+++ b/toolkit/components/jsdownloads/test/unit/test_DownloadList.js
@@ -51,17 +51,17 @@ function promiseExpirableDownloadVisit(a
}]
},
{
handleError: function handleError(aResultCode, aPlaceInfo) {
let ex = new Components.Exception("Unexpected error in adding visits.",
aResultCode);
deferred.reject(ex);
},
- handleResult: function () {},
+ handleResult: function() {},
handleCompletion: function handleCompletion() {
deferred.resolve();
}
});
return deferred.promise;
}
// Tests
@@ -187,17 +187,17 @@ add_task(function* test_notifications_ad
target: getTempFile(TEST_TARGET_FILE_NAME).path,
});
yield list.add(downloadOne);
yield list.add(downloadTwo);
// Check that we receive add notifications for existing elements.
let addNotifications = 0;
let viewOne = {
- onDownloadAdded: function (aDownload) {
+ onDownloadAdded: function(aDownload) {
// The first download to be notified should be the first that was added.
if (addNotifications == 0) {
do_check_eq(aDownload, downloadOne);
} else if (addNotifications == 1) {
do_check_eq(aDownload, downloadTwo);
}
addNotifications++;
},
@@ -207,17 +207,17 @@ add_task(function* test_notifications_ad
// Check that we receive add notifications for new elements.
yield list.add(yield promiseNewDownload());
do_check_eq(addNotifications, 3);
// Check that we receive remove notifications.
let removeNotifications = 0;
let viewTwo = {
- onDownloadRemoved: function (aDownload) {
+ onDownloadRemoved: function(aDownload) {
do_check_eq(aDownload, downloadOne);
removeNotifications++;
},
};
yield list.addView(viewTwo);
yield list.remove(downloadOne);
do_check_eq(removeNotifications, 1);
@@ -252,17 +252,17 @@ add_task(function* test_notifications_ch
target: getTempFile(TEST_TARGET_FILE_NAME).path,
});
yield list.add(downloadOne);
yield list.add(downloadTwo);
// Check that we receive change notifications.
let receivedOnDownloadChanged = false;
yield list.addView({
- onDownloadChanged: function (aDownload) {
+ onDownloadChanged: function(aDownload) {
do_check_eq(aDownload, downloadOne);
receivedOnDownloadChanged = true;
},
});
yield downloadOne.start();
do_check_true(receivedOnDownloadChanged);
// We should not receive change notifications after a download is removed.
@@ -280,28 +280,28 @@ add_task(function* test_notifications_th
{
let list = yield promiseNewList();
// Check that we receive change notifications.
let receivedOnDownloadAdded = false;
let receivedOnDownloadChanged = false;
let receivedOnDownloadRemoved = false;
let view = {
- onDownloadAdded: function () {
+ onDownloadAdded: function() {
do_check_eq(this, view);
receivedOnDownloadAdded = true;
},
- onDownloadChanged: function () {
+ onDownloadChanged: function() {
// Only do this check once.
if (!receivedOnDownloadChanged) {
do_check_eq(this, view);
receivedOnDownloadChanged = true;
}
},
- onDownloadRemoved: function () {
+ onDownloadRemoved: function() {
do_check_eq(this, view);
receivedOnDownloadRemoved = true;
},
};
yield list.addView(view);
let download = yield promiseNewDownload();
yield list.add(download);
@@ -331,17 +331,17 @@ add_task(function* test_history_expirati
let list = yield promiseNewList();
let downloadOne = yield promiseNewDownload();
let downloadTwo = yield promiseNewDownload(httpUrl("interruptible.txt"));
let deferred = Promise.defer();
let removeNotifications = 0;
let downloadView = {
- onDownloadRemoved: function (aDownload) {
+ onDownloadRemoved: function(aDownload) {
if (++removeNotifications == 2) {
deferred.resolve();
}
},
};
yield list.addView(downloadView);
// Work with one finished download and one canceled download.
@@ -378,17 +378,17 @@ add_task(function* test_history_clear()
let downloadOne = yield promiseNewDownload();
let downloadTwo = yield promiseNewDownload();
yield list.add(downloadOne);
yield list.add(downloadTwo);
let deferred = Promise.defer();
let removeNotifications = 0;
let downloadView = {
- onDownloadRemoved: function (aDownload) {
+ onDownloadRemoved: function(aDownload) {
if (++removeNotifications == 2) {
deferred.resolve();
}
},
};
yield list.addView(downloadView);
yield downloadOne.start();
@@ -414,17 +414,17 @@ add_task(function* test_removeFinished()
yield list.add(downloadOne);
yield list.add(downloadTwo);
yield list.add(downloadThree);
yield list.add(downloadFour);
let deferred = Promise.defer();
let removeNotifications = 0;
let downloadView = {
- onDownloadRemoved: function (aDownload) {
+ onDownloadRemoved: function(aDownload) {
do_check_true(aDownload == downloadOne ||
aDownload == downloadTwo ||
aDownload == downloadThree);
do_check_true(removeNotifications < 3);
if (++removeNotifications == 3) {
deferred.resolve();
}
},
@@ -550,15 +550,15 @@ add_task(function* test_DownloadSummary_
let summary = yield Downloads.getSummary(Downloads.ALL);
let download = yield promiseNewDownload();
yield list.add(download);
// Check that we receive change notifications.
let receivedOnSummaryChanged = false;
yield summary.addView({
- onSummaryChanged: function () {
+ onSummaryChanged: function() {
receivedOnSummaryChanged = true;
},
});
yield download.start();
do_check_true(receivedOnSummaryChanged);
});
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadStore.js
+++ b/toolkit/components/jsdownloads/test/unit/test_DownloadStore.js
@@ -25,17 +25,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
* temporary file is deleted when the test file execution finishes.
*
* @return {Promise}
* @resolves Array [ Newly created DownloadList , associated DownloadStore ].
* @rejects JavaScript exception.
*/
function promiseNewListAndStore(aStorePath)
{
- return promiseNewList().then(function (aList) {
+ return promiseNewList().then(function(aList) {
let path = aStorePath || getTempFile(TEST_STORE_FILE_NAME).path;
let store = new DownloadStore(aList, path);
return [aList, store];
});
}
// Tests
--- a/toolkit/components/microformats/microformat-shiv.js
+++ b/toolkit/components/microformats/microformat-shiv.js
@@ -4,37 +4,37 @@
Built: 2016-03-02 10:03 - http://microformat-shiv.com
Copyright (c) 2016 Glenn Jones
Licensed MIT
*/
var Microformats; // jshint ignore:line
-(function (root, factory) {
+(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.Microformats = factory();
}
-}(this, function () {
+}(this, function() {
var modules = {};
modules.version = '1.4.0';
modules.livingStandard = '2015-09-25T12:26:04Z';
/**
* constructor
*
*/
- modules.Parser = function () {
+ modules.Parser = function() {
this.rootPrefix = 'h-';
this.propertyPrefixes = ['p-', 'dt-', 'u-', 'e-'];
this.excludeTags = ['br', 'hr'];
};
// create objects incase the v1 map modules don't load
modules.maps = (modules.maps) ? modules.maps : {};
@@ -270,17 +270,17 @@ var Microformats; // jshint ignore:line
/**
* internal parse to get parent microformats by walking up the tree
*
* @param {DOM Node} node
* @param {Object} options
* @param {Int} recursive
* @return {Object}
*/
- getParentTreeWalk: function (node, options, recursive) {
+ getParentTreeWalk: function(node, options, recursive) {
options = (options) ? options : {};
// recursive calls
if (recursive === undefined) {
if (node.parentNode && node.nodeName !== 'HTML') {
return this.getParentTreeWalk(node.parentNode, options, true);
}
return this.formatEmpty();
@@ -2362,17 +2362,17 @@ var Microformats; // jshint ignore:line
* a sort function - to sort objects in an array by a given property
*
* @param {String} property
* @param {Boolean} reverse
* @return {Int}
*/
sortObjects: function(property, reverse) {
reverse = (reverse) ? -1 : 1;
- return function (a, b) {
+ return function(a, b) {
a = a[property];
b = b[property];
if (a < b) {
return reverse * -1;
}
if (a > b) {
return reverse * 1;
}
@@ -2390,17 +2390,17 @@ var Microformats; // jshint ignore:line
rootNode: null,
/**
* gets DOMParser object
*
* @return {Object || undefined}
*/
- getDOMParser: function () {
+ getDOMParser: function() {
if (typeof DOMParser === "undefined") {
try {
return Components.classes["@mozilla.org/xmlextras/domparser;1"]
.createInstance(Components.interfaces.nsIDOMParser);
} catch (e) {
return undefined;
}
} else {
@@ -2878,17 +2878,17 @@ var Microformats; // jshint ignore:line
/**
* get the child index of a node. Used to create a node path
*
* @param {DOM Node} node
* @return {Int}
*/
- getChildIndex: function (node) {
+ getChildIndex: function(node) {
var parent = node.parentNode,
i = -1,
child;
while (parent && (child = parent.childNodes[++i])) {
if (child === node) {
return i;
}
}
@@ -2897,17 +2897,17 @@ var Microformats; // jshint ignore:line
/**
* get a node's path
*
* @param {DOM Node} node
* @return {Array}
*/
- getNodePath: function (node) {
+ getNodePath: function(node) {
var parent = node.parentNode,
path = [],
index = this.getChildIndex(node);
if (parent && (path = this.getNodePath(parent))) {
if (index > -1) {
path.push(index);
}
@@ -2918,17 +2918,17 @@ var Microformats; // jshint ignore:line
/**
* get a node from a path.
*
* @param {DOM document} document
* @param {Array} path
* @return {DOM Node}
*/
- getNodeByPath: function (document, path) {
+ getNodeByPath: function(document, path) {
var node = document.documentElement,
i = 0,
index;
while ((index = path[++i]) > -1) {
node = node.childNodes[index];
}
return node;
},
@@ -3037,17 +3037,17 @@ var Microformats; // jshint ignore:line
/**
* constructor
* parses text to find just the date element of an ISO date/time string i.e. 2008-05-01
*
* @param {String} dateString
* @param {String} format
* @return {String}
*/
- modules.ISODate = function ( dateString, format ) {
+ modules.ISODate = function( dateString, format ) {
this.clear();
this.format = (format) ? format : 'auto'; // auto or W3C or RFC3339 or HTML5
this.setFormatSep();
// optional should be full iso date/time string
if (arguments[0]) {
this.parse(dateString, format);
@@ -3665,17 +3665,17 @@ var Microformats; // jshint ignore:line
/**
* concatenate an array of date and time text fragments to create an ISODate object
* used for microformat value and value-title rules
*
* @param {Array} arr ( Array of Strings )
* @param {String} format ( Modules.ISODate profile format )
* @return {Object} Modules.ISODate
*/
- concatFragments: function (arr, format) {
+ concatFragments: function(arr, format) {
var out = new modules.ISODate(),
i = 0,
value = '';
// if the fragment already contains a full date just return it once
if (arr[0].toUpperCase().match('T')) {
return new modules.ISODate(arr[0], format);
}
@@ -3716,17 +3716,17 @@ var Microformats; // jshint ignore:line
/**
* parses text by splitting it into an array of time and timezone strings
*
* @param {String} text
* @return {Array} Modules.ISODate
*/
- splitTimeAndZone: function ( text ) {
+ splitTimeAndZone: function( text ) {
var out = [text],
chars = ['-', '+', 'z', 'Z'],
i = chars.length;
while (i--) {
if (text.indexOf(chars[i]) > -1) {
out[0] = text.slice( 0, text.indexOf(chars[i]) );
out.push( text.slice( text.indexOf(chars[i]) ) );
--- a/toolkit/components/microformats/update/update.js
+++ b/toolkit/components/microformats/update/update.js
@@ -152,17 +152,17 @@ function getLastCommitDate( repo, callba
var options = {
url: 'https://api.github.com/repos/' + repo + '/commits?per_page=1',
headers: {
'User-Agent': 'request'
}
};
- request(options, function (error, response, body) {
+ request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
var date = null,
json = JSON.parse(body);
if (json && json.length && json[0].commit && json[0].commit.author ) {
date = json[0].commit.author.date;
}
callback(null, date);
} else {
@@ -184,17 +184,17 @@ function getLastBuildState( repo, callba
var options = {
url: 'https://api.travis-ci.org/repos/' + repo,
headers: {
'User-Agent': 'request',
'Accept': 'application/vnd.travis-ci.2+json'
}
};
- request(options, function (error, response, body) {
+ request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
var buildState = null,
json = JSON.parse(body);
if (json && json.repo && json.repo.last_build_state ) {
buildState = json.repo.last_build_state;
}
callback(null, buildState);
} else {
--- a/toolkit/components/passwordmgr/LoginImport.jsm
+++ b/toolkit/components/passwordmgr/LoginImport.jsm
@@ -38,17 +38,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
* Provides an object that has a method to import login-related data from the
* previous SQLite storage format.
*
* @param aStore
* LoginStore object where imported data will be added.
* @param aPath
* String containing the file path of the SQLite login database.
*/
-this.LoginImport = function (aStore, aPath) {
+this.LoginImport = function(aStore, aPath) {
this.store = aStore;
this.path = aPath;
};
this.LoginImport.prototype = {
/**
* LoginStore object where imported data will be added.
*/
--- a/toolkit/components/passwordmgr/LoginManagerContent.jsm
+++ b/toolkit/components/passwordmgr/LoginManagerContent.jsm
@@ -1004,17 +1004,17 @@ var LoginManagerContent = {
var maxPasswordLen = Number.MAX_VALUE;
// If attribute wasn't set, default is -1.
if (usernameField && usernameField.maxLength >= 0)
maxUsernameLen = usernameField.maxLength;
if (passwordField.maxLength >= 0)
maxPasswordLen = passwordField.maxLength;
- var logins = foundLogins.filter(function (l) {
+ var logins = foundLogins.filter(function(l) {
var fit = (l.username.length <= maxUsernameLen &&
l.password.length <= maxPasswordLen);
if (!fit)
log("Ignored", l.username, "login: won't fit");
return fit;
}, this);
@@ -1212,17 +1212,17 @@ var LoginUtils = {
if (uriString == "")
uriString = form.baseURI; // ala bug 297761
return this._getPasswordOrigin(uriString, true);
},
};
// nsIAutoCompleteResult implementation
-function UserAutoCompleteResult (aSearchString, matchingLogins, {isSecure, messageManager}) {
+function UserAutoCompleteResult(aSearchString, matchingLogins, {isSecure, messageManager}) {
function loginSort(a, b) {
var userA = a.username.toLowerCase();
var userB = b.username.toLowerCase();
if (userA < userB)
return -1;
if (userA > userB)
--- a/toolkit/components/passwordmgr/LoginManagerParent.jsm
+++ b/toolkit/components/passwordmgr/LoginManagerParent.jsm
@@ -52,17 +52,17 @@ var LoginManagerParent = {
const { LoginRecipesParent } = Cu.import("resource://gre/modules/LoginRecipes.jsm", {});
this._recipeManager = new LoginRecipesParent({
defaults: Services.prefs.getComplexValue("signon.recipes.path", Ci.nsISupportsString).data,
});
return this._recipeManager.initializationPromise;
});
},
- receiveMessage: function (msg) {
+ receiveMessage: function(msg) {
let data = msg.data;
switch (msg.name) {
case "RemoteLogins:findLogins": {
// TODO Verify msg.target's principals against the formOrigin?
this.sendLoginDataToChild(data.options.showMasterPassword,
data.formOrigin,
data.actionOrigin,
data.requestId,
@@ -170,17 +170,17 @@ var LoginManagerParent = {
// processing this form until the user handles the prompt.
if (Services.logins.uiBusy) {
log("deferring sendLoginDataToChild for", formOrigin);
let self = this;
let observer = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference]),
- observe: function (subject, topic, data) {
+ observe: function(subject, topic, data) {
log("Got deferred sendLoginDataToChild notification:", topic);
// Only run observer once.
Services.obs.removeObserver(this, "passwordmgr-crypto-login");
Services.obs.removeObserver(this, "passwordmgr-crypto-loginCanceled");
if (topic == "passwordmgr-crypto-loginCanceled") {
target.sendAsyncMessage("RemoteLogins:loginsFound", {
requestId: requestId,
logins: [],
--- a/toolkit/components/passwordmgr/LoginRecipes.jsm
+++ b/toolkit/components/passwordmgr/LoginRecipes.jsm
@@ -92,17 +92,17 @@ LoginRecipesParent.prototype = {
if (this._defaults) {
let channel = NetUtil.newChannel({uri: NetUtil.newURI(this._defaults, "UTF-8"),
loadUsingSystemPrincipal: true});
channel.contentType = "application/json";
try {
this.initializationPromise = new Promise(function(resolve) {
- NetUtil.asyncFetch(channel, function (stream, result) {
+ NetUtil.asyncFetch(channel, function(stream, result) {
if (!Components.isSuccessCode(result)) {
throw new Error("Error fetching recipe file:" + result);
}
let count = stream.available();
let data = NetUtil.readInputStreamToString(stream, count, { charset: "UTF-8" });
resolve(JSON.parse(data));
});
}).then(recipes => {
--- a/toolkit/components/passwordmgr/LoginStore.jsm
+++ b/toolkit/components/passwordmgr/LoginStore.jsm
@@ -117,17 +117,17 @@ LoginStore.prototype._dataPostProcessor
data.version = kDataVersion;
return data;
};
/**
* Migrates disabled hosts to the permission manager.
*/
-LoginStore.prototype._migrateDisabledHosts = function (data) {
+LoginStore.prototype._migrateDisabledHosts = function(data) {
for (let host of data.disabledHosts) {
try {
let uri = Services.io.newURI(host, null, null);
Services.perms.add(uri, PERMISSION_SAVE_LOGINS, Services.perms.DENY_ACTION);
} catch (e) {
Cu.reportError(e);
}
}
--- a/toolkit/components/passwordmgr/crypto-SDR.js
+++ b/toolkit/components/passwordmgr/crypto-SDR.js
@@ -49,17 +49,17 @@ LoginManagerCrypto_SDR.prototype = {
_utfConverterReset : function() {
this.__utfConverter = null;
},
_uiBusy : false,
- init : function () {
+ init : function() {
// Check to see if the internal PKCS#11 token has been initialized.
// If not, set a blank password.
let tokenDB = Cc["@mozilla.org/security/pk11tokendb;1"].
getService(Ci.nsIPK11TokenDB);
let token = tokenDB.getInternalKeyToken();
if (token.needsUserInit) {
this.log("Initializing key3.db with default blank password.");
@@ -71,17 +71,17 @@ LoginManagerCrypto_SDR.prototype = {
/*
* encrypt
*
* Encrypts the specified string, using the SecretDecoderRing.
*
* Returns the encrypted string, or throws an exception if there was a
* problem.
*/
- encrypt : function (plainText) {
+ encrypt : function(plainText) {
let cipherText = null;
let wasLoggedIn = this.isLoggedIn;
let canceledMP = false;
this._uiBusy = true;
try {
let plainOctet = this._utfConverter.ConvertFromUnicode(plainText);
@@ -112,17 +112,17 @@ LoginManagerCrypto_SDR.prototype = {
/*
* decrypt
*
* Decrypts the specified string, using the SecretDecoderRing.
*
* Returns the decrypted string, or throws an exception if there was a
* problem.
*/
- decrypt : function (cipherText) {
+ decrypt : function(cipherText) {
let plainText = null;
let wasLoggedIn = this.isLoggedIn;
let canceledMP = false;
this._uiBusy = true;
try {
let plainOctet;
--- a/toolkit/components/passwordmgr/nsLoginInfo.js
+++ b/toolkit/components/passwordmgr/nsLoginInfo.js
@@ -24,35 +24,35 @@ nsLoginInfo.prototype = {
hostname : null,
formSubmitURL : null,
httpRealm : null,
username : null,
password : null,
usernameField : null,
passwordField : null,
- init : function (aHostname, aFormSubmitURL, aHttpRealm,
- aUsername, aPassword,
- aUsernameField, aPasswordField) {
+ init : function(aHostname, aFormSubmitURL, aHttpRealm,
+ aUsername, aPassword,
+ aUsernameField, aPasswordField) {
this.hostname = aHostname;
this.formSubmitURL = aFormSubmitURL;
this.httpRealm = aHttpRealm;
this.username = aUsername;
this.password = aPassword;
this.usernameField = aUsernameField;
this.passwordField = aPasswordField;
},
matches(aLogin, ignorePassword) {
return LoginHelper.doLoginsMatch(this, aLogin, {
ignorePassword,
});
},
- equals : function (aLogin) {
+ equals : function(aLogin) {
if (this.hostname != aLogin.hostname ||
this.formSubmitURL != aLogin.formSubmitURL ||
this.httpRealm != aLogin.httpRealm ||
this.username != aLogin.username ||
this.password != aLogin.password ||
this.usernameField != aLogin.usernameField ||
this.passwordField != aLogin.passwordField)
return false;
--- a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js
+++ b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js
@@ -41,31 +41,31 @@ function LoginManagerPromptFactory() {
LoginManagerPromptFactory.prototype = {
classID : Components.ID("{749e62f4-60ae-4569-a8a2-de78b649660e}"),
QueryInterface : XPCOMUtils.generateQI([Ci.nsIPromptFactory, Ci.nsIObserver, Ci.nsISupportsWeakReference]),
_asyncPrompts : {},
_asyncPromptInProgress : false,
- observe : function (subject, topic, data) {
+ observe : function(subject, topic, data) {
this.log("Observed: " + topic);
if (topic == "quit-application-granted") {
this._cancelPendingPrompts();
} else if (topic == "passwordmgr-crypto-login") {
// Start processing the deferred prompters.
this._doAsyncPrompt();
} else if (topic == "passwordmgr-crypto-loginCanceled") {
// User canceled a Master Password prompt, so go ahead and cancel
// all pending auth prompts to avoid nagging over and over.
this._cancelPendingPrompts();
}
},
- getPrompt : function (aWindow, aIID) {
+ getPrompt : function(aWindow, aIID) {
var prompt = new LoginManagerPrompter().QueryInterface(aIID);
prompt.init(aWindow, this);
return prompt;
},
_doAsyncPrompt : function() {
if (this._asyncPromptInProgress) {
this.log("_doAsyncPrompt bypassed, already in progress");
@@ -278,18 +278,18 @@ LoginManagerPrompter.prototype = {
/* ---------- nsIAuthPrompt prompts ---------- */
/**
* Wrapper around the prompt service prompt. Saving random fields here
* doesn't really make sense and therefore isn't implemented.
*/
- prompt : function (aDialogTitle, aText, aPasswordRealm,
- aSavePassword, aDefaultText, aResult) {
+ prompt : function(aDialogTitle, aText, aPasswordRealm,
+ aSavePassword, aDefaultText, aResult) {
if (aSavePassword != Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER)
throw new Components.Exception("prompt only supports SAVE_PASSWORD_NEVER",
Cr.NS_ERROR_NOT_IMPLEMENTED);
this.log("===== prompt() called =====");
if (aDefaultText) {
aResult.value = aDefaultText;
@@ -299,17 +299,17 @@ LoginManagerPrompter.prototype = {
aDialogTitle, aText, aResult, null, {});
},
/**
* Looks up a username and password in the database. Will prompt the user
* with a dialog, even if a username and password are found.
*/
- promptUsernameAndPassword : function (aDialogTitle, aText, aPasswordRealm,
+ promptUsernameAndPassword : function(aDialogTitle, aText, aPasswordRealm,
aSavePassword, aUsername, aPassword) {
this.log("===== promptUsernameAndPassword() called =====");
if (aSavePassword == Ci.nsIAuthPrompt.SAVE_PASSWORD_FOR_SESSION)
throw new Components.Exception("promptUsernameAndPassword doesn't support SAVE_PASSWORD_FOR_SESSION",
Cr.NS_ERROR_NOT_IMPLEMENTED);
var selectedLogin = null;
@@ -400,18 +400,18 @@ LoginManagerPrompter.prototype = {
/**
* If a password is found in the database for the password realm, it is
* returned straight away without displaying a dialog.
*
* If a password is not found in the database, the user will be prompted
* with a dialog with a text field and ok/cancel buttons. If the user
* allows it, then the password will be saved in the database.
*/
- promptPassword : function (aDialogTitle, aText, aPasswordRealm,
- aSavePassword, aPassword) {
+ promptPassword : function(aDialogTitle, aText, aPasswordRealm,
+ aSavePassword, aPassword) {
this.log("===== promptPassword called() =====");
if (aSavePassword == Ci.nsIAuthPrompt.SAVE_PASSWORD_FOR_SESSION)
throw new Components.Exception("promptPassword doesn't support SAVE_PASSWORD_FOR_SESSION",
Cr.NS_ERROR_NOT_IMPLEMENTED);
var checkBox = { value : false };
var checkBoxLabel = null;
@@ -476,17 +476,17 @@ LoginManagerPrompter.prototype = {
* - the realm (hostname + path)
* - the username, if present
*
* If aRealmString is in the format produced by NS_GetAuthKey for HTTP[S]
* channels, e.g. "example.com:80 (httprealm)", null is returned for all
* arguments to let callers know the login can't be saved because we don't
* know whether it's http or https.
*/
- _getRealmInfo : function (aRealmString) {
+ _getRealmInfo : function(aRealmString) {
var httpRealm = /^.+ \(.+\)$/;
if (httpRealm.test(aRealmString))
return [null, null, null];
var uri = Services.io.newURI(aRealmString, null, null);
var pathname = "";
if (uri.path != "/")
@@ -504,17 +504,17 @@ LoginManagerPrompter.prototype = {
/**
* Implementation of nsIAuthPrompt2.
*
* @param {nsIChannel} aChannel
* @param {int} aLevel
* @param {nsIAuthInformation} aAuthInfo
*/
- promptAuth : function (aChannel, aLevel, aAuthInfo) {
+ promptAuth : function(aChannel, aLevel, aAuthInfo) {
var selectedLogin = null;
var checkbox = { value : false };
var checkboxLabel = null;
var epicfail = false;
var canAutologin = false;
var notifyObj;
var foundLogins;
@@ -635,17 +635,17 @@ LoginManagerPrompter.prototype = {
} catch (e) {
Components.utils.reportError("LoginManagerPrompter: " +
"Fail2 in promptAuth: " + e + "\n");
}
return ok;
},
- asyncPromptAuth : function (aChannel, aCallback, aContext, aLevel, aAuthInfo) {
+ asyncPromptAuth : function(aChannel, aCallback, aContext, aLevel, aAuthInfo) {
var cancelable = null;
try {
this.log("===== asyncPromptAuth called =====");
// If the user submits a login but it fails, we need to remove the
// notification bar that was displayed. Conveniently, the user will
// be prompted for authentication again, which brings us here.
@@ -688,17 +688,17 @@ LoginManagerPrompter.prototype = {
},
/* ---------- nsILoginManagerPrompter prompts ---------- */
- init : function (aWindow = null, aFactory = null) {
+ init : function(aWindow = null, aFactory = null) {
if (!aWindow) {
// There may be no applicable window e.g. in a Sandbox or JSM.
this._chromeWindow = null;
this._browser = null;
} else if (aWindow instanceof Ci.nsIDOMChromeWindow) {
this._chromeWindow = aWindow;
// needs to be set explicitly using setBrowser
this._browser = null;
@@ -716,29 +716,29 @@ LoginManagerPrompter.prototype = {
set browser(aBrowser) {
this._browser = aBrowser;
},
set opener(aOpener) {
this._opener = aOpener;
},
- promptToSavePassword : function (aLogin) {
+ promptToSavePassword : function(aLogin) {
this.log("promptToSavePassword");
var notifyObj = this._getPopupNote() || this._getNotifyBox();
if (notifyObj)
this._showSaveLoginNotification(notifyObj, aLogin);
else
this._showSaveLoginDialog(aLogin);
},
/**
* Displays a notification bar.
*/
- _showLoginNotification : function (aNotifyBox, aName, aText, aButtons) {
+ _showLoginNotification : function(aNotifyBox, aName, aText, aButtons) {
var oldBar = aNotifyBox.getNotificationWithValue(aName);
const priority = aNotifyBox.PRIORITY_INFO_MEDIUM;
this.log("Adding new " + aName + " notification bar");
var newBar = aNotifyBox.appendNotification(
aText, aName, "",
priority, aButtons);
@@ -956,17 +956,17 @@ LoginManagerPrompter.prototype = {
"password-notification-icon",
mainAction,
secondaryActions,
{
timeout: Date.now() + 10000,
displayURI: Services.io.newURI(login.hostname, null, null),
persistWhileVisible: true,
passwordNotificationType: type,
- eventCallback: function (topic) {
+ eventCallback: function(topic) {
switch (topic) {
case "showing":
currentNotification = this;
chromeDoc.getElementById("password-notification-password")
.removeAttribute("focused");
chromeDoc.getElementById("password-notification-username")
.removeAttribute("focused");
chromeDoc.getElementById("password-notification-username")
@@ -1014,17 +1014,17 @@ LoginManagerPrompter.prototype = {
* to save the specified login. This allows the user to see the results of
* their login, and only save a login which they know worked.
*
* @param aNotifyObj
* A notification box or a popup notification.
* @param aLogin
* The login captured from the form.
*/
- _showSaveLoginNotification : function (aNotifyObj, aLogin) {
+ _showSaveLoginNotification : function(aNotifyObj, aLogin) {
// Ugh. We can't use the strings from the popup window, because they
// have the access key marked in the string (eg "Mo&zilla"), along
// with some weird rules for handling access keys that do not occur
// in the string, for L10N. See commonDialog.js's setLabelForNode().
var neverButtonText =
this._getLocalizedString("notifyBarNeverRememberButtonText");
var neverButtonAccessKey =
this._getLocalizedString("notifyBarNeverRememberButtonAccessKey");
@@ -1083,17 +1083,17 @@ LoginManagerPrompter.prototype = {
this._showLoginNotification(aNotifyObj, "password-save",
notificationText, buttons);
}
Services.obs.notifyObservers(aLogin, "passwordmgr-prompt-save", null);
},
- _removeLoginNotifications : function () {
+ _removeLoginNotifications : function() {
var popupNote = this._getPopupNote();
if (popupNote)
popupNote = popupNote.getNotification("password");
if (popupNote)
popupNote.remove();
var notifyBox = this._getNotifyBox();
if (notifyBox) {
@@ -1111,17 +1111,17 @@ LoginManagerPrompter.prototype = {
}
},
/**
* Called when we detect a new login in a form submission,
* asks the user what to do.
*/
- _showSaveLoginDialog : function (aLogin) {
+ _showSaveLoginDialog : function(aLogin) {
const buttonFlags = Ci.nsIPrompt.BUTTON_POS_1_DEFAULT +
(Ci.nsIPrompt.BUTTON_TITLE_IS_STRING * Ci.nsIPrompt.BUTTON_POS_0) +
(Ci.nsIPrompt.BUTTON_TITLE_IS_STRING * Ci.nsIPrompt.BUTTON_POS_1) +
(Ci.nsIPrompt.BUTTON_TITLE_IS_STRING * Ci.nsIPrompt.BUTTON_POS_2);
var displayHost = this._getShortDisplayHost(aLogin.hostname);
var dialogText;
@@ -1303,17 +1303,17 @@ LoginManagerPrompter.prototype = {
* to select a username and confirm the password change.
*
* Note: The caller doesn't know the username for aNewLogin, so this
* function fills in .username and .usernameField with the values
* from the login selected by the user.
*
* Note; XPCOM stupidity: |count| is just |logins.length|.
*/
- promptToChangePasswordWithUsernames : function (logins, count, aNewLogin) {
+ promptToChangePasswordWithUsernames : function(logins, count, aNewLogin) {
this.log("promptToChangePasswordWithUsernames with count:", count);
var usernames = logins.map(l => l.username);
var dialogText = this._getLocalizedString("userSelectText");
var dialogTitle = this._getLocalizedString("passwordChangeTitle");
var selectedIndex = { value: null };
// If user selects ok, outparam.value is set to the index
@@ -1361,29 +1361,29 @@ LoginManagerPrompter.prototype = {
propBag.setProperty("timeLastUsed", now);
propBag.setProperty("timesUsedIncrement", 1);
this._pwmgr.modifyLogin(login, propBag);
},
/**
* Given a content DOM window, returns the chrome window and browser it's in.
*/
- _getChromeWindow: function (aWindow) {
+ _getChromeWindow: function(aWindow) {
let windows = Services.wm.getEnumerator(null);
while (windows.hasMoreElements()) {
let win = windows.getNext();
let browser = win.gBrowser.getBrowserForContentWindow(aWindow);
if (browser) {
return { win, browser };
}
}
return null;
},
- _getNotifyWindow: function () {
+ _getNotifyWindow: function() {
// Some sites pop up a temporary login window, which disappears
// upon submission of credentials. We want to put the notification
// bar in the opener window if this seems to be happening.
if (this._opener) {
let chromeDoc = this._chromeWindow.document.documentElement;
// Check to see if the current window was opened with chrome
// disabled, and if so use the opener window. But if the window
@@ -1397,17 +1397,17 @@ LoginManagerPrompter.prototype = {
return { win: this._chromeWindow, browser: this._browser };
},
/**
* Returns the popup notification to this prompter,
* or null if there isn't one available.
*/
- _getPopupNote : function () {
+ _getPopupNote : function() {
let popupNote = null;
try {
let { win: notifyWin } = this._getNotifyWindow();
// .wrappedJSObject needed here -- see bug 422974 comment 5.
popupNote = notifyWin.wrappedJSObject.PopupNotifications;
} catch (e) {
@@ -1417,17 +1417,17 @@ LoginManagerPrompter.prototype = {
return popupNote;
},
/**
* Returns the notification box to this prompter, or null if there isn't
* a notification box available.
*/
- _getNotifyBox : function () {
+ _getNotifyBox : function() {
let notifyBox = null;
try {
let { win: notifyWin } = this._getNotifyWindow();
// .wrappedJSObject needed here -- see bug 422974 comment 5.
notifyBox = notifyWin.wrappedJSObject.getNotificationBox(notifyWin);
} catch (e) {
@@ -1438,17 +1438,17 @@ LoginManagerPrompter.prototype = {
},
/**
* The user might enter a login that isn't the one we prefilled, but
* is the same as some other existing login. So, pick a login with a
* matching username, or return null.
*/
- _repickSelectedLogin : function (foundLogins, username) {
+ _repickSelectedLogin : function(foundLogins, username) {
for (var i = 0; i < foundLogins.length; i++)
if (foundLogins[i].username == username)
return foundLogins[i];
return null;
},
/**
@@ -1457,62 +1457,62 @@ LoginManagerPrompter.prototype = {
* _getLocalizedString("key2", ["arg1"]);
* _getLocalizedString("key3", ["arg1", "arg2"]);
* (etc)
*
* Returns the localized string for the specified key,
* formatted if required.
*
*/
- _getLocalizedString : function (key, formatArgs) {
+ _getLocalizedString : function(key, formatArgs) {
if (formatArgs)
return this._strBundle.formatStringFromName(
key, formatArgs, formatArgs.length);
return this._strBundle.GetStringFromName(key);
},
/**
* Sanitizes the specified username, by stripping quotes and truncating if
* it's too long. This helps prevent an evil site from messing with the
* "save password?" prompt too much.
*/
- _sanitizeUsername : function (username) {
+ _sanitizeUsername : function(username) {
if (username.length > 30) {
username = username.substring(0, 30);
username += this._ellipsis;
}
return username.replace(/['"]/g, "");
},
/**
* The aURI parameter may either be a string uri, or an nsIURI instance.
*
* Returns the hostname to use in a nsILoginInfo object (for example,
* "http://example.com").
*/
- _getFormattedHostname : function (aURI) {
+ _getFormattedHostname : function(aURI) {
let uri;
if (aURI instanceof Ci.nsIURI) {
uri = aURI;
} else {
uri = Services.io.newURI(aURI, null, null);
}
return uri.scheme + "://" + uri.hostPort;
},
/**
* Converts a login's hostname field (a URL) to a short string for
* prompting purposes. Eg, "http://foo.com" --> "foo.com", or
* "ftp://www.site.co.uk" --> "site.co.uk".
*/
- _getShortDisplayHost: function (aURIString) {
+ _getShortDisplayHost: function(aURIString) {
var displayHost;
var eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"].
getService(Ci.nsIEffectiveTLDService);
var idnService = Cc["@mozilla.org/network/idn-service;1"].
getService(Ci.nsIIDNService);
try {
var uri = Services.io.newURI(aURIString, null, null);
@@ -1528,17 +1528,17 @@ LoginManagerPrompter.prototype = {
return displayHost;
},
/**
* Returns the hostname and realm for which authentication is being
* requested, in the format expected to be used with nsILoginInfo.
*/
- _getAuthTarget : function (aChannel, aAuthInfo) {
+ _getAuthTarget : function(aChannel, aAuthInfo) {
var hostname, realm;
// If our proxy is demanding authentication, don't use the
// channel's actual destination.
if (aAuthInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY) {
this.log("getAuthTarget is for proxy auth");
if (!(aChannel instanceof Ci.nsIProxiedChannel))
throw new Error("proxy auth needs nsIProxiedChannel");
@@ -1576,17 +1576,17 @@ LoginManagerPrompter.prototype = {
/**
* Returns [username, password] as extracted from aAuthInfo (which
* holds this info after having prompted the user).
*
* If the authentication was for a Windows domain, we'll prepend the
* return username with the domain. (eg, "domain\user")
*/
- _GetAuthInfo : function (aAuthInfo) {
+ _GetAuthInfo : function(aAuthInfo) {
var username, password;
var flags = aAuthInfo.flags;
if (flags & Ci.nsIAuthInformation.NEED_DOMAIN && aAuthInfo.domain)
username = aAuthInfo.domain + "\\" + aAuthInfo.username;
else
username = aAuthInfo.username;
@@ -1596,17 +1596,17 @@ LoginManagerPrompter.prototype = {
},
/**
* Given a username (possibly in DOMAIN\user form) and password, parses the
* domain out of the username if necessary and sets domain, username and
* password on the auth information object.
*/
- _SetAuthInfo : function (aAuthInfo, username, password) {
+ _SetAuthInfo : function(aAuthInfo, username, password) {
var flags = aAuthInfo.flags;
if (flags & Ci.nsIAuthInformation.NEED_DOMAIN) {
// Domain is separated from username by a backslash
var idx = username.indexOf("\\");
if (idx == -1) {
aAuthInfo.username = username;
} else {
aAuthInfo.domain = username.substring(0, idx);
--- a/toolkit/components/passwordmgr/storage-json.js
+++ b/toolkit/components/passwordmgr/storage-json.js
@@ -22,17 +22,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/LoginStore.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "gUUIDGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator");
-this.LoginManagerStorage_json = function () {};
+this.LoginManagerStorage_json = function() {};
this.LoginManagerStorage_json.prototype = {
classID: Components.ID("{c00c432d-a0c9-46d7-bef6-9c45b4d07341}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsILoginManagerStorage]),
__crypto: null, // nsILoginManagerCrypto service
get _crypto() {
if (!this.__crypto)
--- a/toolkit/components/passwordmgr/storage-mozStorage.js
+++ b/toolkit/components/passwordmgr/storage-mozStorage.js
@@ -158,17 +158,17 @@ LoginManagerStorage_mozStorage.prototype
initWithFile : function(aDBFile) {
if (aDBFile)
this._signonsFile = aDBFile;
this.initialize();
},
- initialize : function () {
+ initialize : function() {
this._dbStmts = {};
let isFirstRun;
try {
// Force initialization of the crypto module.
// See bug 717490 comment 17.
this._crypto;
@@ -195,22 +195,22 @@ LoginManagerStorage_mozStorage.prototype
}
},
/**
* Internal method used by regression tests only. It is called before
* replacing this storage module with a new instance.
*/
- terminate : function () {
+ terminate : function() {
return Promise.resolve();
},
- addLogin : function (login) {
+ addLogin : function(login) {
// Throws if there are bogus values.
LoginHelper.checkLoginValues(login);
let [encUsername, encPassword, encType] = this._encryptLogin(login);
// Clone the login, so we don't modify the caller's object.
let loginClone = login.clone();
@@ -274,17 +274,17 @@ LoginManagerStorage_mozStorage.prototype
}
}
// Send a notification that a login was added.
LoginHelper.notifyStorageChanged("addLogin", loginClone);
},
- removeLogin : function (login) {
+ removeLogin : function(login) {
let [idToDelete, storedLogin] = this._getIdForLogin(login);
if (!idToDelete)
throw new Error("No matching logins");
// Execute the statement & remove from DB
let query = "DELETE FROM moz_logins WHERE id = :id";
let params = { id: idToDelete };
let stmt;
@@ -301,17 +301,17 @@ LoginManagerStorage_mozStorage.prototype
} finally {
if (stmt) {
stmt.reset();
}
}
LoginHelper.notifyStorageChanged("removeLogin", storedLogin);
},
- modifyLogin : function (oldLogin, newLoginData) {
+ modifyLogin : function(oldLogin, newLoginData) {
let [idToModify, oldStoredLogin] = this._getIdForLogin(oldLogin);
if (!idToModify)
throw new Error("No matching logins");
let newLogin = LoginHelper.buildModifiedLogin(oldStoredLogin, newLoginData);
// Check if the new GUID is duplicate.
if (newLogin.guid != oldStoredLogin.guid &&
@@ -381,17 +381,17 @@ LoginManagerStorage_mozStorage.prototype
LoginHelper.notifyStorageChanged("modifyLogin", [oldStoredLogin, newLogin]);
},
/**
* Returns an array of nsILoginInfo.
*/
- getAllLogins : function (count) {
+ getAllLogins : function(count) {
let [logins, ids] = this._searchLogins({});
// decrypt entries for caller.
logins = this._decryptLogins(logins);
this.log("_getAllLogins: returning " + logins.length + " logins.");
if (count)
count.value = logins.length; // needed for XPCOM
@@ -438,17 +438,17 @@ LoginManagerStorage_mozStorage.prototype
/**
* Private method to perform arbitrary searches on any field. Decryption is
* left to the caller.
*
* Returns [logins, ids] for logins that match the arguments, where logins
* is an array of encrypted nsLoginInfo and ids is an array of associated
* ids in the database.
*/
- _searchLogins : function (matchData, aOptions = {
+ _searchLogins : function(matchData, aOptions = {
schemeUpgrades: false,
}) {
let conditions = [], params = {};
for (let field in matchData) {
let value = matchData[field];
let condition = "";
switch (field) {
@@ -566,17 +566,17 @@ LoginManagerStorage_mozStorage.prototype
stmt.reset();
}
},
/**
* Removes all logins from storage.
*/
- removeAllLogins : function () {
+ removeAllLogins : function() {
this.log("Removing all logins");
let query;
let stmt;
let transaction = new Transaction(this._dbConnection);
// Disabled hosts kept, as one presumably doesn't want to erase those.
// TODO: Add these items to the deleted items table once we've sorted
// out the issues from bug 756701
@@ -594,17 +594,17 @@ LoginManagerStorage_mozStorage.prototype
stmt.reset();
}
}
LoginHelper.notifyStorageChanged("removeAllLogins", null);
},
- findLogins : function (count, hostname, formSubmitURL, httpRealm) {
+ findLogins : function(count, hostname, formSubmitURL, httpRealm) {
let loginData = {
hostname: hostname,
formSubmitURL: formSubmitURL,
httpRealm: httpRealm
};
let matchData = { };
for (let field of ["hostname", "formSubmitURL", "httpRealm"])
if (loginData[field] != '')
@@ -615,17 +615,17 @@ LoginManagerStorage_mozStorage.prototype
logins = this._decryptLogins(logins);
this.log("_findLogins: returning " + logins.length + " logins");
count.value = logins.length; // needed for XPCOM
return logins;
},
- countLogins : function (hostname, formSubmitURL, httpRealm) {
+ countLogins : function(hostname, formSubmitURL, httpRealm) {
let _countLoginsHelper = (hostname, formSubmitURL, httpRealm) => {
// Do checks for null and empty strings, adjust conditions and params
let [conditions, params] =
this._buildConditionsAndParams(hostname, formSubmitURL, httpRealm);
let query = "SELECT COUNT(1) AS numLogins FROM moz_logins";
if (conditions.length) {
@@ -664,17 +664,17 @@ LoginManagerStorage_mozStorage.prototype
},
/**
* Returns an array with two items: [id, login]. If the login was not
* found, both items will be null. The returned login contains the actual
* stored login (useful for looking at the actual nsILoginMetaInfo values).
*/
- _getIdForLogin : function (login) {
+ _getIdForLogin : function(login) {
let matchData = { };
for (let field of ["hostname", "formSubmitURL", "httpRealm"])
if (login[field] != '')
matchData[field] = login[field];
let [logins, ids] = this._searchLogins(matchData);
let id = null;
let foundLogin = null;
@@ -699,17 +699,17 @@ LoginManagerStorage_mozStorage.prototype
},
/**
* Adjusts the WHERE conditions and parameters for statements prior to the
* statement being created. This fixes the cases where nulls are involved
* and the empty string is supposed to be a wildcard match
*/
- _buildConditionsAndParams : function (hostname, formSubmitURL, httpRealm) {
+ _buildConditionsAndParams : function(hostname, formSubmitURL, httpRealm) {
let conditions = [], params = {};
if (hostname == null) {
conditions.push("hostname isnull");
} else if (hostname != '') {
conditions.push("hostname = :hostname");
params["hostname"] = hostname;
}
@@ -730,17 +730,17 @@ LoginManagerStorage_mozStorage.prototype
return [conditions, params];
},
/**
* Checks to see if the specified GUID already exists.
*/
- _isGuidUnique : function (guid) {
+ _isGuidUnique : function(guid) {
let query = "SELECT COUNT(1) AS numLogins FROM moz_logins WHERE guid = :guid";
let params = { guid: guid };
let stmt, numLogins;
try {
stmt = this._dbCreateStatement(query, params);
stmt.executeStep();
numLogins = stmt.row.numLogins;
@@ -755,17 +755,17 @@ LoginManagerStorage_mozStorage.prototype
return (numLogins == 0);
},
/**
* Returns the encrypted username, password, and encrypton type for the specified
* login. Can throw if the user cancels a master password entry.
*/
- _encryptLogin : function (login) {
+ _encryptLogin : function(login) {
let encUsername = this._crypto.encrypt(login.username);
let encPassword = this._crypto.encrypt(login.password);
let encType = this._crypto.defaultEncType;
return [encUsername, encPassword, encType];
},
@@ -775,17 +775,17 @@ LoginManagerStorage_mozStorage.prototype
*
* The entries specified by the array will be decrypted, if possible.
* An array of successfully decrypted logins will be returned. The return
* value should be given to external callers (since still-encrypted
* entries are useless), whereas internal callers generally don't want
* to lose unencrypted entries (eg, because the user clicked Cancel
* instead of entering their master password)
*/
- _decryptLogins : function (logins) {
+ _decryptLogins : function(logins) {
let result = [];
for (let login of logins) {
try {
login.username = this._crypto.decrypt(login.username);
login.password = this._crypto.decrypt(login.password);
} catch (e) {
// If decryption failed (corrupt entry?), just skip it.
@@ -803,17 +803,17 @@ LoginManagerStorage_mozStorage.prototype
// Database Creation & Access
/**
* Creates a statement, wraps it, and then does parameter replacement
* Returns the wrapped statement for execution. Will use memoization
* so that statements can be reused.
*/
- _dbCreateStatement : function (query, params) {
+ _dbCreateStatement : function(query, params) {
let wrappedStmt = this._dbStmts[query];
// Memoize the statements
if (!wrappedStmt) {
this.log("Creating new statement for query: " + query);
wrappedStmt = this._dbConnection.createStatement(query);
this._dbStmts[query] = wrappedStmt;
}
// Replace parameters, must be done 1 at a time
@@ -823,17 +823,17 @@ LoginManagerStorage_mozStorage.prototype
return wrappedStmt;
},
/**
* Attempts to initialize the database. This creates the file if it doesn't
* exist, performs any migrations, etc. Return if this is the first run.
*/
- _dbInit : function () {
+ _dbInit : function() {
this.log("Initializing Database");
let isFirstRun = false;
try {
this._dbConnection = this._storageService.openDatabase(this._signonsFile);
// Get the version of the schema in the file. It will be 0 if the
// database has not been created yet.
let version = this._dbConnection.schemaVersion;
if (version == 0) {
@@ -850,57 +850,57 @@ LoginManagerStorage_mozStorage.prototype
}
throw e;
}
Services.obs.addObserver(this, "profile-before-change", false);
return isFirstRun;
},
- observe: function (subject, topic, data) {
+ observe: function(subject, topic, data) {
switch (topic) {
case "profile-before-change":
Services.obs.removeObserver(this, "profile-before-change");
this._dbClose();
break;
}
},
- _dbCreate: function () {
+ _dbCreate: function() {
this.log("Creating Database");
this._dbCreateSchema();
this._dbConnection.schemaVersion = DB_VERSION;
},
- _dbCreateSchema : function () {
+ _dbCreateSchema : function() {
this._dbCreateTables();
this._dbCreateIndices();
},
- _dbCreateTables : function () {
+ _dbCreateTables : function() {
this.log("Creating Tables");
for (let name in this._dbSchema.tables)
this._dbConnection.createTable(name, this._dbSchema.tables[name]);
},
- _dbCreateIndices : function () {
+ _dbCreateIndices : function() {
this.log("Creating Indices");
for (let name in this._dbSchema.indices) {
let index = this._dbSchema.indices[name];
let statement = "CREATE INDEX IF NOT EXISTS " + name + " ON " + index.table +
"(" + index.columns.join(", ") + ")";
this._dbConnection.executeSimpleSQL(statement);
}
},
- _dbMigrate : function (oldVersion) {
+ _dbMigrate : function(oldVersion) {
this.log("Attempting to migrate from version " + oldVersion);
if (oldVersion > DB_VERSION) {
this.log("Downgrading to version " + DB_VERSION);
// User's DB is newer. Sanity check that our expected columns are
// present, and if so mark the lower version and merrily continue
// on. If the columns are borked, something is wrong so blow away
// the DB and start from scratch. [Future incompatible upgrades
@@ -937,17 +937,17 @@ LoginManagerStorage_mozStorage.prototype
transaction.commit();
this.log("DB migration completed.");
},
/**
* Version 2 adds a GUID column. Existing logins are assigned a random GUID.
*/
- _dbMigrateToVersion2 : function () {
+ _dbMigrateToVersion2 : function() {
// Check to see if GUID column already exists, add if needed
let query;
if (!this._dbColumnExists("guid")) {
query = "ALTER TABLE moz_logins ADD COLUMN guid TEXT";
this._dbConnection.executeSimpleSQL(query);
query = "CREATE INDEX IF NOT EXISTS moz_logins_guid_index ON moz_logins (guid)";
this._dbConnection.executeSimpleSQL(query);
@@ -991,17 +991,17 @@ LoginManagerStorage_mozStorage.prototype
}
}
},
/**
* Version 3 adds a encType column.
*/
- _dbMigrateToVersion3 : function () {
+ _dbMigrateToVersion3 : function() {
// Check to see if encType column already exists, add if needed
let query;
if (!this._dbColumnExists("encType")) {
query = "ALTER TABLE moz_logins ADD COLUMN encType INTEGER";
this._dbConnection.executeSimpleSQL(query);
query = "CREATE INDEX IF NOT EXISTS " +
"moz_logins_encType_index ON moz_logins (encType)";
@@ -1051,17 +1051,17 @@ LoginManagerStorage_mozStorage.prototype
}
},
/**
* Version 4 adds timeCreated, timeLastUsed, timePasswordChanged,
* and timesUsed columns
*/
- _dbMigrateToVersion4 : function () {
+ _dbMigrateToVersion4 : function() {
let query;
// Add the new columns, if needed.
for (let column of ["timeCreated", "timeLastUsed", "timePasswordChanged", "timesUsed"]) {
if (!this._dbColumnExists(column)) {
query = "ALTER TABLE moz_logins ADD COLUMN " + column + " INTEGER";
this._dbConnection.executeSimpleSQL(query);
}
}
@@ -1106,27 +1106,27 @@ LoginManagerStorage_mozStorage.prototype
}
}
},
/**
* Version 5 adds the moz_deleted_logins table
*/
- _dbMigrateToVersion5 : function () {
+ _dbMigrateToVersion5 : function() {
if (!this._dbConnection.tableExists("moz_deleted_logins")) {
this._dbConnection.createTable("moz_deleted_logins", this._dbSchema.tables.moz_deleted_logins);
}
},
/**
* Version 6 migrates all the hosts from
* moz_disabledHosts to the permission manager.
*/
- _dbMigrateToVersion6 : function () {
+ _dbMigrateToVersion6 : function() {
let disabledHosts = [];
let query = "SELECT hostname FROM moz_disabledHosts";
let stmt;
try {
stmt = this._dbCreateStatement(query);
while (stmt.executeStep()) {
@@ -1152,17 +1152,17 @@ LoginManagerStorage_mozStorage.prototype
query = "DELETE FROM moz_disabledHosts";
this._dbConnection.executeSimpleSQL(query);
},
/**
* Sanity check to ensure that the columns this version of the code expects
* are present in the DB we're using.
*/
- _dbAreExpectedColumnsPresent : function () {
+ _dbAreExpectedColumnsPresent : function() {
let query = "SELECT " +
"id, " +
"hostname, " +
"httpRealm, " +
"formSubmitURL, " +
"usernameField, " +
"passwordField, " +
"encryptedUsername, " +
@@ -1197,29 +1197,29 @@ LoginManagerStorage_mozStorage.prototype
this.log("verified that expected columns are present in DB.");
return true;
},
/**
* Checks to see if the named column already exists.
*/
- _dbColumnExists : function (columnName) {
+ _dbColumnExists : function(columnName) {
let query = "SELECT " + columnName + " FROM moz_logins";
try {
let stmt = this._dbConnection.createStatement(query);
// (no need to execute statement, if it compiled we're good)
stmt.finalize();
return true;
} catch (e) {
return false;
}
},
- _dbClose : function () {
+ _dbClose : function() {
this.log("Closing the DB connection.");
// Finalize all statements to free memory, avoid errors later
for (let query in this._dbStmts) {
let stmt = this._dbStmts[query];
stmt.finalize();
}
this._dbStmts = {};
@@ -1232,17 +1232,17 @@ LoginManagerStorage_mozStorage.prototype
}
this._dbConnection = null;
},
/**
* Called when database creation fails. Finalizes database statements,
* closes the database connection, deletes the database file.
*/
- _dbCleanup : function (backup) {
+ _dbCleanup : function(backup) {
this.log("Cleaning up DB file - close & remove & backup=" + backup);
// Create backup file
if (backup) {
let backupFile = this._signonsFile.leafName + ".corrupt";
this._storageService.backupDatabaseFile(this._signonsFile, backupFile);
}
--- a/toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms_streamConverter.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms_streamConverter.js
@@ -53,17 +53,17 @@ function* registerConverter() {
// nsIStreamListener
onDataAvailable() {},
};
let factory = XPCOMUtils._getFactory(TestStreamConverter);
let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
registrar.registerFactory(TestStreamConverter.prototype.classID, "",
TestStreamConverter.prototype.contractID, factory);
- this.cleanupFunction = function () {
+ this.cleanupFunction = function() {
registrar.unregisterFactory(TestStreamConverter.prototype.classID, factory);
};
}
/**
* Waits for the given number of occurrences of InsecureLoginFormsStateChange
* on the given browser element.
*/
--- a/toolkit/components/passwordmgr/test/browser/browser_insecurePasswordWarning.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_insecurePasswordWarning.js
@@ -55,17 +55,17 @@ add_task(function* testInsecurePasswordW
// For a form with a secure (https) customized action link.
["http://127.0.0.1", "form_cross_origin_secure_action.html", []],
["http://example.com", "form_cross_origin_secure_action.html", ["INSECURE_PAGE"]],
["https://example.com", "form_cross_origin_secure_action.html", []],
]) {
let testURL = origin + TEST_URL_PATH + testFile;
let promiseConsoleMessages = new Promise(resolve => {
- warningPatternHandler = function (warning, originMessage) {
+ warningPatternHandler = function(warning, originMessage) {
ok(warning, "Handling a warning pattern");
let fullMessage = `[${warning.msg} {file: "${testURL}" line: 0 column: 0 source: "0"}]`;
is(originMessage, fullMessage, "Message full matched:" + originMessage);
let index = expectWarnings.indexOf(warning.key);
isnot(index, -1, "Found warning: " + warning.key + " for URL:" + testURL);
if (index !== -1) {
// Remove the shown message.
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_contextmenu.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_contextmenu.js
@@ -72,17 +72,17 @@ function test() {
function assertMenuitemEnabled(idSuffix, expected, reason = "") {
doc.defaultView.UpdateContextMenu();
let actual = !doc.getElementById("context-" + idSuffix).getAttribute("disabled");
is(actual, expected, idSuffix + " should be " + (expected ? "enabled" : "disabled") +
(reason ? ": " + reason : ""));
}
function cleanUp() {
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
+ Services.ww.registerNotification(function(aSubject, aTopic, aData) {
Services.ww.unregisterNotification(arguments.callee);
Services.logins.removeAllLogins();
doc.getElementById("passwordCol").hidden = true;
finish();
});
pwmgrdlg.close();
}
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_editing.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_editing.js
@@ -83,17 +83,17 @@ add_task(function* test_setup() {
registerCleanupFunction(function() {
Services.logins.removeAllLogins();
});
Services.logins.removeAllLogins();
// Open the password manager dialog.
pwmgrdlg = window.openDialog(PWMGR_DLG, "Toolkit:PasswordManager", "");
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
+ Services.ww.registerNotification(function(aSubject, aTopic, aData) {
if (aTopic == "domwindowopened") {
let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
SimpleTest.waitForFocus(function() {
EventUtils.sendKey("RETURN", win);
}, win);
} else if (aSubject.location == pwmgrdlg.location && aTopic == "domwindowclosed") {
// Unregister ourself.
Services.ww.unregisterNotification(arguments.callee);
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_fields.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_fields.js
@@ -44,17 +44,17 @@ function test() {
is(timeLastUsedCol.getAttribute("hidden"), "true",
"Last Used column is not displayed");
let timePasswordChangedCol = doc.getElementById("timePasswordChangedCol");
is(timePasswordChangedCol.getAttribute("hidden"), "",
"Last Changed column is displayed");
// cleanup
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
+ Services.ww.registerNotification(function(aSubject, aTopic, aData) {
if (aSubject.location == pwmgrdlg.location && aTopic == "domwindowclosed") {
// unregister ourself
Services.ww.unregisterNotification(arguments.callee);
pwmgr.removeAllLogins();
finish();
}
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js
@@ -14,17 +14,17 @@ function test() {
"Toolkit:PasswordManager", "");
let logins = [];
let loginCounter = 0;
let loginOrder = null;
let modifiedLogin;
let testNumber = 0;
let testObserver = {
- observe: function (subject, topic, data) {
+ observe: function(subject, topic, data) {
if (topic == "passwordmgr-dialog-updated") {
switch (testNumber) {
case 1:
case 2:
case 3:
case 4:
case 5:
is(countLogins(), loginCounter, "Verify login added");
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_sort.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_sort.js
@@ -69,29 +69,29 @@ function test() {
let toggleCalls = 0;
function toggleShowPasswords(func) {
let toggleButton = doc.getElementById("togglePasswords");
let showMode = (toggleCalls++ % 2) == 0;
// only watch for a confirmation dialog every other time being called
if (showMode) {
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
+ Services.ww.registerNotification(function(aSubject, aTopic, aData) {
if (aTopic == "domwindowclosed")
Services.ww.unregisterNotification(arguments.callee);
else if (aTopic == "domwindowopened") {
let targetWin = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
SimpleTest.waitForFocus(function() {
EventUtils.sendKey("RETURN", targetWin);
}, targetWin);
}
});
}
- Services.obs.addObserver(function (aSubject, aTopic, aData) {
+ Services.obs.addObserver(function(aSubject, aTopic, aData) {
if (aTopic == "passwordmgr-password-toggle-complete") {
Services.obs.removeObserver(arguments.callee, aTopic);
func();
}
}, "passwordmgr-password-toggle-complete", false);
EventUtils.synthesizeMouse(toggleButton, 1, 1, {}, win);
}
@@ -186,17 +186,17 @@ function test() {
// Reset filter
setFilter("");
break;
case 5:
expectedValues = pwds.slice().sort();
checkColumnEntries(2, expectedValues);
checkSortDirection(passwordCol, true);
// cleanup
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
+ Services.ww.registerNotification(function(aSubject, aTopic, aData) {
// unregister ourself
Services.ww.unregisterNotification(arguments.callee);
pwmgr.removeAllLogins();
finish();
});
pwmgrdlg.close();
}
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgrdlg.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgrdlg.js
@@ -80,29 +80,29 @@ function test() {
let toggleCalls = 0;
function toggleShowPasswords(func) {
let toggleButton = doc.getElementById("togglePasswords");
let showMode = (toggleCalls++ % 2) == 0;
// only watch for a confirmation dialog every other time being called
if (showMode) {
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
+ Services.ww.registerNotification(function(aSubject, aTopic, aData) {
if (aTopic == "domwindowclosed")
Services.ww.unregisterNotification(arguments.callee);
else if (aTopic == "domwindowopened") {
let targetWin = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
SimpleTest.waitForFocus(function() {
EventUtils.sendKey("RETURN", targetWin);
}, targetWin);
}
});
}
- Services.obs.addObserver(function (aSubject, aTopic, aData) {
+ Services.obs.addObserver(function(aSubject, aTopic, aData) {
if (aTopic == "passwordmgr-password-toggle-complete") {
Services.obs.removeObserver(arguments.callee, aTopic);
func();
}
}, "passwordmgr-password-toggle-complete", false);
EventUtils.synthesizeMouse(toggleButton, 1, 1, {}, win);
}
@@ -126,17 +126,17 @@ function test() {
expected = testCase.count;
break;
case 2: // showing passwords
expected = ("count2" in testCase) ? testCase.count2 : testCase.count;
break;
case 3: // toggle
expected = testCase.count;
tester();
- toggleShowPasswords(function () {
+ toggleShowPasswords(function() {
expected = ("count2" in testCase) ? testCase.count2 : testCase.count;
tester();
toggleShowPasswords(proceed);
});
return;
}
tester();
proceed();
@@ -172,17 +172,17 @@ function test() {
function step3() {
toggleShowPasswords(function() {
runTests(3, lastStep);
});
}
function lastStep() {
// cleanup
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
+ Services.ww.registerNotification(function(aSubject, aTopic, aData) {
// unregister ourself
Services.ww.unregisterNotification(arguments.callee);
pwmgr.removeAllLogins();
finish();
});
pwmgrdlg.close();
}
--- a/toolkit/components/passwordmgr/test/browser/formless_basic.html
+++ b/toolkit/components/passwordmgr/test/browser/formless_basic.html
@@ -3,16 +3,16 @@
<!-- Simplest form with username and password fields. -->
<input id="form-basic-username" name="username">
<input id="form-basic-password" name="password" type="password">
<input id="form-basic-submit" type="submit">
<button id="add">Add input[type=password]</button>
<script>
- document.getElementById("add").addEventListener("click", function () {
+ document.getElementById("add").addEventListener("click", function() {
var node = document.createElement("input");
node.setAttribute("type", "password");
document.querySelector("body").appendChild(node);
});
</script>
</body></html>
--- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html
+++ b/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html
@@ -78,25 +78,25 @@ function proxyChannelListener() { }
proxyChannelListener.prototype = {
onStartRequest: function(request, context) {
startupCompleteResolver();
},
onStopRequest: function(request, context, status) { }
};
var resolveCallback = SpecialPowers.wrapCallbackObject({
- QueryInterface : function (iid) {
+ QueryInterface : function(iid) {
const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports];
if (!interfaces.some( function(v) { return iid.equals(v); } ))
throw SpecialPowers.Cr.NS_ERROR_NO_INTERFACE;
return this;
},
- onProxyAvailable : function (req, uri, pi, status) {
+ onProxyAvailable : function(req, uri, pi, status) {
initLogins(pi);
// I'm cheating a bit here... We should probably do some magic foo to get
// something implementing nsIProxiedProtocolHandler and then call
// NewProxiedChannel(), so we have something that's definately a proxied
// channel. But Mochitests use a proxy for a number of hosts, so just
// requesting a normal channel will give us a channel that's proxied.
// The proxyChannel needs to move to at least on-modify-request to
--- a/toolkit/components/passwordmgr/test/prompt_common.js
+++ b/toolkit/components/passwordmgr/test/prompt_common.js
@@ -21,26 +21,26 @@ function startCallbackTimer() {
// Use a timer to invoke a callback to twiddle the authentication dialog
timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.init(observer, dialogDelay, Ci.nsITimer.TYPE_ONE_SHOT);
}
var observer = SpecialPowers.wrapCallbackObject({
- QueryInterface : function (iid) {
+ QueryInterface : function(iid) {
const interfaces = [Ci.nsIObserver,
Ci.nsISupports, Ci.nsISupportsWeakReference];
if (!interfaces.some( function(v) { return iid.equals(v); } ))
throw SpecialPowers.Components.results.NS_ERROR_NO_INTERFACE;
return this;
},
- observe : function (subject, topic, data) {
+ observe : function(subject, topic, data) {
var doc = getDialogDoc();
if (doc)
handleDialog(doc, testNum);
else
startCallbackTimer(); // try again in a bit
}
});
--- a/toolkit/components/passwordmgr/test/test_prompt_async.html
+++ b/toolkit/components/passwordmgr/test/test_prompt_async.html
@@ -34,17 +34,17 @@
*
* NB: Because the constructor (above) adds |this| directly as an observer,
* we need to do SpecialPowers.wrapCallbackObject directly on the prototype.
*/
dialogMonitor.prototype = SpecialPowers.wrapCallbackObject({
windowsOpen : 0,
windowsRegistered : 0,
- QueryInterface : function (iid) {
+ QueryInterface : function(iid) {
const interfaces = [Ci.nsIObserver, Ci.nsISupports];
if (!interfaces.some( function(v) { return iid.equals(v); } ))
throw SpecialPowers.Cr.NS_ERROR_NO_INTERFACE;
return this;
},
observe: function(subject, topic, data) {
@@ -125,25 +125,25 @@
.getService(Ci.nsIHttpAuthManager);
authMgr.clearAll();
monitor.shutdown();
SimpleTest.finish();
}
var resolveCallback = SpecialPowers.wrapCallbackObject({
- QueryInterface : function (iid) {
+ QueryInterface : function(iid) {
const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports];
if (!interfaces.some( function(v) { return iid.equals(v); } ))
throw SpecialPowers.Cr.NS_ERROR_NO_INTERFACE;
return this;
},
- onProxyAvailable : function (req, uri, pi, status) {
+ onProxyAvailable : function(req, uri, pi, status) {
initLogins(pi);
doTest(testNum);
}
});
function startup() {
// Need to allow for arbitrary network servers defined in PAC instead of a hardcoded moz-proxy.
var channel = NetUtil.newChannel({
@@ -157,17 +157,17 @@
pps.asyncResolve(channel, 0, resolveCallback);
}
// --------------- Test loop spin ----------------
var testNum = 1;
var iframe1;
var iframe2a;
var iframe2b;
- window.onload = function () {
+ window.onload = function() {
iframe1 = document.getElementById("iframe1");
iframe2a = document.getElementById("iframe2a");
iframe2b = document.getElementById("iframe2b");
iframe1.onload = onFrameLoad;
iframe2a.onload = onFrameLoad;
iframe2b.onload = onFrameLoad;
startup();
--- a/toolkit/components/passwordmgr/test/test_xhr.html
+++ b/toolkit/components/passwordmgr/test/test_xhr.html
@@ -169,17 +169,17 @@ function doTest() {
default:
finishTest();
}
}
function makeRequest(uri) {
var request = new XMLHttpRequest();
request.open("GET", uri, true);
- request.onreadystatechange = function () {
+ request.onreadystatechange = function() {
if (request.readyState == 4)
xhrLoad(request.responseXML);
};
request.send(null);
}
initLogins();
--- a/toolkit/components/passwordmgr/test/unit/head.js
+++ b/toolkit/components/passwordmgr/test/unit/head.js
@@ -74,17 +74,17 @@ function getTempFile(aLeafName)
let [base, ext] = DownloadPaths.splitBaseNameAndExtension(aLeafName);
let leafName = base + "-" + gFileCounter + ext;
gFileCounter++;
// Get a file reference under the temporary directory for this test file.
let file = FileUtils.getFile("TmpD", [leafName]);
do_check_false(file.exists());
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
if (file.exists()) {
file.remove(false);
}
});
return file;
}
--- a/toolkit/components/passwordmgr/test/unit/test_module_LoginImport.js
+++ b/toolkit/components/passwordmgr/test/unit/test_module_LoginImport.js
@@ -141,18 +141,18 @@ add_task(function* test_import()
}
// The "load" method must be called before importing data.
yield store.load();
yield new LoginImport(store, loginsSqlite).import();
// Verify that every login in the test data has a matching imported row.
do_check_eq(loginList.length, store.data.logins.length);
- do_check_true(loginList.every(function (loginInfo) {
- return store.data.logins.some(function (loginDataItem) {
+ do_check_true(loginList.every(function(loginInfo) {
+ return store.data.logins.some(function(loginDataItem) {
let username = gLoginManagerCrypto.decrypt(loginDataItem.encryptedUsername);
let password = gLoginManagerCrypto.decrypt(loginDataItem.encryptedPassword);
return loginDataItem.hostname == loginInfo.hostname &&
loginDataItem.httpRealm == loginInfo.httpRealm &&
loginDataItem.formSubmitURL == loginInfo.formSubmitURL &&
loginDataItem.usernameField == loginInfo.usernameField &&
loginDataItem.passwordField == loginInfo.passwordField &&
username == loginInfo.username &&
--- a/toolkit/components/passwordmgr/test/unit/test_notifications.js
+++ b/toolkit/components/passwordmgr/test/unit/test_notifications.js
@@ -3,17 +3,17 @@
*/
var expectedNotification;
var expectedData;
var TestObserver = {
QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
- observe : function (subject, topic, data) {
+ observe : function(subject, topic, data) {
do_check_eq(topic, "passwordmgr-storage-changed");
do_check_eq(data, expectedNotification);
switch (data) {
case "addLogin":
do_check_true(subject instanceof Ci.nsILoginInfo);
do_check_true(subject instanceof Ci.nsILoginMetaInfo);
do_check_true(expectedData.equals(subject)); // nsILoginInfo.equals()
--- a/toolkit/components/passwordmgr/test/unit/test_telemetry.js
+++ b/toolkit/components/passwordmgr/test/unit/test_telemetry.js
@@ -105,17 +105,17 @@ function testHistogram(histogramId, expe
/**
* Enable local telemetry recording for the duration of the tests, and prepare
* the test data that will be used by the following tests.
*/
add_task(function test_initialize() {
let oldCanRecord = Services.telemetry.canRecordExtended;
Services.telemetry.canRecordExtended = true;
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
Services.telemetry.canRecordExtended = oldCanRecord;
});
let uniqueNumber = 1;
for (let loginModifications of StatisticsTestData) {
loginModifications.hostname = `http://${uniqueNumber++}.example.com`;
Services.logins.addLogin(TestData.formLogin(loginModifications));
}
@@ -165,17 +165,17 @@ add_task(function test_disabledHosts_sta
testHistogram("PWMGR_BLOCKLIST_NUM_SITES", { 0: 1 });
});
/**
* Tests the collection of statistics related to general settings.
*/
add_task(function test_settings_statistics() {
let oldRememberSignons = Services.prefs.getBoolPref("signon.rememberSignons");
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
Services.prefs.setBoolPref("signon.rememberSignons", oldRememberSignons);
});
// Repeat the operation twice per value to test that histograms are reset.
for (let remember of [false, true, false, true]) {
// This change should be observed immediately by the login service.
Services.prefs.setBoolPref("signon.rememberSignons", remember);
--- a/toolkit/components/perfmonitoring/tests/browser/browser_AddonWatcher.js
+++ b/toolkit/components/perfmonitoring/tests/browser/browser_AddonWatcher.js
@@ -72,17 +72,17 @@ add_task(function* init() {
Preferences.reset(k);
}
});
let oldCanRecord = Services.telemetry.canRecordExtended;
Services.telemetry.canRecordExtended = true;
AddonWatcher.init();
- registerCleanupFunction(function () {
+ registerCleanupFunction(function() {
AddonWatcher.paused = true;
Services.telemetry.canRecordExtended = oldCanRecord;
});
});
// Utility function to burn some resource, trigger a reaction of the add-on watcher
// and check both its notification and telemetry.
let burn_rubber = Task.async(function*({histogramName, topic, expectedMinSum}) {
--- a/toolkit/components/places/BookmarkHTMLUtils.jsm
+++ b/toolkit/components/places/BookmarkHTMLUtils.jsm
@@ -1034,29 +1034,29 @@ BookmarkExporter.prototype = {
} finally {
out.close();
}
}.bind(this));
},
_converterOut: null,
- _write: function (aText) {
+ _write: function(aText) {
this._converterOut.writeString(aText || "");
},
- _writeAttribute: function (aName, aValue) {
+ _writeAttribute: function(aName, aValue) {
this._write(' ' + aName + '="' + aValue + '"');
},
- _writeLine: function (aText) {
+ _writeLine: function(aText) {
this._write(aText + "\n");
},
- _writeHeader: function () {
+ _writeHeader: function() {
this._writeLine("<!DOCTYPE NETSCAPE-Bookmark-file-1>");
this._writeLine("<!-- This is an automatically generated file.");
this._writeLine(" It will be read and overwritten.");
this._writeLine(" DO NOT EDIT! -->");
this._writeLine('<META HTTP-EQUIV="Content-Type" CONTENT="text/html; ' +
'charset=UTF-8">');
this._writeLine("<TITLE>Bookmarks</TITLE>");
},
@@ -1099,25 +1099,25 @@ BookmarkExporter.prototype = {
} else if (child.type == PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR) {
this._writeSeparator(child, localIndent);
} else {
yield this._writeItem(child, localIndent);
}
}
},
- _writeSeparator: function (aItem, aIndent) {
+ _writeSeparator: function(aItem, aIndent) {
this._write(aIndent + "<HR");
// We keep exporting separator titles, but don't support them anymore.
if (aItem.title)
this._writeAttribute("NAME", escapeHtmlEntities(aItem.title));
this._write(">");
},
- _writeLivemark: function (aItem, aIndent) {
+ _writeLivemark: function(aItem, aIndent) {
this._write(aIndent + "<DT><A");
let feedSpec = aItem.annos.find(anno => anno.name == PlacesUtils.LMANNO_FEEDURI).value;
this._writeAttribute("FEEDURL", escapeUrl(feedSpec));
let siteSpecAnno = aItem.annos.find(anno => anno.name == PlacesUtils.LMANNO_SITEURI);
if (siteSpecAnno)
this._writeAttribute("HREF", escapeUrl(siteSpecAnno.value));
this._writeLine(">" + escapeHtmlEntities(aItem.title) + "</A>");
this._writeDescription(aItem, aIndent);
@@ -1148,17 +1148,17 @@ BookmarkExporter.prototype = {
if (aItem.charset)
this._writeAttribute("LAST_CHARSET", escapeHtmlEntities(aItem.charset));
if (aItem.tags)
this._writeAttribute("TAGS", aItem.tags);
this._writeLine(">" + escapeHtmlEntities(aItem.title) + "</A>");
this._writeDescription(aItem, aIndent);
},
- _writeDateAttributes: function (aItem) {
+ _writeDateAttributes: function(aItem) {
if (aItem.dateAdded)
this._writeAttribute("ADD_DATE",
Math.floor(aItem.dateAdded / MICROSEC_PER_SEC));
if (aItem.lastModified)
this._writeAttribute("LAST_MODIFIED",
Math.floor(aItem.lastModified / MICROSEC_PER_SEC));
},
@@ -1177,15 +1177,15 @@ BookmarkExporter.prototype = {
if (!favicon.uri.schemeIs("chrome") && favicon.dataLen > 0) {
let faviconContents = "data:image/png;base64," +
base64EncodeString(String.fromCharCode.apply(String, favicon.data));
this._writeAttribute("ICON", faviconContents);
}
},
- _writeDescription: function (aItem, aIndent) {
+ _writeDescription: function(aItem, aIndent) {
let descriptionAnno = aItem.annos &&
aItem.annos.find(anno => anno.name == DESCRIPTION_ANNO);
if (descriptionAnno)
this._writeLine(aIndent + "<DD>" + escapeHtmlEntities(descriptionAnno.value));
}
};
--- a/toolkit/components/places/History.jsm
+++ b/toolkit/components/places/History.jsm
@@ -125,17 +125,17 @@ this.History = Object.freeze({
* @resolves (PageInfo | null) If the page could be found, the information
* on that page. Note that this `PageInfo` does NOT contain the visit
* data (i.e. `visits` is `undefined`).
*
* @throws (Error)
* If `guidOrURI` does not have the expected type or if it is a string
* that may be parsed neither as a valid URL nor as a valid GUID.
*/
- fetch: function (guidOrURI) {
+ fetch: function(guidOrURI) {
throw new Error("Method not implemented");
},
/**
* Adds a number of visits for a single page.
*
* Any change may be observed through nsINavHistoryObserver
*
@@ -170,17 +170,17 @@ this.History = Object.freeze({
* @throws (Error)
* If `pageInfo` does not have a `visits` property or if the
* value of `visits` is ill-typed or is an empty array.
* @throws (Error)
* If an element of `visits` has an invalid `date`.
* @throws (Error)
* If an element of `visits` has an invalid `transition`.
*/
- insert: function (pageInfo) {
+ insert: function(pageInfo) {
if (typeof pageInfo != "object" || !pageInfo) {
throw new TypeError("pageInfo must be an object");
}
let info = validatePageInfo(pageInfo);
return PlacesUtils.withConnectionWrapper("History.jsm: insert",
db => insert(db, info));
@@ -226,17 +226,17 @@ this.History = Object.freeze({
* @throws (Error)
* If a `PageInfo` does not have a `visits` property or if the
* value of `visits` is ill-typed or is an empty array.
* @throws (Error)
* If an element of `visits` has an invalid `date`.
* @throws (Error)
* If an element of `visits` has an invalid `transition`.
*/
- insertMany: function (pageInfos, onResult, onError) {
+ insertMany: function(pageInfos, onResult, onError) {
let infos = [];
if (!Array.isArray(pageInfos)) {
throw new TypeError("pageInfos must be an array");
}
if (!pageInfos.length) {
throw new TypeError("pageInfos may not be an empty array");
}
@@ -276,17 +276,17 @@ this.History = Object.freeze({
* A promise resolved once the operation is complete.
* @resolve (bool)
* `true` if at least one page was removed, `false` otherwise.
* @throws (TypeError)
* If `pages` has an unexpected type or if a string provided
* is neither a valid GUID nor a valid URI or if `pages`
* is an empty array.
*/
- remove: function (pages, onResult = null) {
+ remove: function(pages, onResult = null) {
// Normalize and type-check arguments
if (Array.isArray(pages)) {
if (pages.length == 0) {
throw new TypeError("Expected at least one page");
}
} else {
pages = [pages];
}
--- a/toolkit/components/places/PlacesDBUtils.jsm
+++ b/toolkit/components/places/PlacesDBUtils.jsm
@@ -132,17 +132,17 @@ this.PlacesDBUtils = {
* Tasks object to execute.
*/
_refreshUI: function PDBU__refreshUI(aTasks)
{
let tasks = new Tasks(aTasks);
// Send batch update notifications to update the UI.
PlacesUtils.history.runInBatchMode({
- runBatched: function (aUserData) {}
+ runBatched: function(aUserData) {}
}, null);
PlacesDBUtils._executeTasks(tasks);
},
_handleError: function PDBU__handleError(aError)
{
Cu.reportError("Async statement execution returned with '" +
aError.result + "', '" + aError.message + "'");
@@ -157,19 +157,19 @@ this.PlacesDBUtils = {
reindex: function PDBU_reindex(aTasks)
{
let tasks = new Tasks(aTasks);
tasks.log("> Reindex");
let stmt = DBConn.createAsyncStatement("REINDEX");
stmt.executeAsync({
handleError: PlacesDBUtils._handleError,
- handleResult: function () {},
+ handleResult: function() {},
- handleCompletion: function (aReason)
+ handleCompletion: function(aReason)
{
if (aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) {
tasks.log("+ The database has been reindexed");
}
else {
tasks.log("- Unable to reindex database");
}
@@ -203,23 +203,23 @@ this.PlacesDBUtils = {
tasks.log("> Integrity check");
// Run a integrity check, but stop at the first error.
let stmt = DBConn.createAsyncStatement("PRAGMA integrity_check(1)");
stmt.executeAsync({
handleError: PlacesDBUtils._handleError,
_corrupt: false,
- handleResult: function (aResultSet)
+ handleResult: function(aResultSet)
{
let row = aResultSet.getNextRow();
this._corrupt = row.getResultByIndex(0) != "ok";
},
- handleCompletion: function (aReason)
+ handleCompletion: function(aReason)
{
if (aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) {
if (this._corrupt) {
tasks.log("- The database is corrupt");
if (aSkipReindex) {
tasks.log("- Unable to fix corruption, database will be replaced on next startup");
Services.prefs.setBoolPref("places.database.replaceOnStartup", true);
tasks.clear();
@@ -255,19 +255,19 @@ this.PlacesDBUtils = {
checkCoherence: function PDBU_checkCoherence(aTasks)
{
let tasks = new Tasks(aTasks);
tasks.log("> Coherence check");
let stmts = PlacesDBUtils._getBoundCoherenceStatements();
DBConn.executeAsync(stmts, stmts.length, {
handleError: PlacesDBUtils._handleError,
- handleResult: function () {},
+ handleResult: function() {},
- handleCompletion: function (aReason)
+ handleCompletion: function(aReason)
{
if (aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) {
tasks.log("+ The database is coherent");
}
else {
tasks.log("- Unable to check database coherence");
tasks.clear();
}
@@ -743,19 +743,19 @@ this.PlacesDBUtils = {
let DBFile = Services.dirsvc.get("ProfD", Ci.nsILocalFile);
DBFile.append("places.sqlite");
tasks.log("Initial database size is " +
parseInt(DBFile.fileSize / 1024) + " KiB");
let stmt = DBConn.createAsyncStatement("VACUUM");
stmt.executeAsync({
handleError: PlacesDBUtils._handleError,
- handleResult: function () {},
+ handleResult: function() {},
- handleCompletion: function (aReason)
+ handleCompletion: function(aReason)
{
if (aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) {
tasks.log("+ The database has been vacuumed");
let vacuumedDBFile = Services.dirsvc.get("ProfD", Ci.nsILocalFile);
vacuumedDBFile.append("places.sqlite");
tasks.log("Final database size is " +
parseInt(vacuumedDBFile.fileSize / 1024) + " KiB");
}
@@ -779,17 +779,17 @@ this.PlacesDBUtils = {
expire: function PDBU_expire(aTasks)
{
let tasks = new Tasks(aTasks);
tasks.log("> Orphans expiration");
let expiration = Cc["@mozilla.org/places/expiration;1"].
getService(Ci.nsIObserver);
- Services.obs.addObserver(function (aSubject, aTopic, aData) {
+ Services.obs.addObserver(function(aSubject, aTopic, aData) {
Services.obs.removeObserver(arguments.callee, aTopic);
tasks.log("+ Database cleaned up");
PlacesDBUtils._executeTasks(tasks);
}, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false);
// Force an orphans expiration step.
expiration.observe(null, "places-debug-start-expiration", 0);
},
@@ -809,17 +809,17 @@ this.PlacesDBUtils = {
DBFile.append("places.sqlite");
tasks.log("Database size is " + parseInt(DBFile.fileSize / 1024) + " KiB");
[ "user_version"
, "page_size"
, "cache_size"
, "journal_mode"
, "synchronous"
- ].forEach(function (aPragma) {
+ ].forEach(function(aPragma) {
let stmt = DBConn.createStatement("PRAGMA " + aPragma);
stmt.executeStep();
tasks.log(aPragma + " is " + stmt.getString(0));
stmt.finalize();
});
// Get maximum number of unique URIs.
try {
@@ -924,45 +924,45 @@ this.PlacesDBUtils = {
) * 100 / (
SELECT count(*) FROM moz_bookmarks b
JOIN moz_bookmarks t ON t.id = b.parent
AND t.parent <> :tags_folder
WHERE b.type = :type_bookmark
)), 0)` },
{ histogram: "PLACES_DATABASE_FILESIZE_MB",
- callback: function () {
+ callback: function() {
let DBFile = Services.dirsvc.get("ProfD", Ci.nsILocalFile);
DBFile.append("places.sqlite");
return parseInt(DBFile.fileSize / BYTES_PER_MEBIBYTE);
}
},
{ histogram: "PLACES_DATABASE_PAGESIZE_B",
query: "PRAGMA page_size /* PlacesDBUtils.jsm PAGESIZE_B */" },
{ histogram: "PLACES_DATABASE_SIZE_PER_PAGE_B",
query: "PRAGMA page_count",
- callback: function (aDbPageCount) {
+ callback: function(aDbPageCount) {
// Note that the database file size would not be meaningful for this
// calculation, because the file grows in fixed-size chunks.
let dbPageSize = probeValues.PLACES_DATABASE_PAGESIZE_B;
let placesPageCount = probeValues.PLACES_PAGES_COUNT;
return Math.round((dbPageSize * aDbPageCount) / placesPageCount);
}
},
{ histogram: "PLACES_ANNOS_BOOKMARKS_COUNT",
query: "SELECT count(*) FROM moz_items_annos" },
{ histogram: "PLACES_ANNOS_PAGES_COUNT",
query: "SELECT count(*) FROM moz_annos" },
{ histogram: "PLACES_MAINTENANCE_DAYSFROMLAST",
- callback: function () {
+ callback: function() {
try {
let lastMaintenance = Services.prefs.getIntPref("places.database.lastMaintenance");
let nowSeconds = parseInt(Date.now() / 1000);
return parseInt((nowSeconds - lastMaintenance) / 86400);
} catch (ex) {
return 60;
}
}
@@ -990,21 +990,21 @@ this.PlacesDBUtils = {
if (probe.query.indexOf(":" + param) > 0) {
stmt.params[param] = params[param];
}
}
try {
stmt.executeAsync({
handleError: reject,
- handleResult: function (aResultSet) {
+ handleResult: function(aResultSet) {
let row = aResultSet.getNextRow();
resolve([probe, row.getResultByIndex(0)]);
},
- handleCompletion: function () {}
+ handleCompletion: function() {}
});
} finally {
stmt.finalize();
}
});
// Report the result of the probe through Telemetry.
// The resulting promise cannot reject.
--- a/toolkit/components/places/PlacesSearchAutocompleteProvider.jsm
+++ b/toolkit/components/places/PlacesSearchAutocompleteProvider.jsm
@@ -33,17 +33,17 @@ const SearchAutocompleteProviderInternal
*/
aliasMatches: null,
/**
* Object for the default search match.
**/
defaultMatch: null,
- initialize: function () {
+ initialize: function() {
return new Promise((resolve, reject) => {
Services.search.init(status => {
if (!Components.isSuccessCode(status)) {
reject(new Error("Unable to initialize search service."));
}
try {
// The initial loading of the search engines must succeed.
@@ -57,27 +57,27 @@ const SearchAutocompleteProviderInternal
reject(ex);
}
});
});
},
initialized: false,
- observe: function (subject, topic, data) {
+ observe: function(subject, topic, data) {
switch (data) {
case "engine-added":
case "engine-changed":
case "engine-removed":
case "engine-current":
this._refresh();
}
},
- _refresh: function () {
+ _refresh: function() {
this.priorityMatches = [];
this.aliasMatches = [];
this.defaultMatch = null;
let currentEngine = Services.search.currentEngine;
// This can be null in XCPShell.
if (currentEngine) {
this.defaultMatch = {
@@ -86,17 +86,17 @@ const SearchAutocompleteProviderInternal
}
}
// The search engines will always be processed in the order returned by the
// search service, which can be defined by the user.
Services.search.getVisibleEngines().forEach(e => this._addEngine(e));
},
- _addEngine: function (engine) {
+ _addEngine: function(engine) {
if (engine.alias) {
this.aliasMatches.push({
alias: engine.alias,
engineName: engine.name,
iconUrl: engine.iconURI ? engine.iconURI.spec : null,
});
}
@@ -187,17 +187,17 @@ SearchSuggestionControllerWrapper.protot
var gInitializationPromise = null;
this.PlacesSearchAutocompleteProvider = Object.freeze({
/**
* Starts initializing the component and returns a promise that is resolved or
* rejected when initialization finished. The same promise is returned if
* this function is called multiple times.
*/
- ensureInitialized: function () {
+ ensureInitialized: function() {
if (!gInitializationPromise) {
gInitializationPromise = SearchAutocompleteProviderInternal.initialize();
}
return gInitializationPromise;
},
/**
* Matches a given string to an item that should be included by URL search
@@ -268,17 +268,17 @@ this.PlacesSearchAutocompleteProvider =
* }
*
* @remarks The asynchronous ensureInitialized function must be called before
* this synchronous method can be used.
*
* @note This API function needs to be synchronous because it is called inside
* a row processing callback of Sqlite.jsm, in UnifiedComplete.js.
*/
- parseSubmissionURL: function (url) {
+ parseSubmissionURL: function(url) {
if (!SearchAutocompleteProviderInternal.initialized) {
throw new Error("The component has not been initialized.");
}
let parseUrlResult = Services.search.parseSubmissionURL(url);
return parseUrlResult.engine && {
engineName: parseUrlResult.engine.name,
terms: parseUrlResult.terms,
--- a/toolkit/components/places/PlacesSyncUtils.jsm
+++ b/toolkit/components/places/PlacesSyncUtils.jsm
@@ -880,17 +880,17 @@ var getAnno = Task.async(function* (guid
JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id
JOIN moz_bookmarks b ON b.id = a.item_id
WHERE b.guid = :guid AND
n.name = :anno`,
{ guid, anno });
return rows.length ? rows[0].getResultByName("content") : null;
});
-var tagItem = Task.async(function (item, tags) {
+var tagItem = Task.async(function(item, tags) {
if (!item.url) {
return [];
}
// Remove leading and trailing whitespace, then filter out empty tags.
let newTags = tags.map(tag => tag.trim()).filter(Boolean);
// Removing the last tagged item will also remove the tag. To preserve
--- a/toolkit/components/places/PlacesTransactions.jsm
+++ b/toolkit/components/places/PlacesTransactions.jsm
@@ -216,17 +216,17 @@ TransactionsHistory.__proto__ = {
/**
* Proxify a transaction object for consumers.
* @param aRawTransaction
* the raw transaction object.
* @return the proxified transaction object.
* @see getRawTransaction for retrieving the raw transaction.
*/
- proxifyTransaction: function (aRawTransaction) {
+ proxifyTransaction: function(aRawTransaction) {
let proxy = Object.freeze({
transact() {
return TransactionsManager.transact(this);
}
});
this.proxifiedToRaw.set(proxy, aRawTransaction);
return proxy;
},
@@ -663,17 +663,17 @@ var TransactionsManager = {
* all this bureaucracy while still validating input appropriately.
*/
function DefineTransaction(aRequiredProps = [], aOptionalProps = []) {
for (let prop of [...aRequiredProps, ...aOptionalProps]) {
if (!DefineTransaction.inputProps.has(prop))
throw new Error("Property '" + prop + "' is not defined");
}
- let ctor = function (aInput) {
+ let ctor = function(aInput) {
// We want to support both syntaxes:
// let t = new PlacesTransactions.NewBookmark(),
// let t = PlacesTransactions.NewBookmark()
if (this == PlacesTransactions)
return new ctor(aInput);
if (aRequiredProps.length > 0 || aOptionalProps.length > 0) {
// Bind the input properties to the arguments of execute.
@@ -705,17 +705,17 @@ DefineTransaction.indexValidate =
v >= PlacesUtils.bookmarks.DEFAULT_INDEX);
DefineTransaction.guidValidate =
simpleValidateFunc(v => /^[a-zA-Z0-9\-_]{12}$/.test(v));
function isPrimitive(v) {
return v === null || (typeof(v) != "object" && typeof(v) != "function");
}
-DefineTransaction.annotationObjectValidate = function (obj) {
+DefineTransaction.annotationObjectValidate = function(obj) {
let checkProperty = (aPropName, aRequired, aCheckFunc) => {
if (aPropName in obj)
return aCheckFunc(obj[aPropName]);
return !aRequired;
};
if (obj &&
@@ -737,66 +737,66 @@ DefineTransaction.urlValidate = function
if (url instanceof Components.interfaces.nsIURI)
return url;
let spec = url instanceof URL ? url.href : url;
return NetUtil.newURI(spec);
};
DefineTransaction.inputProps = new Map();
DefineTransaction.defineInputProps =
-function (aNames, aValidationFunction, aDefaultValue) {
+function(aNames, aValidationFunction, aDefaultValue) {
for (let name of aNames) {
// Workaround bug 449811.
let propName = name;
this.inputProps.set(propName, {
- validateValue: function (aValue) {
+ validateValue: function(aValue) {
if (aValue === undefined)
return aDefaultValue;
try {
return aValidationFunction(aValue);
}
catch (ex) {
throw new Error(`Invalid value for input property ${propName}`);
}
},
- validateInput: function (aInput, aRequired) {
+ validateInput: function(aInput, aRequired) {
if (aRequired && !(propName in aInput))
throw new Error(`Required input property is missing: ${propName}`);
return this.validateValue(aInput[propName]);
},
isArrayProperty: false
});
}
};
DefineTransaction.defineArrayInputProp =
-function (aName, aBasePropertyName) {
+function(aName, aBasePropertyName) {
let baseProp = this.inputProps.get(aBasePropertyName);
if (!baseProp)
throw new Error(`Unknown input property: ${aBasePropertyName}`);
this.inputProps.set(aName, {
- validateValue: function (aValue) {
+ validateValue: function(aValue) {
if (aValue == undefined)
return [];
if (!Array.isArray(aValue))
throw new Error(`${aName} input property value must be an array`);
// This also takes care of abandoning the global scope of the input
// array (through Array.prototype).
return aValue.map(baseProp.validateValue);
},
// We allow setting either the array property itself (e.g. urls), or a
// single element of it (url, in that example), that is then transformed
// into a single-element array.
- validateInput: function (aInput, aRequired) {
+ validateInput: function(aInput, aRequired) {
if (aName in aInput) {
// It's not allowed to set both though.
if (aBasePropertyName in aInput) {
throw new Error(`It is not allowed to set both ${aName} and
${aBasePropertyName} as input properties`);
}
let array = this.validateValue(aInput[aName]);
if (aRequired && array.length == 0) {
@@ -816,22 +816,22 @@ function (aName, aBasePropertyName) {
return [];
},
isArrayProperty: true
});
};
DefineTransaction.validatePropertyValue =
-function (aProp, aInput, aRequired) {
+function(aProp, aInput, aRequired) {
return this.inputProps.get(aProp).validateInput(aInput, aRequired);
};
DefineTransaction.getInputObjectForSingleValue =
-function (aInput, aRequiredProps, aOptionalProps) {
+function(aInput, aRequiredProps, aOptionalProps) {
// The following input forms may be deduced from a single value:
// * a single required property with or without optional properties (the given
// value is set to the required property).
// * a single optional property with no required properties.
if (aRequiredProps.length > 1 ||
(aRequiredProps.length == 0 && aOptionalProps.length > 1)) {
throw new Error("Transaction input isn't an object");
}
@@ -840,17 +840,17 @@ function (aInput, aRequiredProps, aOptio
aRequiredProps[0] : aOptionalProps[0];
let propValue =
this.inputProps.get(propName).isArrayProperty && !Array.isArray(aInput) ?
[aInput] : aInput;
return { [propName]: propValue };
};
DefineTransaction.verifyInput =
-function (aInput, aRequiredProps = [], aOptionalProps = []) {
+function(aInput, aRequiredProps = [], aOptionalProps = []) {
if (aRequiredProps.length == 0 && aOptionalProps.length == 0)
return {};
// If there's just a single required/optional property, we allow passing it
// as is, so, for example, one could do PlacesTransactions.RemoveItem(myGuid)
// rather than PlacesTransactions.RemoveItem({ guid: myGuid}).
// This shortcut isn't supported for "complex" properties - e.g. one cannot
// pass an annotation object this way (note there is no use case for this at
@@ -1080,18 +1080,18 @@ var PT = PlacesTransactions;
* Optional Input Properties: index, title, keyword, annotations, tags.
*
* When this transaction is executed, it's resolved to the new bookmark's GUID.
*/
PT.NewBookmark = DefineTransaction(["parentGuid", "url"],
["index", "title", "keyword", "postData",
"annotations", "tags"]);
PT.NewBookmark.prototype = Object.seal({
- execute: function (aParentGuid, aURI, aIndex, aTitle,
- aKeyword, aPostData, aAnnos, aTags) {
+ execute: function(aParentGuid, aURI, aIndex, aTitle,
+ aKeyword, aPostData, aAnnos, aTags) {
return ExecuteCreateItem(this, aParentGuid,
function* (parentId, guidToRestore = "") {
let itemId = PlacesUtils.bookmarks.insertBookmark(
parentId, aURI, aIndex, aTitle, guidToRestore);
if (aKeyword) {
yield PlacesUtils.keywords.insert({
url: aURI.spec,
@@ -1124,17 +1124,17 @@ PT.NewBookmark.prototype = Object.seal({
* Required Input Properties: title, parentGuid.
* Optional Input Properties: index, annotations.
*
* When this transaction is executed, it's resolved to the new folder's GUID.
*/
PT.NewFolder = DefineTransaction(["parentGuid", "title"],
["index", "annotations"]);
PT.NewFolder.prototype = Object.seal({
- execute: function (aParentGuid, aTitle, aIndex, aAnnos) {
+ execute: function(aParentGuid, aTitle, aIndex, aAnnos) {
return ExecuteCreateItem(this, aParentGuid,
function* (parentId, guidToRestore = "") {
let itemId = PlacesUtils.bookmarks.createFolder(
parentId, aTitle, aIndex, guidToRestore);
if (aAnnos.length > 0)
PlacesUtils.setAnnotationsForItem(itemId, aAnnos);
return itemId;
});
@@ -1147,17 +1147,17 @@ PT.NewFolder.prototype = Object.seal({
* Required Input Properties: parentGuid.
* Optional Input Properties: index.
*
* When this transaction is executed, it's resolved to the new separator's
* GUID.
*/
PT.NewSeparator = DefineTransaction(["parentGuid"], ["index"]);
PT.NewSeparator.prototype = Object.seal({
- execute: function (aParentGuid, aIndex) {
+ execute: function(aParentGuid, aIndex) {
return ExecuteCreateItem(this, aParentGuid,
function* (parentId, guidToRestore = "") {
let itemId = PlacesUtils.bookmarks.insertSeparator(
parentId, aIndex, guidToRestore);
return itemId;
});
}
});
--- a/toolkit/components/places/PlacesUtils.jsm
+++ b/toolkit/components/places/PlacesUtils.jsm
@@ -1624,20 +1624,20 @@ this.PlacesUtils = {
/**
* Gets favicon data for a given page url.
*
* @param aPageUrl url of the page to look favicon for.
* @resolves to an object representing a favicon entry, having the following
* properties: { uri, dataLen, data, mimeType }
* @rejects JavaScript exception if the given url has no associated favicon.
*/
- promiseFaviconData: function (aPageUrl) {
+ promiseFaviconData: function(aPageUrl) {
let deferred = Promise.defer();
PlacesUtils.favicons.getFaviconDataForPage(NetUtil.newURI(aPageUrl),
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
if (aURI) {
deferred.resolve({ uri: aURI,
dataLen: aDataLen,
data: aData,
mimeType: aMimeType });
} else {
deferred.reject();
}
@@ -1647,17 +1647,17 @@ this.PlacesUtils = {
/**
* Gets the favicon link url (moz-anno:) for a given page url.
*
* @param aPageURL url of the page to lookup the favicon for.
* @resolves to the nsIURL of the favicon link
* @rejects if the given url has no associated favicon.
*/
- promiseFaviconLinkUrl: function (aPageUrl) {
+ promiseFaviconLinkUrl: function(aPageUrl) {
let deferred = Promise.defer();
if (!(aPageUrl instanceof Ci.nsIURI))
aPageUrl = NetUtil.newURI(aPageUrl);
PlacesUtils.favicons.getFaviconURLForPage(aPageUrl, uri => {
if (uri) {
uri = PlacesUtils.favicons.getFaviconLinkForIcon(uri);
deferred.resolve(uri);
@@ -2014,17 +2014,17 @@ XPCOMUtils.defineLazyServiceGetter(Place
"mozIAsyncLivemarks");
XPCOMUtils.defineLazyGetter(PlacesUtils, "keywords", () => Keywords);
XPCOMUtils.defineLazyGetter(PlacesUtils, "transactionManager", function() {
let tm = Cc["@mozilla.org/transactionmanager;1"].
createInstance(Ci.nsITransactionManager);
tm.AddListener(PlacesUtils);
- this.registerShutdownFunction(function () {
+ this.registerShutdownFunction(function() {
// Clear all references to local transactions in the transaction manager,
// this prevents from leaking it.
this.transactionManager.RemoveListener(this);
this.transactionManager.clear();
});
// Bug 750269
// The transaction manager keeps strong references to transactions, and by
@@ -2511,17 +2511,17 @@ var GuidHelper = {
},
invalidateCacheForItemId(aItemId) {
let guid = this.guidsForIds.get(aItemId);
this.guidsForIds.delete(aItemId);
this.idsForGuids.delete(guid);
},
- ensureObservingRemovedItems: function () {
+ ensureObservingRemovedItems: function() {
if (!("observer" in this)) {
/**
* This observers serves two purposes:
* (1) Invalidate cached id<->GUID paris on when items are removed.
* (2) Cache GUIDs given us free of charge by onItemAdded/onItemRemoved.
* So, for exmaple, when the NewBookmark needs the new GUID, we already
* have it cached.
*/
@@ -3688,17 +3688,17 @@ PlacesSortFolderByNameTransaction.protot
let contents =
PlacesUtils.getFolderContents(this.item.id, false, false).root;
let count = contents.childCount;
// sort between separators
let newOrder = [];
let preSep = []; // temporary array for sorting each group of items
let sortingMethod =
- function (a, b) {
+ function(a, b) {
if (PlacesUtils.nodeIsContainer(a) && !PlacesUtils.nodeIsContainer(b))
return -1;
if (!PlacesUtils.nodeIsContainer(a) && PlacesUtils.nodeIsContainer(b))
return 1;
return a.title.localeCompare(b.title);
};
for (let i = 0; i < count; ++i) {
@@ -3829,17 +3829,17 @@ this.PlacesUntagURITransaction =
PlacesUntagURITransaction.prototype = {
__proto__: BaseTransaction.prototype,
doTransaction: function UTUTXN_doTransaction()
{
// Filter tags existing on the bookmark, otherwise on undo we may try to
// set nonexistent tags.
let tags = PlacesUtils.tagging.getTagsForURI(this.item.uri);
- this.item.tags = this.item.tags.filter(function (aTag) {
+ this.item.tags = this.item.tags.filter(function(aTag) {
return tags.includes(aTag);
});
PlacesUtils.tagging.untagURI(this.item.uri, this.item.tags);
},
undoTransaction: function UTUTXN_undoTransaction()
{
PlacesUtils.tagging.tagURI(this.item.uri, this.item.tags);
--- a/toolkit/components/places/UnifiedComplete.js
+++ b/toolkit/components/places/UnifiedComplete.js
@@ -372,17 +372,17 @@ XPCOMUtils.defineLazyGetter(this, "Switc
this._conn.executeCached(
`UPDATE moz_openpages_temp
SET open_count = open_count - 1
WHERE url = :url
AND userContextId = :userContextId`
, { url: uri.spec, userContextId });
},
- shutdown: function () {
+ shutdown: function() {
this._conn = null;
this._queue.clear();
}
}));
/**
* This helper keeps track of preferences and keeps their values up-to-date.
*/
@@ -411,17 +411,17 @@ XPCOMUtils.defineLazyGetter(this, "Prefs
} else {
// If the preference was deactivated, deactivate all suggest preferences.
for (let type of suggestPrefs) {
prefs.set(type[0], false);
}
}
}
- function loadSyncedPrefs () {
+ function loadSyncedPrefs() {
store.enabled = prefs.get(...PREF_ENABLED);
store.suggestHistory = prefs.get(...PREF_SUGGEST_HISTORY);
store.suggestBookmark = prefs.get(...PREF_SUGGEST_BOOKMARK);
store.suggestOpenpage = prefs.get(...PREF_SUGGEST_OPENPAGE);
store.suggestTyped = prefs.get(...PREF_SUGGEST_HISTORY_ONLYTYPED);
store.suggestSearches = prefs.get(...PREF_SUGGEST_SEARCHES);
}
@@ -752,17 +752,17 @@ function Search(searchString, searchPara
Search.prototype = {
/**
* Enables the desired AutoComplete behavior.
*
* @param type
* The behavior type to set.
*/
- setBehavior: function (type) {
+ setBehavior: function(type) {
type = type.toUpperCase();
this._behavior |=
Ci.mozIPlacesAutoComplete["BEHAVIOR_" + type];
// Setting the "typed" behavior should also set the "history" behavior.
if (type == "TYPED") {
this.setBehavior("history");
}
@@ -770,33 +770,33 @@ Search.prototype = {
/**
* Determines if the specified AutoComplete behavior is set.
*
* @param aType
* The behavior type to test for.
* @return true if the behavior is set, false otherwise.
*/
- hasBehavior: function (type) {
+ hasBehavior: function(type) {
let behavior = Ci.mozIPlacesAutoComplete["BEHAVIOR_" + type.toUpperCase()];
if (this._disablePrivateActions &&
behavior == Ci.mozIPlacesAutoComplete.BEHAVIOR_OPENPAGE) {
return false;
}
return this._behavior & behavior;
},
/**
* Used to delay the most complex queries, to save IO while the user is
* typing.
*/
_sleepDeferred: null,
- _sleep: function (aTimeMs) {
+ _sleep: function(aTimeMs) {
// Reuse a single instance to try shaving off some usless work before
// the first query.
if (!this._sleepTimer)
this._sleepTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this._sleepDeferred = PromiseUtils.defer();
this._sleepTimer.initWithCallback(() => this._sleepDeferred.resolve(),
aTimeMs, Ci.nsITimer.TYPE_ONE_SHOT);
return this._sleepDeferred.promise;
@@ -805,17 +805,17 @@ Search.prototype = {
/**
* Given an array of tokens, this function determines which query should be
* ran. It also removes any special search tokens.
*
* @param tokens
* An array of search tokens.
* @return the filtered list of tokens to search with.
*/
- filterTokens: function (tokens) {
+ filterTokens: function(tokens) {
let foundToken = false;
// Set the proper behavior while filtering tokens.
for (let i = tokens.length - 1; i >= 0; i--) {
let behavior = Prefs.tokenToBehaviorMap.get(tokens[i]);
// Don't remove the token if it didn't match, or if it's an action but
// actions are not enabled.
if (behavior && (behavior != "openpage" || this._enableActions)) {
// Don't use the suggest preferences if it is a token search and
@@ -1376,17 +1376,17 @@ Search.prototype = {
} catch (e) {
// It's possible we don't have a favicon for this - and that's ok.
}
this._addMatch(match);
return true;
},
- _onResultRow: function (row) {
+ _onResultRow: function(row) {
if (this._localMatchesCount == 0) {
TelemetryStopwatch.finish(TELEMETRY_1ST_RESULT, this);
}
let queryType = row.getResultByIndex(QUERYINDEX_QUERYTYPE);
let match;
switch (queryType) {
case QUERYTYPE_AUTOFILL_HOST:
this._result.setDefaultIndex(0);
@@ -1402,17 +1402,17 @@ Search.prototype = {
}
this._addMatch(match);
// If the search has been canceled by the user or by _addMatch, or we
// fetched enough results, we can stop the underlying Sqlite query.
if (!this.pending || this._localMatchesCount == Prefs.maxRichResults)
throw StopIteration;
},
- _maybeRestyleSearchMatch: function (match) {
+ _maybeRestyleSearchMatch: function(match) {
// Return if the URL does not represent a search result.
let parseResult =
PlacesSearchAutocompleteProvider.parseSubmissionURL(match.value);
if (!parseResult) {
return;
}
// Do not apply the special style if the user is doing a search from the
@@ -1503,17 +1503,17 @@ Search.prototype = {
// Append after remote matches.
index = this._localMatchesCount + this._remoteMatchesCount;
}
this._localMatchesCount++;
}
return index;
},
- _processHostRow: function (row) {
+ _processHostRow: function(row) {
let match = {};
let trimmedHost = row.getResultByIndex(QUERYINDEX_URL);
let untrimmedHost = row.getResultByIndex(QUERYINDEX_TITLE);
let frecency = row.getResultByIndex(QUERYINDEX_FRECENCY);
let faviconUrl = row.getResultByIndex(QUERYINDEX_ICONURL);
// If the untrimmed value doesn't preserve the user's input just
// ignore it and complete to the found host.
@@ -1532,17 +1532,17 @@ Search.prototype = {
}
// Although this has a frecency, this query is executed before any other
// queries that would result in frecency matches.
match.frecency = frecency;
match.style = "autofill";
return match;
},
- _processUrlRow: function (row) {
+ _processUrlRow: function(row) {
let match = {};
let value = row.getResultByIndex(QUERYINDEX_URL);
let url = fixupSearchText(value);
let frecency = row.getResultByIndex(QUERYINDEX_FRECENCY);
let faviconUrl = row.getResultByIndex(QUERYINDEX_ICONURL);
let prefix = value.slice(0, value.length - stripPrefix(value).length);
@@ -1574,17 +1574,17 @@ Search.prototype = {
}
// Although this has a frecency, this query is executed before any other
// queries that would result in frecency matches.
match.frecency = frecency;
match.style = "autofill";
return match;
},
- _processRow: function (row) {
+ _processRow: function(row) {
let match = {};
match.placeId = row.getResultByIndex(QUERYINDEX_PLACEID);
let queryType = row.getResultByIndex(QUERYINDEX_QUERYTYPE);
let escapedURL = row.getResultByIndex(QUERYINDEX_URL);
let openPageCount = row.getResultByIndex(QUERYINDEX_SWITCHTAB) || 0;
let historyTitle = row.getResultByIndex(QUERYINDEX_TITLE) || "";
let iconurl = row.getResultByIndex(QUERYINDEX_ICONURL) || "";
let bookmarked = row.getResultByIndex(QUERYINDEX_BOOKMARKED);
@@ -1852,17 +1852,17 @@ Search.prototype = {
},
/**
* Notifies the listener about results.
*
* @param searchOngoing
* Indicates whether the search is ongoing.
*/
- notifyResults: function (searchOngoing) {
+ notifyResults: function(searchOngoing) {
let result = this._result;
let resultCode = result.matchCount ? "RESULT_SUCCESS" : "RESULT_NOMATCH";
if (searchOngoing) {
resultCode += "_ONGOING";
}
result.setSearchResult(Ci.nsIAutoCompleteResult[resultCode]);
this._listener.onSearchResult(this._autocompleteSearch, result);
},
@@ -1890,17 +1890,17 @@ UnifiedComplete.prototype = {
/**
* Gets a Sqlite database handle.
*
* @return {Promise}
* @resolves to the Sqlite database handle (according to Sqlite.jsm).
* @rejects javascript exception.
*/
- getDatabaseHandle: function () {
+ getDatabaseHandle: function() {
if (Prefs.enabled && !this._promiseDatabase) {
this._promiseDatabase = Task.spawn(function* () {
let conn = yield Sqlite.cloneStorageConnection({
connection: PlacesUtils.history.DBConnection,
readOnly: true
});
try {
@@ -1937,17 +1937,17 @@ UnifiedComplete.prototype = {
},
unregisterOpenPage(uri, userContextId) {
SwitchToTabStorage.delete(uri, userContextId);
},
// nsIAutoCompleteSearch
- startSearch: function (searchString, searchParam, previousResult, listener) {
+ startSearch: function(searchString, searchParam, previousResult, listener) {
// Stop the search in case the controller has not taken care of it.
if (this._currentSearch) {
this.stopSearch();
}
// Note: We don't use previousResult to make sure ordering of results are
// consistent. See bug 412730 for more details.
@@ -1976,33 +1976,33 @@ UnifiedComplete.prototype = {
})
.then(() => {
if (search == this._currentSearch) {
this.finishSearch(true);
}
});
},
- stopSearch: function () {
+ stopSearch: function() {
if (this._currentSearch) {
this._currentSearch.stop();
}
// Don't notify since we are canceling this search. This also means we
// won't fire onSearchComplete for this search.
this.finishSearch();
},
/**
* Properly cleans up when searching is completed.
*
* @param notify [optional]
* Indicates if we should notify the AutoComplete listener about our
* results or not.
*/
- finishSearch: function (notify = false) {
+ finishSearch: function(notify = false) {
TelemetryStopwatch.cancel(TELEMETRY_1ST_RESULT, this);
TelemetryStopwatch.cancel(TELEMETRY_6_FIRST_RESULTS, this);
// Clear state now to avoid race conditions, see below.
let search = this._currentSearch;
if (!search)
return;
this._lastLowResultsSearchSuggestion = search._lastLowResultsSearchSuggestion;
delete this._currentSearch;
@@ -2019,17 +2019,17 @@ UnifiedComplete.prototype = {
// notifyResults.
// Thus, ensure that notifyResults is the last call in this method,
// otherwise you might be touching the wrong search.
search.notifyResults(false);
},
// nsIAutoCompleteSimpleResultListener
- onValueRemoved: function (result, spec, removeFromDB) {
+ onValueRemoved: function(result, spec, removeFromDB) {
if (removeFromDB) {
PlacesUtils.history.removePage(NetUtil.newURI(spec));
}
},
// nsIAutoCompleteSearchDescriptor
get searchType() {
--- a/toolkit/components/places/nsLivemarkService.js
+++ b/toolkit/components/places/nsLivemarkService.js
@@ -12,17 +12,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
"resource://gre/modules/NetUtil.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Deprecated",
"resource://gre/modules/Deprecated.jsm");
-XPCOMUtils.defineLazyGetter(this, "asyncHistory", function () {
+XPCOMUtils.defineLazyGetter(this, "asyncHistory", function() {
// Lazily add an history observer when it's actually needed.
PlacesUtils.history.addObserver(PlacesUtils.livemarks, true);
return PlacesUtils.asyncHistory;
});
// Constants
// Delay between reloads of consecute livemarks.
--- a/toolkit/components/places/nsPlacesExpiration.js
+++ b/toolkit/components/places/nsPlacesExpiration.js
@@ -453,17 +453,17 @@ function notify(observers, notification,
}
// nsPlacesExpiration definition
function nsPlacesExpiration()
{
// Smart Getters
- XPCOMUtils.defineLazyGetter(this, "_db", function () {
+ XPCOMUtils.defineLazyGetter(this, "_db", function() {
let db = Cc["@mozilla.org/browser/nav-history-service;1"].
getService(Ci.nsPIPlacesDatabase).
DBConnection;
// Create the temporary notifications table.
let stmt = db.createAsyncStatement(
`CREATE TEMP TABLE expiration_notify (
id INTEGER PRIMARY KEY
@@ -902,17 +902,17 @@ nsPlacesExpiration.prototype = {
this._cachedStatements["LIMIT_COUNT"].executeAsync({
_pagesCount: 0,
_statsCount: 0,
handleResult: function(aResults) {
let row = aResults.getNextRow();
this._pagesCount = row.getResultByIndex(0);
this._statsCount = row.getResultByIndex(1);
},
- handleCompletion: function (aReason) {
+ handleCompletion: function(aReason) {
if (aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) {
aCallback(this._pagesCount, this._statsCount);
}
},
handleError: function(aError) {
Cu.reportError("Async statement execution returned with '" +
aError.result + "', '" + aError.message + "'");
}
--- a/toolkit/components/places/nsTaggingService.js
+++ b/toolkit/components/places/nsTaggingService.js
@@ -453,19 +453,19 @@ TaggingService.prototype = {
onItemMoved: function TS_onItemMoved(aItemId, aOldParent, aOldIndex,
aNewParent, aNewIndex, aItemType) {
if (this._tagFolders[aItemId] && PlacesUtils.tagsFolderId == aOldParent &&
PlacesUtils.tagsFolderId != aNewParent)
delete this._tagFolders[aItemId];
},
- onItemVisited: function () {},
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
+ onItemVisited: function() {},
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
// nsISupports
classID: Components.ID("{bbc23860-2553-479d-8b78-94d9038334f7}"),
_xpcom_factory: XPCOMUtils.generateSingletonFactory(TaggingService),
QueryInterface: XPCOMUtils.generateQI([
--- a/toolkit/components/places/tests/bookmarks/test_393498.js
+++ b/toolkit/components/places/tests/bookmarks/test_393498.js
@@ -2,31 +2,31 @@
/* vim:set ts=2 sw=2 sts=2 et: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var observer = {
__proto__: NavBookmarkObserver.prototype,
- onItemAdded: function (id, folder, index) {
+ onItemAdded: function(id, folder, index) {
this._itemAddedId = id;
this._itemAddedParent = folder;
this._itemAddedIndex = index;
},
- onItemChanged: function (id, property, isAnnotationProperty, value) {
+ onItemChanged: function(id, property, isAnnotationProperty, value) {
this._itemChangedId = id;
this._itemChangedProperty = property;
this._itemChanged_isAnnotationProperty = isAnnotationProperty;
this._itemChangedValue = value;
}
};
PlacesUtils.bookmarks.addObserver(observer, false);
-do_register_cleanup(function () {
+do_register_cleanup(function() {
PlacesUtils.bookmarks.removeObserver(observer);
});
function run_test() {
// We set times in the past to workaround a timing bug due to virtual
// machines and the skew between PR_Now() and Date.now(), see bug 427142 and
// bug 858377 for details.
const PAST_PRTIME = (Date.now() - 86400000) * 1000;
--- a/toolkit/components/places/tests/bookmarks/test_405938_restore_queries.js
+++ b/toolkit/components/places/tests/bookmarks/test_405938_restore_queries.js
@@ -86,17 +86,17 @@ var test = {
options.queryType = options.QUERY_TYPE_BOOKMARKS;
this._queryURI3 =
uri(PlacesUtils.history.queriesToQueryString(queries, queries.length, options));
this._queryTitle3 = "query3";
PlacesUtils.bookmarks.insertBookmark(this._testRootId, this._queryURI3,
DEFAULT_INDEX, this._queryTitle3);
},
- clean: function () {},
+ clean: function() {},
validate: function validate() {
// Throw a wrench in the works by inserting some new bookmarks,
// ensuring folder ids won't be the same, when restoring.
for (let i = 0; i < 10; i++) {
PlacesUtils.bookmarks.
insertBookmark(PlacesUtils.bookmarksMenuFolderId, uri("http://aaaa" + i), DEFAULT_INDEX, "");
}
--- a/toolkit/components/places/tests/bookmarks/test_424958-json-quoted-folders.js
+++ b/toolkit/components/places/tests/bookmarks/test_424958-json-quoted-folders.js
@@ -18,28 +18,28 @@ var myTest = {
this.push(myTest);
*/
var quotesTest = {
_folderTitle: '"quoted folder"',
_folderId: null,
- populate: function () {
+ populate: function() {
this._folderId =
PlacesUtils.bookmarks.createFolder(PlacesUtils.toolbarFolderId,
this._folderTitle,
PlacesUtils.bookmarks.DEFAULT_INDEX);
},
- clean: function () {
+ clean: function() {
PlacesUtils.bookmarks.removeItem(this._folderId);
},
- validate: function () {
+ validate: function() {
var query = PlacesUtils.history.getNewQuery();
query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
var result = PlacesUtils.history.executeQuery(query, PlacesUtils.history.getNewQueryOptions());
var toolbar = result.root;
toolbar.containerOpen = true;
// test for our quoted folder
--- a/toolkit/components/places/tests/bookmarks/test_448584.js
+++ b/toolkit/components/places/tests/bookmarks/test_448584.js
@@ -20,35 +20,35 @@ catch (ex) {
- don't try to add invalid uri nodes to a JSON backup
*/
var invalidURITest = {
_itemTitle: "invalid uri",
_itemUrl: "http://test.mozilla.org/",
_itemId: null,
- populate: function () {
+ populate: function() {
// add a valid bookmark
PlacesUtils.bookmarks.insertBookmark(PlacesUtils.toolbarFolderId,
PlacesUtils._uri(this._itemUrl),
PlacesUtils.bookmarks.DEFAULT_INDEX,
this._itemTitle);
// this bookmark will go corrupt
this._itemId =
PlacesUtils.bookmarks.insertBookmark(PlacesUtils.toolbarFolderId,
PlacesUtils._uri(this._itemUrl),
PlacesUtils.bookmarks.DEFAULT_INDEX,
this._itemTitle);
},
- clean: function () {
+ clean: function() {
PlacesUtils.bookmarks.removeItem(this._itemId);
},
- validate: function (aExpectValidItemsCount) {
+ validate: function(aExpectValidItemsCount) {
var query = PlacesUtils.history.getNewQuery();
query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
var options = PlacesUtils.history.getNewQueryOptions();
var result = PlacesUtils.history.executeQuery(query, options);
var toolbar = result.root;
toolbar.containerOpen = true;
--- a/toolkit/components/places/tests/bookmarks/test_458683.js
+++ b/toolkit/components/places/tests/bookmarks/test_458683.js
@@ -23,17 +23,17 @@ catch (ex) {
var invalidTagChildTest = {
_itemTitle: "invalid uri",
_itemUrl: "http://test.mozilla.org/",
_itemId: -1,
_tag: "testTag",
_tagItemId: -1,
- populate: function () {
+ populate: function() {
// add a valid bookmark
this._itemId = PlacesUtils.bookmarks
.insertBookmark(PlacesUtils.toolbarFolderId,
PlacesUtils._uri(this._itemUrl),
PlacesUtils.bookmarks.DEFAULT_INDEX,
this._itemTitle);
// create a tag
@@ -61,22 +61,22 @@ var invalidTagChildTest = {
// add a separator and a folder inside tag root
PlacesUtils.bookmarks.insertSeparator(PlacesUtils.bookmarks.tagsFolder,
PlacesUtils.bookmarks.DEFAULT_INDEX);
PlacesUtils.bookmarks.createFolder(PlacesUtils.bookmarks.tagsFolder,
"test tags root folder",
PlacesUtils.bookmarks.DEFAULT_INDEX);
},
- clean: function () {
+ clean: function() {
PlacesUtils.tagging.untagURI(PlacesUtils._uri(this._itemUrl), [this._tag]);
PlacesUtils.bookmarks.removeItem(this._itemId);
},
- validate: function () {
+ validate: function() {
var query = PlacesUtils.history.getNewQuery();
query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
var options = PlacesUtils.history.getNewQueryOptions();
var result = PlacesUtils.history.executeQuery(query, options);
var toolbar = result.root;
toolbar.containerOpen = true;
--- a/toolkit/components/places/tests/bookmarks/test_711914.js
+++ b/toolkit/components/places/tests/bookmarks/test_711914.js
@@ -14,17 +14,17 @@ function run_test() {
}
let observer = {
onBeginUpdateBatch: () => forceBookmarkCaching(itemId1),
onEndUpdateBatch: () => forceBookmarkCaching(itemId1),
onItemAdded: forceBookmarkCaching,
onItemChanged: forceBookmarkCaching,
onItemMoved: forceBookmarkCaching,
- onItemRemoved: function (id) {
+ onItemRemoved: function(id) {
try {
forceBookmarkCaching(id);
do_throw("trying to fetch a removed bookmark should throw");
} catch (ex) {}
},
onItemVisited: forceBookmarkCaching,
QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
};
--- a/toolkit/components/places/tests/bookmarks/test_async_observers.js
+++ b/toolkit/components/places/tests/bookmarks/test_async_observers.js
@@ -13,28 +13,28 @@ var observer = {
deferred: null,
/**
* Returns a promise that is resolved when the observer determines that the
* test can continue. This is required rather than calling run_next_test
* directly in the observer because there are cases where we must wait for
* other asynchronous events to be completed in addition to this.
*/
- setupCompletionPromise: function ()
+ setupCompletionPromise: function()
{
this.observedBookmarks = 0;
this.deferred = Promise.defer();
return this.deferred.promise;
},
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onItemAdded: function () {},
- onItemRemoved: function () {},
- onItemMoved: function () {},
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onItemAdded: function() {},
+ onItemRemoved: function() {},
+ onItemMoved: function() {},
onItemChanged: function(aItemId, aProperty, aIsAnnotation, aNewValue,
aLastModified, aItemType)
{
do_print("Check that we got the correct change information.");
do_check_neq(this.bookmarks.indexOf(aItemId), -1);
if (aProperty == "favicon") {
do_check_false(aIsAnnotation);
do_check_eq(aNewValue, SMALLPNG_DATA_URI.spec);
@@ -81,17 +81,17 @@ add_task(function* test_add_visit()
let deferUpdatePlaces = Promise.defer();
PlacesUtils.asyncHistory.updatePlaces({
uri: NetUtil.newURI("http://book.ma.rk/"),
visits: [{ transitionType: TRANSITION_TYPED, visitDate: NOW }]
}, {
handleError: function TAV_handleError() {
deferUpdatePlaces.reject(new Error("Unexpected error in adding visit."));
},
- handleResult: function (aPlaceInfo) {
+ handleResult: function(aPlaceInfo) {
visitId = aPlaceInfo.visits[0].visitId;
},
handleCompletion: function TAV_handleCompletion() {
deferUpdatePlaces.resolve();
}
});
// Wait for both the observer and the asynchronous update, in any order.
--- a/toolkit/components/places/tests/bookmarks/test_nsINavBookmarkObserver.js
+++ b/toolkit/components/places/tests/bookmarks/test_nsINavBookmarkObserver.js
@@ -8,17 +8,17 @@ const GUID_RE = /^[a-zA-Z0-9\-_]{12}$/;
var gBookmarksObserver = {
expected: [],
setup(expected) {
this.expected = expected;
this.deferred = PromiseUtils.defer();
return this.deferred.promise;
},
- validate: function (aMethodName, aArguments) {
+ validate: function(aMethodName, aArguments) {
do_check_eq(this.expected[0].name, aMethodName);
let args = this.expected.shift().args;
do_check_eq(aArguments.length, args.length);
for (let i = 0; i < aArguments.length; i++) {
do_check_true(args[i].check(aArguments[i]), aMethodName + "(args[" + i + "]: " + args[i].name + ")");
}
@@ -59,17 +59,17 @@ var gBookmarkSkipObserver = {
skipDescendantsOnItemRemoval: true,
expected: null,
setup(expected) {
this.expected = expected;
this.deferred = PromiseUtils.defer();
return this.deferred.promise;
},
- validate: function (aMethodName) {
+ validate: function(aMethodName) {
do_check_eq(this.expected.shift(), aMethodName);
if (this.expected.length === 0) {
this.deferred.resolve();
}
},
// nsINavBookmarkObserver
onBeginUpdateBatch() {
@@ -111,17 +111,17 @@ add_task(function* batch() {
args: [] },
{ name: "onEndUpdateBatch",
args: [] },
]),
gBookmarkSkipObserver.setup([
"onBeginUpdateBatch", "onEndUpdateBatch"
])]);
PlacesUtils.bookmarks.runInBatchMode({
- runBatched: function () {
+ runBatched: function() {
// Nothing.
}
}, null);
yield promise;
});
add_task(function* onItemAdded_bookmark() {
const TITLE = "Bookmark 1";
--- a/toolkit/components/places/tests/browser/browser_bug399606.js
+++ b/toolkit/components/places/tests/browser/browser_bug399606.js
@@ -16,31 +16,31 @@ function test() {
"http://example.com/tests/toolkit/components/places/tests/browser/399606-window.location.html",
];
var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
getService(Ci.nsINavHistoryService);
// Create and add history observer.
var historyObserver = {
visitCount: Array(),
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID,
aTransitionType) {
info("Received onVisit: " + aURI.spec);
if (aURI.spec in this.visitCount)
this.visitCount[aURI.spec]++;
else
this.visitCount[aURI.spec] = 1;
},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
+ onTitleChanged: function() {},
+ onDeleteURI: function() {},
+ onClearHistory: function() {},
+ onPageChanged: function() {},
+ onDeleteVisits: function() {},
QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
};
hs.addObserver(historyObserver, false);
function confirm_results() {
gBrowser.removeCurrentTab();
hs.removeObserver(historyObserver, false);
for (let aURI in historyObserver.visitCount) {
--- a/toolkit/components/places/tests/browser/browser_double_redirect.js
+++ b/toolkit/components/places/tests/browser/browser_double_redirect.js
@@ -9,17 +9,17 @@ add_task(function* () {
const TEST_URI = NetUtil.newURI(BASE_URL + "begin.html");
const FIRST_REDIRECTING_URI = NetUtil.newURI(BASE_URL + "redirect_twice.sjs");
const FINAL_URI = NetUtil.newURI(BASE_URL + "final.html");
let promiseVisits = new Promise(resolve => {
PlacesUtils.history.addObserver({
__proto__: NavHistoryObserver.prototype,
_notified: [],
- onVisit: function (uri, id, time, sessionId, referrerId, transition) {
+ onVisit: function(uri, id, time, sessionId, referrerId, transition) {
info("Received onVisit: " + uri.spec);
this._notified.push(uri);
if (!uri.equals(FINAL_URI)) {
return;
}
is(this._notified.length, 4);
--- a/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage.js
+++ b/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage.js
@@ -61,17 +61,17 @@ function test() {
waitForFaviconChanged(pageURI, favIconURI, aWindow,
function testNormalCallback() {
checkFaviconDataForPage(pageURI, favIconMimeType, favIconData, aWindow,
aCallback);
}
);
addVisits({uri: pageURI, transition: TRANSITION_TYPED}, aWindow,
- function () {
+ function() {
aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI, favIconURI,
true, aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
Services.scriptSecurityManager.getSystemPrincipal());
}
);
}
function testAboutURIBookmarked(aWindow, aCallback) {
@@ -128,23 +128,23 @@ function test() {
Services.scriptSecurityManager.getSystemPrincipal());
// The setAndFetchFaviconForPage function calls CanAddURI synchronously, thus
// we can set the preference back to true immediately. We don't clear the
// preference because not all products enable Places by default.
aWindow.Services.prefs.setBoolPref("places.history.enabled", true);
}
- getIconFile(function () {
+ getIconFile(function() {
testOnWindow({}, function(aWin) {
- testNormal(aWin, function () {
+ testNormal(aWin, function() {
testOnWindow({}, function(aWin2) {
- testAboutURIBookmarked(aWin2, function () {
+ testAboutURIBookmarked(aWin2, function() {
testOnWindow({private: true}, function(aWin3) {
- testPrivateBrowsingBookmarked(aWin3, function () {
+ testPrivateBrowsingBookmarked(aWin3, function() {
testOnWindow({}, function(aWin4) {
testDisabledHistoryBookmarked(aWin4, finish);
});
});
});
});
});
});
--- a/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage_failures.js
+++ b/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage_failures.js
@@ -101,32 +101,32 @@ function test() {
if (aCallback) {
aCallback();
}
}
function testPrivateBrowsingNonBookmarkedURI(aWindow, aCallback) {
let pageURI = NetUtil.newURI("http://example.com/privateBrowsing");
addVisits({ uri: pageURI, transitionType: TRANSITION_TYPED }, aWindow,
- function () {
+ function() {
aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI,
favIcon16URI, true,
aWindow.PlacesUtils.favicons.FAVICON_LOAD_PRIVATE, null,
Services.scriptSecurityManager.getSystemPrincipal());
if (aCallback) {
aCallback();
}
});
}
function testDisabledHistory(aWindow, aCallback) {
let pageURI = NetUtil.newURI("http://example.com/disabledHistory");
addVisits({ uri: pageURI, transition: TRANSITION_TYPED }, aWindow,
- function () {
+ function() {
aWindow.Services.prefs.setBoolPref("places.history.enabled", false);
aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI,
favIcon16URI, true,
aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
Services.scriptSecurityManager.getSystemPrincipal());
// The setAndFetchFaviconForPage function calls CanAddURI synchronously, thus
@@ -139,17 +139,17 @@ function test() {
}
});
}
function testErrorIcon(aWindow, aCallback) {
let pageURI = NetUtil.newURI("http://example.com/errorIcon");
let places = [{ uri: pageURI, transition: TRANSITION_TYPED }];
addVisits({ uri: pageURI, transition: TRANSITION_TYPED }, aWindow,
- function () {
+ function() {
aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI,
favIconErrorPageURI, true,
aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
Services.scriptSecurityManager.getSystemPrincipal());
if (aCallback) {
aCallback();
}
@@ -211,35 +211,35 @@ function test() {
});
stmt.finalize();
});
// This is the only test that should cause the waitForFaviconChanged
// callback to be invoked. In turn, the callback will invoke
// finish() causing the tests to finish.
addVisits({ uri: lastPageURI, transition: TRANSITION_TYPED }, aWindow,
- function () {
+ function() {
aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(lastPageURI,
favIcon32URI, true,
aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
Services.scriptSecurityManager.getSystemPrincipal());
});
}
- checkFavIconsDBCount(function () {
+ checkFavIconsDBCount(function() {
testOnWindow({}, function(aWin) {
- testNullPageURI(aWin, function () {
+ testNullPageURI(aWin, function() {
testOnWindow({}, function(aWin2) {
testNullFavIconURI(aWin2, function() {
testOnWindow({}, function(aWin3) {
testAboutURI(aWin3, function() {
testOnWindow({private: true}, function(aWin4) {
- testPrivateBrowsingNonBookmarkedURI(aWin4, function () {
+ testPrivateBrowsingNonBookmarkedURI(aWin4, function() {
testOnWindow({}, function(aWin5) {
- testDisabledHistory(aWin5, function () {
+ testDisabledHistory(aWin5, function() {
testOnWindow({}, function(aWin6) {
testErrorIcon(aWin6, function() {
testOnWindow({}, function(aWin7) {
testNonExistingPage(aWin7, function() {
testOnWindow({}, function(aWin8) {
testFinalVerification(aWin8, function() {
finish();
});
--- a/toolkit/components/places/tests/browser/browser_notfound.js
+++ b/toolkit/components/places/tests/browser/browser_notfound.js
@@ -6,38 +6,38 @@ add_task(function* () {
const TEST_URL = "http://mochi.test:8888/notFoundPage.html";
// Used to verify errors are not marked as typed.
PlacesUtils.history.markPageAsTyped(NetUtil.newURI(TEST_URL));
// Create and add history observer.
let visitedPromise = new Promise(resolve => {
let historyObserver = {
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
+ onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID,
aTransitionType) {
PlacesUtils.history.removeObserver(historyObserver);
info("Received onVisit: " + aURI.spec);
- fieldForUrl(aURI, "frecency", function (aFrecency) {
+ fieldForUrl(aURI, "frecency", function(aFrecency) {
is(aFrecency, 0, "Frecency should be 0");
- fieldForUrl(aURI, "hidden", function (aHidden) {
+ fieldForUrl(aURI, "hidden", function(aHidden) {
is(aHidden, 0, "Page should not be hidden");
- fieldForUrl(aURI, "typed", function (aTyped) {
+ fieldForUrl(aURI, "typed", function(aTyped) {
is(aTyped, 0, "page should not be marked as typed");
resolve();
});
});
});
},
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onTitleChanged: function() {},
+ onDeleteURI: function() {},
+ onClearHistory: function() {},
+ onPageChanged: function() {},
+ onDeleteVisits: function() {},
QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
};
PlacesUtils.history.addObserver(historyObserver, false);
});
let newTabPromise = BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
yield Promise.all([visitedPromise, newTabPromise]);
--- a/toolkit/components/places/tests/browser/browser_redirect.js
+++ b/toolkit/components/places/tests/browser/browser_redirect.js
@@ -5,54 +5,54 @@
add_task(function* () {
const REDIRECT_URI = NetUtil.newURI("http://mochi.test:8888/tests/toolkit/components/places/tests/browser/redirect.sjs");
const TARGET_URI = NetUtil.newURI("http://mochi.test:8888/tests/toolkit/components/places/tests/browser/redirect-target.html");
// Create and add history observer.
let visitedPromise = new Promise(resolve => {
let historyObserver = {
_redirectNotified: false,
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
+ onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID,
aTransitionType) {
info("Received onVisit: " + aURI.spec);
if (aURI.equals(REDIRECT_URI)) {
this._redirectNotified = true;
// Wait for the target page notification.
return;
}
PlacesUtils.history.removeObserver(historyObserver);
ok(this._redirectNotified, "The redirect should have been notified");
- fieldForUrl(REDIRECT_URI, "frecency", function (aFrecency) {
+ fieldForUrl(REDIRECT_URI, "frecency", function(aFrecency) {
ok(aFrecency != 0, "Frecency or the redirecting page should not be 0");
- fieldForUrl(REDIRECT_URI, "hidden", function (aHidden) {
+ fieldForUrl(REDIRECT_URI, "hidden", function(aHidden) {
is(aHidden, 1, "The redirecting page should be hidden");
- fieldForUrl(TARGET_URI, "frecency", function (aFrecency2) {
+ fieldForUrl(TARGET_URI, "frecency", function(aFrecency2) {
ok(aFrecency2 != 0, "Frecency of the target page should not be 0");
- fieldForUrl(TARGET_URI, "hidden", function (aHidden2) {
+ fieldForUrl(TARGET_URI, "hidden", function(aHidden2) {
is(aHidden2, 0, "The target page should not be hidden");
resolve();
});
});
});
});
},
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onTitleChanged: function() {},
+ onDeleteURI: function() {},
+ onClearHistory: function() {},
+ onPageChanged: function() {},
+ onDeleteVisits: function() {},
QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
};
PlacesUtils.history.addObserver(historyObserver, false);
});
let newTabPromise = BrowserTestUtils.openNewForegroundTab(gBrowser, REDIRECT_URI.spec);
yield Promise.all([visitedPromise, newTabPromise]);
--- a/toolkit/components/places/tests/browser/browser_visited_notfound.js
+++ b/toolkit/components/places/tests/browser/browser_visited_notfound.js
@@ -26,25 +26,25 @@ function test() {
function continueTest(aOldFrecency) {
// Used to verify errors are not marked as typed.
PlacesUtils.history.markPageAsTyped(TEST_URI);
gBrowser.selectedBrowser.loadURI(TEST_URI.spec);
// Create and add history observer.
let historyObserver = {
__proto__: NavHistoryObserver.prototype,
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
+ onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID,
aTransitionType) {
PlacesUtils.history.removeObserver(historyObserver);
info("Received onVisit: " + aURI.spec);
- fieldForUrl(aURI, "frecency", function (aFrecency) {
+ fieldForUrl(aURI, "frecency", function(aFrecency) {
is(aFrecency, aOldFrecency, "Frecency should be unchanged");
- fieldForUrl(aURI, "hidden", function (aHidden) {
+ fieldForUrl(aURI, "hidden", function(aHidden) {
is(aHidden, 0, "Page should not be hidden");
- fieldForUrl(aURI, "typed", function (aTyped) {
+ fieldForUrl(aURI, "typed", function(aTyped) {
is(aTyped, 0, "page should not be marked as typed");
PlacesTestUtils.clearHistory().then(finish);
});
});
});
}
};
PlacesUtils.history.addObserver(historyObserver, false);
--- a/toolkit/components/places/tests/browser/browser_visituri_privatebrowsing_perwindowpb.js
+++ b/toolkit/components/places/tests/browser/browser_visituri_privatebrowsing_perwindowpb.js
@@ -60,15 +60,15 @@ function test() {
});
});
// test first when on private mode
testOnWindow({private: true}, function(aWin) {
doTest(true, aWin, initialURL, function() {
// then test when not on private mode
testOnWindow({}, function(aWin2) {
- doTest(false, aWin2, finalURL, function () {
+ doTest(false, aWin2, finalURL, function() {
PlacesTestUtils.clearHistory().then(finish);
});
});
});
});
}
--- a/toolkit/components/places/tests/browser/head.js
+++ b/toolkit/components/places/tests/browser/head.js
@@ -51,24 +51,24 @@ function fieldForUrl(aURI, aFieldName, a
/**
* Generic nsINavHistoryObserver that doesn't implement anything, but provides
* dummy methods to prevent errors about an object not having a certain method.
*/
function NavHistoryObserver() {}
NavHistoryObserver.prototype = {
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function () {},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onVisit: function() {},
+ onTitleChanged: function() {},
+ onDeleteURI: function() {},
+ onClearHistory: function() {},
+ onPageChanged: function() {},
+ onDeleteVisits: function() {},
QueryInterface: XPCOMUtils.generateQI([
Ci.nsINavHistoryObserver,
])
};
/**
* Waits for the first OnPageChanged notification for ATTRIBUTE_FAVICON, and
* verifies that it matches the expected page URI and associated favicon URI.
@@ -151,17 +151,17 @@ function addVisits(aPlaceInfo, aWindow,
}
aWindow.PlacesUtils.asyncHistory.updatePlaces(
places,
{
handleError: function AAV_handleError() {
throw ("Unexpected error in adding visit.");
},
- handleResult: function () {},
+ handleResult: function() {},
handleCompletion: function UP_handleCompletion() {
if (aCallback)
aCallback();
}
}
);
}
@@ -175,17 +175,17 @@ function addVisits(aPlaceInfo, aWindow,
* @param aExpectedData
* Expected icon data, expressed as an array of byte values.
* @param aCallback
* This function is called after the check finished.
*/
function checkFaviconDataForPage(aPageURI, aExpectedMimeType, aExpectedData,
aWindow, aCallback) {
aWindow.PlacesUtils.favicons.getFaviconDataForPage(aPageURI,
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
is(aExpectedMimeType, aMimeType, "Check expected MimeType");
is(aExpectedData.length, aData.length,
"Check favicon data for the given page matches the provided data");
checkGuidForURI(aPageURI);
aCallback();
});
}
--- a/toolkit/components/places/tests/favicons/head_favicons.js
+++ b/toolkit/components/places/tests/favicons/head_favicons.js
@@ -67,17 +67,17 @@ function waitForFaviconChanged(aExpected
* @param aExpectedData
* Expected icon data, expressed as an array of byte values.
* @param aCallback
* This function is called after the check finished.
*/
function checkFaviconDataForPage(aPageURI, aExpectedMimeType, aExpectedData,
aCallback) {
PlacesUtils.favicons.getFaviconDataForPage(aPageURI,
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
do_check_eq(aExpectedMimeType, aMimeType);
do_check_true(compareArrays(aExpectedData, aData));
do_check_guid_for_uri(aPageURI);
aCallback();
});
}
/**
@@ -85,17 +85,17 @@ function checkFaviconDataForPage(aPageUR
*
* @param aPageURI
* nsIURI object for the page to check.
* @param aCallback
* This function is called after the check finished.
*/
function checkFaviconMissingForPage(aPageURI, aCallback) {
PlacesUtils.favicons.getFaviconURLForPage(aPageURI,
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
do_check_true(aURI === null);
aCallback();
});
}
function promiseFaviconMissingForPage(aPageURI) {
return new Promise(resolve => checkFaviconMissingForPage(aPageURI, resolve));
}
--- a/toolkit/components/places/tests/favicons/test_favicons_conversions.js
+++ b/toolkit/components/places/tests/favicons/test_favicons_conversions.js
@@ -29,17 +29,17 @@ var isWindows = ("@mozilla.org/windows-r
* @param aCallback
* This function is called after the check finished.
*/
function checkFaviconDataConversion(aFileName, aFileMimeType, aFileLength,
aExpectConversion, aVaryOnWindows,
aCallback) {
let pageURI = NetUtil.newURI("http://places.test/page/" + aFileName);
PlacesTestUtils.addVisits({ uri: pageURI, transition: TRANSITION_TYPED }).then(
- function () {
+ function() {
let faviconURI = NetUtil.newURI("http://places.test/icon/" + aFileName);
let fileData = readFileOfLength(aFileName, aFileLength);
PlacesUtils.favicons.replaceFaviconData(faviconURI, fileData, fileData.length,
aFileMimeType);
PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI, faviconURI, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
function CFDC_verify(aURI, aDataLen, aData, aMimeType) {
--- a/toolkit/components/places/tests/favicons/test_getFaviconDataForPage.js
+++ b/toolkit/components/places/tests/favicons/test_getFaviconDataForPage.js
@@ -19,39 +19,39 @@ function run_test()
do_check_eq(FAVICON_DATA.length, 344);
run_next_test();
}
add_test(function test_normal()
{
let pageURI = NetUtil.newURI("http://example.com/normal");
- PlacesTestUtils.addVisits(pageURI).then(function () {
+ PlacesTestUtils.addVisits(pageURI).then(function() {
PlacesUtils.favicons.setAndFetchFaviconForPage(
pageURI, FAVICON_URI, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function () {
+ function() {
PlacesUtils.favicons.getFaviconDataForPage(pageURI,
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
do_check_true(aURI.equals(FAVICON_URI));
do_check_eq(FAVICON_DATA.length, aDataLen);
do_check_true(compareArrays(FAVICON_DATA, aData));
do_check_eq(FAVICON_MIMETYPE, aMimeType);
run_next_test();
});
}, Services.scriptSecurityManager.getSystemPrincipal());
});
});
add_test(function test_missing()
{
let pageURI = NetUtil.newURI("http://example.com/missing");
PlacesUtils.favicons.getFaviconDataForPage(pageURI,
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
// Check also the expected data types.
do_check_true(aURI === null);
do_check_true(aDataLen === 0);
do_check_true(aData.length === 0);
do_check_true(aMimeType === "");
run_next_test();
});
});
--- a/toolkit/components/places/tests/favicons/test_getFaviconURLForPage.js
+++ b/toolkit/components/places/tests/favicons/test_getFaviconURLForPage.js
@@ -11,23 +11,23 @@ function run_test()
{
run_next_test();
}
add_test(function test_normal()
{
let pageURI = NetUtil.newURI("http://example.com/normal");
- PlacesTestUtils.addVisits(pageURI).then(function () {
+ PlacesTestUtils.addVisits(pageURI).then(function() {
PlacesUtils.favicons.setAndFetchFaviconForPage(
pageURI, SMALLPNG_DATA_URI, true,
PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function () {
+ function() {
PlacesUtils.favicons.getFaviconURLForPage(pageURI,
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
do_check_true(aURI.equals(SMALLPNG_DATA_URI));
// Check also the expected data types.
do_check_true(aDataLen === 0);
do_check_true(aData.length === 0);
do_check_true(aMimeType === "");
run_next_test();
});
@@ -35,17 +35,17 @@ add_test(function test_normal()
});
});
add_test(function test_missing()
{
let pageURI = NetUtil.newURI("http://example.com/missing");
PlacesUtils.favicons.getFaviconURLForPage(pageURI,
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
// Check also the expected data types.
do_check_true(aURI === null);
do_check_true(aDataLen === 0);
do_check_true(aData.length === 0);
do_check_true(aMimeType === "");
run_next_test();
});
});
--- a/toolkit/components/places/tests/head_common.js
+++ b/toolkit/components/places/tests/head_common.js
@@ -744,72 +744,72 @@ function do_compare_arrays(a1, a2, sorte
/**
* Generic nsINavBookmarkObserver that doesn't implement anything, but provides
* dummy methods to prevent errors about an object not having a certain method.
*/
function NavBookmarkObserver() {}
NavBookmarkObserver.prototype = {
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onItemAdded: function () {},
- onItemRemoved: function () {},
- onItemChanged: function () {},
- onItemVisited: function () {},
- onItemMoved: function () {},
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onItemAdded: function() {},
+ onItemRemoved: function() {},
+ onItemChanged: function() {},
+ onItemVisited: function() {},
+ onItemMoved: function() {},
QueryInterface: XPCOMUtils.generateQI([
Ci.nsINavBookmarkObserver,
])
};
/**
* Generic nsINavHistoryObserver that doesn't implement anything, but provides
* dummy methods to prevent errors about an object not having a certain method.
*/
function NavHistoryObserver() {}
NavHistoryObserver.prototype = {
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function () {},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onVisit: function() {},
+ onTitleChanged: function() {},
+ onDeleteURI: function() {},
+ onClearHistory: function() {},
+ onPageChanged: function() {},
+ onDeleteVisits: function() {},
QueryInterface: XPCOMUtils.generateQI([
Ci.nsINavHistoryObserver,
])
};
/**
* Generic nsINavHistoryResultObserver that doesn't implement anything, but
* provides dummy methods to prevent errors about an object not having a certain
* method.
*/
function NavHistoryResultObserver() {}
NavHistoryResultObserver.prototype = {
- batching: function () {},
- containerStateChanged: function () {},
- invalidateContainer: function () {},
- nodeAnnotationChanged: function () {},
- nodeDateAddedChanged: function () {},
- nodeHistoryDetailsChanged: function () {},
- nodeIconChanged: function () {},
- nodeInserted: function () {},
- nodeKeywordChanged: function () {},
- nodeLastModifiedChanged: function () {},
- nodeMoved: function () {},
- nodeRemoved: function () {},
- nodeTagsChanged: function () {},
- nodeTitleChanged: function () {},
- nodeURIChanged: function () {},
- sortingChanged: function () {},
+ batching: function() {},
+ containerStateChanged: function() {},
+ invalidateContainer: function() {},
+ nodeAnnotationChanged: function() {},
+ nodeDateAddedChanged: function() {},
+ nodeHistoryDetailsChanged: function() {},
+ nodeIconChanged: function() {},
+ nodeInserted: function() {},
+ nodeKeywordChanged: function() {},
+ nodeLastModifiedChanged: function() {},
+ nodeMoved: function() {},
+ nodeRemoved: function() {},
+ nodeTagsChanged: function() {},
+ nodeTitleChanged: function() {},
+ nodeURIChanged: function() {},
+ sortingChanged: function() {},
QueryInterface: XPCOMUtils.generateQI([
Ci.nsINavHistoryResultObserver,
])
};
/**
* Asynchronously check a url is visited.
*
--- a/toolkit/components/places/tests/queries/test_async.js
+++ b/toolkit/components/places/tests/queries/test_async.js
@@ -4,64 +4,64 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var tests = [
{
desc: "nsNavHistoryFolderResultNode: Basic test, asynchronously open and " +
"close container with a single child",
- loading: function (node, newState, oldState) {
+ loading: function(node, newState, oldState) {
this.checkStateChanged("loading", 1);
this.checkArgs("loading", node, oldState, node.STATE_CLOSED);
},
- opened: function (node, newState, oldState) {
+ opened: function(node, newState, oldState) {
this.checkStateChanged("opened", 1);
this.checkState("loading", 1);
this.checkArgs("opened", node, oldState, node.STATE_LOADING);
print("Checking node children");
compareArrayToResult(this.data, node);
print("Closing container");
node.containerOpen = false;
},
- closed: function (node, newState, oldState) {
+ closed: function(node, newState, oldState) {
this.checkStateChanged("closed", 1);
this.checkState("opened", 1);
this.checkArgs("closed", node, oldState, node.STATE_OPENED);
this.success();
}
},
{
desc: "nsNavHistoryFolderResultNode: After async open and no changes, " +
"second open should be synchronous",
- loading: function (node, newState, oldState) {
+ loading: function(node, newState, oldState) {
this.checkStateChanged("loading", 1);
this.checkState("closed", 0);
this.checkArgs("loading", node, oldState, node.STATE_CLOSED);
},
- opened: function (node, newState, oldState) {
+ opened: function(node, newState, oldState) {
let cnt = this.checkStateChanged("opened", 1, 2);
let expectOldState = cnt === 1 ? node.STATE_LOADING : node.STATE_CLOSED;
this.checkArgs("opened", node, oldState, expectOldState);
print("Checking node children");
compareArrayToResult(this.data, node);
print("Closing container");
node.containerOpen = false;
},
- closed: function (node, newState, oldState) {
+ closed: function(node, newState, oldState) {
let cnt = this.checkStateChanged("closed", 1, 2);
this.checkArgs("closed", node, oldState, node.STATE_OPENED);
switch (cnt) {
case 1:
node.containerOpen = true;
break;
case 2:
@@ -70,28 +70,28 @@ var tests = [
}
}
},
{
desc: "nsNavHistoryFolderResultNode: After closing container in " +
"loading(), opened() should not be called",
- loading: function (node, newState, oldState) {
+ loading: function(node, newState, oldState) {
this.checkStateChanged("loading", 1);
this.checkArgs("loading", node, oldState, node.STATE_CLOSED);
print("Closing container");
node.containerOpen = false;
},
- opened: function (node, newState, oldState) {
+ opened: function(node, newState, oldState) {
do_throw("opened should not be called");
},
- closed: function (node, newState, oldState) {
+ closed: function(node, newState, oldState) {
this.checkStateChanged("closed", 1);
this.checkState("loading", 1);
this.checkArgs("closed", node, oldState, node.STATE_LOADING);
this.success();
}
}
];
@@ -117,17 +117,17 @@ Test.prototype = {
* The name of the new state. Used only for printing out helpful info.
* @param aNode
* The node argument passed to containerStateChanged.
* @param aOldState
* The old state argument passed to containerStateChanged.
* @param aExpectOldState
* The expected old state.
*/
- checkArgs: function (aNewState, aNode, aOldState, aExpectOldState) {
+ checkArgs: function(aNewState, aNode, aOldState, aExpectOldState) {
print("Node passed on " + aNewState + " should be result.root");
do_check_eq(this.result.root, aNode);
print("Old state passed on " + aNewState + " should be " + aExpectOldState);
// aOldState comes from xpconnect and will therefore be defined. It may be
// zero, though, so use strict equality just to make sure aExpectOldState is
// also defined.
do_check_true(aOldState === aExpectOldState);
@@ -136,17 +136,17 @@ Test.prototype = {
/**
* Call this when an observer observes a container state change. It registers
* the state change and ensures that it has been observed the given number
* of times. See checkState for parameter explanations.
*
* @return The number of times aState has been observed, including the new
* observation.
*/
- checkStateChanged: function (aState, aExpectedMin, aExpectedMax) {
+ checkStateChanged: function(aState, aExpectedMin, aExpectedMax) {
print(aState + " state change observed");
if (!this.stateCounts.hasOwnProperty(aState))
this.stateCounts[aState] = 0;
this.stateCounts[aState]++;
return this.checkState(aState, aExpectedMin, aExpectedMax);
},
/**
@@ -158,17 +158,17 @@ Test.prototype = {
* The state must have been observed at least this number of times.
* @param aExpectedMax
* The state must have been observed at most this number of times.
* This parameter is optional. If undefined, it's set to
* aExpectedMin.
* @return The number of times aState has been observed, including the new
* observation.
*/
- checkState: function (aState, aExpectedMin, aExpectedMax) {
+ checkState: function(aState, aExpectedMin, aExpectedMax) {
let cnt = this.stateCounts[aState] || 0;
if (aExpectedMax === undefined)
aExpectedMax = aExpectedMin;
if (aExpectedMin === aExpectedMax) {
print(aState + " should be observed only " + aExpectedMin +
" times (actual = " + cnt + ")");
}
else {
@@ -178,22 +178,22 @@ Test.prototype = {
}
do_check_true(cnt >= aExpectedMin && cnt <= aExpectedMax);
return cnt;
},
/**
* Asynchronously opens the root of the test's result.
*/
- openContainer: function () {
+ openContainer: function() {
// Set up the result observer. It delegates to this object's callbacks and
// wraps them in a try-catch so that errors don't get eaten.
let self = this;
this.observer = {
- containerStateChanged: function (container, oldState, newState) {
+ containerStateChanged: function(container, oldState, newState) {
print("New state passed to containerStateChanged() should equal the " +
"container's current state");
do_check_eq(newState, container.state);
try {
switch (newState) {
case Ci.nsINavHistoryContainerResultNode.STATE_LOADING:
self.loading(container, newState, oldState);
@@ -217,17 +217,17 @@ Test.prototype = {
print("Opening container");
this.result.root.containerOpen = true;
},
/**
* Starts the test and returns a promise resolved when the test completes.
*/
- run: function () {
+ run: function() {
this.openContainer();
return this.deferNextTest.promise;
},
/**
* This must be called before run(). It adds a bookmark and sets up the
* test's result. Override if need be.
*/
@@ -248,17 +248,17 @@ Test.prototype = {
this.opts.asyncEnabled = true;
this.result = PlacesUtils.history.executeQuery(this.query, this.opts);
},
/**
* Call this when the test has succeeded. It cleans up resources and starts
* the next test.
*/
- success: function () {
+ success: function() {
this.result.removeObserver(this.observer);
// Resolve the promise object that indicates that the next test can be run.
this.deferNextTest.resolve();
}
};
/**
@@ -290,17 +290,17 @@ var DataHelper = {
* format required by task_populateDB() in head_queries.js.
*
* @param aData
* An array of objects, each of which describes a bookmark item.
* @return An array of objects suitable for passing to populateDB().
*/
makeDataArray: function DH_makeDataArray(aData) {
let self = this;
- return aData.map(function (dat) {
+ return aData.map(function(dat) {
let type = dat.type;
dat = self._makeDataWithDefaults(dat, self.defaults[type]);
switch (type) {
case "bookmark":
return {
isBookmark: true,
uri: dat.uri,
parentGuid: dat.parentGuid,
--- a/toolkit/components/places/tests/queries/test_containersQueries_sorting.js
+++ b/toolkit/components/places/tests/queries/test_containersQueries_sorting.js
@@ -325,46 +325,46 @@ function check_children_sorting(aRootNod
return 1;
return 0;
}
// Get a comparator based on expected sortingMode.
var comparator;
switch (aExpectedSortingMode) {
case Ci.nsINavHistoryQueryOptions.SORT_BY_NONE:
- comparator = function (a, b) {
+ comparator = function(a, b) {
return 0;
}
break;
case Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING:
- comparator = function (a, b) {
+ comparator = function(a, b) {
return caseInsensitiveStringComparator(a.title, b.title);
}
break;
case Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_DESCENDING:
- comparator = function (a, b) {
+ comparator = function(a, b) {
return -caseInsensitiveStringComparator(a.title, b.title);
}
break;
case Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING:
- comparator = function (a, b) {
+ comparator = function(a, b) {
return a.time - b.time;
}
break;
case Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING:
- comparator = function (a, b) {
+ comparator = function(a, b) {
return b.time - a.time;
}
case Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_ASCENDING:
- comparator = function (a, b) {
+ comparator = function(a, b) {
return a.dateAdded - b.dateAdded;
}
break;
case Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING:
- comparator = function (a, b) {
+ comparator = function(a, b) {
return b.dateAdded - a.dateAdded;
}
break;
default:
do_throw("Unknown sorting type: " + aExpectedSortingMode);
}
// Make an independent copy of the results array and sort it.
--- a/toolkit/components/places/tests/queries/test_history_queries_tags_liveUpdate.js
+++ b/toolkit/components/places/tests/queries/test_history_queries_tags_liveUpdate.js
@@ -66,17 +66,17 @@ function run_test()
add_task(function* test_initialize()
{
yield task_populateDB(gTestData);
});
add_task(function pages_query()
{
let [query, options] = newQueryWithOptions();
- testQueryContents(query, options, function (root) {
+ testQueryContents(query, options, function(root) {
compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
for (let i = 0; i < root.childCount; i++) {
let node = root.getChild(i);
let uri = NetUtil.newURI(node.uri);
do_check_eq(node.tags, null);
PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
do_check_eq(node.tags, "test-tag");
PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
@@ -84,17 +84,17 @@ add_task(function pages_query()
}
});
});
add_task(function visits_query()
{
let [query, options] = newQueryWithOptions();
options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT;
- testQueryContents(query, options, function (root) {
+ testQueryContents(query, options, function(root) {
compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
for (let i = 0; i < root.childCount; i++) {
let node = root.getChild(i);
let uri = NetUtil.newURI(node.uri);
do_check_eq(node.tags, null);
PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
do_check_eq(node.tags, "test-tag");
PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
@@ -102,17 +102,17 @@ add_task(function visits_query()
}
});
});
add_task(function bookmarks_query()
{
let [query, options] = newQueryWithOptions();
query.setFolders([PlacesUtils.unfiledBookmarksFolderId], 1);
- testQueryContents(query, options, function (root) {
+ testQueryContents(query, options, function(root) {
compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
for (let i = 0; i < root.childCount; i++) {
let node = root.getChild(i);
let uri = NetUtil.newURI(node.uri);
do_check_eq(node.tags, null);
PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
do_check_eq(node.tags, "test-tag");
PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
@@ -120,17 +120,17 @@ add_task(function bookmarks_query()
}
});
});
add_task(function pages_searchterm_query()
{
let [query, options] = newQueryWithOptions();
query.searchTerms = "example";
- testQueryContents(query, options, function (root) {
+ testQueryContents(query, options, function(root) {
compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
for (let i = 0; i < root.childCount; i++) {
let node = root.getChild(i);
let uri = NetUtil.newURI(node.uri);
do_check_eq(node.tags, null);
PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
do_check_eq(node.tags, "test-tag");
PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
@@ -139,17 +139,17 @@ add_task(function pages_searchterm_query
});
});
add_task(function visits_searchterm_query()
{
let [query, options] = newQueryWithOptions();
query.searchTerms = "example";
options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT;
- testQueryContents(query, options, function (root) {
+ testQueryContents(query, options, function(root) {
compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
for (let i = 0; i < root.childCount; i++) {
let node = root.getChild(i);
let uri = NetUtil.newURI(node.uri);
do_check_eq(node.tags, null);
PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
do_check_eq(node.tags, "test-tag");
PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
@@ -157,19 +157,19 @@ add_task(function visits_searchterm_quer
}
});
});
add_task(function pages_searchterm_is_tag_query()
{
let [query, options] = newQueryWithOptions();
query.searchTerms = "test-tag";
- testQueryContents(query, options, function (root) {
+ testQueryContents(query, options, function(root) {
compareArrayToResult([], root);
- gTestData.forEach(function (data) {
+ gTestData.forEach(function(data) {
let uri = NetUtil.newURI(data.uri);
PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
uri,
PlacesUtils.bookmarks.DEFAULT_INDEX,
data.title);
PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
compareArrayToResult([data], root);
PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
@@ -178,19 +178,19 @@ add_task(function pages_searchterm_is_ta
});
});
add_task(function visits_searchterm_is_tag_query()
{
let [query, options] = newQueryWithOptions();
query.searchTerms = "test-tag";
options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT;
- testQueryContents(query, options, function (root) {
+ testQueryContents(query, options, function(root) {
compareArrayToResult([], root);
- gTestData.forEach(function (data) {
+ gTestData.forEach(function(data) {
let uri = NetUtil.newURI(data.uri);
PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
uri,
PlacesUtils.bookmarks.DEFAULT_INDEX,
data.title);
PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
compareArrayToResult([data], root);
PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
--- a/toolkit/components/places/tests/queries/test_querySerialization.js
+++ b/toolkit/components/places/tests/queries/test_querySerialization.js
@@ -95,175 +95,175 @@ const querySwitches = [
// flag and subswitches are used by the flagSwitchMatches function. Several
// of the nsINavHistoryQuery switches (like this one) are really guard flags
// that indicate if other "subswitches" are enabled.
flag: "hasBeginTime",
subswitches: ["beginTime", "beginTimeReference", "absoluteBeginTime"],
desc: "nsINavHistoryQuery.hasBeginTime",
matches: flagSwitchMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.beginTime = Date.now() * 1000;
aQuery.beginTimeReference = Ci.nsINavHistoryQuery.TIME_RELATIVE_EPOCH;
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.beginTime = Date.now() * 1000;
aQuery.beginTimeReference = Ci.nsINavHistoryQuery.TIME_RELATIVE_TODAY;
}
]
},
// hasEndTime
{
flag: "hasEndTime",
subswitches: ["endTime", "endTimeReference", "absoluteEndTime"],
desc: "nsINavHistoryQuery.hasEndTime",
matches: flagSwitchMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.endTime = Date.now() * 1000;
aQuery.endTimeReference = Ci.nsINavHistoryQuery.TIME_RELATIVE_EPOCH;
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.endTime = Date.now() * 1000;
aQuery.endTimeReference = Ci.nsINavHistoryQuery.TIME_RELATIVE_TODAY;
}
]
},
// hasSearchTerms
{
flag: "hasSearchTerms",
subswitches: ["searchTerms"],
desc: "nsINavHistoryQuery.hasSearchTerms",
matches: flagSwitchMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.searchTerms = "shrimp and white wine";
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.searchTerms = "";
}
]
},
// hasDomain
{
flag: "hasDomain",
subswitches: ["domain", "domainIsHost"],
desc: "nsINavHistoryQuery.hasDomain",
matches: flagSwitchMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.domain = "mozilla.com";
aQuery.domainIsHost = false;
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.domain = "www.mozilla.com";
aQuery.domainIsHost = true;
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.domain = "";
}
]
},
// hasUri
{
flag: "hasUri",
subswitches: ["uri"],
desc: "nsINavHistoryQuery.hasUri",
matches: flagSwitchMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.uri = uri("http://mozilla.com");
},
]
},
// hasAnnotation
{
flag: "hasAnnotation",
subswitches: ["annotation", "annotationIsNot"],
desc: "nsINavHistoryQuery.hasAnnotation",
matches: flagSwitchMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.annotation = "bookmarks/toolbarFolder";
aQuery.annotationIsNot = false;
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.annotation = "bookmarks/toolbarFolder";
aQuery.annotationIsNot = true;
}
]
},
// minVisits
{
// property is used by function simplePropertyMatches.
property: "minVisits",
desc: "nsINavHistoryQuery.minVisits",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.minVisits = 0x7fffffff; // 2^31 - 1
}
]
},
// maxVisits
{
property: "maxVisits",
desc: "nsINavHistoryQuery.maxVisits",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.maxVisits = 0x7fffffff; // 2^31 - 1
}
]
},
// onlyBookmarked
{
property: "onlyBookmarked",
desc: "nsINavHistoryQuery.onlyBookmarked",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.onlyBookmarked = true;
}
]
},
// getFolders
{
desc: "nsINavHistoryQuery.getFolders",
- matches: function (aQuery1, aQuery2) {
+ matches: function(aQuery1, aQuery2) {
var q1Folders = aQuery1.getFolders();
var q2Folders = aQuery2.getFolders();
if (q1Folders.length !== q2Folders.length)
return false;
for (let i = 0; i < q1Folders.length; i++) {
if (q2Folders.indexOf(q1Folders[i]) < 0)
return false;
}
for (let i = 0; i < q2Folders.length; i++) {
if (q1Folders.indexOf(q2Folders[i]) < 0)
return false;
}
return true;
},
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.setFolders([], 0);
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.setFolders([PlacesUtils.placesRootId], 1);
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.setFolders([PlacesUtils.placesRootId, PlacesUtils.tagsFolderId], 2);
}
]
},
// tags
{
desc: "nsINavHistoryQuery.getTags",
- matches: function (aQuery1, aQuery2) {
+ matches: function(aQuery1, aQuery2) {
if (aQuery1.tagsAreNot !== aQuery2.tagsAreNot)
return false;
var q1Tags = aQuery1.tags;
var q2Tags = aQuery2.tags;
if (q1Tags.length !== q2Tags.length)
return false;
for (let i = 0; i < q1Tags.length; i++) {
if (q2Tags.indexOf(q1Tags[i]) < 0)
@@ -271,36 +271,36 @@ const querySwitches = [
}
for (let i = 0; i < q2Tags.length; i++) {
if (q1Tags.indexOf(q2Tags[i]) < 0)
return false;
}
return true;
},
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.tags = [];
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.tags = [""];
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.tags = [
"foo",
"七難",
"",
"いっぱいおっぱい",
"Abracadabra",
"123",
"Here's a pretty long tag name with some = signs and 1 2 3s and spaces oh jeez will it work I hope so!",
"アスキーでございません",
"あいうえお",
];
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.tags = [
"foo",
"七難",
"",
"いっぱいおっぱい",
"Abracadabra",
"123",
"Here's a pretty long tag name with some = signs and 1 2 3s and spaces oh jeez will it work I hope so!",
@@ -309,153 +309,153 @@ const querySwitches = [
];
aQuery.tagsAreNot = true;
}
]
},
// transitions
{
desc: "tests nsINavHistoryQuery.getTransitions",
- matches: function (aQuery1, aQuery2) {
+ matches: function(aQuery1, aQuery2) {
var q1Trans = aQuery1.getTransitions();
var q2Trans = aQuery2.getTransitions();
if (q1Trans.length !== q2Trans.length)
return false;
for (let i = 0; i < q1Trans.length; i++) {
if (q2Trans.indexOf(q1Trans[i]) < 0)
return false;
}
for (let i = 0; i < q2Trans.length; i++) {
if (q1Trans.indexOf(q2Trans[i]) < 0)
return false;
}
return true;
},
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.setTransitions([], 0);
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.setTransitions([Ci.nsINavHistoryService.TRANSITION_DOWNLOAD],
1);
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQuery.setTransitions([Ci.nsINavHistoryService.TRANSITION_TYPED,
Ci.nsINavHistoryService.TRANSITION_BOOKMARK], 2);
}
]
},
];
// nsINavHistoryQueryOptions switches
const queryOptionSwitches = [
// sortingMode
{
desc: "nsINavHistoryQueryOptions.sortingMode",
- matches: function (aOptions1, aOptions2) {
+ matches: function(aOptions1, aOptions2) {
if (aOptions1.sortingMode === aOptions2.sortingMode) {
switch (aOptions1.sortingMode) {
case aOptions1.SORT_BY_ANNOTATION_ASCENDING:
case aOptions1.SORT_BY_ANNOTATION_DESCENDING:
return aOptions1.sortingAnnotation === aOptions2.sortingAnnotation;
}
return true;
}
return false;
},
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.sortingMode = aQueryOptions.SORT_BY_DATE_ASCENDING;
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.sortingMode = aQueryOptions.SORT_BY_ANNOTATION_ASCENDING;
aQueryOptions.sortingAnnotation = "bookmarks/toolbarFolder";
}
]
},
// resultType
{
// property is used by function simplePropertyMatches.
property: "resultType",
desc: "nsINavHistoryQueryOptions.resultType",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.resultType = aQueryOptions.RESULTS_AS_URI;
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.resultType = aQueryOptions.RESULTS_AS_FULL_VISIT;
}
]
},
// excludeItems
{
property: "excludeItems",
desc: "nsINavHistoryQueryOptions.excludeItems",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.excludeItems = true;
}
]
},
// excludeQueries
{
property: "excludeQueries",
desc: "nsINavHistoryQueryOptions.excludeQueries",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.excludeQueries = true;
}
]
},
// expandQueries
{
property: "expandQueries",
desc: "nsINavHistoryQueryOptions.expandQueries",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.expandQueries = true;
}
]
},
// includeHidden
{
property: "includeHidden",
desc: "nsINavHistoryQueryOptions.includeHidden",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.includeHidden = true;
}
]
},
// maxResults
{
property: "maxResults",
desc: "nsINavHistoryQueryOptions.maxResults",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.maxResults = 0xffffffff; // 2^32 - 1
}
]
},
// queryType
{
property: "queryType",
desc: "nsINavHistoryQueryOptions.queryType",
matches: simplePropertyMatches,
runs: [
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.queryType = aQueryOptions.QUERY_TYPE_HISTORY;
},
- function (aQuery, aQueryOptions) {
+ function(aQuery, aQueryOptions) {
aQueryOptions.queryType = aQueryOptions.QUERY_TYPE_UNIFIED;
}
]
},
];
/**
* Enumerates all the sequences of the cartesian product of the arrays contained
@@ -674,38 +674,38 @@ function runQuerySequences(aHowManyLo, a
var prevOpts = [];
// Choose aHowManyLo switches up to aHowManyHi switches.
for (let howMany = aHowManyLo; howMany <= aHowManyHi; howMany++) {
let numIters = 0;
print("CHOOSING " + howMany + " SWITCHES");
// Choose all subsets of size howMany from allSwitches.
- choose(allSwitches, howMany, function (chosenSwitches) {
+ choose(allSwitches, howMany, function(chosenSwitches) {
print(numIters);
numIters++;
// Collect the runs.
// runs = [ [runs from switch 1], ..., [runs from switch howMany] ]
- var runs = chosenSwitches.map(function (s) {
+ var runs = chosenSwitches.map(function(s) {
if (s.desc)
print(" " + s.desc);
return s.runs;
});
// cartProd(runs) => [
// [switch 1 run 1, switch 2 run 1, ..., switch howMany run 1 ],
// ...,
// [switch 1 run 1, switch 2 run 1, ..., switch howMany run N ],
// ..., ...,
// [switch 1 run N, switch 2 run N, ..., switch howMany run 1 ],
// ...,
// [switch 1 run N, switch 2 run N, ..., switch howMany run N ],
// ]
- cartProd(runs, function (runSet) {
+ cartProd(runs, function(runSet) {
// Create a new query, apply the switches in runSet, and test it.
var query = PlacesUtils.history.getNewQuery();
var opts = PlacesUtils.history.getNewQueryOptions();
for (let i = 0; i < runSet.length; i++) {
runSet[i](query, opts);
}
serializeDeserialize([query], opts);
--- a/toolkit/components/places/tests/queries/test_redirects.js
+++ b/toolkit/components/places/tests/queries/test_redirects.js
@@ -26,35 +26,35 @@ function check_results_callback(aSequenc
" sortingMode(" + sortingMode + ").");
function isHidden(aVisit) {
return aVisit.transType == Ci.nsINavHistoryService.TRANSITION_FRAMED_LINK ||
aVisit.isRedirect;
}
// Build expectedData array.
- let expectedData = visits.filter(function (aVisit, aIndex, aArray) {
+ let expectedData = visits.filter(function(aVisit, aIndex, aArray) {
// Embed visits never appear in results.
if (aVisit.transType == Ci.nsINavHistoryService.TRANSITION_EMBED)
return false;
if (!includeHidden && isHidden(aVisit)) {
// If the page has any non-hidden visit, then it's visible.
- if (visits.filter(function (refVisit) {
+ if (visits.filter(function(refVisit) {
return refVisit.uri == aVisit.uri && !isHidden(refVisit);
}).length == 0)
return false;
}
return true;
});
// Remove duplicates, since queries are RESULTS_AS_URI (unique pages).
let seen = [];
- expectedData = expectedData.filter(function (aData) {
+ expectedData = expectedData.filter(function(aData) {
if (seen.includes(aData.uri)) {
return false;
}
seen.push(aData.uri);
return true;
});
// Sort expectedData.
--- a/toolkit/components/places/tests/queries/test_tags.js
+++ b/toolkit/components/places/tests/queries/test_tags.js
@@ -151,95 +151,95 @@ add_task(function* () {
"アスキーでございません",
"あいうえお",
], true);
});
add_task(function* tag_to_uri() {
do_print("Querying history on tag associated with a URI should return " +
"that URI");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithVisit(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["foo"]);
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["bar"]);
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["baz"]);
executeAndCheckQueryResults(query, opts, [aURI.spec]);
});
});
add_task(function* tags_to_uri() {
do_print("Querying history on many tags associated with a URI should " +
"return that URI");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithVisit(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["foo", "bar"]);
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["foo", "baz"]);
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["bar", "baz"]);
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["foo", "bar", "baz"]);
executeAndCheckQueryResults(query, opts, [aURI.spec]);
});
});
add_task(function* repeated_tag() {
do_print("Specifying the same tag multiple times in a history query " +
"should not matter");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithVisit(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["foo", "foo"]);
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["foo", "foo", "foo", "bar", "bar", "baz"]);
executeAndCheckQueryResults(query, opts, [aURI.spec]);
});
});
add_task(function* many_tags_no_uri() {
do_print("Querying history on many tags associated with a URI and " +
"tags not associated with that URI should not return that URI");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithVisit(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["foo", "bogus"]);
executeAndCheckQueryResults(query, opts, []);
[query, opts] = makeQuery(["foo", "bar", "bogus"]);
executeAndCheckQueryResults(query, opts, []);
[query, opts] = makeQuery(["foo", "bar", "baz", "bogus"]);
executeAndCheckQueryResults(query, opts, []);
});
});
add_task(function* nonexistent_tags() {
do_print("Querying history on nonexistent tags should return no results");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithVisit(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["bogus"]);
executeAndCheckQueryResults(query, opts, []);
[query, opts] = makeQuery(["bogus", "gnarly"]);
executeAndCheckQueryResults(query, opts, []);
});
});
add_task(function* tag_to_bookmark() {
do_print("Querying bookmarks on tag associated with a URI should " +
"return that URI");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithBookmark(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["foo"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["bar"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["baz"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, [aURI.spec]);
});
});
add_task(function* many_tags_to_bookmark() {
do_print("Querying bookmarks on many tags associated with a URI " +
"should return that URI");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithBookmark(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["foo", "bar"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["foo", "baz"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["bar", "baz"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
@@ -248,45 +248,45 @@ add_task(function* many_tags_to_bookmark
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, [aURI.spec]);
});
});
add_task(function* repeated_tag_to_bookmarks() {
do_print("Specifying the same tag multiple times in a bookmark query " +
"should not matter");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithBookmark(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["foo", "foo"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, [aURI.spec]);
[query, opts] = makeQuery(["foo", "foo", "foo", "bar", "bar", "baz"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, [aURI.spec]);
});
});
add_task(function* many_tags_no_bookmark() {
do_print("Querying bookmarks on many tags associated with a URI and " +
"tags not associated with that URI should not return that URI");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithBookmark(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["foo", "bogus"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, []);
[query, opts] = makeQuery(["foo", "bar", "bogus"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, []);
[query, opts] = makeQuery(["foo", "bar", "baz", "bogus"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, []);
});
});
add_task(function* nonexistent_tags_bookmark() {
do_print("Querying bookmarks on nonexistent tag should return no results");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
+ yield task_doWithBookmark(["foo", "bar", "baz"], function(aURI) {
var [query, opts] = makeQuery(["bogus"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, []);
[query, opts] = makeQuery(["bogus", "gnarly"]);
opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
executeAndCheckQueryResults(query, opts, []);
});
});
@@ -665,17 +665,17 @@ function makeQuery(aTags, aTagsAreNot) {
"without calling setTags() at all") +
" and with tagsAreNot=" +
aTagsAreNot);
var query = PlacesUtils.history.getNewQuery();
query.tagsAreNot = aTagsAreNot;
if (aTags) {
query.tags = aTags;
var uniqueTags = [];
- aTags.forEach(function (t) {
+ aTags.forEach(function(t) {
if (typeof(t) === "string" && uniqueTags.indexOf(t) < 0)
uniqueTags.push(t);
});
uniqueTags.sort();
}
do_print("Made query should be correct for tags and tagsAreNot");
if (uniqueTags)
--- a/toolkit/components/places/tests/queries/test_transitions.js
+++ b/toolkit/components/places/tests/queries/test_transitions.js
@@ -103,22 +103,22 @@ add_task(function* test_transitions()
visitDate: timeNow++ * 1000,
title: item.title
});
}
// dump_table("moz_places");
// dump_table("moz_historyvisits");
- var numSortFunc = function (a, b) { return (a - b); };
+ var numSortFunc = function(a, b) { return (a - b); };
var arrs = testDataTyped.concat(testDataDownload).concat(testDataBookmark)
.sort(numSortFunc);
// Four tests which compare the result of a query to an expected set.
- var data = arrs.filter(function (index) {
+ var data = arrs.filter(function(index) {
return (testData[index].uri.match(/arewefastyet\.com/) &&
testData[index].transType ==
Ci.nsINavHistoryService.TRANSITION_DOWNLOAD);
});
compareQueryToTestData("place:domain=arewefastyet.com&transition=" +
Ci.nsINavHistoryService.TRANSITION_DOWNLOAD,
data.slice());
--- a/toolkit/components/places/tests/unifiedcomplete/head_autocomplete.js
+++ b/toolkit/components/places/tests/unifiedcomplete/head_autocomplete.js
@@ -53,17 +53,17 @@ do_register_cleanup(cleanup);
* Array of AutoCompleteSearch names.
*/
function AutoCompleteInput(aSearches) {
this.searches = aSearches;
}
AutoCompleteInput.prototype = {
popup: {
selectedIndex: -1,
- invalidate: function () {},
+ invalidate: function() {},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup])
},
popupOpen: false,
disableAutoComplete: false,
completeDefaultIndex: true,
completeSelectedIndex: true,
forceComplete: false,
@@ -94,18 +94,18 @@ AutoCompleteInput.prototype = {
get selectionEnd() {
return this._selEnd;
},
selectTextRange: function(aStart, aEnd) {
this._selStart = aStart;
this._selEnd = aEnd;
},
- onSearchBegin: function () {},
- onSearchComplete: function () {},
+ onSearchBegin: function() {},
+ onSearchComplete: function() {},
onTextEntered: () => false,
onTextReverted: () => false,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput])
}
// A helper for check_autocomplete to check a specific match against data from
--- a/toolkit/components/places/tests/unit/nsDummyObserver.js
+++ b/toolkit/components/places/tests/unit/nsDummyObserver.js
@@ -10,34 +10,34 @@ const Ci = Components.interfaces;
// Dummy boomark/history observer
function DummyObserver() {
Services.obs.notifyObservers(null, "dummy-observer-created", null);
}
DummyObserver.prototype = {
// history observer
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID, aTransitionType) {
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID, aTransitionType) {
Services.obs.notifyObservers(null, "dummy-observer-visited", null);
},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
+ onTitleChanged: function() {},
+ onDeleteURI: function() {},
+ onClearHistory: function() {},
+ onPageChanged: function() {},
+ onDeleteVisits: function() {},
// bookmark observer
// onBeginUpdateBatch: function() {},
// onEndUpdateBatch: function() {},
onItemAdded: function(aItemId, aParentId, aIndex, aItemType, aURI) {
Services.obs.notifyObservers(null, "dummy-observer-item-added", null);
},
- onItemChanged: function () {},
+ onItemChanged: function() {},
onItemRemoved: function() {},
onItemVisited: function() {},
onItemMoved: function() {},
classID: Components.ID("62e221d3-68c3-4e1a-8943-a27beb5005fe"),
QueryInterface: XPCOMUtils.generateQI([
Ci.nsINavBookmarkObserver,
--- a/toolkit/components/places/tests/unit/test_454977.js
+++ b/toolkit/components/places/tests/unit/test_454977.js
@@ -15,17 +15,17 @@ function* task_add_visit(aURI, aVisitTyp
{
PlacesUtils.asyncHistory.updatePlaces({
uri: aURI,
visits: [{ transitionType: aVisitType, visitDate: Date.now() * 1000 }]
}, {
handleError: function TAV_handleError() {
reject(new Error("Unexpected error in adding visit."));
},
- handleResult: function (aPlaceInfo) {
+ handleResult: function(aPlaceInfo) {
this.visitId = aPlaceInfo.visits[0].visitId;
},
handleCompletion: function TAV_handleCompletion() {
resolve(this.visitId);
}
});
});
--- a/toolkit/components/places/tests/unit/test_PlacesUtils_lazyobservers.js
+++ b/toolkit/components/places/tests/unit/test_PlacesUtils_lazyobservers.js
@@ -5,27 +5,27 @@ function run_test() {
do_test_pending();
const TEST_URI = NetUtil.newURI("http://moz.org/")
let observer = {
QueryInterface: XPCOMUtils.generateQI([
Ci.nsINavBookmarkObserver,
]),
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onItemAdded: function (aItemId, aParentId, aIndex, aItemType, aURI) {
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onItemAdded: function(aItemId, aParentId, aIndex, aItemType, aURI) {
do_check_true(aURI.equals(TEST_URI));
PlacesUtils.removeLazyBookmarkObserver(this);
do_test_finished();
},
- onItemRemoved: function () {},
- onItemChanged: function () {},
- onItemVisited: function () {},
- onItemMoved: function () {},
+ onItemRemoved: function() {},
+ onItemChanged: function() {},
+ onItemVisited: function() {},
+ onItemMoved: function() {},
};
// Check registration and removal with uninitialized bookmarks service.
PlacesUtils.addLazyBookmarkObserver(observer);
PlacesUtils.removeLazyBookmarkObserver(observer);
// Add a proper lazy observer we will test.
PlacesUtils.addLazyBookmarkObserver(observer);
--- a/toolkit/components/places/tests/unit/test_adaptive.js
+++ b/toolkit/components/places/tests/unit/test_adaptive.js
@@ -41,29 +41,29 @@ AutoCompleteInput.prototype = {
},
get completeDefaultIndex() {
return false;
},
get searchCount() {
return this.searches.length;
},
- getSearchAt: function (aIndex) {
+ getSearchAt: function(aIndex) {
return this.searches[aIndex];
},
- onSearchBegin: function () {},
+ onSearchBegin: function() {},
onSearchComplete: function() {},
get popupOpen() {
return false;
},
popup: {
set selectedIndex(aIndex) {},
- invalidate: function () {},
+ invalidate: function() {},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup])
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput])
}
/**
* Checks that autocomplete results are ordered correctly.
--- a/toolkit/components/places/tests/unit/test_asyncExecuteLegacyQueries.js
+++ b/toolkit/components/places/tests/unit/test_asyncExecuteLegacyQueries.js
@@ -4,37 +4,37 @@
// This is a test for asyncExecuteLegacyQueries API.
var tests = [
function test_history_query() {
let uri = NetUtil.newURI("http://test.visit.mozilla.com/");
let title = "Test visit";
- PlacesTestUtils.addVisits({ uri: uri, title: title }).then(function () {
+ PlacesTestUtils.addVisits({ uri: uri, title: title }).then(function() {
let options = PlacesUtils.history.getNewQueryOptions();
options.sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING;
let query = PlacesUtils.history.getNewQuery();
PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
.asyncExecuteLegacyQueries([query], 1, options, {
- handleResult: function (aResultSet) {
+ handleResult: function(aResultSet) {
for (let row; (row = aResultSet.getNextRow());) {
try {
do_check_eq(row.getResultByIndex(1), uri.spec);
do_check_eq(row.getResultByIndex(2), title);
} catch (e) {
do_throw("Error while fetching page data.");
}
}
},
- handleError: function (aError) {
+ handleError: function(aError) {
do_throw("Async execution error (" + aError.result + "): " + aError.message);
},
- handleCompletion: function (aReason) {
+ handleCompletion: function(aReason) {
run_next_test();
},
});
});
},
function test_bookmarks_query() {
let uri = NetUtil.newURI("http://test.bookmark.mozilla.com/");
@@ -42,30 +42,30 @@ function test_bookmarks_query() {
bookmark(uri, title);
let options = PlacesUtils.history.getNewQueryOptions();
options.sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_LASMODIFIED_DESCENDING;
options.queryType = options.QUERY_TYPE_BOOKMARKS;
let query = PlacesUtils.history.getNewQuery();
PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
.asyncExecuteLegacyQueries([query], 1, options, {
- handleResult: function (aResultSet) {
+ handleResult: function(aResultSet) {
for (let row; (row = aResultSet.getNextRow());) {
try {
do_check_eq(row.getResultByIndex(1), uri.spec);
do_check_eq(row.getResultByIndex(2), title);
} catch (e) {
do_throw("Error while fetching page data.");
}
}
},
- handleError: function (aError) {
+ handleError: function(aError) {
do_throw("Async execution error (" + aError.result + "): " + aError.message);
},
- handleCompletion: function (aReason) {
+ handleCompletion: function(aReason) {
run_next_test();
},
});
},
];
function bookmark(aURI, aTitle)
--- a/toolkit/components/places/tests/unit/test_async_transactions.js
+++ b/toolkit/components/places/tests/unit/test_async_transactions.js
@@ -13,36 +13,36 @@ const rootGuid = PlacesUtils.bookmarks.r
Components.utils.importGlobalProperties(["URL"]);
// Create and add bookmarks observer.
var observer = {
__proto__: NavBookmarkObserver.prototype,
tagRelatedGuids: new Set(),
- reset: function () {
+ reset: function() {
this.itemsAdded = new Map();
this.itemsRemoved = new Map();
this.itemsChanged = new Map();
this.itemsMoved = new Map();
this.beginUpdateBatch = false;
this.endUpdateBatch = false;
},
- onBeginUpdateBatch: function () {
+ onBeginUpdateBatch: function() {
this.beginUpdateBatch = true;
},
- onEndUpdateBatch: function () {
+ onEndUpdateBatch: function() {
this.endUpdateBatch = true;
},
onItemAdded:
- function (aItemId, aParentId, aIndex, aItemType, aURI, aTitle, aDateAdded,
- aGuid, aParentGuid) {
+ function(aItemId, aParentId, aIndex, aItemType, aURI, aTitle, aDateAdded,
+ aGuid, aParentGuid) {
// Ignore tag items.
if (aParentId == PlacesUtils.tagsFolderId ||
(aParentId != PlacesUtils.placesRootId &&
bmsvc.getFolderIdForItem(aParentId) == PlacesUtils.tagsFolderId)) {
this.tagRelatedGuids.add(aGuid);
return;
}
@@ -50,28 +50,28 @@ var observer = {
, parentGuid: aParentGuid
, index: aIndex
, itemType: aItemType
, title: aTitle
, url: aURI });
},
onItemRemoved:
- function (aItemId, aParentId, aIndex, aItemType, aURI, aGuid, aParentGuid) {
+ function(aItemId, aParentId, aIndex, aItemType, aURI, aGuid, aParentGuid) {
if (this.tagRelatedGuids.has(aGuid))
return;
this.itemsRemoved.set(aGuid, { parentGuid: aParentGuid
, index: aIndex
, itemType: aItemType });
},
onItemChanged:
- function (aItemId, aProperty, aIsAnnoProperty, aNewValue, aLastModified,
- aItemType, aParentId, aGuid, aParentGuid) {
+ function(aItemId, aProperty, aIsAnnoProperty, aNewValue, aLastModified,
+ aItemType, aParentId, aGuid, aParentGuid) {
if (this.tagRelatedGuids.has(aGuid))
return;
let changesForGuid = this.itemsChanged.get(aGuid);
if (changesForGuid === undefined) {
changesForGuid = new Map();
this.itemsChanged.set(aGuid, changesForGuid);
}
@@ -88,33 +88,33 @@ var observer = {
, lastModified: aLastModified
, itemType: aItemType };
changesForGuid.set(aProperty, change);
},
onItemVisited: () => {},
onItemMoved:
- function (aItemId, aOldParent, aOldIndex, aNewParent, aNewIndex, aItemType,
- aGuid, aOldParentGuid, aNewParentGuid) {
+ function(aItemId, aOldParent, aOldIndex, aNewParent, aNewIndex, aItemType,
+ aGuid, aOldParentGuid, aNewParentGuid) {
this.itemsMoved.set(aGuid, { oldParentGuid: aOldParentGuid
, oldIndex: aOldIndex
, newParentGuid: aNewParentGuid
, newIndex: aNewIndex
, itemType: aItemType });
}
};
observer.reset();
// index at which items should begin
var bmStartIndex = 0;
function run_test() {
bmsvc.addObserver(observer, false);
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
bmsvc.removeObserver(observer);
});
run_next_test();
}
function sanityCheckTransactionHistory() {
do_check_true(PT.undoPosition <= PT.length);
--- a/toolkit/components/places/tests/unit/test_bookmarks_html.js
+++ b/toolkit/components/places/tests/unit/test_bookmarks_html.js
@@ -328,17 +328,17 @@ function* checkItem(aExpected, aNode)
case "url":
if (!("feedUrl" in aExpected))
do_check_eq(aNode.uri, aExpected.url)
break;
case "icon":
let deferred = Promise.defer();
PlacesUtils.favicons.getFaviconDataForPage(
NetUtil.newURI(aExpected.url),
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
deferred.resolve(aData);
});
let data = yield deferred.promise;
let base64Icon = "data:image/png;base64," +
base64EncodeString(String.fromCharCode.apply(String, data));
do_check_true(base64Icon == aExpected.icon);
break;
case "keyword": {
--- a/toolkit/components/places/tests/unit/test_bookmarks_json.js
+++ b/toolkit/components/places/tests/unit/test_bookmarks_json.js
@@ -181,17 +181,17 @@ function* checkItem(aExpected, aNode) {
case "url":
if (!("feedUrl" in aExpected))
do_check_eq(aNode.uri, aExpected.url);
break;
case "icon":
let deferred = Promise.defer();
PlacesUtils.favicons.getFaviconDataForPage(
NetUtil.newURI(aExpected.url),
- function (aURI, aDataLen, aData, aMimeType) {
+ function(aURI, aDataLen, aData, aMimeType) {
deferred.resolve(aData);
});
let data = yield deferred.promise;
let base64Icon = "data:image/png;base64," +
base64EncodeString(String.fromCharCode.apply(String, data));
do_check_true(base64Icon == aExpected.icon);
break;
case "keyword": {
--- a/toolkit/components/places/tests/unit/test_bookmarks_restore_notification.js
+++ b/toolkit/components/places/tests/unit/test_bookmarks_restore_notification.js
@@ -42,17 +42,17 @@ function* addBookmarks() {
/**
* Checks that all of the bookmarks created for |uris| exist. It works by
* creating one query per URI and then ORing all the queries. The number of
* results returned should be uris.length.
*/
function checkBookmarksExist() {
let hs = PlacesUtils.history;
- let queries = uris.map(function (u) {
+ let queries = uris.map(function(u) {
let q = hs.getNewQuery();
q.uri = uri(u);
return q;
});
let options = hs.getNewQueryOptions();
options.queryType = options.QUERY_TYPE_BOOKMARKS;
let root = hs.executeQueries(queries, uris.length, options).root;
root.containerOpen = true;
--- a/toolkit/components/places/tests/unit/test_childlessTags.js
+++ b/toolkit/components/places/tests/unit/test_childlessTags.js
@@ -9,17 +9,17 @@
* contained in any regular, non-tag folders. See bug 444849.
*/
// Add your tests here. Each is an object with a summary string |desc| and a
// method run() that's called to run the test.
var tests = [
{
desc: "Removing a tagged bookmark should cause the tag to be removed.",
- run: function () {
+ run: function() {
print(" Make a bookmark.");
var bmId = bmsvc.insertBookmark(bmsvc.unfiledBookmarksFolder,
BOOKMARK_URI,
bmsvc.DEFAULT_INDEX,
"test bookmark");
do_check_true(bmId > 0);
print(" Tag it up.");
@@ -31,17 +31,17 @@ var tests = [
bmsvc.removeItem(bmId);
ensureTagsExist([]);
}
},
{
desc: "Removing a folder containing a tagged bookmark should cause the " +
"tag to be removed.",
- run: function () {
+ run: function() {
print(" Make a folder.");
var folderId = bmsvc.createFolder(bmsvc.unfiledBookmarksFolder,
"test folder",
bmsvc.DEFAULT_INDEX);
do_check_true(folderId > 0);
print(" Stick a bookmark in the folder.");
var bmId = bmsvc.insertBookmark(folderId,
@@ -105,13 +105,13 @@ function ensureTagsExist(aTags) {
tags.splice(indexOfTag, 1);
}
resultRoot.containerOpen = false;
}
function run_test()
{
- tests.forEach(function (test) {
+ tests.forEach(function(test) {
print("Running test: " + test.desc);
test.run();
});
}
--- a/toolkit/components/places/tests/unit/test_download_history.js
+++ b/toolkit/components/places/tests/unit/test_download_history.js
@@ -99,17 +99,17 @@ add_test(function test_dh_addRemoveDownl
gDownloadHistory.addDownload(DOWNLOAD_URI, null, Date.now() * 1000);
});
add_test(function test_dh_addMultiRemoveDownload()
{
PlacesTestUtils.addVisits({
uri: DOWNLOAD_URI,
transition: TRANSITION_TYPED
- }).then(function () {
+ }).then(function() {
waitForOnVisit(function DHAD_onVisit(aURI) {
do_check_true(aURI.equals(DOWNLOAD_URI));
do_check_true(!!page_in_database(DOWNLOAD_URI));
waitForOnDeleteVisits(function DHRAD_onDeleteVisits(aDeletedURI) {
do_check_true(aDeletedURI.equals(DOWNLOAD_URI));
do_check_true(!!page_in_database(DOWNLOAD_URI));
--- a/toolkit/components/places/tests/unit/test_history_observer.js
+++ b/toolkit/components/places/tests/unit/test_history_observer.js
@@ -22,17 +22,17 @@ NavHistoryObserver.prototype = {
/**
* Registers a one-time history observer for and calls the callback
* when the specified nsINavHistoryObserver method is called.
* Returns a promise that is resolved when the callback returns.
*/
function onNotify(callback) {
return new Promise(resolve => {
let obs = new NavHistoryObserver();
- obs[callback.name] = function () {
+ obs[callback.name] = function() {
PlacesUtils.history.removeObserver(this);
callback.apply(this, arguments);
resolve();
};
PlacesUtils.history.addObserver(obs, false);
});
}
--- a/toolkit/components/places/tests/unit/test_isURIVisited.js
+++ b/toolkit/components/places/tests/unit/test_isURIVisited.js
@@ -44,27 +44,27 @@ function* step()
let uri = NetUtil.newURI(scheme + "mozilla.org/");
history.isURIVisited(uri, function(aURI, aIsVisited) {
do_check_true(uri.equals(aURI));
do_check_false(aIsVisited);
let callback = {
- handleError: function () {},
- handleResult: function () {},
- handleCompletion: function () {
+ handleError: function() {},
+ handleResult: function() {},
+ handleCompletion: function() {
do_print("Added visit to " + uri.spec);
- history.isURIVisited(uri, function (aURI2, aIsVisited2) {
+ history.isURIVisited(uri, function(aURI2, aIsVisited2) {
do_check_true(uri.equals(aURI2));
let checker = SCHEMES[scheme] ? do_check_true : do_check_false;
checker(aIsVisited2);
- PlacesTestUtils.clearHistory().then(function () {
+ PlacesTestUtils.clearHistory().then(function() {
history.isURIVisited(uri, function(aURI3, aIsVisited3) {
do_check_true(uri.equals(aURI3));
do_check_false(aIsVisited3);
gRunner.next();
});
});
});
},
--- a/toolkit/components/places/tests/unit/test_markpageas.js
+++ b/toolkit/components/places/tests/unit/test_markpageas.js
@@ -18,18 +18,18 @@ function run_test()
add_task(function* test_execute()
{
let observer;
let completionPromise = new Promise(resolveCompletionPromise => {
observer = {
__proto__: NavHistoryObserver.prototype,
_visitCount: 0,
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
- aTransitionType, aAdded)
+ onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID,
+ aTransitionType, aAdded)
{
do_check_eq(aURI.spec, gVisits[this._visitCount].url);
do_check_eq(aTransitionType, gVisits[this._visitCount].transition);
this._visitCount++;
if (this._visitCount == gVisits.length) {
resolveCompletionPromise();
}
--- a/toolkit/components/places/tests/unit/test_nsINavHistoryViewer.js
+++ b/toolkit/components/places/tests/unit/test_nsINavHistoryViewer.js
@@ -40,17 +40,17 @@ var resultObserver = {
},
movedNode: null,
nodeMoved: function(node, oldParent, oldIndex, newParent, newIndex) {
this.movedNode = node;
},
openedContainer: null,
closedContainer: null,
- containerStateChanged: function (aNode, aOldState, aNewState) {
+ containerStateChanged: function(aNode, aOldState, aNewState) {
if (aNewState == Ci.nsINavHistoryContainerResultNode.STATE_OPENED) {
this.openedContainer = aNode;
}
else if (aNewState == Ci.nsINavHistoryContainerResultNode.STATE_CLOSED) {
this.closedContainer = aNode;
}
},
invalidatedContainer: null,
@@ -104,17 +104,17 @@ add_test(function check_history_query()
PlacesTestUtils.addVisits(testURI).then(function() {
do_check_eq(testURI.spec, resultObserver.insertedNode.uri);
// nsINavHistoryResultObserver.nodeHistoryDetailsChanged
// adding a visit causes nodeHistoryDetailsChanged for the folder
do_check_eq(root.uri, resultObserver.nodeChangedByHistoryDetails.uri);
// nsINavHistoryResultObserver.itemTitleChanged for a leaf node
- PlacesTestUtils.addVisits({ uri: testURI, title: "baz" }).then(function () {
+ PlacesTestUtils.addVisits({ uri: testURI, title: "baz" }).then(function() {
do_check_eq(resultObserver.nodeChangedByTitle.title, "baz");
// nsINavHistoryResultObserver.nodeRemoved
var removedURI = uri("http://google.com");
PlacesTestUtils.addVisits(removedURI).then(function() {
bhist.removePage(removedURI);
do_check_eq(removedURI.spec, resultObserver.removedNode.uri);
@@ -130,23 +130,23 @@ add_test(function check_history_query()
// nsINavHistoryResultObserver.invalidateContainer
PlacesTestUtils.clearHistoryEnabled().then(() => {
do_check_eq(root.uri, resultObserver.invalidatedContainer.uri);
// nsINavHistoryResultObserver.batching
do_check_false(resultObserver.inBatchMode);
histsvc.runInBatchMode({
- runBatched: function (aUserData) {
+ runBatched: function(aUserData) {
do_check_true(resultObserver.inBatchMode);
}
}, null);
do_check_false(resultObserver.inBatchMode);
bmsvc.runInBatchMode({
- runBatched: function (aUserData) {
+ runBatched: function(aUserData) {
do_check_true(resultObserver.inBatchMode);
}
}, null);
do_check_false(resultObserver.inBatchMode);
root.containerOpen = false;
do_check_eq(resultObserver.closedContainer, resultObserver.openedContainer);
result.removeObserver(resultObserver);
@@ -198,23 +198,23 @@ add_test(function check_bookmarks_query(
resultObserver.invalidatedContainer = null;
result.sortingMode = options.SORT_BY_TITLE_ASCENDING;
do_check_eq(resultObserver.sortingMode, options.SORT_BY_TITLE_ASCENDING);
do_check_eq(resultObserver.invalidatedContainer, result.root);
// nsINavHistoryResultObserver.batching
do_check_false(resultObserver.inBatchMode);
histsvc.runInBatchMode({
- runBatched: function (aUserData) {
+ runBatched: function(aUserData) {
do_check_true(resultObserver.inBatchMode);
}
}, null);
do_check_false(resultObserver.inBatchMode);
bmsvc.runInBatchMode({
- runBatched: function (aUserData) {
+ runBatched: function(aUserData) {
do_check_true(resultObserver.inBatchMode);
}
}, null);
do_check_false(resultObserver.inBatchMode);
root.containerOpen = false;
do_check_eq(resultObserver.closedContainer, resultObserver.openedContainer);
result.removeObserver(resultObserver);
@@ -231,23 +231,23 @@ add_test(function check_mixed_query() {
var root = result.root;
root.containerOpen = true;
do_check_neq(resultObserver.openedContainer, null);
// nsINavHistoryResultObserver.batching
do_check_false(resultObserver.inBatchMode);
histsvc.runInBatchMode({
- runBatched: function (aUserData) {
+ runBatched: function(aUserData) {
do_check_true(resultObserver.inBatchMode);
}
}, null);
do_check_false(resultObserver.inBatchMode);
bmsvc.runInBatchMode({
- runBatched: function (aUserData) {
+ runBatched: function(aUserData) {
do_check_true(resultObserver.inBatchMode);
}
}, null);
do_check_false(resultObserver.inBatchMode);
root.containerOpen = false;
do_check_eq(resultObserver.closedContainer, resultObserver.openedContainer);
result.removeObserver(resultObserver);
--- a/toolkit/components/places/tests/unit/test_onItemChanged_tags.js
+++ b/toolkit/components/places/tests/unit/test_onItemChanged_tags.js
@@ -17,36 +17,36 @@ function run_test() {
PlacesUtils.tagging.tagURI(uri, tags);
let bookmarksObserver = {
QueryInterface: XPCOMUtils.generateQI([
Ci.nsINavBookmarkObserver
]),
_changedCount: 0,
- onItemChanged: function (aItemId, aProperty, aIsAnnotationProperty, aValue,
- aLastModified, aItemType) {
+ onItemChanged: function(aItemId, aProperty, aIsAnnotationProperty, aValue,
+ aLastModified, aItemType) {
if (aProperty == "tags") {
do_check_eq(aItemId, id);
this._changedCount++;
}
},
- onItemRemoved: function (aItemId, aParentId, aIndex, aItemType) {
+ onItemRemoved: function(aItemId, aParentId, aIndex, aItemType) {
if (aItemId == id) {
PlacesUtils.bookmarks.removeObserver(this);
do_check_eq(this._changedCount, 2);
do_test_finished();
}
},
- onItemAdded: function () {},
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onItemVisited: function () {},
- onItemMoved: function () {},
+ onItemAdded: function() {},
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onItemVisited: function() {},
+ onItemMoved: function() {},
};
PlacesUtils.bookmarks.addObserver(bookmarksObserver, false);
PlacesUtils.tagging.tagURI(uri, ["d"]);
PlacesUtils.tagging.tagURI(uri, ["e"]);
PlacesUtils.bookmarks.removeItem(id);
}
--- a/toolkit/components/places/tests/unit/test_placesTxn.js
+++ b/toolkit/components/places/tests/unit/test_placesTxn.js
@@ -107,17 +107,17 @@ var observer = {
// index at which items should begin
var bmStartIndex = 0;
// get bookmarks root id
var root = PlacesUtils.bookmarksMenuFolderId;
add_task(function* init() {
bmsvc.addObserver(observer, false);
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
bmsvc.removeObserver(observer);
});
});
add_task(function* test_create_folder_with_description() {
const TEST_FOLDERNAME = "Test creating a folder with a description";
const TEST_DESCRIPTION = "this is my test description";
@@ -669,17 +669,17 @@ add_task(function* test_edit_item_last_m
txn.undoTransaction();
do_check_eq(oldModified, bmsvc.getItemLastModified(testBkmId));
});
add_task(function* test_generic_page_annotation() {
const TEST_ANNO = "testAnno/testInt";
let testURI = NetUtil.newURI("http://www.mozilla.org/");
- PlacesTestUtils.addVisits(testURI).then(function () {
+ PlacesTestUtils.addVisits(testURI).then(function() {
let pageAnnoObj = { name: TEST_ANNO,
type: Ci.nsIAnnotationService.TYPE_INT32,
flags: 0,
value: 123,
expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
let txn = new PlacesSetPageAnnotationTransaction(testURI, pageAnnoObj);
txn.doTransaction();
--- a/toolkit/components/places/tests/unit/test_preventive_maintenance.js
+++ b/toolkit/components/places/tests/unit/test_preventive_maintenance.js
@@ -654,17 +654,17 @@ tests.push({
desc: "Recalculate positions",
_unfiledBookmarks: [],
_toolbarBookmarks: [],
setup: function() {
const NUM_BOOKMARKS = 20;
bs.runInBatchMode({
- runBatched: function (aUserData) {
+ runBatched: function(aUserData) {
// Add bookmarks to two folders to better perturbate the table.
for (let i = 0; i < NUM_BOOKMARKS; i++) {
bs.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
NetUtil.newURI("http://example.com/"),
bs.DEFAULT_INDEX, "testbookmark");
}
for (let i = 0; i < NUM_BOOKMARKS; i++) {
bs.insertBookmark(PlacesUtils.toolbarFolderId,
@@ -1163,17 +1163,17 @@ tests.push({
transition: TRANSITION_REDIRECT_TEMPORARY,
referrer: NetUtil.newURI("http://l3.moz.org/redirecting/") },
{ uri: NetUtil.newURI("http://l3.moz.org/target/"),
transition: TRANSITION_REDIRECT_PERMANENT,
referrer: NetUtil.newURI("http://l3.moz.org/redirecting2/") },
]);
},
- check: function () {
+ check: function() {
return new Promise(resolve => {
let stmt = mDBConn.createAsyncStatement(
"SELECT h.url FROM moz_places h WHERE h.hidden = 1"
);
stmt.executeAsync({
_count: 0,
handleResult: function(aResultSet) {
for (let row; (row = aResultSet.getNextRow());) {
--- a/toolkit/components/places/tests/unit/test_preventive_maintenance_checkAndFixDatabase.js
+++ b/toolkit/components/places/tests/unit/test_preventive_maintenance_checkAndFixDatabase.js
@@ -14,17 +14,17 @@ Components.utils.import("resource://gre/
function run_test() {
do_test_pending();
PlacesDBUtils.checkAndFixDatabase(function(aLog) {
let sections = [];
let positives = [];
let negatives = [];
let infos = [];
- aLog.forEach(function (aMsg) {
+ aLog.forEach(function(aMsg) {
print(aMsg);
switch (aMsg.substr(0, 1)) {
case "+":
positives.push(aMsg);
break;
case "-":
negatives.push(aMsg);
break;
--- a/toolkit/components/places/tests/unit/test_preventive_maintenance_runTasks.js
+++ b/toolkit/components/places/tests/unit/test_preventive_maintenance_runTasks.js
@@ -12,17 +12,17 @@ Components.utils.import("resource://gre/
function run_test() {
do_test_pending();
PlacesDBUtils.runTasks([PlacesDBUtils.reindex], function(aLog) {
let sections = [];
let positives = [];
let negatives = [];
let infos = [];
- aLog.forEach(function (aMsg) {
+ aLog.forEach(function(aMsg) {
print(aMsg);
switch (aMsg.substr(0, 1)) {
case "+":
positives.push(aMsg);
break;
case "-":
negatives.push(aMsg);
break;
--- a/toolkit/components/places/tests/unit/test_resolveNullBookmarkTitles.js
+++ b/toolkit/components/places/tests/unit/test_resolveNullBookmarkTitles.js
@@ -10,17 +10,17 @@ function run_test() {
add_test(function test_resolveNullBookmarkTitles() {
let uri1 = uri("http://foo.tld/");
let uri2 = uri("https://bar.tld/");
PlacesTestUtils.addVisits([
{ uri: uri1, title: "foo title" },
{ uri: uri2, title: "bar title" }
- ]).then(function () {
+ ]).then(function() {
PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId,
uri1,
PlacesUtils.bookmarks.DEFAULT_INDEX,
null);
PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId,
uri2,
PlacesUtils.bookmarks.DEFAULT_INDEX,
null);
--- a/toolkit/components/printing/content/printPreviewProgress.js
+++ b/toolkit/components/printing/content/printPreviewProgress.js
@@ -30,49 +30,49 @@ function ellipseString(aStr, doFront)
return "..." + aStr.substr(aStr.length - fixedLen, fixedLen);
return aStr.substr(0, fixedLen) + "...";
}
// all progress notifications are done through the nsIWebProgressListener implementation...
var progressListener = {
- onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus)
+ onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus)
{
if (aStateFlags & Components.interfaces.nsIWebProgressListener.STATE_STOP)
window.close();
},
- onProgressChange: function (aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress)
+ onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress)
{
if (!progressParams)
return;
var docTitleStr = ellipseString(progressParams.docTitle, false);
if (docTitleStr != docTitle) {
docTitle = docTitleStr;
dialog.title.value = docTitle;
}
var docURLStr = ellipseString(progressParams.docURL, true);
if (docURLStr != docURL && dialog.title != null) {
docURL = docURLStr;
if (docTitle == "")
dialog.title.value = docURLStr;
}
},
- onLocationChange: function (aWebProgress, aRequest, aLocation, aFlags) {},
- onSecurityChange: function (aWebProgress, aRequest, state) {},
+ onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) {},
+ onSecurityChange: function(aWebProgress, aRequest, state) {},
- onStatusChange: function (aWebProgress, aRequest, aStatus, aMessage)
+ onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage)
{
if (aMessage)
dialog.title.setAttribute("value", aMessage);
},
- QueryInterface: function (iid)
+ QueryInterface: function(iid)
{
if (iid.equals(Components.interfaces.nsIWebProgressListener) || iid.equals(Components.interfaces.nsISupportsWeakReference))
return this;
throw Components.results.NS_NOINTERFACE;
}
}
function onLoad() {
@@ -112,17 +112,17 @@ function onUnload()
return;
try {
printProgress.unregisterListener(progressListener);
printProgress = null;
}
catch (e) {}
}
-function getString (stringId) {
+function getString(stringId) {
// Check if we've fetched this string already.
if (!(stringId in dialog.strings)) {
// Try to get it.
var elem = document.getElementById( "dialog.strings." + stringId);
try {
if (elem && elem.childNodes && elem.childNodes[0] &&
elem.childNodes[0].nodeValue)
dialog.strings[stringId] = elem.childNodes[0].nodeValue;
@@ -130,17 +130,17 @@ function getString (stringId) {
else
dialog.strings[stringId] = "";
} catch (e) { dialog.strings[stringId] = ""; }
}
return dialog.strings[stringId];
}
// If the user presses cancel, tell the app launcher and close the dialog...
-function onCancel ()
+function onCancel()
{
// Cancel app launcher.
try {
printProgress.processCanceledByUser = true;
}
catch (e) { return true; }
// don't Close up dialog by returning false, the backend will close the dialog when everything will be aborted.
--- a/toolkit/components/printing/content/printProgress.js
+++ b/toolkit/components/printing/content/printProgress.js
@@ -258,17 +258,17 @@ function onUnload()
printProgress = null;
}
catch ( exception ) {}
}
}
// If the user presses cancel, tell the app launcher and close the dialog...
-function onCancel ()
+function onCancel()
{
// Cancel app launcher.
try
{
printProgress.processCanceledByUser = true;
}
catch ( exception ) { return true; }
--- a/toolkit/components/printing/content/printUtils.js
+++ b/toolkit/components/printing/content/printUtils.js
@@ -77,17 +77,17 @@ var PrintUtils = {
},
/**
* Shows the page setup dialog, and saves any settings changed in
* that dialog if print.save_print_settings is set to true.
*
* @return true on success, false on failure
*/
- showPageSetup: function () {
+ showPageSetup: function() {
try {
var printSettings = this.getPrintSettings();
var PRINTPROMPTSVC = Components.classes["@mozilla.org/embedcomp/printingprompt-service;1"]
.getService(Components.interfaces.nsIPrintingPromptService);
PRINTPROMPTSVC.showPageSetup(window, printSettings, null);
if (gSavePrintSettings) {
// Page Setup data is a "native" setting on the Mac
var PSSVC = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
@@ -104,32 +104,32 @@ var PrintUtils = {
/**
* Starts the process of printing the contents of a window.
*
* @param aWindowID
* The outer window ID of the nsIDOMWindow to print.
* @param aBrowser
* The <xul:browser> that the nsIDOMWindow for aWindowID belongs to.
*/
- printWindow: function (aWindowID, aBrowser)
+ printWindow: function(aWindowID, aBrowser)
{
let mm = aBrowser.messageManager;
mm.sendAsyncMessage("Printing:Print", {
windowID: aWindowID,
simplifiedMode: this._shouldSimplify,
});
},
/**
* Deprecated.
*
* Starts the process of printing the contents of window.content.
*
*/
- print: function ()
+ print: function()
{
if (gBrowser) {
return this.printWindow(gBrowser.selectedBrowser.outerWindowID,
gBrowser.selectedBrowser);
}
if (this.usingRemoteTabs) {
throw new Error("PrintUtils.print cannot be run in windows running with " +
@@ -183,17 +183,17 @@ var PrintUtils = {
* onExit:
* Called upon exiting print preview.
*
* These methods must be defined. printPreview can be called
* with aListenerObj as null iff this window is already displaying
* print preview (in which case, the previous aListenerObj passed
* to it will be used).
*/
- printPreview: function (aListenerObj)
+ printPreview: function(aListenerObj)
{
// if we're already in PP mode, don't set the listener; chances
// are it is null because someone is calling printPreview() to
// get us to refresh the display.
if (!this.inPrintPreview) {
this._listener = aListenerObj;
this._sourceBrowser = aListenerObj.getSourceBrowser();
this._originalTitle = this._sourceBrowser.contentTitle;
@@ -251,17 +251,17 @@ var PrintUtils = {
* Returns the nsIWebBrowserPrint associated with some content window.
* This method is being kept here for compatibility reasons, but should not
* be called by code hoping to support e10s / remote browsers.
*
* @param aWindow
* The window from which to get the nsIWebBrowserPrint from.
* @return nsIWebBrowserPrint
*/
- getWebBrowserPrint: function (aWindow)
+ getWebBrowserPrint: function(aWindow)
{
let Deprecated = Components.utils.import("resource://gre/modules/Deprecated.jsm", {}).Deprecated;
let text = "getWebBrowserPrint is now deprecated, and fully unsupported for " +
"multi-process browsers. Please use a frame script to get " +
"access to nsIWebBrowserPrint from content.";
let url = "https://developer.mozilla.org/en-US/docs/Printing_from_a_XUL_App";
Deprecated.warning(text, url);
@@ -427,28 +427,28 @@ var PrintUtils = {
return listener.onStateChange(null, null,
data.stateFlags,
data.status);
}
}
return undefined;
},
- setPrinterDefaultsForSelectedPrinter: function (aPSSVC, aPrintSettings)
+ setPrinterDefaultsForSelectedPrinter: function(aPSSVC, aPrintSettings)
{
if (!aPrintSettings.printerName)
aPrintSettings.printerName = aPSSVC.defaultPrinterName;
// First get any defaults from the printer
aPSSVC.initPrintSettingsFromPrinter(aPrintSettings.printerName, aPrintSettings);
// now augment them with any values from last time
aPSSVC.initPrintSettingsFromPrefs(aPrintSettings, true, aPrintSettings.kInitSaveAll);
},
- getPrintSettings: function ()
+ getPrintSettings: function()
{
var pref = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
if (pref) {
gPrintSettingsAreGlobal = pref.getBoolPref("print.use_global_printsettings", false);
gSavePrintSettings = pref.getBoolPref("print.save_print_settings", false);
}
@@ -469,45 +469,45 @@ var PrintUtils = {
},
// This observer is called once the progress dialog has been "opened"
_obsPP:
{
observe: function(aSubject, aTopic, aData)
{
// delay the print preview to show the content of the progress dialog
- setTimeout(function () { PrintUtils.enterPrintPreview(); }, 0);
+ setTimeout(function() { PrintUtils.enterPrintPreview(); }, 0);
},
QueryInterface : function(iid)
{
if (iid.equals(Components.interfaces.nsIObserver) ||
iid.equals(Components.interfaces.nsISupportsWeakReference) ||
iid.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
}
},
- setSimplifiedMode: function (shouldSimplify)
+ setSimplifiedMode: function(shouldSimplify)
{
this._shouldSimplify = shouldSimplify;
},
- enterPrintPreview: function ()
+ enterPrintPreview: function()
{
// Send a message to the print preview browser to initialize
// print preview. If we happen to have gotten a print preview
// progress listener from nsIPrintingPromptService.showProgress
// in printPreview, we add listeners to feed that progress
// listener.
let ppBrowser = this._listener.getPrintPreviewBrowser();
let mm = ppBrowser.messageManager;
- let sendEnterPreviewMessage = function (browser, simplified) {
+ let sendEnterPreviewMessage = function(browser, simplified) {
mm.sendAsyncMessage("Printing:Preview:Enter", {
windowID: browser.outerWindowID,
simplifiedMode: simplified,
});
};
// If we happen to have gotten simplify page checked, we will lazily
// instantiate a new tab that parses the original page using ReaderMode
@@ -617,17 +617,17 @@ var PrintUtils = {
ppBrowser.focus();
// on Enter PP Call back
this._listener.onEnter();
};
mm.addMessageListener("Printing:Preview:Entered", onEntered);
},
- exitPrintPreview: function ()
+ exitPrintPreview: function()
{
let ppBrowser = this._listener.getPrintPreviewBrowser();
let browserMM = ppBrowser.messageManager;
browserMM.sendAsyncMessage("Printing:Preview:Exit");
window.removeEventListener("keydown", this.onKeyDownPP, true);
window.removeEventListener("keypress", this.onKeyPressPP, true);
// restore the old close handler
@@ -646,31 +646,31 @@ var PrintUtils = {
this._sourceBrowser.focus();
gFocusedElement = null;
this.setSimplifiedMode(false);
this._listener.onExit();
},
- logTelemetry: function (ID)
+ logTelemetry: function(ID)
{
let histogram = Services.telemetry.getHistogramById(ID);
histogram.add(true);
},
- onKeyDownPP: function (aEvent)
+ onKeyDownPP: function(aEvent)
{
// Esc exits the PP
if (aEvent.keyCode == aEvent.DOM_VK_ESCAPE) {
PrintUtils.exitPrintPreview();
}
},
- onKeyPressPP: function (aEvent)
+ onKeyPressPP: function(aEvent)
{
var closeKey;
try {
closeKey = document.getElementById("key_close")
.getAttribute("key");
closeKey = aEvent["DOM_VK_" + closeKey];
} catch (e) {}
var isModif = aEvent.ctrlKey || aEvent.metaKey;
--- a/toolkit/components/printing/content/printdialog.js
+++ b/toolkit/components/printing/content/printdialog.js
@@ -94,27 +94,27 @@ function getPrinterDescription(printerNa
function listElement(aListElement)
{
this.listElement = aListElement;
}
listElement.prototype =
{
clearList:
- function ()
+ function()
{
// remove the menupopup node child of the menulist.
var popup = this.listElement.firstChild;
if (popup) {
this.listElement.removeChild(popup);
}
},
appendPrinterNames:
- function (aDataObject)
+ function(aDataObject)
{
if ((null == aDataObject) || !aDataObject.hasMore()) {
// disable dialog
this.listElement.setAttribute("value", "");
this.listElement.setAttribute("label",
document.getElementById("printingBundle")
.getString("noprinter"));
--- a/toolkit/components/printing/content/printjoboptions.js
+++ b/toolkit/components/printing/content/printjoboptions.js
@@ -87,24 +87,24 @@ function round10(val)
function paperListElement(aPaperListElement)
{
this.paperListElement = aPaperListElement;
}
paperListElement.prototype =
{
clearPaperList:
- function ()
+ function()
{
// remove the menupopup node child of the menulist.
this.paperListElement.removeChild(this.paperListElement.firstChild);
},
appendPaperNames:
- function (aDataObject)
+ function(aDataObject)
{
var popupNode = document.createElement("menupopup");
for (var i = 0;i < aDataObject.length;i++) {
var paperObj = aDataObject[i];
var itemNode = document.createElement("menuitem");
var label;
try {
label = gPrintBundle.getString(paperObj.name);
--- a/toolkit/components/privatebrowsing/PrivateBrowsingTrackingProtectionWhitelist.js
+++ b/toolkit/components/privatebrowsing/PrivateBrowsingTrackingProtectionWhitelist.js
@@ -53,16 +53,16 @@ PrivateBrowsingTrackingProtectionWhiteli
*
* @param uri nsIURI
* The URI to add to the list.
*/
existsInAllowList(uri) {
return this._allowlist.indexOf(uri.spec) !== -1;
},
- observe: function (subject, topic, data) {
+ observe: function(subject, topic, data) {
if (topic == "last-pb-context-exited") {
this._allowlist = [];
}
}
};
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([PrivateBrowsingTrackingProtectionWhitelist]);
--- a/toolkit/components/processsingleton/ContentProcessSingleton.js
+++ b/toolkit/components/processsingleton/ContentProcessSingleton.js
@@ -99,17 +99,17 @@ ContentProcessSingleton.prototype = {
case "xpcom-shutdown":
Services.obs.removeObserver(this, "console-api-log-event");
Services.obs.removeObserver(this, "xpcom-shutdown");
cpmm.removeMessageListener("DevTools:InitDebuggerServer", this);
break;
}
},
- receiveMessage: function (message) {
+ receiveMessage: function(message) {
// load devtools component on-demand
// Only reply if we are in a real content process
if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
let {init} = Cu.import("resource://devtools/server/content-server.jsm", {});
init(message);
}
},
};
--- a/toolkit/components/prompts/src/CommonDialog.jsm
+++ b/toolkit/components/prompts/src/CommonDialog.jsm
@@ -216,17 +216,17 @@ CommonDialog.prototype = {
// XXXjag bug 325251
// Need to set this after aNode.setAttribute("value", aLabel);
if (accessKey)
aNode.accessKey = accessKey;
},
- initTextbox : function (aName, aValue) {
+ initTextbox : function(aName, aValue) {
this.ui[aName + "Container"].hidden = false;
this.ui[aName + "Textbox"].setAttribute("value",
aValue !== null ? aValue : "");
},
setButtonsEnabledState : function(enabled) {
this.ui.button0.disabled = !enabled;
// button1 (cancel) remains enabled.
--- a/toolkit/components/prompts/src/SharedPromptUtils.jsm
+++ b/toolkit/components/prompts/src/SharedPromptUtils.jsm
@@ -11,40 +11,40 @@ this.PromptUtils = {
// Fire a dialog open/close event. Used by tabbrowser to focus the
// tab which is triggering a prompt.
// For remote dialogs, we pass in a different DOM window and a separate
// target. If the caller doesn't pass in the target, then we'll simply use
// the passed-in DOM window.
// The detail may contain information about the principal on which the
// prompt is triggered, as well as whether or not this is a tabprompt
// (ie tabmodal alert/prompt/confirm and friends)
- fireDialogEvent : function (domWin, eventName, maybeTarget, detail) {
+ fireDialogEvent : function(domWin, eventName, maybeTarget, detail) {
let target = maybeTarget || domWin;
let eventOptions = {cancelable: true, bubbles: true};
if (detail) {
eventOptions.detail = detail;
}
let event = new domWin.CustomEvent(eventName, eventOptions);
let winUtils = domWin.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
winUtils.dispatchEventToChromeOnly(target, event);
},
- objectToPropBag : function (obj) {
+ objectToPropBag : function(obj) {
let bag = Cc["@mozilla.org/hash-property-bag;1"].
createInstance(Ci.nsIWritablePropertyBag2);
bag.QueryInterface(Ci.nsIWritablePropertyBag);
for (let propName in obj)
bag.setProperty(propName, obj[propName]);
return bag;
},
- propBagToObject : function (propBag, obj) {
+ propBagToObject : function(propBag, obj) {
// Here we iterate over the object's original properties, not the bag
// (ie, the prompt can't return more/different properties than were
// passed in). This just helps ensure that the caller provides default
// values, lest the prompt forget to set them.
for (let propName in obj)
obj[propName] = propBag.getProperty(propName);
},
};
@@ -95,27 +95,27 @@ this.EnableDelayHelper.prototype = {
break;
case "unload":
this.onUnload();
break;
}
},
- onBlur : function () {
+ onBlur : function() {
this.disableDialog();
// If we blur while waiting to enable the buttons, just cancel the
// timer to ensure the delay doesn't fire while not focused.
if (this._focusTimer) {
this._focusTimer.cancel();
this._focusTimer = null;
}
},
- onFocus : function () {
+ onFocus : function() {
this.startOnFocusDelay();
},
onUnload: function() {
this.focusTarget.removeEventListener("blur", this, false);
this.focusTarget.removeEventListener("focus", this, false);
this.focusTarget.document.removeEventListener("unload", this, false);
@@ -142,16 +142,16 @@ this.EnableDelayHelper.prototype = {
onFocusTimeout : function() {
this._focusTimer = null;
this.enableDialog();
},
};
function makeSafe(fn) {
- return function () {
+ return function() {
// The dialog could be gone by now (if the user closed it),
// which makes it likely that the given fn might throw.
try {
fn();
} catch (e) { }
};
}
--- a/toolkit/components/prompts/src/nsPrompter.js
+++ b/toolkit/components/prompts/src/nsPrompter.js
@@ -19,25 +19,25 @@ function Prompter() {
Prompter.prototype = {
classID : Components.ID("{1c978d25-b37f-43a8-a2d6-0c7a239ead87}"),
QueryInterface : XPCOMUtils.generateQI([Ci.nsIPromptFactory, Ci.nsIPromptService, Ci.nsIPromptService2]),
/* ---------- private members ---------- */
- pickPrompter : function (domWin) {
+ pickPrompter : function(domWin) {
return new ModalPrompter(domWin);
},
/* ---------- nsIPromptFactory ---------- */
- getPrompt : function (domWin, iid) {
+ getPrompt : function(domWin, iid) {
// This is still kind of dumb; the C++ code delegated to login manager
// here, which in turn calls back into us via nsIPromptService2.
if (iid.equals(Ci.nsIAuthPrompt2) || iid.equals(Ci.nsIAuthPrompt)) {
try {
let pwmgr = Cc["@mozilla.org/passwordmanager/authpromptfactory;1"].
getService(Ci.nsIPromptFactory);
return pwmgr.getPrompt(domWin, iid);
} catch (e) {
@@ -49,89 +49,89 @@ Prompter.prototype = {
p.QueryInterface(iid);
return p;
},
/* ---------- nsIPromptService ---------- */
- alert : function (domWin, title, text) {
+ alert : function(domWin, title, text) {
let p = this.pickPrompter(domWin);
p.alert(title, text);
},
- alertCheck : function (domWin, title, text, checkLabel, checkValue) {
+ alertCheck : function(domWin, title, text, checkLabel, checkValue) {
let p = this.pickPrompter(domWin);
p.alertCheck(title, text, checkLabel, checkValue);
},
- confirm : function (domWin, title, text) {
+ confirm : function(domWin, title, text) {
let p = this.pickPrompter(domWin);
return p.confirm(title, text);
},
- confirmCheck : function (domWin, title, text, checkLabel, checkValue) {
+ confirmCheck : function(domWin, title, text, checkLabel, checkValue) {
let p = this.pickPrompter(domWin);
return p.confirmCheck(title, text, checkLabel, checkValue);
},
- confirmEx : function (domWin, title, text, flags, button0, button1, button2, checkLabel, checkValue) {
+ confirmEx : function(domWin, title, text, flags, button0, button1, button2, checkLabel, checkValue) {
let p = this.pickPrompter(domWin);
return p.confirmEx(title, text, flags, button0, button1, button2, checkLabel, checkValue);
},
- prompt : function (domWin, title, text, value, checkLabel, checkValue) {
+ prompt : function(domWin, title, text, value, checkLabel, checkValue) {
let p = this.pickPrompter(domWin);
return p.nsIPrompt_prompt(title, text, value, checkLabel, checkValue);
},
- promptUsernameAndPassword : function (domWin, title, text, user, pass, checkLabel, checkValue) {
+ promptUsernameAndPassword : function(domWin, title, text, user, pass, checkLabel, checkValue) {
let p = this.pickPrompter(domWin);
return p.nsIPrompt_promptUsernameAndPassword(title, text, user, pass, checkLabel, checkValue);
},
- promptPassword : function (domWin, title, text, pass, checkLabel, checkValue) {
+ promptPassword : function(domWin, title, text, pass, checkLabel, checkValue) {
let p = this.pickPrompter(domWin);
return p.nsIPrompt_promptPassword(title, text, pass, checkLabel, checkValue);
},
- select : function (domWin, title, text, count, list, selected) {
+ select : function(domWin, title, text, count, list, selected) {
let p = this.pickPrompter(domWin);
return p.select(title, text, count, list, selected);
},
/* ---------- nsIPromptService2 ---------- */
- promptAuth : function (domWin, channel, level, authInfo, checkLabel, checkValue) {
+ promptAuth : function(domWin, channel, level, authInfo, checkLabel, checkValue) {
let p = this.pickPrompter(domWin);
return p.promptAuth(channel, level, authInfo, checkLabel, checkValue);
},
- asyncPromptAuth : function (domWin, channel, callback, context, level, authInfo, checkLabel, checkValue) {
+ asyncPromptAuth : function(domWin, channel, callback, context, level, authInfo, checkLabel, checkValue) {
let p = this.pickPrompter(domWin);
return p.asyncPromptAuth(channel, callback, context, level, authInfo, checkLabel, checkValue);
},
};
// Common utils not specific to a particular prompter style.
var PromptUtilsTemp = {
__proto__ : PromptUtils,
- getLocalizedString : function (key, formatArgs) {
+ getLocalizedString : function(key, formatArgs) {
if (formatArgs)
return this.strBundle.formatStringFromName(key, formatArgs, formatArgs.length);
return this.strBundle.GetStringFromName(key);
},
- confirmExHelper : function (flags, button0, button1, button2) {
+ confirmExHelper : function(flags, button0, button1, button2) {
const BUTTON_DEFAULT_MASK = 0x03000000;
let defaultButtonNum = (flags & BUTTON_DEFAULT_MASK) >> 24;
let isDelayEnabled = (flags & Ci.nsIPrompt.BUTTON_DELAY_ENABLE);
// Flags can be used to select a specific pre-defined button label or
// a caller-supplied string (button0/button1/button2). If no flags are
// set for a button, then the button won't be shown.
let argText = [button0, button1, button2];
@@ -167,31 +167,31 @@ var PromptUtilsTemp = {
if (buttonLabel)
buttonLabels[i] = buttonLabel;
flags >>= 8;
}
return [buttonLabels[0], buttonLabels[1], buttonLabels[2], defaultButtonNum, isDelayEnabled];
},
- getAuthInfo : function (authInfo) {
+ getAuthInfo : function(authInfo) {
let username, password;
let flags = authInfo.flags;
if (flags & Ci.nsIAuthInformation.NEED_DOMAIN && authInfo.domain)
username = authInfo.domain + "\\" + authInfo.username;
else
username = authInfo.username;
password = authInfo.password;
return [username, password];
},
- setAuthInfo : function (authInfo, username, password) {
+ setAuthInfo : function(authInfo, username, password) {
let flags = authInfo.flags;
if (flags & Ci.nsIAuthInformation.NEED_DOMAIN) {
// Domain is separated from username by a backslash
let idx = username.indexOf("\\");
if (idx == -1) {
authInfo.username = username;
} else {
authInfo.domain = username.substring(0, idx);
@@ -201,22 +201,22 @@ var PromptUtilsTemp = {
authInfo.username = username;
}
authInfo.password = password;
},
/**
* Strip out things like userPass and path for display.
*/
- getFormattedHostname : function (uri) {
+ getFormattedHostname : function(uri) {
return uri.scheme + "://" + uri.hostPort;
},
// Copied from login manager
- getAuthTarget : function (aChannel, aAuthInfo) {
+ getAuthTarget : function(aChannel, aAuthInfo) {
let hostname, realm;
// If our proxy is demanding authentication, don't use the
// channel's actual destination.
if (aAuthInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY) {
if (!(aChannel instanceof Ci.nsIProxiedChannel))
throw "proxy auth needs nsIProxiedChannel";
@@ -246,17 +246,17 @@ var PromptUtilsTemp = {
realm = aAuthInfo.realm;
if (!realm)
realm = hostname;
return [hostname, realm];
},
- makeAuthMessage : function (channel, authInfo) {
+ makeAuthMessage : function(channel, authInfo) {
let isProxy = (authInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY);
let isPassOnly = (authInfo.flags & Ci.nsIAuthInformation.ONLY_PASSWORD);
let isCrossOrig = (authInfo.flags &
Ci.nsIAuthInformation.CROSS_ORIGIN_SUB_RESOURCE);
let username = authInfo.username;
let [displayHost, realm] = this.getAuthTarget(channel, authInfo);
@@ -282,17 +282,17 @@ var PromptUtilsTemp = {
text = PromptUtils.getLocalizedString("EnterUserPasswordFor2", [displayHost]);
} else {
text = PromptUtils.getLocalizedString("EnterLoginForRealm3", [realm, displayHost]);
}
return text;
},
- getTabModalPrompt : function (domWin) {
+ getTabModalPrompt : function(domWin) {
var promptBox = null;
try {
// Get the topmost window, in case we're in a frame.
var promptWin = domWin.top;
// Get the chrome window for the content window we're using.
// (Unwrap because we need a non-IDL property below.)
@@ -309,26 +309,26 @@ var PromptUtilsTemp = {
}
return promptBox;
},
};
PromptUtils = PromptUtilsTemp;
-XPCOMUtils.defineLazyGetter(PromptUtils, "strBundle", function () {
+XPCOMUtils.defineLazyGetter(PromptUtils, "strBundle", function() {
let bunService = Cc["@mozilla.org/intl/stringbundle;1"].
getService(Ci.nsIStringBundleService);
let bundle = bunService.createBundle("chrome://global/locale/commonDialogs.properties");
if (!bundle)
throw "String bundle for Prompter not present!";
return bundle;
});
-XPCOMUtils.defineLazyGetter(PromptUtils, "ellipsis", function () {
+XPCOMUtils.defineLazyGetter(PromptUtils, "ellipsis", function() {
let ellipsis = "\u2026";
try {
ellipsis = Services.prefs.getComplexValue("intl.ellipsis", Ci.nsIPrefLocalizedString).data;
} catch (e) { }
return ellipsis;
});
@@ -511,17 +511,17 @@ ModalPrompter.prototype = {
QueryInterface : XPCOMUtils.generateQI([Ci.nsIPrompt, Ci.nsIAuthPrompt,
Ci.nsIAuthPrompt2,
Ci.nsIWritablePropertyBag2]),
/* ---------- internal methods ---------- */
- openPrompt : function (args) {
+ openPrompt : function(args) {
// Check pref, if false/missing do not ever allow tab-modal prompts.
const prefName = "prompts.tab_modal.enabled";
let prefValue = false;
if (Services.prefs.getPrefType(prefName) == Services.prefs.PREF_BOOL)
prefValue = Services.prefs.getBoolPref(prefName);
let allowTabModal = this.allowTabModal && prefValue;
@@ -585,30 +585,30 @@ ModalPrompter.prototype = {
return this.nsIPrompt_promptPassword.apply(this, arguments);
return this.nsIAuthPrompt_promptPassword.apply(this, arguments);
},
/* ---------- nsIPrompt ---------- */
- alert : function (title, text) {
+ alert : function(title, text) {
if (!title)
title = PromptUtils.getLocalizedString("Alert");
let args = {
promptType: "alert",
title: title,
text: text,
};
this.openPrompt(args);
},
- alertCheck : function (title, text, checkLabel, checkValue) {
+ alertCheck : function(title, text, checkLabel, checkValue) {
if (!title)
title = PromptUtils.getLocalizedString("Alert");
let args = {
promptType: "alertCheck",
title: title,
text: text,
checkLabel: checkLabel,
@@ -616,34 +616,34 @@ ModalPrompter.prototype = {
};
this.openPrompt(args);
// Checkbox state always returned, even if cancel clicked.
checkValue.value = args.checked;
},
- confirm : function (title, text) {
+ confirm : function(title, text) {
if (!title)
title = PromptUtils.getLocalizedString("Confirm");
let args = {
promptType: "confirm",
title: title,
text: text,
ok: false,
};
this.openPrompt(args);
// Did user click Ok or Cancel?
return args.ok;
},
- confirmCheck : function (title, text, checkLabel, checkValue) {
+ confirmCheck : function(title, text, checkLabel, checkValue) {
if (!title)
title = PromptUtils.getLocalizedString("ConfirmCheck");
let args = {
promptType: "confirmCheck",
title: title,
text: text,
checkLabel: checkLabel,
@@ -655,18 +655,18 @@ ModalPrompter.prototype = {
// Checkbox state always returned, even if cancel clicked.
checkValue.value = args.checked;
// Did user click Ok or Cancel?
return args.ok;
},
- confirmEx : function (title, text, flags, button0, button1, button2,
- checkLabel, checkValue) {
+ confirmEx : function(title, text, flags, button0, button1, button2,
+ checkLabel, checkValue) {
if (!title)
title = PromptUtils.getLocalizedString("Confirm");
let args = {
promptType: "confirmEx",
title: title,
text: text,
@@ -696,17 +696,17 @@ ModalPrompter.prototype = {
// Checkbox state always returned, even if cancel clicked.
checkValue.value = args.checked;
// Get the number of the button the user clicked.
return args.buttonNumClicked;
},
- nsIPrompt_prompt : function (title, text, value, checkLabel, checkValue) {
+ nsIPrompt_prompt : function(title, text, value, checkLabel, checkValue) {
if (!title)
title = PromptUtils.getLocalizedString("Prompt");
let args = {
promptType: "prompt",
title: title,
text: text,
value: value.value,
@@ -722,17 +722,17 @@ ModalPrompter.prototype = {
if (ok) {
checkValue.value = args.checked;
value.value = args.value;
}
return ok;
},
- nsIPrompt_promptUsernameAndPassword : function (title, text, user, pass, checkLabel, checkValue) {
+ nsIPrompt_promptUsernameAndPassword : function(title, text, user, pass, checkLabel, checkValue) {
if (!title)
title = PromptUtils.getLocalizedString("PromptUsernameAndPassword2");
let args = {
promptType: "promptUserAndPass",
title: title,
text: text,
user: user.value,
@@ -750,17 +750,17 @@ ModalPrompter.prototype = {
checkValue.value = args.checked;
user.value = args.user;
pass.value = args.pass;
}
return ok;
},
- nsIPrompt_promptPassword : function (title, text, pass, checkLabel, checkValue) {
+ nsIPrompt_promptPassword : function(title, text, pass, checkLabel, checkValue) {
if (!title)
title = PromptUtils.getLocalizedString("PromptPassword2");
let args = {
promptType: "promptPassword",
title: title,
text: text,
pass: pass.value,
@@ -776,17 +776,17 @@ ModalPrompter.prototype = {
if (ok) {
checkValue.value = args.checked;
pass.value = args.pass;
}
return ok;
},
- select : function (title, text, count, list, selected) {
+ select : function(title, text, count, list, selected) {
if (!title)
title = PromptUtils.getLocalizedString("Select");
let args = {
promptType: "select",
title: title,
text: text,
list: list,
@@ -803,38 +803,38 @@ ModalPrompter.prototype = {
return ok;
},
/* ---------- nsIAuthPrompt ---------- */
- nsIAuthPrompt_prompt : function (title, text, passwordRealm, savePassword, defaultText, result) {
+ nsIAuthPrompt_prompt : function(title, text, passwordRealm, savePassword, defaultText, result) {
// The passwordRealm and savePassword args were ignored by nsPrompt.cpp
if (defaultText)
result.value = defaultText;
return this.nsIPrompt_prompt(title, text, result, null, {});
},
- nsIAuthPrompt_promptUsernameAndPassword : function (title, text, passwordRealm, savePassword, user, pass) {
+ nsIAuthPrompt_promptUsernameAndPassword : function(title, text, passwordRealm, savePassword, user, pass) {
// The passwordRealm and savePassword args were ignored by nsPrompt.cpp
return this.nsIPrompt_promptUsernameAndPassword(title, text, user, pass, null, {});
},
- nsIAuthPrompt_promptPassword : function (title, text, passwordRealm, savePassword, pass) {
+ nsIAuthPrompt_promptPassword : function(title, text, passwordRealm, savePassword, pass) {
// The passwordRealm and savePassword args were ignored by nsPrompt.cpp
return this.nsIPrompt_promptPassword(title, text, pass, null, {});
},
/* ---------- nsIAuthPrompt2 ---------- */
- promptAuth : function (channel, level, authInfo, checkLabel, checkValue) {
+ promptAuth : function(channel, level, authInfo, checkLabel, checkValue) {
let message = PromptUtils.makeAuthMessage(channel, authInfo);
let [username, password] = PromptUtils.getAuthInfo(authInfo);
let userParam = { value: username };
let passParam = { value: password };
let ok;
@@ -843,17 +843,17 @@ ModalPrompter.prototype = {
else
ok = this.nsIPrompt_promptUsernameAndPassword(null, message, userParam, passParam, checkLabel, checkValue);
if (ok)
PromptUtils.setAuthInfo(authInfo, userParam.value, passParam.value);
return ok;
},
- asyncPromptAuth : function (channel, callback, context, level, authInfo, checkLabel, checkValue) {
+ asyncPromptAuth : function(channel, callback, context, level, authInfo, checkLabel, checkValue) {
// Nothing calls this directly; netwerk ends up going through
// nsIPromptService::GetPrompt, which delegates to login manager.
// Login manger handles the async bits itself, and only calls out
// promptAuth, never asyncPromptAuth.
//
// Bug 565582 will change this.
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
},
@@ -874,33 +874,33 @@ ModalPrompter.prototype = {
function AuthPromptAdapterFactory() {
}
AuthPromptAdapterFactory.prototype = {
classID : Components.ID("{6e134924-6c3a-4d86-81ac-69432dd971dc}"),
QueryInterface : XPCOMUtils.generateQI([Ci.nsIAuthPromptAdapterFactory]),
/* ---------- nsIAuthPromptAdapterFactory ---------- */
- createAdapter : function (oldPrompter) {
+ createAdapter : function(oldPrompter) {
return new AuthPromptAdapter(oldPrompter);
}
};
// Takes an nsIAuthPrompt implementation, wraps it with a nsIAuthPrompt2 shell.
function AuthPromptAdapter(oldPrompter) {
this.oldPrompter = oldPrompter;
}
AuthPromptAdapter.prototype = {
QueryInterface : XPCOMUtils.generateQI([Ci.nsIAuthPrompt2]),
oldPrompter : null,
/* ---------- nsIAuthPrompt2 ---------- */
- promptAuth : function (channel, level, authInfo, checkLabel, checkValue) {
+ promptAuth : function(channel, level, authInfo, checkLabel, checkValue) {
let message = PromptUtils.makeAuthMessage(channel, authInfo);
let [username, password] = PromptUtils.getAuthInfo(authInfo);
let userParam = { value: username };
let passParam = { value: password };
let [host, realm] = PromptUtils.getAuthTarget(channel, authInfo);
let authTarget = host + " (" + realm + ")";
@@ -911,17 +911,17 @@ AuthPromptAdapter.prototype = {
else
ok = this.oldPrompter.promptUsernameAndPassword(null, message, authTarget, Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, userParam, passParam);
if (ok)
PromptUtils.setAuthInfo(authInfo, userParam.value, passParam.value);
return ok;
},
- asyncPromptAuth : function (channel, callback, context, level, authInfo, checkLabel, checkValue) {
+ asyncPromptAuth : function(channel, callback, context, level, authInfo, checkLabel, checkValue) {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
};
// Wrapper using the old embedding contractID, since it's already common in
// the addon ecosystem.
function EmbedPrompter() {
--- a/toolkit/components/prompts/test/test_bug619644.html
+++ b/toolkit/components/prompts/test/test_bug619644.html
@@ -13,17 +13,17 @@ https://bugzilla.mozilla.org/show_bug.cg
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=619644">Mozilla Bug 619644</a>
<pre id="test">
<script class="testbody" type="text/javascript">
// This is a little yucky, but it works
// The contents of bug619644_inner.html
const expectedFinalDoc =
-"<head><\/head><body><p>Original content<\/p>\n<script>\n window.opener.postMessage(\"\", \"*\");\n confirm (\"Message\");\n document.write (\"Extra content\");\n window.opener.postMessage(document.documentElement.innerHTML, \"*\");\n<\/script>Extra content<\/body>";
+"<head><\/head><body><p>Original content<\/p>\n<script>\n window.opener.postMessage(\"\", \"*\");\n confirm(\"Message\");\n document.write(\"Extra content\");\n window.opener.postMessage(document.documentElement.innerHTML, \"*\");\n<\/script>Extra content<\/body>";
if (!isTabModal) {
todo(false, "Test disabled when tab modal prompts are not enabled.");
} else {
inittest();
}
var promptDone;
--- a/toolkit/components/reader/AboutReader.jsm
+++ b/toolkit/components/reader/AboutReader.jsm
@@ -173,17 +173,17 @@ AboutReader.prototype = {
get viewId() {
let _viewId = Cc["@mozilla.org/uuid-generator;1"].
getService(Ci.nsIUUIDGenerator).generateUUID().toString();
Object.defineProperty(this, "viewId", { value: _viewId });
return _viewId;
},
- receiveMessage: function (message) {
+ receiveMessage: function(message) {
switch (message.name) {
// Triggered by Android user pressing BACK while the banner font-dropdown is open.
case "Reader:CloseDropdown": {
// Just close it.
this._closeDropdowns();
break;
}
--- a/toolkit/components/reader/ReaderMode.jsm
+++ b/toolkit/components/reader/ReaderMode.jsm
@@ -62,17 +62,17 @@ this.ReaderMode = {
},
get isOnLowMemoryPlatform() {
let memory = Cc["@mozilla.org/xpcom/memory-service;1"].getService(Ci.nsIMemory);
delete this.isOnLowMemoryPlatform;
return this.isOnLowMemoryPlatform = memory.isLowMemoryPlatform();
},
- _getStateForParseOnLoad: function () {
+ _getStateForParseOnLoad: function() {
let isEnabled = Services.prefs.getBoolPref("reader.parse-on-load.enabled");
let isForceEnabled = Services.prefs.getBoolPref("reader.parse-on-load.force-enabled");
// For low-memory devices, don't allow reader mode since it takes up a lot of memory.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=792603 for details.
return isForceEnabled || (isEnabled && !this.isOnLowMemoryPlatform);
},
observe: function(aMessage, aTopic, aData) {
@@ -228,17 +228,17 @@ this.ReaderMode = {
if (!this._shouldCheckUri(uri, true)) {
this.log("Reader mode disabled for URI");
return null;
}
return yield this._readerParse(uri, doc);
}),
- _downloadDocument: function (url) {
+ _downloadDocument: function(url) {
let histogram = Services.telemetry.getHistogramById("READER_MODE_DOWNLOAD_RESULT");
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onerror = evt => reject(evt.error);
xhr.responseType = "document";
xhr.onload = evt => {
if (xhr.status !== 200) {
@@ -377,17 +377,17 @@ this.ReaderMode = {
"mail.google.com",
"github.com",
"pinterest.com",
"reddit.com",
"twitter.com",
"youtube.com",
],
- _shouldCheckUri: function (uri, isBaseUri = false) {
+ _shouldCheckUri: function(uri, isBaseUri = false) {
if (!(uri.schemeIs("http") || uri.schemeIs("https"))) {
this.log("Not parsing URI scheme: " + uri.scheme);
return false;
}
try {
uri.QueryInterface(Ci.nsIURL);
} catch (ex) {
@@ -480,34 +480,34 @@ this.ReaderMode = {
},
/**
* Calculate the hashed path for a stripped article URL.
*
* @param url The article URL. This should have referrers removed.
* @return The file path to the cached article.
*/
- _toHashedPath: function (url) {
+ _toHashedPath: function(url) {
let value = this._unicodeConverter.convertToByteArray(url);
this._cryptoHash.init(this._cryptoHash.MD5);
this._cryptoHash.update(value, value.length);
let hash = CommonUtils.encodeBase32(this._cryptoHash.finish(false));
let fileName = hash.substring(0, hash.indexOf("=")) + ".json";
return OS.Path.join(OS.Constants.Path.profileDir, "readercache", fileName);
},
/**
* Ensures the cache directory exists.
*
* @return Promise
* @resolves When the cache directory exists.
* @rejects OS.File.Error
*/
- _ensureCacheDir: function () {
+ _ensureCacheDir: function() {
let dir = OS.Path.join(OS.Constants.Path.profileDir, "readercache");
return OS.File.exists(dir).then(exists => {
if (!exists) {
return OS.File.makeDir(dir);
}
return undefined;
});
}
--- a/toolkit/components/reader/ReaderWorker.js
+++ b/toolkit/components/reader/ReaderWorker.js
@@ -38,13 +38,13 @@ var Agent = {
/**
* Parses structured article data from a document.
*
* @param {object} uri URI data for the document.
* @param {string} serializedDoc The serialized document.
*
* @return {object} Article object returned from Readability.
*/
- parseDocument: function (uri, serializedDoc) {
+ parseDocument: function(uri, serializedDoc) {
let doc = new JSDOMParser().parse(serializedDoc);
return new Readability(uri, doc).parse();
},
};
--- a/toolkit/components/reader/content/aboutReader.js
+++ b/toolkit/components/reader/content/aboutReader.js
@@ -1,9 +1,9 @@
/* 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";
-window.addEventListener("DOMContentLoaded", function () {
+window.addEventListener("DOMContentLoaded", function() {
document.dispatchEvent(new CustomEvent("AboutReaderContentLoaded", { bubbles: true }));
});
--- a/toolkit/components/reader/test/browser_readerMode.js
+++ b/toolkit/components/reader/test/browser_readerMode.js
@@ -61,17 +61,17 @@ add_task(function* test_reader_button()
ok(readerUrl.startsWith("about:reader"), "about:reader loaded after clicking reader mode button");
is_element_visible(readerButton, "Reader mode button is present on about:reader");
is(gURLBar.value, readerUrl, "gURLBar value is about:reader URL");
is(gURLBar.textValue, url.substring("http://".length), "gURLBar is displaying original article URL");
// Check selected value for URL bar
yield new Promise((resolve, reject) => {
- waitForClipboard(url, function () {
+ waitForClipboard(url, function() {
gURLBar.focus();
gURLBar.select();
goDoCommand("cmd_copy");
}, resolve, reject);
});
info("Got correct URL when copying");
--- a/toolkit/components/satchel/FormHistory.jsm
+++ b/toolkit/components/satchel/FormHistory.jsm
@@ -1041,39 +1041,39 @@ this.FormHistory = {
stmt.params["tokenContains" + i] = "%" + escapedToken + "%";
}
} else {
// no additional params need to be substituted into the query when the
// length is zero or one
}
let pending = stmt.executeAsync({
- handleResult : function (aResultSet) {
+ handleResult : function(aResultSet) {
for (let row = aResultSet.getNextRow(); row; row = aResultSet.getNextRow()) {
let value = row.getResultByName("value");
let frecency = row.getResultByName("frecency");
let entry = {
text : value,
textLowerCase : value.toLowerCase(),
frecency : frecency,
totalScore : Math.round(frecency * row.getResultByName("boundaryBonuses"))
};
if (aCallbacks && aCallbacks.handleResult) {
aCallbacks.handleResult(entry);
}
}
},
- handleError : function (aError) {
+ handleError : function(aError) {
if (aCallbacks && aCallbacks.handleError) {
aCallbacks.handleError(aError);
}
},
- handleCompletion : function (aReason) {
+ handleCompletion : function(aReason) {
if (aCallbacks && aCallbacks.handleCompletion) {
aCallbacks.handleCompletion(aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED ? 0 : 1);
}
}
});
return pending;
},
--- a/toolkit/components/satchel/formSubmitListener.js
+++ b/toolkit/components/satchel/formSubmitListener.js
@@ -23,25 +23,25 @@ var satchelFormListener = {
init : function() {
Services.obs.addObserver(this, "earlyformsubmit", false);
Services.prefs.addObserver("browser.formfill.", this, false);
this.updatePrefs();
addEventListener("unload", this, false);
},
- updatePrefs : function () {
+ updatePrefs : function() {
this.debug = Services.prefs.getBoolPref("browser.formfill.debug");
this.enabled = Services.prefs.getBoolPref("browser.formfill.enable");
this.saveHttpsForms = Services.prefs.getBoolPref("browser.formfill.saveHttpsForms");
},
// Implements the Luhn checksum algorithm as described at
// http://wikipedia.org/wiki/Luhn_algorithm
- isValidCCNumber : function (ccNumber) {
+ isValidCCNumber : function(ccNumber) {
// Remove dashes and whitespace
ccNumber = ccNumber.replace(/[\-\s]/g, '');
let len = ccNumber.length;
if (len != 9 && len != 15 && len != 16)
return false;
if (!/^\d+$/.test(ccNumber))
@@ -56,17 +56,17 @@ var satchelFormListener = {
if (ch > 9)
ch -= 9;
}
total += ch;
}
return total % 10 == 0;
},
- log : function (message) {
+ log : function(message) {
if (!this.debug)
return;
dump("satchelFormListener: " + message + "\n");
Services.console.logStringMessage("satchelFormListener: " + message);
},
/* ---- dom event handler ---- */
@@ -80,17 +80,17 @@ var satchelFormListener = {
default:
this.log("Oops! Unexpected event: " + e.type);
break;
}
},
/* ---- nsIObserver interface ---- */
- observe : function (subject, topic, data) {
+ observe : function(subject, topic, data) {
if (topic == "nsPref:changed")
this.updatePrefs();
else
this.log("Oops! Unexpected notification: " + topic);
},
/* ---- nsIFormSubmitObserver interfaces ---- */
--- a/toolkit/components/satchel/nsFormAutoComplete.js
+++ b/toolkit/components/satchel/nsFormAutoComplete.js
@@ -205,17 +205,17 @@ FormAutoComplete.prototype = {
},
observer : {
_self : null,
QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference]),
- observe : function (subject, topic, data) {
+ observe : function(subject, topic, data) {
let self = this._self;
if (topic == "nsPref:changed") {
let prefName = data;
self.log("got change to " + prefName + " preference");
switch (prefName) {
case "agedWeight":
self._agedWeight = self._prefBranch.getIntPref(prefName);
@@ -255,17 +255,17 @@ FormAutoComplete.prototype = {
},
/*
* log
*
* Internal function for logging debug messages to the Error Console
* window
*/
- log : function (message) {
+ log : function(message) {
if (!this._debug)
return;
dump("FormAutoComplete: " + message + "\n");
Services.console.logStringMessage("FormAutoComplete: " + message);
},
/*
* autoCompleteSearchAsync
@@ -273,23 +273,23 @@ FormAutoComplete.prototype = {
* aInputName -- |name| attribute from the form input being autocompleted.
* aUntrimmedSearchString -- current value of the input
* aField -- nsIDOMHTMLInputElement being autocompleted (may be null if from chrome)
* aPreviousResult -- previous search result, if any.
* aDatalistResult -- results from list=datalist for aField.
* aListener -- nsIFormAutoCompleteObserver that listens for the nsIAutoCompleteResult
* that may be returned asynchronously.
*/
- autoCompleteSearchAsync : function (aInputName,
+ autoCompleteSearchAsync : function(aInputName,
aUntrimmedSearchString,
aField,
aPreviousResult,
aDatalistResult,
aListener) {
- function sortBytotalScore (a, b) {
+ function sortBytotalScore(a, b) {
return b.totalScore - a.totalScore;
}
// Guard against void DOM strings filtering into this code.
if (typeof aInputName === "object") {
aInputName = "";
}
if (typeof aUntrimmedSearchString === "object") {
@@ -416,17 +416,17 @@ FormAutoComplete.prototype = {
// Start with an empty list.
let result = aDatalistResult ?
new FormAutoCompleteResult(client, [], aInputName, aUntrimmedSearchString, null) :
emptyResult;
let processEntry = (aEntries) => {
if (aField && aField.maxLength > -1) {
result.entries =
- aEntries.filter(function (el) { return el.text.length <= aField.maxLength; });
+ aEntries.filter(function(el) { return el.text.length <= aField.maxLength; });
} else {
result.entries = aEntries;
}
if (aDatalistResult && aDatalistResult.matchCount > 0) {
result = this.mergeResults(result, aDatalistResult);
}
@@ -463,34 +463,34 @@ FormAutoComplete.prototype = {
// FormAutoCompleteResult.
let {FormAutoCompleteResult} = Cu.import("resource://gre/modules/nsFormAutoCompleteResult.jsm", {});
return new FormAutoCompleteResult(datalistResult.searchString,
Ci.nsIAutoCompleteResult.RESULT_SUCCESS,
0, "", finalValues, finalLabels,
finalComments, historyResult);
},
- stopAutoCompleteSearch : function () {
+ stopAutoCompleteSearch : function() {
if (this._pendingClient) {
this._pendingClient.cancel();
this._pendingClient = null;
}
},
/*
* Get the values for an autocomplete list given a search string.
*
* client - a FormHistoryClient instance to perform the search with
* fieldName - fieldname field within form history (the form input name)
* searchString - string to search for
* callback - called when the values are available. Passed an array of objects,
* containing properties for each result. The callback is only called
* when successful.
*/
- getAutoCompleteValues : function (client, fieldName, searchString, callback) {
+ getAutoCompleteValues : function(client, fieldName, searchString, callback) {
let params = {
agedWeight: this._agedWeight,
bucketSize: this._bucketSize,
expiryDate: 1000 * (Date.now() - this._expireDays * 24 * 60 * 60 * 1000),
fieldname: fieldName,
maxTimeGroupings: this._maxTimeGroupings,
timeGroupingSize: this._timeGroupingSize,
prefixWeight: this._prefixWeight,
@@ -509,17 +509,17 @@ FormAutoComplete.prototype = {
* _calculateScore
*
* entry -- an nsIAutoCompleteResult entry
* aSearchString -- current value of the input (lowercase)
* searchTokens -- array of tokens of the search string
*
* Returns: an int
*/
- _calculateScore : function (entry, aSearchString, searchTokens) {
+ _calculateScore : function(entry, aSearchString, searchTokens) {
let boundaryCalc = 0;
// for each word, calculate word boundary weights
for (let token of searchTokens) {
boundaryCalc += (entry.textLowerCase.indexOf(token) == 0);
boundaryCalc += (entry.textLowerCase.indexOf(" " + token) >= 0);
}
boundaryCalc = boundaryCalc * this._boundaryWeight;
// now add more weight if we have a traditional prefix match and
@@ -549,17 +549,17 @@ FormAutoCompleteResult.prototype = {
QueryInterface : XPCOMUtils.generateQI([Ci.nsIAutoCompleteResult,
Ci.nsISupportsWeakReference]),
// private
client : null,
entries : null,
fieldName : null,
- _checkIndexBounds : function (index) {
+ _checkIndexBounds : function(index) {
if (index < 0 || index >= this.entries.length)
throw Components.Exception("Index out of range.", Cr.NS_ERROR_ILLEGAL_VALUE);
},
// Allow autoCompleteSearch to get at the JS object so it can
// modify some readonly properties for internal use.
get wrappedJSObject() {
return this;
@@ -577,45 +577,45 @@ FormAutoCompleteResult.prototype = {
if (this.entries.length == 0)
return Ci.nsIAutoCompleteResult.RESULT_NOMATCH;
return Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
},
get matchCount() {
return this.entries.length;
},
- getValueAt : function (index) {
+ getValueAt : function(index) {
this._checkIndexBounds(index);
return this.entries[index].text;
},
getLabelAt: function(index) {
return this.getValueAt(index);
},
- getCommentAt : function (index) {
+ getCommentAt : function(index) {
this._checkIndexBounds(index);
return "";
},
- getStyleAt : function (index) {
+ getStyleAt : function(index) {
this._checkIndexBounds(index);
return "";
},
- getImageAt : function (index) {
+ getImageAt : function(index) {
this._checkIndexBounds(index);
return "";
},
- getFinalCompleteValueAt : function (index) {
+ getFinalCompleteValueAt : function(index) {
return this.getValueAt(index);
},
- removeValueAt : function (index, removeFromDB) {
+ removeValueAt : function(index, removeFromDB) {
this._checkIndexBounds(index);
let [removedEntry] = this.entries.splice(index, 1);
if (removeFromDB) {
this.client.remove(removedEntry.text);
}
}
--- a/toolkit/components/satchel/nsFormAutoCompleteResult.jsm
+++ b/toolkit/components/satchel/nsFormAutoCompleteResult.jsm
@@ -87,17 +87,17 @@ FormAutoCompleteResult.prototype = {
/**
* @return the number of results
*/
get matchCount() {
return this._values.length;
},
- _checkIndexBounds : function (index) {
+ _checkIndexBounds : function(index) {
if (index < 0 || index >= this._values.length) {
throw Components.Exception("Index out of range.", Cr.NS_ERROR_ILLEGAL_VALUE);
}
},
/**
* Retrieves a result
* @param index the index of the result requested
--- a/toolkit/components/satchel/nsFormHistory.js
+++ b/toolkit/components/satchel/nsFormHistory.js
@@ -437,17 +437,17 @@ FormHistory.prototype = {
let hexVal = parseInt(uuid[i] + uuid[i + 1], 16);
raw += String.fromCharCode(hexVal);
bytes++;
}
return btoa(raw);
},
- sendStringNotification : function (changeType, str1, str2, str3) {
+ sendStringNotification : function(changeType, str1, str2, str3) {
function wrapit(str) {
let wrapper = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
wrapper.data = str;
return wrapper;
}
let strData;
@@ -461,17 +461,17 @@ FormHistory.prototype = {
strData.appendElement(wrapit(str1), false);
strData.appendElement(wrapit(str2), false);
strData.appendElement(wrapit(str3), false);
}
this.sendNotification(changeType, strData);
},
- sendIntNotification : function (changeType, int1, int2) {
+ sendIntNotification : function(changeType, int1, int2) {
function wrapit(int) {
let wrapper = Cc["@mozilla.org/supports-PRInt64;1"].
createInstance(Ci.nsISupportsPRInt64);
wrapper.data = int;
return wrapper;
}
let intData;
@@ -484,22 +484,22 @@ FormHistory.prototype = {
createInstance(Ci.nsIMutableArray);
intData.appendElement(wrapit(int1), false);
intData.appendElement(wrapit(int2), false);
}
this.sendNotification(changeType, intData);
},
- sendNotification : function (changeType, data) {
+ sendNotification : function(changeType, data) {
Services.obs.notifyObservers(data, "satchel-storage-changed", changeType);
},
- getExistingEntryID : function (name, value) {
+ getExistingEntryID : function(name, value) {
let id = -1, guid = null;
let stmt;
let query = "SELECT id, guid FROM moz_formhistory WHERE fieldname = :fieldname AND value = :value";
let params = {
fieldname : name,
value : value
};
try {
@@ -516,17 +516,17 @@ FormHistory.prototype = {
stmt.reset();
}
}
return [id, guid];
},
- countAllEntries : function () {
+ countAllEntries : function() {
let query = "SELECT COUNT(1) AS numEntries FROM moz_formhistory";
let stmt, numEntries;
try {
stmt = this.dbCreateStatement(query, null);
stmt.executeStep();
numEntries = stmt.row.numEntries;
} catch (e) {
@@ -538,30 +538,30 @@ FormHistory.prototype = {
}
}
this.log("countAllEntries: counted entries: " + numEntries);
return numEntries;
},
- updatePrefs : function () {
+ updatePrefs : function() {
this.debug = Services.prefs.getBoolPref("browser.formfill.debug");
this.enabled = Services.prefs.getBoolPref("browser.formfill.enable");
},
// Database Creation & Access
/*
* dbCreateStatement
*
* Creates a statement, wraps it, and then does parameter replacement
* Will use memoization so that statements can be reused.
*/
- dbCreateStatement : function (query, params) {
+ dbCreateStatement : function(query, params) {
let stmt = this.dbStmts[query];
// Memoize the statements
if (!stmt) {
this.log("Creating new statement for query: " + query);
stmt = this.dbConnection.createStatement(query);
this.dbStmts[query] = stmt;
}
// Replace parameters, must be done 1 at a time
@@ -573,45 +573,45 @@ FormHistory.prototype = {
/*
* dbOpen
*
* Open a connection with the database and returns it.
*
* @returns a db connection object.
*/
- dbOpen : function () {
+ dbOpen : function() {
this.log("Open Database");
let storage = Cc["@mozilla.org/storage/service;1"].
getService(Ci.mozIStorageService);
return storage.openDatabase(this.dbFile);
},
/*
* dbInit
*
* Attempts to initialize the database. This creates the file if it doesn't
* exist, performs any migrations, etc.
*/
- dbInit : function () {
+ dbInit : function() {
this.log("Initializing Database");
let version = this.dbConnection.schemaVersion;
// Note: Firefox 3 didn't set a schema value, so it started from 0.
// So we can't depend on a simple version == 0 check
if (version == 0 && !this.dbConnection.tableExists("moz_formhistory"))
this.dbCreate();
else if (version != DB_VERSION)
this.dbMigrate(version);
},
- dbCreate: function () {
+ dbCreate: function() {
this.log("Creating DB -- tables");
for (let name in this.dbSchema.tables) {
let table = this.dbSchema.tables[name];
this.dbCreateTable(name, table);
}
this.log("Creating DB -- indices");
for (let name in this.dbSchema.indices) {
@@ -625,17 +625,17 @@ FormHistory.prototype = {
},
dbCreateTable: function(name, table) {
let tSQL = Object.keys(table).map(col => [col, table[col]].join(" ")).join(", ");
this.log("Creating table " + name + " with " + tSQL);
this.dbConnection.createTable(name, tSQL);
},
- dbMigrate : function (oldVersion) {
+ dbMigrate : function(oldVersion) {
this.log("Attempting to migrate from version " + oldVersion);
if (oldVersion > DB_VERSION) {
this.log("Downgrading to version " + DB_VERSION);
// User's DB is newer. Sanity check that our expected columns are
// present, and if so mark the lower version and merrily continue
// on. If the columns are borked, something is wrong so blow away
// the DB and start from scratch. [Future incompatible upgrades
@@ -675,17 +675,17 @@ FormHistory.prototype = {
/*
* dbMigrateToVersion1
*
* Updates the DB schema to v1 (bug 463154).
* Adds firstUsed, lastUsed, timesUsed columns.
*/
- dbMigrateToVersion1 : function () {
+ dbMigrateToVersion1 : function() {
// Check to see if the new columns already exist (could be a v1 DB that
// was downgraded to v0). If they exist, we don't need to add them.
let query;
["timesUsed", "firstUsed", "lastUsed"].forEach(function(column) {
if (!this.dbColumnExists(column)) {
query = "ALTER TABLE moz_formhistory ADD COLUMN " + column + " INTEGER";
this.dbConnection.executeSimpleSQL(query);
}
@@ -717,32 +717,32 @@ FormHistory.prototype = {
/*
* dbMigrateToVersion2
*
* Updates the DB schema to v2 (bug 243136).
* Adds lastUsed index, removes moz_dummy_table
*/
- dbMigrateToVersion2 : function () {
+ dbMigrateToVersion2 : function() {
let query = "DROP TABLE IF EXISTS moz_dummy_table";
this.dbConnection.executeSimpleSQL(query);
query = "CREATE INDEX IF NOT EXISTS moz_formhistory_lastused_index ON moz_formhistory (lastUsed)";
this.dbConnection.executeSimpleSQL(query);
},
/*
* dbMigrateToVersion3
*
* Updates the DB schema to v3 (bug 506402).
* Adds guid column and index.
*/
- dbMigrateToVersion3 : function () {
+ dbMigrateToVersion3 : function() {
// Check to see if GUID column already exists, add if needed
let query;
if (!this.dbColumnExists("guid")) {
query = "ALTER TABLE moz_formhistory ADD COLUMN guid TEXT";
this.dbConnection.executeSimpleSQL(query);
query = "CREATE INDEX IF NOT EXISTS moz_formhistory_guid_index ON moz_formhistory (guid)";
this.dbConnection.executeSimpleSQL(query);
@@ -782,29 +782,29 @@ FormHistory.prototype = {
} finally {
if (stmt) {
stmt.reset();
}
}
}
},
- dbMigrateToVersion4 : function () {
+ dbMigrateToVersion4 : function() {
if (!this.dbConnection.tableExists("moz_deleted_formhistory")) {
this.dbCreateTable("moz_deleted_formhistory", this.dbSchema.tables.moz_deleted_formhistory);
}
},
/*
* dbAreExpectedColumnsPresent
*
* Sanity check to ensure that the columns this version of the code expects
* are present in the DB we're using.
*/
- dbAreExpectedColumnsPresent : function () {
+ dbAreExpectedColumnsPresent : function() {
for (let name in this.dbSchema.tables) {
let table = this.dbSchema.tables[name];
let query = "SELECT " +
Object.keys(table).join(", ") +
" FROM " + name;
try {
let stmt = this.dbConnection.createStatement(query);
// (no need to execute statement, if it compiled we're good)
@@ -819,17 +819,17 @@ FormHistory.prototype = {
},
/*
* dbColumnExists
*
* Checks to see if the named column already exists.
*/
- dbColumnExists : function (columnName) {
+ dbColumnExists : function(columnName) {
let query = "SELECT " + columnName + " FROM moz_formhistory";
try {
let stmt = this.dbConnection.createStatement(query);
// (no need to execute statement, if it compiled we're good)
stmt.finalize();
return true;
} catch (e) {
return false;
@@ -853,17 +853,17 @@ FormHistory.prototype = {
let connectionDescriptor = Object.getOwnPropertyDescriptor(FormHistory.prototype, "dbConnection");
// Return if the database hasn't been opened.
if (!connectionDescriptor || connectionDescriptor.value === undefined)
return;
let completed = false;
try {
- this.dbConnection.asyncClose(function () { completed = true; });
+ this.dbConnection.asyncClose(function() { completed = true; });
} catch (e) {
completed = true;
Components.utils.reportError(e);
}
let thread = Services.tm.currentThread;
while (aBlocking && !completed) {
thread.processNextEvent(true);
@@ -871,17 +871,17 @@ FormHistory.prototype = {
},
/*
* dbCleanup
*
* Called when database creation fails. Finalizes database statements,
* closes the database connection, deletes the database file.
*/
- dbCleanup : function () {
+ dbCleanup : function() {
this.log("Cleaning up DB file - close & remove & backup")
// Create backup file
let storage = Cc["@mozilla.org/storage/service;1"].
getService(Ci.mozIStorageService);
let backupFile = this.dbFile.leafName + ".corrupt";
storage.backupDatabaseFile(this.dbFile, backupFile);
--- a/toolkit/components/satchel/nsInputListAutoComplete.js
+++ b/toolkit/components/satchel/nsInputListAutoComplete.js
@@ -9,27 +9,27 @@ Components.utils.import("resource://gre/
Components.utils.import("resource://gre/modules/nsFormAutoCompleteResult.jsm");
function InputListAutoComplete() {}
InputListAutoComplete.prototype = {
classID : Components.ID("{bf1e01d0-953e-11df-981c-0800200c9a66}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsIInputListAutoComplete]),
- autoCompleteSearch : function (aUntrimmedSearchString, aField) {
+ autoCompleteSearch : function(aUntrimmedSearchString, aField) {
let [values, labels] = this.getListSuggestions(aField);
let searchResult = values.length > 0 ? Ci.nsIAutoCompleteResult.RESULT_SUCCESS
: Ci.nsIAutoCompleteResult.RESULT_NOMATCH;
let defaultIndex = values.length > 0 ? 0 : -1;
return new FormAutoCompleteResult(aUntrimmedSearchString,
searchResult, defaultIndex, "",
values, labels, [], null);
},
- getListSuggestions : function (aField) {
+ getListSuggestions : function(aField) {
let values = [];
let labels = [];
if (aField) {
let filter = !aField.hasAttribute("mozNoFilter");
let lowerFieldValue = aField.value.toLowerCase();
if (aField.list) {
--- a/toolkit/components/satchel/test/parent_utils.js
+++ b/toolkit/components/satchel/test/parent_utils.js
@@ -20,21 +20,21 @@ var ParentUtils = {
},
cleanUpFormHist() {
FormHistory.update({ op: "remove" });
},
updateFormHistory(changes) {
let handler = {
- handleError: function (error) {
+ handleError: function(error) {
assert.ok(false, error);
sendAsyncMessage("formHistoryUpdated", { ok: false });
},
- handleCompletion: function (reason) {
+ handleCompletion: function(reason) {
if (!reason)
sendAsyncMessage("formHistoryUpdated", { ok: true });
},
};
FormHistory.update(changes, handler);
},
popupshownListener() {
--- a/toolkit/components/satchel/test/test_form_autocomplete.html
+++ b/toolkit/components/satchel/test/test_form_autocomplete.html
@@ -438,17 +438,17 @@ function runTest() {
// This tests that on OS X shift-backspace didn't delete the last character
// in the input (bug 480262).
waitForMenuChange(3);
break;
case 51:
checkForm("value");
countEntries("field1", "value1",
- function (num) {
+ function(num) {
ok(!num, testNum + " checking that f1/v1 was deleted");
runTest();
});
break;
case 52:
doKey("return");
checkForm("value2");
@@ -478,17 +478,17 @@ function runTest() {
doKey("down");
doKey("delete", shiftModifier);
waitForMenuChange(2);
break;
case 55:
checkForm("");
countEntries("field1", "value3",
- function (num) {
+ function(num) {
ok(!num, testNum + " checking that f1/v3 was deleted");
runTest();
});
break;
case 56:
doKey("return");
checkForm("value4")
@@ -518,17 +518,17 @@ function runTest() {
doKey("down");
doKey("delete", shiftModifier);
checkForm("");
waitForMenuChange(1);
break;
case 59:
countEntries("field1", "value4",
- function (num) {
+ function(num) {
ok(!num, testNum + " checking that f1/v4 was deleted");
runTest();
});
break;
case 60:
doKey("return");
checkForm("value2");
@@ -557,17 +557,17 @@ function runTest() {
doKey("down");
doKey("delete", shiftModifier);
waitForMenuChange(0);
break;
case 63:
checkForm("");
countEntries("field1", "value2",
- function (num) {
+ function(num) {
ok(!num, testNum + " checking that f1/v2 was deleted");
runTest();
});
break;
case 64:
// Look at form 2, trigger autocomplete popup
input = $_(2, "field2");
--- a/toolkit/components/satchel/test/test_form_autocomplete_with_list.html
+++ b/toolkit/components/satchel/test/test_form_autocomplete_with_list.html
@@ -174,17 +174,17 @@ function runTest() {
doKey("down");
doKey("delete", shiftModifier);
waitForMenuChange(3);
break;
case 7:
checkForm("");
countEntries("field1", "historyvalue",
- function (num) {
+ function(num) {
ok(!num, testNum + " checking that form history value was deleted");
runTest();
});
break;
case 8:
doKey("return");
checkForm("Google")
--- a/toolkit/components/satchel/test/test_form_submission.html
+++ b/toolkit/components/satchel/test/test_form_submission.html
@@ -290,17 +290,17 @@ var ccNumbers = {
"6723210018630429", "4411962856225025",
"8276996369036686", "4449796938248871",
"3350852696538147", "5011802870046957"
],
};
function checkInitialState() {
countEntries(null, null,
- function (num) {
+ function(num) {
ok(!num, "checking for initially empty storage");
startTest();
});
}
function startTest() {
// Fill in values for the various fields. We could just set the <input>'s
// value attribute, but we don't save default form values (and we want to
@@ -397,17 +397,17 @@ function checkSubmit(formNum) {
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
countEntries(null, null,
- function (num) {
+ function(num) {
ok(!num, "checking for empty storage");
submitForm(formNum);
});
return false;
case 100:
checkForSave("subtest2", "subtestValue", "checking saved subtest value");
break;
case 101:
--- a/toolkit/components/satchel/test/test_form_submission_cap.html
+++ b/toolkit/components/satchel/test/test_form_submission_cap.html
@@ -25,17 +25,17 @@
field # numInputFields was not saved.
*/
var numSubmittedForms = 0;
var numInputFields = 101;
function checkInitialState() {
countEntries(null, null,
- function (num) {
+ function(num) {
ok(!num, "checking for initially empty storage");
startTest();
});
}
function startTest() {
var form = document.getElementById("form1");
for (i = 1; i <= numInputFields; i++) {
--- a/toolkit/components/satchel/test/test_form_submission_cap2.html
+++ b/toolkit/components/satchel/test/test_form_submission_cap2.html
@@ -123,17 +123,17 @@
<pre id="test">
<script class="testbody" type="text/javascript">
var numSubmittedForms = 0;
var numInputFields = 101;
function checkInitialState() {
countEntries(null, null,
- function (num) {
+ function(num) {
ok(!num, "checking for initially empty storage");
startTest();
});
}
function startTest() {
// Fill in values for the various fields. We could just set the <input>'s
// value attribute, but we don't save default form values (and we want to
@@ -145,17 +145,17 @@ function startTest() {
button.click();
}
// Make sure that the first (numInputFields - 1) were not saved (as they were not changed).
// Call done() when finished.
function checkCountEntries(formNum, index, done)
{
countEntries("test" + index, index,
- function (num) {
+ function(num) {
ok(!num, "checking unsaved value " + index);
if (index < numInputFields) {
checkCountEntries(formNum, index + 1, done);
}
else {
done(formNum);
}
});
--- a/toolkit/components/satchel/test/unit/head_satchel.js
+++ b/toolkit/components/satchel/test/unit/head_satchel.js
@@ -35,38 +35,38 @@ function getDBVersion(dbfile) {
}
const isGUID = /[A-Za-z0-9\+\/]{16}/;
// Find form history entries.
function searchEntries(terms, params, iter) {
let results = [];
FormHistory.search(terms, params, { handleResult: result => results.push(result),
- handleError: function (error) {
+ handleError: function(error) {
do_throw("Error occurred searching form history: " + error);
},
- handleCompletion: function (reason) { if (!reason) iter.next(results); }
+ handleCompletion: function(reason) { if (!reason) iter.next(results); }
});
}
// Count the number of entries with the given name and value, and call then(number)
// when done. If name or value is null, then the value of that field does not matter.
function countEntries(name, value, then) {
var obj = {};
if (name !== null)
obj.fieldname = name;
if (value !== null)
obj.value = value;
let count = 0;
FormHistory.count(obj, { handleResult: result => count = result,
- handleError: function (error) {
+ handleError: function(error) {
do_throw("Error occurred searching form history: " + error);
},
- handleCompletion: function (reason) { if (!reason) then(count); }
+ handleCompletion: function(reason) { if (!reason) then(count); }
});
}
// Perform a single form history update and call then() when done.
function updateEntry(op, name, value, then) {
var obj = { op: op };
if (name !== null)
obj.fieldname = name;
@@ -79,20 +79,20 @@ function updateEntry(op, name, value, th
function addEntry(name, value, then) {
let now = Date.now() * 1000;
updateFormHistory({ op: "add", fieldname: name, value: value, timesUsed: 1,
firstUsed: now, lastUsed: now }, then);
}
// Wrapper around FormHistory.update which handles errors. Calls then() when done.
function updateFormHistory(changes, then) {
- FormHistory.update(changes, { handleError: function (error) {
+ FormHistory.update(changes, { handleError: function(error) {
do_throw("Error occurred updating form history: " + error);
},
- handleCompletion: function (reason) { if (!reason) then(); },
+ handleCompletion: function(reason) { if (!reason) then(); },
});
}
/**
* Logs info to the console in the standard way (includes the filename).
*
* @param aMessage
* The message to log to the console.
--- a/toolkit/components/satchel/test/unit/test_async_expire.js
+++ b/toolkit/components/satchel/test/unit/test_async_expire.js
@@ -13,17 +13,17 @@ function triggerExpiration() {
}
var checkExists = function(num) { do_check_true(num > 0); next_test(); }
var checkNotExists = function(num) { do_check_true(!num); next_test(); }
var TestObserver = {
QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
- observe : function (subject, topic, data) {
+ observe : function(subject, topic, data) {
do_check_eq(topic, "satchel-storage-changed");
if (data == "formhistory-expireoldentries") {
next_test();
}
}
};
--- a/toolkit/components/satchel/test/unit/test_autocomplete.js
+++ b/toolkit/components/satchel/test/unit/test_autocomplete.js
@@ -69,18 +69,18 @@ add_test(function test0() {
}
updateFormHistory(changes, run_next_test);
});
add_test(function test1() {
do_log_info("Check initial state is as expected");
- countEntries(null, null, function () {
- countEntries("field1", null, function (count) {
+ countEntries(null, null, function() {
+ countEntries("field1", null, function(count) {
do_check_true(count > 0);
run_next_test();
});
});
});
add_test(function test2() {
do_log_info("Check search contains all entries");
--- a/toolkit/components/satchel/test/unit/test_db_corrupt.js
+++ b/toolkit/components/satchel/test/unit/test_db_corrupt.js
@@ -51,17 +51,17 @@ add_test(function test_corruptFormHistor
do_check_true(aNumEntries2 == 0);
run_next_test();
},
handleError : function(aError2) {
do_throw("DB initialized after reading a corrupt DB file found an entry.");
}
});
},
- handleError : function (aError) {
+ handleError : function(aError) {
do_throw("DB initialized after reading a corrupt DB file is not empty.");
}
});
});
add_test(function test_corruptFormHistoryDB_addEntry() {
do_log_info("test adding an entry to the empty DB.");
--- a/toolkit/components/satchel/test/unit/test_db_update_v4.js
+++ b/toolkit/components/satchel/test/unit/test_db_update_v4.js
@@ -43,17 +43,17 @@ function* next_test()
// Check that the index was added
do_check_true(dbConnection.tableExists("moz_deleted_formhistory"));
dbConnection.close();
// check for upgraded schema.
do_check_eq(CURRENT_SCHEMA, FormHistory.schemaVersion);
// check that an entry still exists
yield countEntries("name-A", "value-A",
- function (num) {
+ function(num) {
do_check_true(num > 0);
do_test_finished();
}
);
} catch (e) {
throw "FAILED in test #" + testnum + " -- " + e;
}
--- a/toolkit/components/satchel/test/unit/test_db_update_v4b.js
+++ b/toolkit/components/satchel/test/unit/test_db_update_v4b.js
@@ -41,17 +41,17 @@ function* next_test()
do_check_eq(CURRENT_SCHEMA, FormHistory.schemaVersion);
// Check that the index was added
do_check_true(dbConnection.tableExists("moz_deleted_formhistory"));
dbConnection.close();
// check that an entry still exists
yield countEntries("name-A", "value-A",
- function (num) {
+ function(num) {
do_check_true(num > 0);
do_test_finished();
}
);
} catch (e) {
throw "FAILED in test #" + testnum + " -- " + e;
}
--- a/toolkit/components/satchel/test/unit/test_history_api.js
+++ b/toolkit/components/satchel/test/unit/test_history_api.js
@@ -11,42 +11,42 @@ function countDeletedEntries(expected)
{
let deferred = Promise.defer();
let stmt = dbConnection.createAsyncStatement("SELECT COUNT(*) AS numEntries FROM moz_deleted_formhistory");
stmt.executeAsync({
handleResult: function(resultSet) {
do_check_eq(expected, resultSet.getNextRow().getResultByName("numEntries"));
deferred.resolve();
},
- handleError : function () {
+ handleError : function() {
do_throw("Error occurred counting deleted entries: " + error);
deferred.reject();
},
- handleCompletion : function () {
+ handleCompletion : function() {
stmt.finalize();
}
});
return deferred.promise;
}
function checkTimeDeleted(guid, checkFunction)
{
let deferred = Promise.defer();
let stmt = dbConnection.createAsyncStatement("SELECT timeDeleted FROM moz_deleted_formhistory WHERE guid = :guid");
stmt.params.guid = guid;
stmt.executeAsync({
handleResult: function(resultSet) {
checkFunction(resultSet.getNextRow().getResultByName("timeDeleted"));
deferred.resolve();
},
- handleError : function () {
+ handleError : function() {
do_throw("Error occurred getting deleted entries: " + error);
deferred.reject();
},
- handleCompletion : function () {
+ handleCompletion : function() {
stmt.finalize();
}
});
return deferred.promise;
}
function promiseUpdateEntry(op, name, value)
{
@@ -76,29 +76,29 @@ function promiseUpdate(change) {
}
function promiseSearchEntries(terms, params)
{
let deferred = Promise.defer();
let results = [];
FormHistory.search(terms, params,
{ handleResult: result => results.push(result),
- handleError: function (error) {
+ handleError: function(error) {
do_throw("Error occurred searching form history: " + error);
deferred.reject(error);
},
- handleCompletion: function (reason) { if (!reason) deferred.resolve(results); }
+ handleCompletion: function(reason) { if (!reason) deferred.resolve(results); }
});
return deferred.promise;
}
function promiseCountEntries(name, value, checkFn)
{
let deferred = Promise.defer();
- countEntries(name, value, function (result) { checkFn(result); deferred.resolve(); } );
+ countEntries(name, value, function(result) { checkFn(result); deferred.resolve(); } );
return deferred.promise;
}
add_task(function* ()
{
let oldSupportsDeletedTable = FormHistory._supportsDeletedTable;
FormHistory._supportsDeletedTable = true;
@@ -138,20 +138,20 @@ add_task(function* ()
dbFile.append("formhistory.sqlite");
dbConnection = Services.storage.openUnsharedDatabase(dbFile);
let deferred = Promise.defer();
let stmt = dbConnection.createAsyncStatement("DELETE FROM moz_deleted_formhistory");
stmt.executeAsync({
handleResult: function(resultSet) { },
- handleError : function () {
+ handleError : function() {
do_throw("Error occurred counting deleted all entries: " + error);
},
- handleCompletion : function () {
+ handleCompletion : function() {
stmt.finalize();
deferred.resolve();
}
});
yield deferred.promise;
// ===== 2 =====
// Test looking for nonexistent / bogus data.
@@ -165,17 +165,17 @@ add_task(function* ()
yield promiseCountEntries("", "value-A", checkNotExists);
yield promiseCountEntries(null, "value-A", checkExists);
// Cannot use promiseCountEntries when name and value are null because it treats null values as not set
// and here a search should be done explicity for null.
deferred = Promise.defer();
yield FormHistory.count({ fieldname: null, value: null },
{ handleResult: result => checkNotExists(result),
- handleError: function (error) {
+ handleError: function(error) {
do_throw("Error occurred searching form history: " + error);
},
handleCompletion: function(reason) { if (!reason) deferred.resolve() }
});
yield deferred.promise;
// ===== 3 =====
// Test removeEntriesForName with a single matching value
--- a/toolkit/components/satchel/test/unit/test_notify.js
+++ b/toolkit/components/satchel/test/unit/test_notify.js
@@ -6,17 +6,17 @@
*/
var expectedNotification;
var expectedData;
var TestObserver = {
QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
- observe : function (subject, topic, data) {
+ observe : function(subject, topic, data) {
do_check_eq(topic, "satchel-storage-changed");
do_check_eq(data, expectedNotification);
switch (data) {
case "formhistory-add":
case "formhistory-update":
do_check_true(subject instanceof Ci.nsISupportsString);
do_check_true(isGUID.test(subject.toString()));
@@ -57,44 +57,44 @@ var entry1 = ["entry1", "value1"];
var entry2 = ["entry2", "value2"];
/* ========== 1 ========== */
testnum = 1;
testdesc = "Initial connection to storage module"
yield updateEntry("remove", null, null, next_test);
-yield countEntries(null, null, function (num) { do_check_false(num, "Checking initial DB is empty"); next_test(); });
+yield countEntries(null, null, function(num) { do_check_false(num, "Checking initial DB is empty"); next_test(); });
// Add the observer
var os = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
os.addObserver(TestObserver, "satchel-storage-changed", false);
/* ========== 2 ========== */
testnum++;
testdesc = "addEntry";
expectedNotification = "formhistory-add";
expectedData = entry1;
yield updateEntry("add", entry1[0], entry1[1], next_test);
do_check_eq(expectedNotification, null); // check that observer got a notification
-yield countEntries(entry1[0], entry1[1], function (num) { do_check_true(num > 0); next_test(); });
+yield countEntries(entry1[0], entry1[1], function(num) { do_check_true(num > 0); next_test(); });
/* ========== 3 ========== */
testnum++;
testdesc = "modifyEntry";
expectedNotification = "formhistory-update";
expectedData = entry1;
// will update previous entry
yield updateEntry("update", entry1[0], entry1[1], next_test);
-yield countEntries(entry1[0], entry1[1], function (num) { do_check_true(num > 0); next_test(); });
+yield countEntries(entry1[0], entry1[1], function(num) { do_check_true(num > 0); next_test(); });
do_check_eq(expectedNotification, null);
/* ========== 4 ========== */
testnum++;
testdesc = "removeEntry";
expectedNotification = "formhistory-remove";
@@ -138,17 +138,17 @@ do_check_eq(expectedNotification, null);
testnum++;
testdesc = "removeEntriesByTimeframe";
expectedNotification = "formhistory-remove";
expectedData = [10, 99999999999];
yield FormHistory.update({ op: "remove", firstUsedStart: expectedData[0], firstUsedEnd: expectedData[1] },
{ handleCompletion: function(reason) { if (!reason) next_test() },
- handleErrors: function (error) {
+ handleErrors: function(error) {
do_throw("Error occurred updating form history: " + error);
}
});
do_check_eq(expectedNotification, null);
os.removeObserver(TestObserver, "satchel-storage-changed", false);
--- a/toolkit/components/search/SearchStaticData.jsm
+++ b/toolkit/components/search/SearchStaticData.jsm
@@ -32,12 +32,12 @@ this.SearchStaticData = {
* @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) {
+ getAlternateDomains: function(aDomain) {
return gGoogleDomains.indexOf(aDomain) == -1 ? [] : gGoogleDomains;
},
};
--- a/toolkit/components/search/SearchSuggestionController.jsm
+++ b/toolkit/components/search/SearchSuggestionController.jsm
@@ -297,17 +297,17 @@ this.SearchSuggestionController.prototyp
}
let results = serverResults[1] || [];
deferredResponse.resolve({ result: results });
},
/**
* Called when this._remoteResultTimer fires indicating the remote request took too long.
*/
- _onRemoteTimeout: function () {
+ _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.
--- a/toolkit/components/search/nsSearchService.js
+++ b/toolkit/components/search/nsSearchService.js
@@ -230,17 +230,17 @@ function DO_LOG(aText) {
* In debug builds, use a live, pref-based (browser.search.log) LOG function
* to allow enabling/disabling without a restart. Otherwise, don't log at all by
* default. This can be overridden at startup by the pref, see SearchService's
* _init method.
*/
var LOG = function() {};
if (AppConstants.DEBUG) {
- LOG = function (aText) {
+ LOG = function(aText) {
if (getBoolPref(BROWSER_SEARCH_PREF + "log", false)) {
DO_LOG(aText);
}
};
}
/**
* Presents an assertion dialog in non-release builds and throws.
@@ -366,20 +366,20 @@ loadListener.prototype = {
// nsIInterfaceRequestor
getInterface: function SRCH_load_GI(aIID) {
return this.QueryInterface(aIID);
},
// FIXME: bug 253127
// nsIHttpEventSink
- onRedirect: function (aChannel, aNewChannel) {},
+ onRedirect: function(aChannel, aNewChannel) {},
// nsIProgressEventSink
- onProgress: function (aRequest, aContext, aProgress, aProgressMax) {},
- onStatus: function (aRequest, aContext, aStatus, aStatusArg) {}
+ onProgress: function(aRequest, aContext, aProgress, aProgressMax) {},
+ onStatus: function(aRequest, aContext, aStatus, aStatusArg) {}
}
function isPartnerBuild() {
try {
let distroID = Services.prefs.getCharPref("distribution.id");
// Mozilla-provided builds (i.e. funnelcake) are not partner builds
if (distroID && !distroID.startsWith("mozilla")) {
@@ -1778,17 +1778,17 @@ Engine.prototype = {
case "ftp":
LOG("_setIcon: Downloading icon: \"" + uri.spec +
"\" for engine: \"" + this.name + "\"");
var chan = NetUtil.newChannel({
uri: uri,
loadUsingSystemPrincipal: true
});
- let iconLoadCallback = function (aByteArray, aEngine) {
+ let iconLoadCallback = function(aByteArray, aEngine) {
// This callback may run after we've already set a preferred icon,
// so check again.
if (aEngine._hasPreferredIcon && !aIsPreferred)
return;
if (!aByteArray || aByteArray.length > MAX_ICON_SIZE) {
LOG("iconLoadCallback: load failed, or the icon was too large!");
return;
@@ -2472,17 +2472,17 @@ Engine.prototype = {
if (url)
return url.resultDomain;
return "";
},
/**
* Returns URL parsing properties used by _buildParseSubmissionMap.
*/
- getURLParsingInfo: function () {
+ getURLParsingInfo: function() {
let responseType = AppConstants.platform == "android" ? this._defaultMobileResponseType :
URLTYPE_SEARCH_HTML;
LOG("getURLParsingInfo: responseType: \"" + responseType + "\"");
let url = this._getURLOfType(responseType);
if (!url || url.method != "GET") {
return null;
@@ -3109,17 +3109,17 @@ SearchService.prototype = {
}
LOG("_asyncLoadEngines: loading from cache directories");
this._loadEnginesFromCache(cache);
LOG("_asyncLoadEngines: done");
}),
- _asyncReInit: function () {
+ _asyncReInit: function() {
LOG("_asyncReInit");
// Start by clearing the initialized state, so we don't abort early.
gInitialized = false;
Task.spawn(function* () {
try {
if (this._batchTask) {
LOG("finalizing batch task");
@@ -3500,17 +3500,17 @@ SearchService.prototype = {
}
LOG("_asyncLoadEnginesFromDir: Failed to load " + osfile.path + "!\n" + ex);
}
}
return engines;
}),
_loadFromChromeURLs: function SRCH_SVC_loadFromChromeURLs(aURLs) {
- aURLs.forEach(function (url) {
+ aURLs.forEach(function(url) {
try {
LOG("_loadFromChromeURLs: loading engine from chrome url: " + url);
let uri = makeURI(url);
let engine = new Engine(uri, true);
engine._initFromURISync(uri);
@@ -3867,17 +3867,17 @@ SearchService.prototype = {
* Get a sorted array of engines.
* @param aWithHidden
* True if hidden plugins should be included in the result.
*/
_getSortedEngines: function SRCH_SVC_getSorted(aWithHidden) {
if (aWithHidden)
return this._sortedEngines;
- return this._sortedEngines.filter(function (engine) {
+ return this._sortedEngines.filter(function(engine) {
return !engine.hidden;
});
},
// nsIBrowserSearchService
init: function SRCH_SVC_init(observer) {
LOG("SearchService.init");
let self = this;
@@ -3975,17 +3975,17 @@ SearchService.prototype = {
break;
if (!(engineName in engineOrder))
engineOrder[engineName] = i++;
}
LOG("getDefaultEngines: engineOrder: " + engineOrder.toSource());
- function compareEngines (a, b) {
+ function compareEngines(a, b) {
var aIdx = engineOrder[a.name];
var bIdx = engineOrder[b.name];
if (aIdx && bIdx)
return aIdx - bIdx;
if (aIdx)
return -1;
if (bIdx)
@@ -4037,17 +4037,17 @@ SearchService.prototype = {
addEngine: function SRCH_SVC_addEngine(aEngineURL, aDataType, aIconURL,
aConfirm, aCallback) {
LOG("addEngine: Adding \"" + aEngineURL + "\".");
this._ensureInitialized();
try {
var uri = makeURI(aEngineURL);
var engine = new Engine(uri, false);
if (aCallback) {
- engine._installCallback = function (errorCode) {
+ engine._installCallback = function(errorCode) {
try {
if (errorCode == null)
aCallback.onSuccess(engine);
else
aCallback.onError(errorCode);
} catch (ex) {
Cu.reportError("Error invoking addEngine install callback: " + ex);
}
--- a/toolkit/components/search/tests/xpcshell/head_search.js
+++ b/toolkit/components/search/tests/xpcshell/head_search.js
@@ -96,21 +96,21 @@ function installAddonEngine(name = "engi
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) {
+ getFile: function(prop, persistant) {
throw Cr.NS_ERROR_FAILURE;
},
- getFiles: function (prop) {
+ getFiles: function(prop) {
let result = [];
switch (prop) {
case XRE_EXTENSIONS_DIR_LIST:
result.push(addonDir);
break;
default:
throw Cr.NS_ERROR_FAILURE;
--- a/toolkit/components/search/tests/xpcshell/test_addEngine_callback.js
+++ b/toolkit/components/search/tests/xpcshell/test_addEngine_callback.js
@@ -22,66 +22,66 @@ var prompt = {
// 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) {
+ 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) {
+ 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) {
+ 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) {
+ onSuccess: function(engine) {
do_throw("this addition should not have succeeded");
},
- onError: function (errorCode) {
+ 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) {
+ onSuccess: function(engine) {
do_throw("this addition should not have succeeded");
},
- onError: function (errorCode) {
+ 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);
--- a/toolkit/components/search/tests/xpcshell/test_location_malformed_json.js
+++ b/toolkit/components/search/tests/xpcshell/test_location_malformed_json.js
@@ -1,17 +1,17 @@
/* 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) {
+ 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);
});
--- a/toolkit/components/search/tests/xpcshell/test_location_sync.js
+++ b/toolkit/components/search/tests/xpcshell/test_location_sync.js
@@ -17,17 +17,17 @@ function getIsUSPref() {
}
}
// 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) {
+ 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);
});
--- a/toolkit/components/search/tests/xpcshell/test_notifications.js
+++ b/toolkit/components/search/tests/xpcshell/test_notifications.js
@@ -32,17 +32,17 @@ function search_observer(subject, topic,
do_print("Observer: " + data + " for " + engine.name);
switch (data) {
case "engine-added":
let retrievedEngine = Services.search.getEngineByName("Test search engine");
do_check_eq(engine, retrievedEngine);
Services.search.defaultEngine = engine;
Services.search.currentEngine = engine;
- do_execute_soon(function () {
+ do_execute_soon(function() {
Services.search.removeEngine(engine);
});
break;
case "engine-removed":
let engineNameOutput = " for Test search engine";
expectedLog = expectedLog.map(logLine => logLine + engineNameOutput);
do_print("expectedLog:\n" + expectedLog.join("\n"))
do_print("gTestLog:\n" + gTestLog.join("\n"))
--- a/toolkit/components/search/tests/xpcshell/test_searchSuggest.js
+++ b/toolkit/components/search/tests/xpcshell/test_searchSuggest.js
@@ -554,19 +554,19 @@ add_task(function* test_userContextId()
function updateSearchHistory(operation, value) {
let deferred = Promise.defer();
FormHistory.update({
op: operation,
fieldname: "searchbar-history",
value: value,
},
{
- handleError: function (error) {
+ handleError: function(error) {
do_throw("Error occurred updating form history: " + error);
deferred.reject(error);
},
- handleCompletion: function (reason) {
+ handleCompletion: function(reason) {
if (!reason)
deferred.resolve();
}
});
return deferred.promise;
}
--- a/toolkit/components/securityreporter/SecurityReporter.js
+++ b/toolkit/components/securityreporter/SecurityReporter.js
@@ -87,26 +87,26 @@ SecurityReporter.prototype = {
}
fetch(endpoint, {
method: "POST",
body: JSON.stringify(report),
headers: {
'Content-Type': 'application/json'
}
- }).then(function (aResponse) {
+ }).then(function(aResponse) {
if (!aResponse.ok) {
// request returned non-success status
Services.telemetry.getHistogramById(HISTOGRAM_ID)
.add(TLS_ERROR_REPORT_TELEMETRY_FAILURE);
} else {
Services.telemetry.getHistogramById(HISTOGRAM_ID)
.add(TLS_ERROR_REPORT_TELEMETRY_SUCCESS);
}
- }).catch(function (e) {
+ }).catch(function(e) {
// error making request to reportURL
Services.telemetry.getHistogramById(HISTOGRAM_ID)
.add(TLS_ERROR_REPORT_TELEMETRY_FAILURE);
});
}
};
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SecurityReporter]);
--- a/toolkit/components/startup/tests/browser/browser_bug511456.js
+++ b/toolkit/components/startup/tests/browser/browser_bug511456.js
@@ -14,17 +14,17 @@ function test() {
let win2 = window.openDialog(location, "", "chrome,all,dialog=no", "about:blank");
win2.addEventListener("load", function onLoad() {
win2.removeEventListener("load", onLoad);
gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
let browser = gBrowser.selectedBrowser;
- whenBrowserLoaded(browser, function () {
+ whenBrowserLoaded(browser, function() {
let seenDialog = false;
// Cancel the prompt the first time.
waitForOnBeforeUnloadDialog(browser, (btnLeave, btnStay) => {
seenDialog = true;
btnStay.click();
});
--- a/toolkit/components/startup/tests/browser/browser_bug537449.js
+++ b/toolkit/components/startup/tests/browser/browser_bug537449.js
@@ -15,17 +15,17 @@ SpecialPowers.pushPrefEnv({"set": [["dom
const TEST_URL = "http://example.com/browser/toolkit/components/startup/tests/browser/beforeunload.html";
function test() {
waitForExplicitFinish();
gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
let browser = gBrowser.selectedBrowser;
- whenBrowserLoaded(browser, function () {
+ whenBrowserLoaded(browser, function() {
let seenDialog = false;
// Cancel the prompt the first time.
waitForOnBeforeUnloadDialog(browser, (btnLeave, btnStay) => {
seenDialog = true;
btnStay.click();
});
--- a/toolkit/components/startup/tests/unit/head_startup.js
+++ b/toolkit/components/startup/tests/unit/head_startup.js
@@ -13,17 +13,17 @@ function createAppInfo(ID, name, version
Components.utils.import("resource://testing-common/AppInfo.jsm", tmp);
gAppInfo = tmp.newAppInfo({
ID, name, version, platformVersion,
crashReporter: true,
replacedLockTime: 0,
});
let XULAppInfoFactory = {
- createInstance: function (outer, iid) {
+ createInstance: function(outer, iid) {
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return gAppInfo.QueryInterface(iid);
}
};
let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
registrar.registerFactory(XULRUNTIME_CID, "XULRuntime",
XULRUNTIME_CONTRACTID, XULAppInfoFactory);
--- a/toolkit/components/telemetry/TelemetryController.jsm
+++ b/toolkit/components/telemetry/TelemetryController.jsm
@@ -169,17 +169,17 @@ this.TelemetryController = Object.freeze
*/
testSetupContent: function() {
return Impl.setupContentTelemetry(true);
},
/**
* Send a notification.
*/
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
return Impl.observe(aSubject, aTopic, aData);
},
/**
* Submit ping payloads to Telemetry. This will assemble a complete ping, adding
* environment data, client id and some general info.
* Depending on configuration, the ping will be sent to the server (immediately or later)
* and archived locally.
@@ -425,17 +425,17 @@ var Impl = {
return pingData;
},
/**
* Track any pending ping send and save tasks through the promise passed here.
* This is needed to block shutdown on any outstanding ping activity.
*/
- _trackPendingPingTask: function (aPromise) {
+ _trackPendingPingTask: function(aPromise) {
this._connectionsBarrier.client.addBlocker("Waiting for ping task", aPromise);
},
/**
* Internal function to assemble a complete ping, adding environment data, client id
* and some general info. This waits on the client id to be loaded/generated if it's
* not yet available. Note that this function is synchronous unless we need to load
* the client id.
@@ -740,17 +740,17 @@ var Impl = {
this._delayedInitTask.arm();
return this._delayedInitTaskDeferred.promise;
},
/**
* This triggers basic telemetry initialization for content processes.
* @param {Boolean} [testing=false] True if we are in test mode, false otherwise.
*/
- setupContentTelemetry: function (testing = false) {
+ setupContentTelemetry: function(testing = false) {
this._testMode = testing;
// We call |enableTelemetryRecording| here to make sure that Telemetry.canRecord* flags
// are in sync between chrome and content processes.
if (!this.enableTelemetryRecording()) {
this._log.trace("setupContentTelemetry - Content process recording disabled.");
return;
}
@@ -815,17 +815,17 @@ var Impl = {
// This handles 2) and 3).
return this._delayedInitTask.finalize().then(() => this._cleanupOnShutdown());
},
/**
* This observer drives telemetry.
*/
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
// The logger might still be not available at this point.
if (aTopic == "profile-after-change" || aTopic == "app-startup") {
// If we don't have a logger, we need to make sure |Log.repository.getLogger()| is
// called before |getLoggerWithMessagePrefix|. Otherwise logging won't work.
configureLogging();
}
this._log.trace("observe - " + aTopic + " notified.");
--- a/toolkit/components/telemetry/TelemetryEnvironment.jsm
+++ b/toolkit/components/telemetry/TelemetryEnvironment.jsm
@@ -483,17 +483,17 @@ EnvironmentAddonBuilder.prototype = {
},
_onAddonChange: function() {
this._environment._log.trace("_onAddonChange");
this._checkForChanges("addons-changed");
},
// nsIObserver
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
this._environment._log.trace("observe - Topic " + aTopic);
this._checkForChanges("experiment-changed");
},
_checkForChanges: function(changeReason) {
if (this._pendingTask) {
this._environment._log.trace("_checkForChanges - task already pending, dropping change with reason " + changeReason);
return;
@@ -648,17 +648,17 @@ EnvironmentAddonBuilder.prototype = {
return activeTheme;
}),
/**
* Get the plugins data in object form.
* @return Object containing the plugins data.
*/
- _getActivePlugins: function () {
+ _getActivePlugins: function() {
let pluginTags =
Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost).getPluginTags({});
let activePlugins = [];
for (let tag of pluginTags) {
// Skip plugins which are not active.
if (tag.disabled) {
continue;
@@ -719,17 +719,17 @@ EnvironmentAddonBuilder.prototype = {
return activeGMPlugins;
}),
/**
* Get the active experiment data in object form.
* @return Object containing the active experiment data.
*/
- _getActiveExperiment: function () {
+ _getActiveExperiment: function() {
let experimentInfo = {};
try {
let scope = {};
Cu.import("resource:///modules/experiments/Experiments.jsm", scope);
let experiments = scope.Experiments.instance();
let activeExperiment = experiments.getActiveExperimentID();
if (activeExperiment) {
experimentInfo.id = activeExperiment;
@@ -835,31 +835,31 @@ EnvironmentCache.prototype = {
/**
* Register a listener for environment changes.
* @param name The name of the listener. If a new listener is registered
* with the same name, the old listener will be replaced.
* @param listener function(reason, oldEnvironment) - Will receive a reason for
the change and the environment data before the change.
*/
- registerChangeListener: function (name, listener) {
+ registerChangeListener: function(name, listener) {
this._log.trace("registerChangeListener for " + name);
if (this._shutdown) {
this._log.warn("registerChangeListener - already shutdown");
return;
}
this._changeListeners.set(name, listener);
},
/**
* Unregister from listening to environment changes.
* It's fine to call this on an unitialized TelemetryEnvironment.
* @param name The name of the listener to remove.
*/
- unregisterChangeListener: function (name) {
+ unregisterChangeListener: function(name) {
this._log.trace("unregisterChangeListener for " + name);
if (this._shutdown) {
this._log.warn("registerChangeListener - already shutdown");
return;
}
this._changeListeners.delete(name);
},
@@ -867,30 +867,30 @@ EnvironmentCache.prototype = {
this._log.trace("shutdown");
this._shutdown = true;
},
/**
* Only used in tests, set the preferences to watch.
* @param aPreferences A map of preferences names and their recording policy.
*/
- _watchPreferences: function (aPreferences) {
+ _watchPreferences: function(aPreferences) {
this._stopWatchingPrefs();
this._watchedPrefs = aPreferences;
this._updateSettings();
this._startWatchingPrefs();
},
/**
* Get an object containing the values for the watched preferences. Depending on the
* policy, the value for a preference or whether it was changed by user is reported.
*
* @return An object containing the preferences values.
*/
- _getPrefData: function () {
+ _getPrefData: function() {
let prefData = {};
for (let [pref, policy] of this._watchedPrefs.entries()) {
// Only record preferences if they are non-default
if (!Preferences.isSet(pref)) {
continue;
}
// Check the policy for the preference and decide if we need to store its value
@@ -904,17 +904,17 @@ EnvironmentCache.prototype = {
prefData[pref] = prefValue;
}
return prefData;
},
/**
* Start watching the preferences.
*/
- _startWatchingPrefs: function () {
+ _startWatchingPrefs: function() {
this._log.trace("_startWatchingPrefs - " + this._watchedPrefs);
for (let [pref, options] of this._watchedPrefs) {
if (!("requiresRestart" in options) || !options.requiresRestart) {
Preferences.observe(pref, this._onPrefChanged, this);
}
}
},
@@ -924,46 +924,46 @@ EnvironmentCache.prototype = {
let oldEnvironment = Cu.cloneInto(this._currentEnvironment, myScope);
this._updateSettings();
this._onEnvironmentChange("pref-changed", oldEnvironment);
},
/**
* Do not receive any more change notifications for the preferences.
*/
- _stopWatchingPrefs: function () {
+ _stopWatchingPrefs: function() {
this._log.trace("_stopWatchingPrefs");
for (let [pref, options] of this._watchedPrefs) {
if (!("requiresRestart" in options) || !options.requiresRestart) {
Preferences.ignore(pref, this._onPrefChanged, this);
}
}
},
- _addObservers: function () {
+ _addObservers: function() {
// Watch the search engine change and service topics.
Services.obs.addObserver(this, COMPOSITOR_CREATED_TOPIC, false);
Services.obs.addObserver(this, DISTRIBUTION_CUSTOMIZATION_COMPLETE_TOPIC, false);
Services.obs.addObserver(this, GFX_FEATURES_READY_TOPIC, false);
Services.obs.addObserver(this, SEARCH_ENGINE_MODIFIED_TOPIC, false);
Services.obs.addObserver(this, SEARCH_SERVICE_TOPIC, false);
},
- _removeObservers: function () {
+ _removeObservers: function() {
Services.obs.removeObserver(this, COMPOSITOR_CREATED_TOPIC);
try {
Services.obs.removeObserver(this, DISTRIBUTION_CUSTOMIZATION_COMPLETE_TOPIC);
} catch (ex) {}
Services.obs.removeObserver(this, GFX_FEATURES_READY_TOPIC);
Services.obs.removeObserver(this, SEARCH_ENGINE_MODIFIED_TOPIC);
Services.obs.removeObserver(this, SEARCH_SERVICE_TOPIC);
},
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
this._log.trace("observe - aTopic: " + aTopic + ", aData: " + aData);
switch (aTopic) {
case SEARCH_ENGINE_MODIFIED_TOPIC:
if (aData != "engine-current") {
return;
}
// Record the new default search choice and send the change notification.
this._onSearchEngineChange();
@@ -991,17 +991,17 @@ EnvironmentCache.prototype = {
}
},
/**
* Get the default search engine.
* @return {String} Returns the search engine identifier, "NONE" if no default search
* engine is defined or "UNDEFINED" if no engine identifier or name can be found.
*/
- _getDefaultSearchEngine: function () {
+ _getDefaultSearchEngine: function() {
let engine;
try {
engine = Services.search.defaultEngine;
} catch (e) {}
let name;
if (!engine) {
name = "NONE";
@@ -1014,17 +1014,17 @@ EnvironmentCache.prototype = {
}
return name;
},
/**
* Update the default search engine value.
*/
- _updateSearchEngine: function () {
+ _updateSearchEngine: function() {
if (!Services.search) {
// Just ignore cases where the search service is not implemented.
return;
}
this._log.trace("_updateSearchEngine - isInitialized: " + Services.search.isInitialized);
if (!Services.search.isInitialized) {
return;
@@ -1040,29 +1040,29 @@ EnvironmentCache.prototype = {
// Record the cohort identifier used for search defaults A/B testing.
if (Services.prefs.prefHasUserValue(PREF_SEARCH_COHORT))
this._currentEnvironment.settings.searchCohort = Services.prefs.getCharPref(PREF_SEARCH_COHORT);
},
/**
* Update the default search engine value and trigger the environment change.
*/
- _onSearchEngineChange: function () {
+ _onSearchEngineChange: function() {
this._log.trace("_onSearchEngineChange");
// Finally trigger the environment change notification.
let oldEnvironment = Cu.cloneInto(this._currentEnvironment, myScope);
this._updateSearchEngine();
this._onEnvironmentChange("search-engine-changed", oldEnvironment);
},
/**
* Update the graphics features object.
*/
- _updateGraphicsFeatures: function () {
+ _updateGraphicsFeatures: function() {
let gfxData = this._currentEnvironment.system.gfx;
try {
let gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo);
gfxData.features = gfxInfo.getFeatures();
} catch (e) {
this._log.error("nsIGfxInfo.getFeatures() caught error", e);
}
},
@@ -1073,17 +1073,17 @@ EnvironmentCache.prototype = {
_updatePartner: function() {
this._currentEnvironment.partner = this._getPartner();
},
/**
* Get the build data in object form.
* @return Object containing the build data.
*/
- _getBuild: function () {
+ _getBuild: function() {
let buildData = {
applicationId: Services.appinfo.ID || null,
applicationName: Services.appinfo.name || null,
architecture: Services.sysinfo.get("arch"),
buildId: Services.appinfo.appBuildID || null,
version: Services.appinfo.version || null,
vendor: Services.appinfo.vendor || null,
platformVersion: Services.appinfo.platformVersion || null,
@@ -1101,17 +1101,17 @@ EnvironmentCache.prototype = {
return buildData;
},
/**
* Determine if we're the default browser.
* @returns null on error, true if we are the default browser, or false otherwise.
*/
- _isDefaultBrowser: function () {
+ _isDefaultBrowser: function() {
if (AppConstants.platform === "gonk") {
return true;
}
if (!("@mozilla.org/browser/shell-service;1" in Cc)) {
this._log.info("_isDefaultBrowser - Could not obtain browser shell service");
return null;
}
@@ -1142,17 +1142,17 @@ EnvironmentCache.prototype = {
this._log.error("_isDefaultBrowser - Could not determine if default browser", ex);
return null;
}
},
/**
* Update the cached settings data.
*/
- _updateSettings: function () {
+ _updateSettings: function() {
let updateChannel = null;
try {
updateChannel = UpdateUtils.getUpdateChannel(false);
} catch (e) {}
this._currentEnvironment.settings = {
blocklistEnabled: Preferences.get(PREF_BLOCKLIST_ENABLED, true),
e10sEnabled: Services.appinfo.browserTabsRemoteAutostart,
@@ -1213,17 +1213,17 @@ EnvironmentCache.prototype = {
}
}
}),
/**
* Get the partner data in object form.
* @return Object containing the partner data.
*/
- _getPartner: function () {
+ _getPartner: function() {
let partnerData = {
distributionId: Preferences.get(PREF_DISTRIBUTION_ID, null),
distributionVersion: Preferences.get(PREF_DISTRIBUTION_VERSION, null),
partnerId: Preferences.get(PREF_PARTNER_ID, null),
distributor: Preferences.get(PREF_DISTRIBUTOR, null),
distributorChannel: Preferences.get(PREF_DISTRIBUTOR_CHANNEL, null),
};
@@ -1233,17 +1233,17 @@ EnvironmentCache.prototype = {
return partnerData;
},
/**
* Get the CPU information.
* @return Object containing the CPU information data.
*/
- _getCpuData: function () {
+ _getCpuData: function() {
let cpuData = {
count: getSysinfoProperty("cpucount", null),
cores: getSysinfoProperty("cpucores", null),
vendor: getSysinfoProperty("cpuvendor", null),
family: getSysinfoProperty("cpufamily", null),
model: getSysinfoProperty("cpumodel", null),
stepping: getSysinfoProperty("cpustepping", null),
l2cacheKB: getSysinfoProperty("cpucachel2", null),
@@ -1268,34 +1268,34 @@ EnvironmentCache.prototype = {
return cpuData;
},
/**
* Get the device information, if we are on a portable device.
* @return Object containing the device information data, or null if
* not a portable device.
*/
- _getDeviceData: function () {
+ _getDeviceData: function() {
if (!["gonk", "android"].includes(AppConstants.platform)) {
return null;
}
return {
model: getSysinfoProperty("device", null),
manufacturer: getSysinfoProperty("manufacturer", null),
hardware: getSysinfoProperty("hardware", null),
isTablet: getSysinfoProperty("tablet", null),
};
},
/**
* Get the OS information.
* @return Object containing the OS data.
*/
- _getOSData: function () {
+ _getOSData: function() {
let data = {
name: forceToStringOrNull(getSysinfoProperty("name", null)),
version: forceToStringOrNull(getSysinfoProperty("version", null)),
locale: forceToStringOrNull(getSystemLocale()),
};
if (["gonk", "android"].includes(AppConstants.platform)) {
data.kernelVersion = forceToStringOrNull(getSysinfoProperty("kernel_version", null));
@@ -1322,17 +1322,17 @@ EnvironmentCache.prototype = {
return data;
},
/**
* Get the HDD information.
* @return Object containing the HDD data.
*/
- _getHDDData: function () {
+ _getHDDData: function() {
return {
profile: { // hdd where the profile folder is located
model: getSysinfoProperty("profileHDDModel", null),
revision: getSysinfoProperty("profileHDDRevision", null),
},
binary: { // hdd where the application binary is located
model: getSysinfoProperty("binHDDModel", null),
revision: getSysinfoProperty("binHDDRevision", null),
@@ -1343,17 +1343,17 @@ EnvironmentCache.prototype = {
},
};
},
/**
* Get the GFX information.
* @return Object containing the GFX data.
*/
- _getGFXData: function () {
+ _getGFXData: function() {
let gfxData = {
D2DEnabled: getGfxField("D2DEnabled", null),
DWriteEnabled: getGfxField("DWriteEnabled", null),
ContentBackend: getGfxField("ContentBackend", null),
// The following line is disabled due to main thread jank and will be enabled
// again as part of bug 1154500.
// DWriteVersion: getGfxField("DWriteVersion", null),
adapters: [],
@@ -1395,17 +1395,17 @@ EnvironmentCache.prototype = {
return gfxData;
},
/**
* Get the system data in object form.
* @return Object containing the system data.
*/
- _getSystem: function () {
+ _getSystem: function() {
let memoryMB = getSysinfoProperty("memsize", null);
if (memoryMB) {
// Send RAM size in megabytes. Rounding because sysinfo doesn't
// always provide RAM in multiples of 1024.
memoryMB = Math.round(memoryMB / 1024 / 1024);
}
let virtualMB = getSysinfoProperty("virtualmemsize", null);
@@ -1428,17 +1428,17 @@ EnvironmentCache.prototype = {
data.isWow64 = getSysinfoProperty("isWow64", null);
} else if (["gonk", "android"].includes(AppConstants.platform)) {
data.device = this._getDeviceData();
}
return data;
},
- _onEnvironmentChange: function (what, oldEnvironment) {
+ _onEnvironmentChange: function(what, oldEnvironment) {
this._log.trace("_onEnvironmentChange for " + what);
// We are already skipping change events in _checkChanges if there is a pending change task running.
if (this._shutdown) {
this._log.trace("_onEnvironmentChange - Already shut down.");
return;
}
@@ -1447,13 +1447,13 @@ EnvironmentCache.prototype = {
this._log.debug("_onEnvironmentChange - calling " + name);
listener(what, oldEnvironment);
} catch (e) {
this._log.error("_onEnvironmentChange - listener " + name + " caught error", e);
}
}
},
- reset: function () {
+ reset: function() {
this._shutdown = false;
this._delayedInitFinished = false;
}
};
--- a/toolkit/components/telemetry/TelemetryReportingPolicy.jsm
+++ b/toolkit/components/telemetry/TelemetryReportingPolicy.jsm
@@ -90,27 +90,27 @@ var Policy = {
function NotifyPolicyRequest(aLog) {
this._log = aLog;
}
NotifyPolicyRequest.prototype = Object.freeze({
/**
* Called when the user is notified of the policy.
*/
- onUserNotifyComplete: function () {
+ onUserNotifyComplete: function() {
return TelemetryReportingPolicyImpl._infobarShownCallback();
},
/**
* Called when there was an error notifying the user about the policy.
*
* @param error
* (Error) Explains what went wrong.
*/
- onUserNotifyFailed: function (error) {
+ onUserNotifyFailed: function(error) {
this._log.error("onUserNotifyFailed - " + error);
},
});
this.TelemetryReportingPolicy = {
// The current policy version number. If the version number stored in the prefs
// is smaller than this, data upload will be disabled until the user is re-notified
// about the policy changes.
--- a/toolkit/components/telemetry/TelemetrySend.jsm
+++ b/toolkit/components/telemetry/TelemetrySend.jsm
@@ -702,17 +702,17 @@ var TelemetrySendImpl = {
this._currentPings.set(ping.id, ping);
SendScheduler.triggerSendingPings(true);
return Promise.resolve();
},
/**
* Only used in tests.
*/
- setServer: function (server) {
+ setServer: function(server) {
this._log.trace("setServer", server);
this._server = server;
},
/**
* Clear out unpersisted, yet to be sent, pings and cancel outgoing ping requests.
*/
clearCurrentPings: Task.async(function*() {
@@ -1045,28 +1045,28 @@ var TelemetrySendImpl = {
// Without unified Telemetry, the Telemetry enabled pref controls ping sending.
return Utils.isTelemetryEnabled;
},
/**
* Track any pending ping send and save tasks through the promise passed here.
* This is needed to block shutdown on any outstanding ping activity.
*/
- _trackPendingPingTask: function (promise) {
+ _trackPendingPingTask: function(promise) {
let clear = () => this._pendingPingActivity.delete(promise);
promise.then(clear, clear);
this._pendingPingActivity.add(promise);
},
/**
* Return a promise that allows to wait on pending pings.
* @return {Object<Promise>} A promise resolved when all the pending pings promises
* are resolved.
*/
- promisePendingPingActivity: function () {
+ promisePendingPingActivity: function() {
this._log.trace("promisePendingPingActivity - Waiting for ping task");
let p = Array.from(this._pendingPingActivity, p => p.catch(ex => {
this._log.error("promisePendingPingActivity - ping activity had an error", ex);
}));
p.push(SendScheduler.waitOnSendTask());
return Promise.all(p);
},
--- a/toolkit/components/telemetry/TelemetrySession.jsm
+++ b/toolkit/components/telemetry/TelemetrySession.jsm
@@ -640,17 +640,17 @@ this.TelemetrySession = Object.freeze({
* @return {Promise} Resolved when the initialization completes.
*/
delayedInit: function() {
return Impl.delayedInit();
},
/**
* Send a notification.
*/
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
return Impl.observe(aSubject, aTopic, aData);
},
});
var Impl = {
_histograms: {},
_initialized: false,
_logger: null,
@@ -976,17 +976,17 @@ var Impl = {
/**
* Get a snapshot of the scalars and clear them.
* @param {subsession} If true, then we collect the data for a subsession.
* @param {clearSubsession} If true, we need to clear the subsession.
* @param {keyed} Take a snapshot of keyed or non keyed scalars.
* @return {Object} The scalar data as a Javascript object.
*/
- getScalars: function (subsession, clearSubsession, keyed) {
+ getScalars: function(subsession, clearSubsession, keyed) {
this._log.trace("getScalars - subsession: " + subsession + ", clearSubsession: " +
clearSubsession + ", keyed: " + keyed);
if (!subsession) {
// We only support scalars for subsessions.
this._log.trace("getScalars - We only support scalars in subsessions.");
return {};
}
@@ -1334,17 +1334,17 @@ var Impl = {
}
return payloadObj;
},
/**
* Start a new subsession.
*/
- startNewSubsession: function () {
+ startNewSubsession: function() {
this._subsessionStartDate = Policy.now();
this._subsessionStartTimeMonotonic = Policy.monotonicNow();
this._previousSubsessionId = this._subsessionId;
this._subsessionId = Policy.generateSubsessionUUID();
this._subsessionCounter++;
this._profileSubsessionCounter++;
},
@@ -1497,17 +1497,17 @@ var Impl = {
this.attachObservers();
this.gatherMemory();
if (Telemetry.canRecordExtended) {
GCTelemetry.init();
}
- Telemetry.asyncFetchTelemetryData(function () {});
+ Telemetry.asyncFetchTelemetryData(function() {});
if (IS_UNIFIED_TELEMETRY) {
// Check for a previously written aborted session ping.
yield TelemetryController.checkAbortedSessionPing();
// Write the first aborted-session ping as early as possible. Just do that
// if we are not testing, since calling Telemetry.reset() will make a previous
// aborted ping a pending ping.
@@ -1839,17 +1839,17 @@ var Impl = {
testPing: function testPing() {
return this.send(REASON_TEST_PING);
},
/**
* This observer drives telemetry.
*/
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
// Prevent the cycle collector begin topic from cluttering the log.
if (aTopic != TOPIC_CYCLE_COLLECTOR_BEGIN) {
this._log.trace("observe - " + aTopic + " notified.");
}
switch (aTopic) {
case "content-child-shutdown":
// content-child-shutdown is only registered for content processes.
--- a/toolkit/components/telemetry/TelemetryStopwatch.jsm
+++ b/toolkit/components/telemetry/TelemetryStopwatch.jsm
@@ -282,17 +282,17 @@ this.TelemetryStopwatchImpl = {
Cu.reportError(`TelemetryStopwatch: key "${histogram}" was already ` +
"initialized");
return false;
}
return Timers.put(histogram, object, key, Components.utils.now());
},
- cancel: function (histogram, object, key) {
+ cancel: function(histogram, object, key) {
return Timers.delete(histogram, object, key);
},
timeElapsed: function(histogram, object, key) {
let startTime = Timers.get(histogram, object, key);
if (startTime === null) {
Cu.reportError("TelemetryStopwatch: requesting elapsed time for " +
`nonexisting stopwatch. Histogram: "${histogram}", ` +
--- a/toolkit/components/telemetry/TelemetryStorage.jsm
+++ b/toolkit/components/telemetry/TelemetryStorage.jsm
@@ -481,40 +481,40 @@ function SaveSerializer() {
SaveSerializer.prototype = {
/**
* Enqueues an operation to a list to serialise their execution in order to prevent race
* conditions. Useful to serialise access to disk.
*
* @param {Function} aFunction The task function to enqueue. It must return a promise.
* @return {Promise} A promise resolved when the enqueued task completes.
*/
- enqueueTask: function (aFunction) {
+ enqueueTask: function(aFunction) {
let promise = new Promise((resolve, reject) =>
this._queuedOperations.push([aFunction, resolve, reject]));
if (this._queuedOperations.length == 1) {
this._popAndPerformQueuedOperation();
}
return promise;
},
/**
* Make sure to flush all the pending operations.
* @return {Promise} A promise resolved when all the pending operations have completed.
*/
- flushTasks: function () {
+ flushTasks: function() {
let dummyTask = () => new Promise(resolve => resolve());
return this.enqueueTask(dummyTask);
},
/**
* Pop a task from the queue, executes it and continue to the next one.
* This function recursively pops all the tasks.
*/
- _popAndPerformQueuedOperation: function () {
+ _popAndPerformQueuedOperation: function() {
if (!this._queuedOperations.length || this._queuedInProgress) {
return;
}
this._log.trace("_popAndPerformQueuedOperation - Performing queued operation.");
let [func, resolve, reject] = this._queuedOperations.shift();
let promise;
@@ -1382,28 +1382,28 @@ var TelemetryStorageImpl = {
},
/**
* Track any pending ping save tasks through the promise passed here.
* This is needed to block on any outstanding ping save activity.
*
* @param {Object<Promise>} The save promise to track.
*/
- _trackPendingPingSaveTask: function (promise) {
+ _trackPendingPingSaveTask: function(promise) {
let clear = () => this._activePendingPingSaves.delete(promise);
promise.then(clear, clear);
this._activePendingPingSaves.add(promise);
},
/**
* Return a promise that allows to wait on pending pings being saved.
* @return {Object<Promise>} A promise resolved when all the pending pings save promises
* are resolved.
*/
- promisePendingPingSaves: function () {
+ promisePendingPingSaves: function() {
// Make sure to wait for all the promises, even if they reject. We don't need to log
// the failures here, as they are already logged elsewhere.
return waitForAll(this._activePendingPingSaves);
},
/**
* Run the task to remove all the pending pings (except the deletion ping).
*
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryEnvironment.js
+++ b/toolkit/components/telemetry/tests/unit/test_TelemetryEnvironment.js
@@ -238,17 +238,17 @@ function createMockAddonProvider(aName)
return aName;
},
addAddon: function(aAddon) {
this._addons.push(aAddon);
AddonManagerPrivate.callAddonListeners("onInstalled", new MockAddonWrapper(aAddon));
},
- getAddonsByTypes: function (aTypes, aCallback) {
+ getAddonsByTypes: function(aTypes, aCallback) {
aCallback(this._addons.map(a => new MockAddonWrapper(a)));
},
shutdown() {
return Promise.resolve();
},
};
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryLateWrites.js
+++ b/toolkit/components/telemetry/tests/unit/test_TelemetryLateWrites.js
@@ -80,17 +80,17 @@ function run_test() {
let lateWrites = Telemetry.lateWrites;
do_check_true("memoryMap" in lateWrites);
do_check_eq(lateWrites.memoryMap.length, 0);
do_check_true("stacks" in lateWrites);
do_check_eq(lateWrites.stacks.length, 0);
do_test_pending();
- Telemetry.asyncFetchTelemetryData(function () {
+ Telemetry.asyncFetchTelemetryData(function() {
actual_test();
});
}
function actual_test() {
do_check_false(construct_file(STACK_SUFFIX1).exists());
do_check_false(construct_file(STACK_SUFFIX2).exists());
do_check_false(construct_file(STACK_BOGUS_SUFFIX).exists());
--- a/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js
+++ b/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js
@@ -127,17 +127,17 @@ function setupTestData() {
function getSavedPingFile(basename) {
let tmpDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
let pingFile = tmpDir.clone();
pingFile.append(basename);
if (pingFile.exists()) {
pingFile.remove(true);
}
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
try {
pingFile.remove(true);
} catch (e) {
}
});
return pingFile;
}
--- a/toolkit/components/thumbnails/BackgroundPageThumbs.jsm
+++ b/toolkit/components/thumbnails/BackgroundPageThumbs.jsm
@@ -54,17 +54,17 @@ const BackgroundPageThumbs = {
* @opt onDone A function that will be asynchronously called when the
* capture is complete or times out. It's called as
* onDone(url),
* where `url` is the captured URL.
* @opt timeout The capture will time out after this many milliseconds have
* elapsed after the capture has progressed to the head of
* the queue and started. Defaults to 30000 (30 seconds).
*/
- capture: function (url, options = {}) {
+ capture: function(url, options = {}) {
if (!PageThumbs._prefEnabled()) {
if (options.onDone)
schedule(() => options.onDone(url));
return;
}
this._captureQueue = this._captureQueue || [];
this._capturesByURL = this._capturesByURL || new Map();
@@ -145,17 +145,17 @@ const BackgroundPageThumbs = {
/**
* Ensures that initialization of the thumbnail browser's parent window has
* begun.
*
* @return True if the parent window is completely initialized and can be
* used, and false if initialization has started but not completed.
*/
- _ensureParentWindowReady: function () {
+ _ensureParentWindowReady: function() {
if (this._parentWin)
// Already fully initialized.
return true;
if (this._startedParentWinInit)
// Already started initializing.
return false;
this._startedParentWinInit = true;
@@ -177,32 +177,32 @@ const BackgroundPageThumbs = {
return false;
},
/**
* Destroys the service. Queued and pending captures will never complete, and
* their consumer callbacks will never be called.
*/
- _destroy: function () {
+ _destroy: function() {
if (this._captureQueue)
this._captureQueue.forEach(cap => cap.destroy());
this._destroyBrowser();
if (this._hostIframe)
this._hostIframe.remove();
delete this._captureQueue;
delete this._hostIframe;
delete this._startedParentWinInit;
delete this._parentWin;
},
/**
* Creates the thumbnail browser if it doesn't already exist.
*/
- _ensureBrowser: function () {
+ _ensureBrowser: function() {
if (this._thumbBrowser && !this._renewThumbBrowser)
return;
this._destroyBrowser();
this._renewThumbBrowser = false;
let browser = this._parentWin.document.createElementNS(XUL_NS, "browser");
browser.setAttribute("type", "content");
@@ -259,28 +259,28 @@ const BackgroundPageThumbs = {
// maybe a GC or similar crashed) - so there's no need to attempt a
// queue restart - the next capture request will set everything up.
});
browser.messageManager.loadFrameScript(FRAME_SCRIPT_URL, false);
this._thumbBrowser = browser;
},
- _destroyBrowser: function () {
+ _destroyBrowser: function() {
if (!this._thumbBrowser)
return;
this._thumbBrowser.remove();
delete this._thumbBrowser;
},
/**
* Starts the next capture if the queue is not empty and the service is fully
* initialized.
*/
- _processCaptureQueue: function () {
+ _processCaptureQueue: function() {
if (!this._captureQueue.length ||
this._captureQueue[0].pending ||
!this._ensureParentWindowReady())
return;
// Ready to start the first capture in the queue.
this._ensureBrowser();
this._captureQueue[0].start(this._thumbBrowser.messageManager);
@@ -289,17 +289,17 @@ const BackgroundPageThumbs = {
delete this._destroyBrowserTimer;
}
},
/**
* Called when the current capture completes or fails (eg, times out, remote
* process crashes.)
*/
- _onCaptureOrTimeout: function (capture) {
+ _onCaptureOrTimeout: function(capture) {
// Since timeouts start as an item is being processed, only the first
// item in the queue can be passed to this method.
if (capture !== this._captureQueue[0])
throw new Error("The capture should be at the head of the queue.");
this._captureQueue.shift();
this._capturesByURL.delete(capture.url);
if (capture.doneReason != TEL_CAPTURE_DONE_OK) {
Services.obs.notifyObservers(null, "page-thumbnail:error", capture.url);
@@ -358,17 +358,17 @@ Capture.prototype = {
return !!this._msgMan;
},
/**
* Sends a message to the content script to start the capture.
*
* @param messageManager The nsIMessageSender of the thumbnail browser.
*/
- start: function (messageManager) {
+ start: function(messageManager) {
this.startDate = new Date();
tel("CAPTURE_QUEUE_TIME_MS", this.startDate - this.creationDate);
// timeout timer
let timeout = typeof(this.options.timeout) == "number" ?
this.options.timeout :
DEFAULT_CAPTURE_TIMEOUT;
this._timeoutTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
@@ -382,17 +382,17 @@ Capture.prototype = {
this._msgMan.addMessageListener("BackgroundPageThumbs:didCapture", this);
},
/**
* The only intended external use of this method is by the service when it's
* uninitializing and doing things like destroying the thumbnail browser. In
* that case the consumer's completion callback will never be called.
*/
- destroy: function () {
+ destroy: function() {
// This method may be called for captures that haven't started yet, so
// guard against not yet having _timeoutTimer, _msgMan etc properties...
if (this._timeoutTimer) {
this._timeoutTimer.cancel();
delete this._timeoutTimer;
}
if (this._msgMan) {
this._msgMan.removeMessageListener("BackgroundPageThumbs:didCapture",
@@ -400,17 +400,17 @@ Capture.prototype = {
delete this._msgMan;
}
delete this.captureCallback;
delete this.doneCallbacks;
delete this.options;
},
// Called when the didCapture message is received.
- receiveMessage: function (msg) {
+ receiveMessage: function(msg) {
if (msg.data.imageData)
tel("CAPTURE_SERVICE_TIME_MS", new Date() - this.startDate);
// A different timed-out capture may have finally successfully completed, so
// discard messages that aren't meant for this capture.
if (msg.data.id != this.id)
return;
@@ -419,21 +419,21 @@ Capture.prototype = {
this._done(null, reason);
return;
}
this._done(msg.data, TEL_CAPTURE_DONE_OK);
},
// Called when the timeout timer fires.
- notify: function () {
+ notify: function() {
this._done(null, TEL_CAPTURE_DONE_TIMEOUT);
},
- _done: function (data, reason) {
+ _done: function(data, reason) {
// Note that _done will be called only once, by either receiveMessage or
// notify, since it calls destroy here, which cancels the timeout timer and
// removes the didCapture message listener.
let { captureCallback, doneCallbacks, options } = this;
this.destroy();
this.doneReason = reason;
if (typeof(reason) != "number") {
--- a/toolkit/components/thumbnails/PageThumbUtils.jsm
+++ b/toolkit/components/thumbnails/PageThumbUtils.jsm
@@ -30,17 +30,17 @@ this.PageThumbUtils = {
* is undefined, in the context of hiddenDOMWindow.
*
* @param aWindow (optional) The document of this window will be used to
* create the canvas. If not given, the hidden window will be used.
* @param aWidth (optional) width of the canvas to create
* @param aHeight (optional) height of the canvas to create
* @return The newly created canvas.
*/
- createCanvas: function (aWindow, aWidth = 0, aHeight = 0) {
+ createCanvas: function(aWindow, aWidth = 0, aHeight = 0) {
let doc = (aWindow || Services.appShell.hiddenDOMWindow).document;
let canvas = doc.createElementNS(this.HTML_NAMESPACE, "canvas");
canvas.mozOpaque = true;
canvas.imageSmoothingEnabled = true;
let [thumbnailWidth, thumbnailHeight] = this.getThumbnailSize(aWindow);
canvas.width = aWidth ? aWidth : thumbnailWidth;
canvas.height = aHeight ? aHeight : thumbnailHeight;
return canvas;
@@ -49,17 +49,17 @@ this.PageThumbUtils = {
/**
* Calculates a preferred initial thumbnail size based based on newtab.css
* sizes or a preference for other applications. The sizes should be the same
* as set for the tile sizes in newtab.
*
* @param aWindow (optional) aWindow that is used to calculate the scaling size.
* @return The calculated thumbnail size or a default if unable to calculate.
*/
- getThumbnailSize: function (aWindow = null) {
+ getThumbnailSize: function(aWindow = null) {
if (!this._thumbnailWidth || !this._thumbnailHeight) {
let screenManager = Cc["@mozilla.org/gfx/screenmanager;1"]
.getService(Ci.nsIScreenManager);
let left = {}, top = {}, screenWidth = {}, screenHeight = {};
screenManager.primaryScreen.GetRectDisplayPix(left, top, screenWidth, screenHeight);
/** *
* The system default scale might be different than
@@ -224,17 +224,17 @@ this.PageThumbUtils = {
/**
* Determine a good thumbnail crop size and scale for a given content
* window.
*
* @param aWindow The content window.
* @param aCanvas The target canvas.
* @return An array containing width, height and scale.
*/
- determineCropSize: function (aWindow, aCanvas) {
+ determineCropSize: function(aWindow, aCanvas) {
if (Cu.isCrossProcessWrapper(aWindow)) {
throw new Error('Do not pass cpows here.');
}
let utils = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
// aWindow may be a cpow, add exposed props security values.
let sbWidth = {}, sbHeight = {};
@@ -260,17 +260,17 @@ this.PageThumbUtils = {
height -= Math.floor(Math.abs(scaledHeight - thumbnailHeight) * scale);
if (scaledWidth > thumbnailWidth)
width -= Math.floor(Math.abs(scaledWidth - thumbnailWidth) * scale);
return [width, height, scale];
},
- shouldStoreContentThumbnail: function (aDocument, aDocShell) {
+ shouldStoreContentThumbnail: function(aDocument, aDocShell) {
if (BrowserUtils.isToolbarVisible(aDocShell, "findbar")) {
return false;
}
// FIXME Bug 720575 - Don't capture thumbnails for SVG or XML documents as
// that currently regresses Talos SVG tests.
if (aDocument instanceof Ci.nsIDOMXMLDocument) {
return false;
--- a/toolkit/components/thumbnails/PageThumbs.jsm
+++ b/toolkit/components/thumbnails/PageThumbs.jsm
@@ -45,21 +45,21 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/FileUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "gUpdateTimerManager",
"@mozilla.org/updates/timer-manager;1", "nsIUpdateTimerManager");
-XPCOMUtils.defineLazyGetter(this, "gCryptoHash", function () {
+XPCOMUtils.defineLazyGetter(this, "gCryptoHash", function() {
return Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
});
-XPCOMUtils.defineLazyGetter(this, "gUnicodeConverter", function () {
+XPCOMUtils.defineLazyGetter(this, "gUnicodeConverter", function() {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = 'utf8';
return converter;
});
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
@@ -210,17 +210,17 @@ this.PageThumbs = {
* @param aCanvas The canvas to draw to. The thumbnail will be scaled to match
* the dimensions of this canvas. If callers pass a 0x0 canvas, the canvas
* will be resized to default thumbnail dimensions just prior to painting.
* @param aCallback (optional) A callback invoked once the thumbnail has been
* rendered to aCanvas.
* @param aArgs (optional) Additional named parameters:
* fullScale - request that a non-downscaled image be returned.
*/
- captureToCanvas: function (aBrowser, aCanvas, aCallback, aArgs) {
+ captureToCanvas: function(aBrowser, aCanvas, aCallback, aArgs) {
let telemetryCaptureTime = new Date();
let args = {
fullScale: aArgs ? aArgs.fullScale : false
};
this._captureToCanvas(aBrowser, aCanvas, args, (aCanvas) => {
Services.telemetry
.getHistogramById("FX_THUMBNAILS_CAPTURE_TIME_MS")
.add(new Date() - telemetryCaptureTime);
@@ -237,39 +237,39 @@ this.PageThumbs = {
* transitory as it is based on current navigation state and the type of
* content being displayed.
*
* @param aBrowser The target browser
* @param aCallback(aResult) A callback invoked once security checks have
* completed. aResult is a boolean indicating the combined result of the
* security checks performed.
*/
- shouldStoreThumbnail: function (aBrowser, aCallback) {
+ shouldStoreThumbnail: function(aBrowser, aCallback) {
// Don't capture in private browsing mode.
if (PrivateBrowsingUtils.isBrowserPrivate(aBrowser)) {
aCallback(false);
return;
}
if (aBrowser.isRemoteBrowser) {
let mm = aBrowser.messageManager;
- let resultFunc = function (aMsg) {
+ let resultFunc = function(aMsg) {
mm.removeMessageListener("Browser:Thumbnail:CheckState:Response", resultFunc);
aCallback(aMsg.data.result);
}
mm.addMessageListener("Browser:Thumbnail:CheckState:Response", resultFunc);
mm.sendAsyncMessage("Browser:Thumbnail:CheckState");
} else {
aCallback(PageThumbUtils.shouldStoreContentThumbnail(aBrowser.contentDocument,
aBrowser.docShell));
}
},
// The background thumbnail service captures to canvas but doesn't want to
// participate in this service's telemetry, which is why this method exists.
- _captureToCanvas: function (aBrowser, aCanvas, aArgs, aCallback) {
+ _captureToCanvas: function(aBrowser, aCanvas, aArgs, aCallback) {
if (aBrowser.isRemoteBrowser) {
Task.spawn(function* () {
let data =
yield this._captureRemoteThumbnail(aBrowser, aCanvas.width,
aCanvas.height, aArgs);
let canvas = data.thumbnail;
let ctx = canvas.getContext("2d");
let imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
@@ -297,40 +297,40 @@ this.PageThumbs = {
*
* @param aBrowser The browser to capture a thumbnail from.
* @param aWidth The desired canvas width.
* @param aHeight The desired canvas height.
* @param aArgs (optional) Additional named parameters:
* fullScale - request that a non-downscaled image be returned.
* @return a promise
*/
- _captureRemoteThumbnail: function (aBrowser, aWidth, aHeight, aArgs) {
+ _captureRemoteThumbnail: function(aBrowser, aWidth, aHeight, aArgs) {
let deferred = Promise.defer();
// The index we send with the request so we can identify the
// correct response.
let index = gRemoteThumbId++;
// Thumbnail request response handler
let mm = aBrowser.messageManager;
// Browser:Thumbnail:Response handler
- let thumbFunc = function (aMsg) {
+ let thumbFunc = function(aMsg) {
// Ignore events unrelated to our request
if (aMsg.data.id != index) {
return;
}
mm.removeMessageListener("Browser:Thumbnail:Response", thumbFunc);
let imageBlob = aMsg.data.thumbnail;
let doc = aBrowser.parentElement.ownerDocument;
let reader = new FileReader();
reader.addEventListener("loadend", function() {
let image = doc.createElementNS(PageThumbUtils.HTML_NAMESPACE, "img");
- image.onload = function () {
+ image.onload = function() {
let thumbnail = doc.createElementNS(PageThumbUtils.HTML_NAMESPACE, "canvas");
thumbnail.width = image.naturalWidth;
thumbnail.height = image.naturalHeight;
let ctx = thumbnail.getContext("2d");
ctx.drawImage(image, 0, 0);
deferred.resolve({
thumbnail: thumbnail
});
@@ -879,17 +879,17 @@ var PageThumbsHistoryObserver = {
onDeleteURI: function Thumbnails_onDeleteURI(aURI, aGUID) {
PageThumbsStorage.remove(aURI.spec);
},
onClearHistory: function Thumbnails_onClearHistory() {
PageThumbsStorage.wipe();
},
- onTitleChanged: function () {},
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
+ onTitleChanged: function() {},
+ onBeginUpdateBatch: function() {},
+ onEndUpdateBatch: function() {},
+ onVisit: function() {},
+ onPageChanged: function() {},
+ onDeleteVisits: function() {},
QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
};
--- a/toolkit/components/thumbnails/PageThumbsProtocol.js
+++ b/toolkit/components/thumbnails/PageThumbsProtocol.js
@@ -140,15 +140,15 @@ this.NSGetFactory = XPCOMUtils.generateN
*/
function parseURI(aURI) {
if (aURI.host != PageThumbs.staticHost)
throw Cr.NS_ERROR_NOT_AVAILABLE;
let {query} = aURI.QueryInterface(Ci.nsIURL);
let params = {};
- query.split("&").forEach(function (aParam) {
+ query.split("&").forEach(function(aParam) {
let [key, value] = aParam.split("=").map(decodeURIComponent);
params[key.toLowerCase()] = value;
});
return params;
}
--- a/toolkit/components/thumbnails/content/backgroundPageThumbsContent.js
+++ b/toolkit/components/thumbnails/content/backgroundPageThumbsContent.js
@@ -19,17 +19,17 @@ const STATE_CANCELED = 3;
* This flag prevents content from creating new auxiliary browsing contexts,
* e.g. using the target attribute, the window.open() method, or the
* showModalDialog() method.
*/
const SANDBOXED_AUXILIARY_NAVIGATION = 0x2;
const backgroundPageThumbsContent = {
- init: function () {
+ init: function() {
Services.obs.addObserver(this, "document-element-inserted", true);
// We want a low network priority for this service - lower than b/g tabs
// etc - so set it to the lowest priority available.
this._webNav.QueryInterface(Ci.nsIDocumentLoader).
loadGroup.QueryInterface(Ci.nsISupportsPriority).
priority = Ci.nsISupportsPriority.PRIORITY_LOWEST;
@@ -46,34 +46,34 @@ const backgroundPageThumbsContent = {
addMessageListener("BackgroundPageThumbs:capture",
this._onCapture.bind(this));
docShell.
QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIWebProgress).
addProgressListener(this, Ci.nsIWebProgress.NOTIFY_STATE_WINDOW);
},
- observe: function (subj, topic, data) {
+ observe: function(subj, topic, data) {
// Arrange to prevent (most) popup dialogs for this window - popups done
// in the parent (eg, auth) aren't prevented, but alert() etc are.
// disableDialogs only works on the current inner window, so it has
// to be called every page load, but before scripts run.
if (content && subj == content.document) {
content.
QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIDOMWindowUtils).
disableDialogs();
}
},
get _webNav() {
return docShell.QueryInterface(Ci.nsIWebNavigation);
},
- _onCapture: function (msg) {
+ _onCapture: function(msg) {
this._nextCapture = {
id: msg.data.id,
url: msg.data.url,
};
if (this._currentCapture) {
if (this._state == STATE_LOADING) {
// Cancel the current capture.
this._state = STATE_CANCELED;
@@ -81,17 +81,17 @@ const backgroundPageThumbsContent = {
}
// Let the current capture finish capturing, or if it was just canceled,
// wait for onStateChange due to the about:blank load.
return;
}
this._startNextCapture();
},
- _startNextCapture: function () {
+ _startNextCapture: function() {
if (!this._nextCapture)
return;
this._currentCapture = this._nextCapture;
delete this._nextCapture;
this._state = STATE_LOADING;
this._currentCapture.pageLoadStartDate = new Date();
try {
@@ -100,17 +100,17 @@ const backgroundPageThumbsContent = {
null, null, null);
} catch (e) {
this._failCurrentCapture("BAD_URI");
delete this._currentCapture;
this._startNextCapture();
}
},
- onStateChange: function (webProgress, req, flags, status) {
+ onStateChange: function(webProgress, req, flags, status) {
if (webProgress.isTopLevel &&
(flags & Ci.nsIWebProgressListener.STATE_STOP) &&
this._currentCapture) {
if (req.name == "about:blank") {
if (this._state == STATE_CAPTURING) {
// about:blank has loaded, ending the current capture.
this._finishCurrentCapture();
delete this._currentCapture;
@@ -139,51 +139,51 @@ const backgroundPageThumbsContent = {
this._loadAboutBlank();
delete this._cancelTimer;
}, 0, Ci.nsITimer.TYPE_ONE_SHOT);
}
}
}
},
- _captureCurrentPage: function () {
+ _captureCurrentPage: function() {
let capture = this._currentCapture;
capture.finalURL = this._webNav.currentURI.spec;
capture.pageLoadTime = new Date() - capture.pageLoadStartDate;
let canvasDrawDate = new Date();
let finalCanvas = PageThumbUtils.createSnapshotThumbnail(content, null);
capture.canvasDrawTime = new Date() - canvasDrawDate;
finalCanvas.toBlob(blob => {
capture.imageBlob = new Blob([blob]);
// Load about:blank to finish the capture and wait for onStateChange.
this._loadAboutBlank();
});
},
- _finishCurrentCapture: function () {
+ _finishCurrentCapture: function() {
let capture = this._currentCapture;
let fileReader = new FileReader();
fileReader.onloadend = () => {
sendAsyncMessage("BackgroundPageThumbs:didCapture", {
id: capture.id,
imageData: fileReader.result,
finalURL: capture.finalURL,
telemetry: {
CAPTURE_PAGE_LOAD_TIME_MS: capture.pageLoadTime,
CAPTURE_CANVAS_DRAW_TIME_MS: capture.canvasDrawTime,
},
});
};
fileReader.readAsArrayBuffer(capture.imageBlob);
},
- _failCurrentCapture: function (reason) {
+ _failCurrentCapture: function(reason) {
let capture = this._currentCapture;
sendAsyncMessage("BackgroundPageThumbs:didCapture", {
id: capture.id,
failReason: reason,
});
},
// We load about:blank to finish all captures, even canceled captures. Two
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_sent.js
+++ b/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_sent.js
@@ -3,38 +3,38 @@
function* runTests() {
// Visit the test page in the browser and tell it to set a cookie.
let url = bgTestPageURL({ setGreenCookie: true });
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
let browser = tab.linkedBrowser;
// The root element of the page shouldn't be green yet.
- yield ContentTask.spawn(browser, null, function () {
+ yield ContentTask.spawn(browser, null, function() {
Assert.notEqual(content.document.documentElement.style.backgroundColor,
"rgb(0, 255, 0)",
"The page shouldn't be green yet.");
});
// Cookie should be set now. Reload the page to verify. Its root element
// will be green if the cookie's set.
browser.reload();
yield BrowserTestUtils.browserLoaded(browser);
- yield ContentTask.spawn(browser, null, function () {
+ yield ContentTask.spawn(browser, null, function() {
Assert.equal(content.document.documentElement.style.backgroundColor,
"rgb(0, 255, 0)",
"The page should be green now.");
});
// Capture the page. Get the image data of the capture and verify it's not
// green. (Checking only the first pixel suffices.)
yield bgCapture(url);
ok(thumbnailExists(url), "Thumbnail file should exist after capture.");
- retrieveImageDataForURL(url, function ([r, g, b]) {
+ retrieveImageDataForURL(url, function([r, g, b]) {
isnot([r, g, b].toString(), [0, 255, 0].toString(),
"The captured page should not be green.");
gBrowser.removeTab(tab);
removeThumbnail(url);
next();
});
yield true;
}
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bug727765.js
+++ b/toolkit/components/thumbnails/test/browser_thumbnails_bug727765.js
@@ -14,16 +14,16 @@ function isRedThumbnailFuzz(r, g, b, exp
// Test for black borders caused by scrollbars.
function* runTests() {
// Create a tab with a page with a red background and scrollbars.
yield addTab(URL);
yield captureAndCheckColor(255, 0, 0, "we have a red thumbnail");
// Check the thumbnail color of the bottom right pixel.
yield whenFileExists(URL);
- yield retrieveImageDataForURL(URL, function (aData) {
+ yield retrieveImageDataForURL(URL, function(aData) {
let [r, g, b] = [].slice.call(aData, -4);
let fuzz = 2; // Windows 8 x64 blends with the scrollbar a bit.
var message = "Expected red thumbnail rgb(255, 0, 0), got " + r + "," + g + "," + b;
ok(isRedThumbnailFuzz(r, g, b, 255, 0, 0, fuzz), message);
next();
});
}
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bug818225.js
+++ b/toolkit/components/thumbnails/test/browser_thumbnails_bug818225.js
@@ -17,18 +17,18 @@ function* runTests() {
let expectedPath = PageThumbsStorage.getFilePathForURL(URL);
is(path, expectedPath, "Thumbnail file has correct path");
yield testIfExists(path, true, "Thumbnail file exists");
}
function createThumbnail(aURL) {
- addTab(aURL, function () {
- whenFileExists(aURL, function () {
+ addTab(aURL, function() {
+ whenFileExists(aURL, function() {
gBrowser.removeTab(gBrowser.selectedTab);
next();
});
});
}
function testIfExists(aPath, aExpected, aMessage) {
return OS.File.exists(aPath).then(
--- a/toolkit/components/thumbnails/test/browser_thumbnails_privacy.js
+++ b/toolkit/components/thumbnails/test/browser_thumbnails_privacy.js
@@ -1,17 +1,17 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
const PREF_DISK_CACHE_SSL = "browser.cache.disk_cache_ssl";
const URL = "://example.com/browser/toolkit/components/thumbnails/" +
"test/privacy_cache_control.sjs";
function* runTests() {
- registerCleanupFunction(function () {
+ registerCleanupFunction(function() {
Services.prefs.clearUserPref(PREF_DISK_CACHE_SSL);
});
let positive = [
// A normal HTTP page without any Cache-Control header.
{scheme: "http", cacheControl: null, diskCacheSSL: false},
// A normal HTTP page with 'Cache-Control: private'.
--- a/toolkit/components/thumbnails/test/browser_thumbnails_redirect.js
+++ b/toolkit/components/thumbnails/test/browser_thumbnails_redirect.js
@@ -18,13 +18,13 @@ function* runTests() {
gBrowser.removeTab(gBrowser.selectedTab);
// Create a tab, redirecting to a page with a red background.
yield addTab(URL);
yield captureAndCheckColor(255, 0, 0, "we have a red thumbnail");
// Wait until the referrer's thumbnail's file has been written.
yield whenFileExists(URL);
- yield retrieveImageDataForURL(URL, function ([r, g, b]) {
+ yield retrieveImageDataForURL(URL, function([r, g, b]) {
is("" + [r, g, b], "255,0,0", "referrer has a red thumbnail");
next();
});
}
--- a/toolkit/components/thumbnails/test/browser_thumbnails_storage.js
+++ b/toolkit/components/thumbnails/test/browser_thumbnails_storage.js
@@ -1,15 +1,15 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
const URL = "http://mochi.test:8888/";
const URL_COPY = URL + "#copy";
-XPCOMUtils.defineLazyGetter(this, "Sanitizer", function () {
+XPCOMUtils.defineLazyGetter(this, "Sanitizer", function() {
let tmp = {};
Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader)
.loadSubScript("chrome://browser/content/sanitize.js", tmp);
return tmp.Sanitizer;
});
/**
@@ -97,16 +97,16 @@ function promiseClearHistory(aUseRange)
return s.sanitize().then(() => {
s.range = null;
s.ignoreTimespan = true;
});
}
function promiseCreateThumbnail() {
return new Promise(resolve => {
- addTab(URL, function () {
- whenFileExists(URL, function () {
+ addTab(URL, function() {
+ whenFileExists(URL, function() {
gBrowser.removeTab(gBrowser.selectedTab);
resolve();
});
});
});
}
--- a/toolkit/components/thumbnails/test/browser_thumbnails_storage_migrate3.js
+++ b/toolkit/components/thumbnails/test/browser_thumbnails_storage_migrate3.js
@@ -80,17 +80,17 @@ function* runTests() {
}
}
function changeLocation(aLocation, aNewDir) {
let oldDir = gDirSvc.get(aLocation, Ci.nsILocalFile);
gDirSvc.undefine(aLocation);
gDirSvc.set(aLocation, aNewDir);
- registerCleanupFunction(function () {
+ registerCleanupFunction(function() {
gDirSvc.undefine(aLocation);
gDirSvc.set(aLocation, oldDir);
});
}
function writeDummyFile(aFile, aContents) {
let fos = FileUtils.openSafeFileOutputStream(aFile);
let data = aContents || "dummy";
--- a/toolkit/components/thumbnails/test/browser_thumbnails_update.js
+++ b/toolkit/components/thumbnails/test/browser_thumbnails_update.js
@@ -57,17 +57,17 @@ function* simpleCaptureTest() {
}
Services.obs.addObserver(observe, "page-thumbnail:create", false);
// Create a tab - we don't care what the content is.
yield addTab(URL);
let browser = gBrowser.selectedBrowser;
// Capture the screenshot.
- PageThumbs.captureAndStore(browser, function () {
+ PageThumbs.captureAndStore(browser, function() {
// We've got a capture so should have seen the observer.
is(numNotifications, 1, "got notification of item being created.");
// The capture is now "fresh" - so requesting the URL should not cause
// a new capture.
PageThumbs.captureAndStoreIfStale(browser, function() {
is(numNotifications, 1, "still only 1 notification of item being created.");
ensureThumbnailStale(URL);
@@ -95,17 +95,17 @@ function* capIfStaleErrorResponseUpdateT
ensureThumbnailStale(URL);
yield navigateTo(URL);
// now() returns a higher-precision value than the modified time of a file.
// As we set the thumbnail very stale, allowing 1 second of "slop" here
// works around this while still keeping the test valid.
let now = Date.now() - 1000 ;
PageThumbs.captureAndStoreIfStale(gBrowser.selectedBrowser, () => {
ok(getThumbnailModifiedTime(URL) < now, "modified time should be < now");
- retrieveImageDataForURL(URL, function ([r, g, b]) {
+ retrieveImageDataForURL(URL, function([r, g, b]) {
is("" + [r, g, b], "" + [0, 255, 0], "thumbnail is still green");
gBrowser.removeTab(gBrowser.selectedTab);
next();
});
});
yield undefined; // wait for callback to call 'next'...
}
@@ -127,17 +127,17 @@ function* capIfStaleGoodResponseUpdateTe
// now() returns a higher-precision value than the modified time of a file.
// As we set the thumbnail very stale, allowing 1 second of "slop" here
// works around this while still keeping the test valid.
let now = Date.now() - 1000 ;
PageThumbs.captureAndStoreIfStale(browser, () => {
ok(getThumbnailModifiedTime(URL) >= now, "modified time should be >= now");
// the captureAndStoreIfStale request saw a 200 response with the red body,
// so we expect to see the red version here.
- retrieveImageDataForURL(URL, function ([r, g, b]) {
+ retrieveImageDataForURL(URL, function([r, g, b]) {
is("" + [r, g, b], "" + [255, 0, 0], "thumbnail is now red");
next();
});
});
yield undefined; // wait for callback to call 'next'...
}
/* Check functionality of captureAndStore when there is an error response
--- a/toolkit/components/thumbnails/test/head.js
+++ b/toolkit/components/thumbnails/test/head.js
@@ -11,17 +11,17 @@ Cu.import("resource://gre/modules/osfile
var {PageThumbs, BackgroundPageThumbs, NewTabUtils, PageThumbsStorage, SessionStore, FileUtils, OS} = tmp;
XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
"resource://testing-common/PlacesTestUtils.jsm");
var oldEnabledPref = Services.prefs.getBoolPref("browser.pagethumbnails.capturing_disabled");
Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", false);
-registerCleanupFunction(function () {
+registerCleanupFunction(function() {
while (gBrowser.tabs.length > 1)
gBrowser.removeTab(gBrowser.tabs[1]);
Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", oldEnabledPref)
});
/**
* Provide the default test function to start our test runner.
*/
@@ -31,35 +31,35 @@ function test() {
/**
* The test runner that controls the execution flow of our tests.
*/
var TestRunner = {
/**
* Starts the test runner.
*/
- run: function () {
+ run: function() {
waitForExplicitFinish();
- SessionStore.promiseInitialized.then(function () {
+ SessionStore.promiseInitialized.then(function() {
this._iter = runTests();
if (this._iter) {
this.next();
} else {
finish();
}
}.bind(this));
},
/**
* Runs the next available test or finishes if there's no test left.
* @param aValue This value will be passed to the yielder via the runner's
* iterator.
*/
- next: function (aValue) {
+ next: function(aValue) {
let obj = TestRunner._iter.next(aValue);
if (obj.done) {
finish();
return;
}
let value = obj.value || obj;
if (value && typeof value.then == "function") {
@@ -124,18 +124,18 @@ function whenLoaded(aElement, aCallback
*/
function captureAndCheckColor(aRed, aGreen, aBlue, aMessage) {
let browser = gBrowser.selectedBrowser;
// We'll get oranges if the expiration filter removes the file during the
// test.
dontExpireThumbnailURLs([browser.currentURI.spec]);
// Capture the screenshot.
- PageThumbs.captureAndStore(browser, function () {
- retrieveImageDataForURL(browser.currentURI.spec, function ([r, g, b]) {
+ PageThumbs.captureAndStore(browser, function() {
+ retrieveImageDataForURL(browser.currentURI.spec, function([r, g, b]) {
is("" + [r, g, b], "" + [aRed, aGreen, aBlue], aMessage);
next();
});
});
}
/**
* For a given URL, loads the corresponding thumbnail
@@ -147,17 +147,17 @@ function captureAndCheckColor(aRed, aGre
function retrieveImageDataForURL(aURL, aCallback) {
let width = 100, height = 100;
let thumb = PageThumbs.getThumbnailURL(aURL, width, height);
let htmlns = "http://www.w3.org/1999/xhtml";
let img = document.createElementNS(htmlns, "img");
img.setAttribute("src", thumb);
- whenLoaded(img, function () {
+ whenLoaded(img, function() {
let canvas = document.createElementNS(htmlns, "canvas");
canvas.setAttribute("width", width);
canvas.setAttribute("height", height);
// Draw the image to a canvas and compare the pixel color values.
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
let result = ctx.getImageData(0, 0, 100, 100).data;
@@ -246,17 +246,17 @@ function wait(aMillis) {
* Makes sure that a given list of URLs is not implicitly expired.
*
* @param aURLs The list of URLs that should not be expired.
*/
function dontExpireThumbnailURLs(aURLs) {
let dontExpireURLs = (cb) => cb(aURLs);
PageThumbs.addExpirationFilter(dontExpireURLs);
- registerCleanupFunction(function () {
+ registerCleanupFunction(function() {
PageThumbs.removeExpirationFilter(dontExpireURLs);
});
}
function bgCapture(aURL, aOptions) {
bgCaptureWithMethod("capture", aURL, aOptions);
}
--- a/toolkit/components/timermanager/nsUpdateTimerManager.js
+++ b/toolkit/components/timermanager/nsUpdateTimerManager.js
@@ -208,17 +208,17 @@ TimerManager.prototype = {
if (lastUpdateTime > now) {
lastUpdateTime = 0;
}
if (lastUpdateTime == 0) {
Services.prefs.setIntPref(prefLastUpdate, lastUpdateTime);
}
- tryFire(function () {
+ tryFire(function() {
try {
Components.classes[cid][method](Ci.nsITimerCallback).notify(timer);
LOG("TimerManager:notify - notified " + cid);
} catch (e) {
LOG("TimerManager:notify - error notifying component id: " +
cid + " ,error: " + e);
}
lastUpdateTime = now;
@@ -233,17 +233,17 @@ TimerManager.prototype = {
// If the last update time is greater than the current time then reset
// it to 0 and the timer manager will correct the value when it fires
// next for this consumer.
if (timerData.lastUpdateTime > now) {
let prefLastUpdate = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
timerData.lastUpdateTime = 0;
Services.prefs.setIntPref(prefLastUpdate, timerData.lastUpdateTime);
}
- tryFire(function () {
+ tryFire(function() {
if (timerData.callback && timerData.callback.notify) {
try {
timerData.callback.notify(timer);
LOG("TimerManager:notify - notified timerID: " + timerID);
} catch (e) {
LOG("TimerManager:notify - error notifying timerID: " + timerID +
", error: " + e);
}
@@ -274,34 +274,34 @@ TimerManager.prototype = {
this._cancelTimer();
}
},
/**
* Starts the timer, if necessary, and ensures that it will fire soon enough
* to happen after time |interval| (in milliseconds).
*/
- _ensureTimer: function (interval) {
+ _ensureTimer: function(interval) {
if (!this._canEnsureTimer) {
return;
}
if (!this._timer) {
this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this._timer.initWithCallback(this, interval,
Ci.nsITimer.TYPE_REPEATING_SLACK);
this.lastTimerReset = Date.now();
} else if (Date.now() + interval < this.lastTimerReset + this._timer.delay) {
this._timer.delay = Math.max(this.lastTimerReset + interval - Date.now(), 0);
}
},
/**
* Stops the timer, if it is running.
*/
- _cancelTimer: function () {
+ _cancelTimer: function() {
if (this._timer) {
this._timer.cancel();
this._timer = null;
}
},
/**
* See nsIUpdateTimerManager.idl
--- a/toolkit/components/timermanager/tests/unit/consumerNotifications.js
+++ b/toolkit/components/timermanager/tests/unit/consumerNotifications.js
@@ -119,17 +119,17 @@ var gNextFunc;
XPCOMUtils.defineLazyServiceGetter(this, "gPref",
"@mozilla.org/preferences-service;1",
"nsIPrefBranch");
XPCOMUtils.defineLazyServiceGetter(this, "gCatMan",
"@mozilla.org/categorymanager;1",
"nsICategoryManager");
-XPCOMUtils.defineLazyGetter(this, "gCompReg", function () {
+XPCOMUtils.defineLazyGetter(this, "gCompReg", function() {
return Cm.QueryInterface(Ci.nsIComponentRegistrar);
});
const gTest0TimerCallback = {
notify: function T0CB_notify(aTimer) {
// This can happen when another notification fails and this timer having
// time to fire so check other timers are successful.
do_throw("gTest0TimerCallback notify method should not have been called");
@@ -266,17 +266,17 @@ const gTest7Factory = {
throw Cr.NS_ERROR_NO_AGGREGATION;
}
};
const gTest8TimerCallback = {
notify: function T8CB_notify(aTimer) {
TESTS[8].notified = true;
TESTS[8].notifyTime = Date.now();
- do_execute_soon(function () {
+ do_execute_soon(function() {
check_test8thru9(gTest8TimerCallback);
});
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
};
const gTest8Factory = {
createInstance: function T8F_createInstance(aOuter, aIID) {
@@ -286,17 +286,17 @@ const gTest8Factory = {
throw Cr.NS_ERROR_NO_AGGREGATION;
}
};
const gTest9TimerCallback = {
notify: function T9CB_notify(aTimer) {
TESTS[9].notified = true;
TESTS[9].notifyTime = Date.now();
- do_execute_soon(function () {
+ do_execute_soon(function() {
check_test8thru9(gTest9TimerCallback);
});
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
};
const gTest9Factory = {
createInstance: function T9F_createInstance(aOuter, aIID) {
--- a/toolkit/components/tooltiptext/TooltipTextProvider.js
+++ b/toolkit/components/tooltiptext/TooltipTextProvider.js
@@ -123,17 +123,17 @@ TooltipTextProvider.prototype = {
direction = defView.getComputedStyle(tipElement, "")
.getPropertyValue("direction");
}
tipElement = tipElement.parentNode;
}
- return [titleText, XLinkTitleText, SVGTitleText, XULtooltiptextText].some(function (t) {
+ return [titleText, XLinkTitleText, SVGTitleText, XULtooltiptextText].some(function(t) {
if (t && /\S/.test(t)) {
// Make CRLF and CR render one line break each.
textOut.value = t.replace(/\r\n?/g, '\n');
directionOut.value = direction;
return true;
}
return false;
--- a/toolkit/components/viewsource/content/viewSource.js
+++ b/toolkit/components/viewsource/content/viewSource.js
@@ -15,18 +15,18 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/CharsetMenu.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Deprecated",
"resource://gre/modules/Deprecated.jsm");
[
["gBrowser", "content"],
["gViewSourceBundle", "viewSourceBundle"],
["gContextMenu", "viewSourceContextMenu"]
-].forEach(function ([name, id]) {
- window.__defineGetter__(name, function () {
+].forEach(function([name, id]) {
+ window.__defineGetter__(name, function() {
var element = document.getElementById(id);
if (!element)
return null;
delete window[name];
return window[name] = element;
});
});
@@ -763,17 +763,17 @@ var PrintPreviewListener = {
},
};
// viewZoomOverlay.js uses this
function getBrowser() {
return gBrowser;
}
-this.__defineGetter__("gPageLoader", function () {
+this.__defineGetter__("gPageLoader", function() {
var webnav = viewSourceChrome.webNav;
if (!webnav)
return null;
delete this.gPageLoader;
this.gPageLoader = (webnav instanceof Ci.nsIWebPageDescriptor) ? webnav
: null;
return this.gPageLoader;
});
@@ -785,17 +785,17 @@ function ViewSourceSavePage()
null, null, null, null, null, "SaveLinkTitle",
null, null, gBrowser.contentDocumentAsCPOW, null,
gPageLoader);
}
// Below are old deprecated functions and variables left behind for
// compatibility reasons. These will be removed soon via bug 1159293.
-this.__defineGetter__("gLastLineFound", function () {
+this.__defineGetter__("gLastLineFound", function() {
Deprecated.warning("gLastLineFound is deprecated - please use " +
"viewSourceChrome.lastLineFound instead.",
"https://developer.mozilla.org/en-US/Add-ons/Code_snippets/View_Source_for_XUL_Applications");
return viewSourceChrome.lastLineFound;
});
function onLoadViewSource() {
Deprecated.warning("onLoadViewSource() is deprecated - please use " +
--- a/toolkit/components/xulstore/XULStore.js
+++ b/toolkit/components/xulstore/XULStore.js
@@ -55,17 +55,17 @@ XULStore.prototype = {
* }
*/
_data: {},
_storeFile: null,
_needsSaving: false,
_saveAllowed: true,
_writeTimer: Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer),
- load: function () {
+ load: function() {
Services.obs.addObserver(this, "profile-before-change", true);
this._storeFile = Services.dirsvc.get("ProfD", Ci.nsIFile);
this._storeFile.append(STOREDB_FILENAME);
if (!this._storeFile.exists()) {
this.import();
} else {
@@ -78,17 +78,17 @@ XULStore.prototype = {
if (topic == "profile-before-change") {
this._saveAllowed = false;
}
},
/*
* Internal function for logging debug messages to the Error Console window
*/
- log: function (message) {
+ log: function(message) {
if (!debugMode)
return;
dump("XULStore: " + message + "\n");
Services.console.logStringMessage("XULStore: " + message);
},
import: function() {
let localStoreFile = Services.dirsvc.get("ProfD", Ci.nsIFile);
@@ -187,17 +187,17 @@ XULStore.prototype = {
// Don't write the file more than once every 30 seconds.
this._needsSaving = true;
this._writeTimer.init(this, WRITE_DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT);
},
/* ---------- interface implementation ---------- */
- setValue: function (docURI, id, attr, value) {
+ setValue: function(docURI, id, attr, value) {
this.log("Saving " + attr + "=" + value + " for id=" + id + ", doc=" + docURI);
if (!this._saveAllowed) {
Services.console.logStringMessage("XULStore: Changes after profile-before-change are ignored!");
return;
}
// bug 319846 -- don't save really long attributes or values.
@@ -224,45 +224,45 @@ XULStore.prototype = {
if (attr in obj && obj[attr] == value)
return;
obj[attr] = value; // IE, this._data[docURI][id][attr] = value;
this.markAsChanged();
},
- hasValue: function (docURI, id, attr) {
+ hasValue: function(docURI, id, attr) {
this.log("has store value for id=" + id + ", attr=" + attr + ", doc=" + docURI);
let ids = this._data[docURI];
if (ids) {
let attrs = ids[id];
if (attrs) {
return attr in attrs;
}
}
return false;
},
- getValue: function (docURI, id, attr) {
+ getValue: function(docURI, id, attr) {
this.log("get store value for id=" + id + ", attr=" + attr + ", doc=" + docURI);
let ids = this._data[docURI];
if (ids) {
let attrs = ids[id];
if (attrs) {
return attrs[attr] || "";
}
}
return "";
},
- removeValue: function (docURI, id, attr) {
+ removeValue: function(docURI, id, attr) {
this.log("remove store value for id=" + id + ", attr=" + attr + ", doc=" + docURI);
if (!this._saveAllowed) {
Services.console.logStringMessage("XULStore: Changes after profile-before-change are ignored!");
return;
}
let ids = this._data[docURI];
@@ -279,34 +279,34 @@ XULStore.prototype = {
}
}
this.markAsChanged();
}
}
},
- getIDsEnumerator: function (docURI) {
+ getIDsEnumerator: function(docURI) {
this.log("Getting ID enumerator for doc=" + docURI);
if (!(docURI in this._data))
return new nsStringEnumerator([]);
let result = [];
let ids = this._data[docURI];
if (ids) {
for (let id in this._data[docURI]) {
result.push(id);
}
}
return new nsStringEnumerator(result);
},
- getAttributeEnumerator: function (docURI, id) {
+ getAttributeEnumerator: function(docURI, id) {
this.log("Getting attribute enumerator for id=" + id + ", doc=" + docURI);
if (!(docURI in this._data) || !(id in this._data[docURI]))
return new nsStringEnumerator([]);
let attrs = [];
for (let attr in this._data[docURI][id]) {
attrs.push(attr);
--- a/toolkit/content/aboutAbout.js
+++ b/toolkit/content/aboutAbout.js
@@ -1,17 +1,17 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var Cc = Components.classes;
var Ci = Components.interfaces;
var gProtocols = [];
var gContainer;
-window.onload = function () {
+window.onload = function() {
gContainer = document.getElementById("abouts");
findAbouts();
}
function findAbouts() {
var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
for (var cid in Cc) {
var result = cid.match(/@mozilla.org\/network\/protocol\/about;1\?what\=(.*)$/);
--- a/toolkit/content/aboutNetworking.js
+++ b/toolkit/content/aboutNetworking.js
@@ -337,17 +337,17 @@ function startLogging() {
function stopLogging() {
clearLogModules();
// clear the log file as well
Services.prefs.clearUserPref("logging.config.LOG_FILE");
updateLogFile();
}
-function confirm () {
+function confirm() {
let div = document.getElementById("warning_message");
div.classList.remove("active");
div.hidden = true;
let warnBox = document.getElementById("warncheck");
Services.prefs.setBoolPref("network.warnOnAboutNetworking", warnBox.checked);
}
function show(button) {
--- a/toolkit/content/aboutSupport.js
+++ b/toolkit/content/aboutSupport.js
@@ -15,17 +15,17 @@ Cu.import("resource://gre/modules/AppCon
XPCOMUtils.defineLazyModuleGetter(this, "PluralForm",
"resource://gre/modules/PluralForm.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesDBUtils",
"resource://gre/modules/PlacesDBUtils.jsm");
window.addEventListener("load", function onload(event) {
try {
window.removeEventListener("load", onload, false);
- Troubleshoot.snapshot(function (snapshot) {
+ Troubleshoot.snapshot(function(snapshot) {
for (let prop in snapshotFormatters)
snapshotFormatters[prop](snapshot[prop]);
});
populateActionBox();
setupEventListeners();
} catch (e) {
Cu.reportError("stack of load error for about:support: " + e + ": " + e.stack);
}
@@ -101,17 +101,17 @@ var snapshotFormatters = {
if (data.pending > 0) {
$("crashes-allReportsWithPending").textContent =
PluralForm.get(data.pending, strings.GetStringFromName("pendingReports"))
.replace("#1", data.pending);
}
let dateNow = new Date();
- $.append($("crashes-tbody"), data.submitted.map(function (crash) {
+ $.append($("crashes-tbody"), data.submitted.map(function(crash) {
let date = new Date(crash.date);
let timePassed = dateNow - date;
let formattedDate;
if (timePassed >= 24 * 60 * 60 * 1000)
{
let daysPassed = Math.round(timePassed / (24 * 60 * 60 * 1000));
let daysPassedString = strings.GetStringFromName("crashesTimeDays");
formattedDate = PluralForm.get(daysPassed, daysPassedString)
@@ -136,59 +136,59 @@ var snapshotFormatters = {
$.new("a", crash.id, null, {href : reportURL + crash.id})
]),
$.new("td", formattedDate)
]);
}));
},
extensions: function extensions(data) {
- $.append($("extensions-tbody"), data.map(function (extension) {
+ $.append($("extensions-tbody"), data.map(function(extension) {
return $.new("tr", [
$.new("td", extension.name),
$.new("td", extension.version),
$.new("td", extension.isActive),
$.new("td", extension.id),
]);
}));
},
experiments: function experiments(data) {
- $.append($("experiments-tbody"), data.map(function (experiment) {
+ $.append($("experiments-tbody"), data.map(function(experiment) {
return $.new("tr", [
$.new("td", experiment.name),
$.new("td", experiment.id),
$.new("td", experiment.description),
$.new("td", experiment.active),
$.new("td", experiment.endDate),
$.new("td", [
$.new("a", experiment.detailURL, null, {href : experiment.detailURL, })
]),
$.new("td", experiment.branch),
]);
}));
},
modifiedPreferences: function modifiedPreferences(data) {
$.append($("prefs-tbody"), sortedArrayFromObject(data).map(
- function ([name, value]) {
+ function([name, value]) {
return $.new("tr", [
$.new("td", name, "pref-name"),
// Very long preference values can cause users problems when they
// copy and paste them into some text editors. Long values generally
// aren't useful anyway, so truncate them to a reasonable length.
$.new("td", String(value).substr(0, 120), "pref-value"),
]);
}
));
},
lockedPreferences: function lockedPreferences(data) {
$.append($("locked-prefs-tbody"), sortedArrayFromObject(data).map(
- function ([name, value]) {
+ function([name, value]) {
return $.new("tr", [
$.new("td", name, "pref-name"),
$.new("td", String(value).substr(0, 120), "pref-value"),
]);
}
));
},
@@ -218,17 +218,17 @@ var snapshotFormatters = {
catch (err) {
// Throws if nameOrMsg is not a name in the bundle.
}
return nameOrMsg;
}
// Read APZ info out of data.info, stripping it out in the process.
let apzInfo = [];
- let formatApzInfo = function (info) {
+ let formatApzInfo = function(info) {
let out = [];
for (let type of ['Wheel', 'Touch', 'Drag']) {
let key = 'Apz' + type + 'Input';
if (!(key in info))
continue;
delete info[key];
@@ -274,17 +274,17 @@ var snapshotFormatters = {
addRows(where, [buildRow(key, value)]);
}
if (data.clearTypeParameters !== undefined) {
addRow("diagnostics", "clearTypeParameters", data.clearTypeParameters);
}
if ("info" in data) {
apzInfo = formatApzInfo(data.info);
- let trs = sortedArrayFromObject(data.info).map(function ([prop, val]) {
+ let trs = sortedArrayFromObject(data.info).map(function([prop, val]) {
return $.new("tr", [
$.new("th", prop, "column"),
$.new("td", String(val)),
]);
});
addRows("diagnostics", trs);
delete data.info;
@@ -327,17 +327,17 @@ var snapshotFormatters = {
combined.map(function(val) {
return $.new("tr", [$.new("th", val.header, "column"),
$.new("td", val.message)]);
}));
delete data.indices;
} else {
$.append($("graphics-failures-tbody"),
[$.new("tr", [$.new("th", "LogFailure", "column"),
- $.new("td", data.failures.map(function (val) {
+ $.new("td", data.failures.map(function(val) {
return $.new("p", val);
}))])]);
}
} else {
$("graphics-failures-tbody").style.display = "none";
}
// Add a new row to the table, and take the key (or keys) out of data.
@@ -502,19 +502,19 @@ var snapshotFormatters = {
}
let crashGuards = data.crashGuards;
delete data.crashGuards;
if (crashGuards.length) {
for (let guard of crashGuards) {
let resetButton = $.new("button");
- let onClickReset = (function (guard) {
+ let onClickReset = (function(guard) {
// Note - need this wrapper until bug 449811 fixes |guard| scoping.
- return function () {
+ return function() {
Services.prefs.setIntPref(guard.prefName, 0);
resetButton.removeEventListener("click", onClickReset);
resetButton.disabled = true;
};
})(guard);
resetButton.textContent = strings.GetStringFromName("resetOnNextRestart");
resetButton.addEventListener("click", onClickReset);
@@ -550,17 +550,17 @@ var snapshotFormatters = {
let trs = [
$.new("tr", [
$.new("th", ""),
$.new("th", strings.GetStringFromName("minLibVersions")),
$.new("th", strings.GetStringFromName("loadedLibVersions")),
])
];
sortedArrayFromObject(data).forEach(
- function ([name, val]) {
+ function([name, val]) {
trs.push($.new("tr", [
$.new("td", name),
$.new("td", val.minVersion),
$.new("td", val.version),
]));
}
);
$.append($("libversions-tbody"), trs);
@@ -656,17 +656,17 @@ function sortedArrayFromObject(obj) {
tuples.sort(([prop1, v1], [prop2, v2]) => prop1.localeCompare(prop2));
return tuples;
}
function copyRawDataToClipboard(button) {
if (button)
button.disabled = true;
try {
- Troubleshoot.snapshot(function (snapshot) {
+ Troubleshoot.snapshot(function(snapshot) {
if (button)
button.disabled = false;
let str = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
str.data = JSON.stringify(snapshot, undefined, 2);
let transferable = Cc["@mozilla.org/widget/transferable;1"].
createInstance(Ci.nsITransferable);
transferable.init(getLoadContext());
@@ -754,17 +754,17 @@ function createTextForElement(elem) {
return text;
}
function Serializer() {
}
Serializer.prototype = {
- serialize: function (rootElem) {
+ serialize: function(rootElem) {
this._lines = [];
this._startNewLine();
this._serializeElement(rootElem);
this._startNewLine();
return this._lines.join("\n").trim() + "\n";
},
// The current line is always the line that writing will start at next. When
@@ -773,17 +773,17 @@ Serializer.prototype = {
get _currentLine() {
return this._lines.length ? this._lines[this._lines.length - 1] : null;
},
set _currentLine(val) {
return this._lines[this._lines.length - 1] = val;
},
- _serializeElement: function (elem) {
+ _serializeElement: function(elem) {
if (this._ignoreElement(elem))
return;
// table
if (elem.localName == "table") {
this._serializeTable(elem);
return;
}
@@ -815,37 +815,37 @@ Serializer.prototype = {
let display = window.getComputedStyle(elem).getPropertyValue("display");
if (display == "block") {
this._startNewLine();
this._startNewLine();
}
}
},
- _startNewLine: function (lines) {
+ _startNewLine: function(lines) {
let currLine = this._currentLine;
if (currLine) {
// The current line is not empty. Trim it.
this._currentLine = currLine.trim();
if (!this._currentLine)
// The current line became empty. Discard it.
this._lines.pop();
}
this._lines.push("");
},
- _appendText: function (text, lines) {
+ _appendText: function(text, lines) {
this._currentLine += text;
},
- _isHiddenSubHeading: function (th) {
+ _isHiddenSubHeading: function(th) {
return th.parentNode.parentNode.style.display == "none";
},
- _serializeTable: function (table) {
+ _serializeTable: function(table) {
// Collect the table's column headings if in fact there are any. First
// check thead. If there's no thead, check the first tr.
let colHeadings = {};
let tableHeadingElem = table.querySelector("thead");
if (!tableHeadingElem)
tableHeadingElem = table.querySelector("tr");
if (tableHeadingElem) {
let tableHeadingCols = tableHeadingElem.querySelectorAll("th,td");
@@ -915,21 +915,21 @@ Serializer.prototype = {
this._appendText(rowHeading + ": " + this._nodeText(children[1]).trim());
}
}
this._startNewLine();
}
this._startNewLine();
},
- _ignoreElement: function (elem) {
+ _ignoreElement: function(elem) {
return elem.classList.contains("no-copy");
},
- _nodeText: function (node) {
+ _nodeText: function(node) {
return node.textContent.replace(/\s+/g, " ");
},
};
function openProfileDirectory() {
// Get the profile directory.
let currProfD = Services.dirsvc.get("ProfD", Ci.nsIFile);
let profileDir = currProfD.path;
@@ -963,41 +963,41 @@ function safeModeRestart() {
if (!cancelQuit.data) {
Services.startup.restartInSafeMode(Ci.nsIAppStartup.eAttemptQuit);
}
}
/**
* Set up event listeners for buttons.
*/
function setupEventListeners() {
- $("show-update-history-button").addEventListener("click", function (event) {
+ $("show-update-history-button").addEventListener("click", function(event) {
var prompter = Cc["@mozilla.org/updates/update-prompt;1"].createInstance(Ci.nsIUpdatePrompt);
prompter.showUpdateHistory(window);
});
- $("reset-box-button").addEventListener("click", function (event) {
+ $("reset-box-button").addEventListener("click", function(event) {
ResetProfile.openConfirmationDialog(window);
});
- $("copy-raw-data-to-clipboard").addEventListener("click", function (event) {
+ $("copy-raw-data-to-clipboard").addEventListener("click", function(event) {
copyRawDataToClipboard(this);
});
- $("copy-to-clipboard").addEventListener("click", function (event) {
+ $("copy-to-clipboard").addEventListener("click", function(event) {
copyContentsToClipboard();
});
- $("profile-dir-button").addEventListener("click", function (event) {
+ $("profile-dir-button").addEventListener("click", function(event) {
openProfileDirectory();
});
- $("restart-in-safe-mode-button").addEventListener("click", function (event) {
+ $("restart-in-safe-mode-button").addEventListener("click", function(event) {
if (Services.obs.enumerateObservers("restart-in-safe-mode").hasMoreElements()) {
Services.obs.notifyObservers(null, "restart-in-safe-mode", "");
}
else {
safeModeRestart();
}
});
- $("verify-place-integrity-button").addEventListener("click", function (event) {
+ $("verify-place-integrity-button").addEventListener("click", function(event) {
PlacesDBUtils.checkAndFixDatabase(function(aLog) {
let msg = aLog.join("\n");
$("verify-place-result").style.display = "block";
$("verify-place-result").classList.remove("no-copy");
$("verify-place-result").textContent = msg;
});
});
}
--- a/toolkit/content/aboutTelemetry.js
+++ b/toolkit/content/aboutTelemetry.js
@@ -1669,55 +1669,55 @@ function setupListeners() {
// Clean up observers when page is closed
window.addEventListener("unload",
function unloadHandler(aEvent) {
window.removeEventListener("unload", unloadHandler);
Settings.detachObservers();
}, false);
document.getElementById("chrome-hangs-fetch-symbols").addEventListener("click",
- function () {
+ function() {
if (!gPingData) {
return;
}
let hangs = gPingData.payload.chromeHangs;
let req = new SymbolicationRequest("chrome-hangs",
ChromeHangs.renderHangHeader,
hangs.memoryMap,
hangs.stacks,
hangs.durations);
req.fetchSymbols();
}, false);
document.getElementById("chrome-hangs-hide-symbols").addEventListener("click",
- function () {
+ function() {
if (!gPingData) {
return;
}
ChromeHangs.render(gPingData);
}, false);
document.getElementById("late-writes-fetch-symbols").addEventListener("click",
- function () {
+ function() {
if (!gPingData) {
return;
}
let lateWrites = gPingData.payload.lateWrites;
let req = new SymbolicationRequest("late-writes",
LateWritesSingleton.renderHeader,
lateWrites.memoryMap,
lateWrites.stacks);
req.fetchSymbols();
}, false);
document.getElementById("late-writes-hide-symbols").addEventListener("click",
- function () {
+ function() {
if (!gPingData) {
return;
}
LateWritesSingleton.renderLateWrites(gPingData.payload.lateWrites);
}, false);
// Clicking on the section name will toggle its state
--- a/toolkit/content/aboutwebrtc/aboutWebrtc.js
+++ b/toolkit/content/aboutwebrtc/aboutWebrtc.js
@@ -105,17 +105,17 @@ var ControlSet = {
function Control() {
this._label = null;
this._message = null;
this._messageHeader = null;
}
Control.prototype = {
- render: function () {
+ render: function() {
let controlElem = document.createElement("button");
let messageElem = document.createElement("p");
this.ctrl = controlElem;
controlElem.onclick = this.onClick.bind(this);
this.msg = messageElem;
this.update();
@@ -254,37 +254,37 @@ function AecLogging() {
this._label = getString("aec_logging_off_state_label");
this._message = null;
}
}
AecLogging.prototype = Object.create(Control.prototype);
AecLogging.prototype.constructor = AecLogging;
-AecLogging.prototype.offState = function () {
+AecLogging.prototype.offState = function() {
this._label = getString("aec_logging_off_state_label");
try {
let file = Services.prefs.getCharPref("media.webrtc.debug.aec_log_dir");
this._message = formatString("aec_logging_off_state_msg", [file], 1);
} catch (e) {
this._message = null;
}
};
-AecLogging.prototype.onState = function () {
+AecLogging.prototype.onState = function() {
this._label = getString("aec_logging_on_state_label");
try {
let file = Services.prefs.getCharPref("media.webrtc.debug.aec_log_dir");
this._message = getString("aec_logging_on_state_msg");
} catch (e) {
this._message = null;
}
};
-AecLogging.prototype.onClick = function () {
+AecLogging.prototype.onClick = function() {
if (WebrtcGlobalInformation.aecDebug) {
WebrtcGlobalInformation.aecDebug = false;
this.offState();
} else {
WebrtcGlobalInformation.aecDebug = true;
this.onState();
}
this.update();
@@ -432,17 +432,17 @@ PeerConnection.prototype = {
div.appendChild(new ICEStats(this._report).render());
div.appendChild(new SDPStats(this._report).render());
div.appendChild(new RTPStats(this._report).render());
pc.appendChild(div);
return pc;
},
- renderHeading: function () {
+ renderHeading: function() {
let pcInfo = this.getPCInfo(this._report);
let heading = document.createElement("h3");
let now = new Date(this._report.timestamp).toTimeString();
heading.textContent =
`[ ${pcInfo.id} ] ${pcInfo.url} ${pcInfo.closed ? `(${getString("connection_closed")})` : ""} ${now}`;
return heading;
},
--- a/toolkit/content/browser-child.js
+++ b/toolkit/content/browser-child.js
@@ -45,17 +45,17 @@ var WebProgressListener = {
let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebProgress);
webProgress.removeProgressListener(this._filter);
this._filter.removeProgressListener(this);
this._filter = null;
},
- _requestSpec: function (aRequest, aPropertyName) {
+ _requestSpec: function(aRequest, aPropertyName) {
if (!aRequest || !(aRequest instanceof Ci.nsIChannel))
return null;
return aRequest.QueryInterface(Ci.nsIChannel)[aPropertyName].spec;
},
_setupJSON: function setupJSON(aWebProgress, aRequest) {
let innerWindowID = null;
if (aWebProgress) {
@@ -364,17 +364,17 @@ var SecurityUI = {
return helper.serializeToString(status);
}
return null;
}
};
var ControllerCommands = {
- init: function () {
+ init: function() {
addMessageListener("ControllerCommands:Do", this);
addMessageListener("ControllerCommands:DoWithParams", this);
},
receiveMessage: function(message) {
switch (message.name) {
case "ControllerCommands:Do":
if (docShell.isCommandEnabled(message.data))
@@ -398,35 +398,35 @@ var ControllerCommands = {
}
break;
}
}
}
ControllerCommands.init()
-addEventListener("DOMTitleChanged", function (aEvent) {
+addEventListener("DOMTitleChanged", function(aEvent) {
let document = content.document;
switch (aEvent.type) {
case "DOMTitleChanged":
if (!aEvent.isTrusted || aEvent.target.defaultView != content)
return;
sendAsyncMessage("DOMTitleChanged", { title: document.title });
break;
}
}, false);
-addEventListener("DOMWindowClose", function (aEvent) {
+addEventListener("DOMWindowClose", function(aEvent) {
if (!aEvent.isTrusted)
return;
sendAsyncMessage("DOMWindowClose");
}, false);
-addEventListener("ImageContentLoaded", function (aEvent) {
+addEventListener("ImageContentLoaded", function(aEvent) {
if (content.document instanceof Ci.nsIImageDocument) {
let req = content.document.imageRequest;
if (!req.image)
return;
sendAsyncMessage("ImageDocumentLoaded", { width: req.image.width,
height: req.image.height });
}
}, false);
@@ -481,84 +481,84 @@ const ZoomManager = {
},
_cache: {
fullZoom: NaN,
textZoom: NaN
}
};
-addMessageListener("FullZoom", function (aMessage) {
+addMessageListener("FullZoom", function(aMessage) {
ZoomManager.fullZoom = aMessage.data.value;
});
-addMessageListener("TextZoom", function (aMessage) {
+addMessageListener("TextZoom", function(aMessage) {
ZoomManager.textZoom = aMessage.data.value;
});
-addEventListener("FullZoomChange", function () {
+addEventListener("FullZoomChange", function() {
if (ZoomManager.refreshFullZoom()) {
sendAsyncMessage("FullZoomChange", { value: ZoomManager.fullZoom });
}
}, false);
-addEventListener("TextZoomChange", function (aEvent) {
+addEventListener("TextZoomChange", function(aEvent) {
if (ZoomManager.refreshTextZoom()) {
sendAsyncMessage("TextZoomChange", { value: ZoomManager.textZoom });
}
}, false);
-addEventListener("ZoomChangeUsingMouseWheel", function () {
+addEventListener("ZoomChangeUsingMouseWheel", function() {
sendAsyncMessage("ZoomChangeUsingMouseWheel", {});
}, false);
-addMessageListener("UpdateCharacterSet", function (aMessage) {
+addMessageListener("UpdateCharacterSet", function(aMessage) {
docShell.charset = aMessage.data.value;
docShell.gatherCharsetMenuTelemetry();
});
/**
* Remote thumbnail request handler for PageThumbs thumbnails.
*/
-addMessageListener("Browser:Thumbnail:Request", function (aMessage) {
+addMessageListener("Browser:Thumbnail:Request", function(aMessage) {
let snapshot;
let args = aMessage.data.additionalArgs;
let fullScale = args ? args.fullScale : false;
if (fullScale) {
snapshot = PageThumbUtils.createSnapshotThumbnail(content, null, args);
} else {
let snapshotWidth = aMessage.data.canvasWidth;
let snapshotHeight = aMessage.data.canvasHeight;
snapshot =
PageThumbUtils.createCanvas(content, snapshotWidth, snapshotHeight);
PageThumbUtils.createSnapshotThumbnail(content, snapshot, args);
}
- snapshot.toBlob(function (aBlob) {
+ snapshot.toBlob(function(aBlob) {
sendAsyncMessage("Browser:Thumbnail:Response", {
thumbnail: aBlob,
id: aMessage.data.id
});
});
});
/**
* Remote isSafeForCapture request handler for PageThumbs.
*/
-addMessageListener("Browser:Thumbnail:CheckState", function (aMessage) {
+addMessageListener("Browser:Thumbnail:CheckState", function(aMessage) {
let result = PageThumbUtils.shouldStoreContentThumbnail(content, docShell);
sendAsyncMessage("Browser:Thumbnail:CheckState:Response", {
result: result
});
});
/**
* Remote GetOriginalURL request handler for PageThumbs.
*/
-addMessageListener("Browser:Thumbnail:GetOriginalURL", function (aMessage) {
+addMessageListener("Browser:Thumbnail:GetOriginalURL", function(aMessage) {
let channel = docShell.currentDocumentChannel;
let channelError = PageThumbUtils.isChannelErrorResponse(channel);
let originalURL;
try {
originalURL = channel.originalURI.spec;
} catch (ex) {}
sendAsyncMessage("Browser:Thumbnail:GetOriginalURL:Response", {
channelError: channelError,
--- a/toolkit/content/browser-content.js
+++ b/toolkit/content/browser-content.js
@@ -15,17 +15,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/ReaderMode.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm");
var global = this;
// Lazily load the finder code
-addMessageListener("Finder:Initialize", function () {
+addMessageListener("Finder:Initialize", function() {
let {RemoteFinderListener} = Cu.import("resource://gre/modules/RemoteFinder.jsm", {});
new RemoteFinderListener(global);
});
var ClickEventHandler = {
init: function init() {
this._scrollable = null;
this._scrolldir = "";
@@ -496,22 +496,22 @@ var Printing = {
return null;
},
parseDocument(URL, contentWindow) {
// By using ReaderMode primitives, we parse given document and place the
// resulting JS object into the DOM of current browser.
let articlePromise = ReaderMode.parseDocument(contentWindow.document).catch(Cu.reportError);
- articlePromise.then(function (article) {
+ articlePromise.then(function(article) {
// We make use of a web progress listener in order to know when the content we inject
// into the DOM has finished rendering. If our layout engine is still painting, we
// will wait for MozAfterPaint event to be fired.
let webProgressListener = {
- onStateChange: function (webProgress, req, flags, status) {
+ onStateChange: function(webProgress, req, flags, status) {
if (flags & Ci.nsIWebProgressListener.STATE_STOP) {
webProgress.removeProgressListener(webProgressListener);
let domUtils = content.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
// Here we tell the parent that we have parsed the document successfully
// using ReaderMode primitives and we are able to enter on preview mode.
if (domUtils.isMozAfterPaintPending) {
addEventListener("MozAfterPaint", function onPaint() {
@@ -914,17 +914,17 @@ let WebChannelMessageToChromeListener =
}
}
};
WebChannelMessageToChromeListener.init();
// This should be kept in sync with /browser/base/content.js.
// Add message listener for "WebChannelMessageToContent" messages from chrome scripts.
-addMessageListener("WebChannelMessageToContent", function (e) {
+addMessageListener("WebChannelMessageToContent", function(e) {
if (e.data) {
// e.objects.eventTarget will be defined if sending a response to
// a WebChannelMessageToChrome event. An unsolicited send
// may not have an eventTarget defined, in this case send to the
// main content window.
let eventTarget = e.objects.eventTarget || content;
// Use nodePrincipal if available, otherwise fallback to document principal.
@@ -1049,17 +1049,17 @@ addMessageListener("Browser:PurgeSession
}
if (purge > 0) {
sessionHistory.PurgeHistory(purge);
}
});
var ViewSelectionSource = {
- init: function () {
+ init: function() {
addMessageListener("ViewSource:GetSelection", this);
},
receiveMessage: function(message) {
if (message.name == "ViewSource:GetSelection") {
let selectionDetails;
try {
selectionDetails = message.objects.target ? this.getMathMLSelection(message.objects.target)
@@ -1091,17 +1091,17 @@ var ViewSelectionSource = {
}
}
n = p;
p = n.parentNode;
} while (n != ancestor && p);
return path;
},
- getSelection: function () {
+ getSelection: function() {
// These are markers used to delimit the selection during processing. They
// are removed from the final rendering.
// We use noncharacter Unicode codepoints to minimize the risk of clashing
// with anything that might legitimately be present in the document.
// U+FDD0..FDEF <noncharacters>
const MARK_SELECTION_START = "\uFDD0";
const MARK_SELECTION_END = "\uFDEF";
@@ -1514,59 +1514,59 @@ let AutoCompletePopup = {
if (this._input) {
this._input.focus();
}
break;
}
}
},
- get input () { return this._input; },
- get overrideValue () { return null; },
- set selectedIndex (index) {
+ get input() { return this._input; },
+ get overrideValue() { return null; },
+ set selectedIndex(index) {
sendAsyncMessage("FormAutoComplete:SetSelectedIndex", { index });
},
- get selectedIndex () {
+ get selectedIndex() {
// selectedIndex getter must be synchronous because we need the
// correct value when the controller is in controller::HandleEnter.
// We can't easily just let the parent inform us the new value every
// time it changes because not every action that can change the
// selectedIndex is trivial to catch (e.g. moving the mouse over the
// list).
return sendSyncMessage("FormAutoComplete:GetSelectedIndex", {});
},
- get popupOpen () {
+ get popupOpen() {
return this._popupOpen;
},
- openAutocompletePopup: function (input, element) {
+ openAutocompletePopup: function(input, element) {
if (this._popupOpen || !input) {
return;
}
let rect = BrowserUtils.getElementBoundingScreenRect(element);
let window = element.ownerDocument.defaultView;
let dir = window.getComputedStyle(element).direction;
let results = this.getResultsFromController(input);
sendAsyncMessage("FormAutoComplete:MaybeOpenPopup",
{ results, rect, dir });
this._input = input;
},
- closePopup: function () {
+ closePopup: function() {
// We set this here instead of just waiting for the
// PopupClosed message to do it so that we don't end
// up in a state where the content thinks that a popup
// is open when it isn't (or soon won't be).
this._popupOpen = false;
sendAsyncMessage("FormAutoComplete:ClosePopup", {});
},
- invalidate: function () {
+ invalidate: function() {
if (this._popupOpen) {
let results = this.getResultsFromController(this._input);
sendAsyncMessage("FormAutoComplete:Invalidate", { results });
}
},
selectBy: function(reverse, page) {
this._index = sendSyncMessage("FormAutoComplete:SelectBy", {
--- a/toolkit/content/contentAreaUtils.js
+++ b/toolkit/content/contentAreaUtils.js
@@ -193,20 +193,20 @@ function saveBrowser(aBrowser, aSkipProm
if (!aBrowser) {
throw "Must have a browser when calling saveBrowser";
}
let persistable = aBrowser.QueryInterface(Ci.nsIFrameLoaderOwner)
.frameLoader
.QueryInterface(Ci.nsIWebBrowserPersistable);
let stack = Components.stack.caller;
persistable.startPersistence(aOuterWindowID, {
- onDocumentReady: function (document) {
+ onDocumentReady: function(document) {
saveDocument(document, aSkipPrompt);
},
- onError: function (status) {
+ onError: function(status) {
throw new Components.Exception("saveBrowser failed asynchronously in startPersistence",
status, stack);
}
});
}
// Saves a document; aDocument can be an nsIWebBrowserPersistDocument
// (see saveBrowser, above) or an nsIDOMDocument.
--- a/toolkit/content/customizeToolbar.js
+++ b/toolkit/content/customizeToolbar.js
@@ -27,17 +27,17 @@ function onLoad()
}
function InitWithToolbox(aToolbox)
{
gToolbox = aToolbox;
dispatchCustomizationEvent("beforecustomization");
gToolboxDocument = gToolbox.ownerDocument;
gToolbox.customizing = true;
- forEachCustomizableToolbar(function (toolbar) {
+ forEachCustomizableToolbar(function(toolbar) {
toolbar.setAttribute("customizing", "true");
});
gPaletteBox = document.getElementById("palette-box");
var elts = getRootElements();
for (let i = 0; i < elts.length; i++) {
elts[i].addEventListener("dragstart", onToolbarDragStart, true);
elts[i].addEventListener("dragover", onToolbarDragOver, true);
@@ -63,17 +63,17 @@ function onUnload()
}
function finishToolbarCustomization()
{
removeToolboxListeners();
unwrapToolbarItems();
persistCurrentSets();
gToolbox.customizing = false;
- forEachCustomizableToolbar(function (toolbar) {
+ forEachCustomizableToolbar(function(toolbar) {
toolbar.removeAttribute("customizing");
});
notifyParentComplete();
}
function initDialog()
{
@@ -157,17 +157,17 @@ function dispatchCustomizationEvent(aEve
* localstore.
*/
function persistCurrentSets()
{
if (!gToolboxChanged || gToolboxDocument.defaultView.closed)
return;
var customCount = 0;
- forEachCustomizableToolbar(function (toolbar) {
+ forEachCustomizableToolbar(function(toolbar) {
// Calculate currentset and store it in the attribute.
var currentSet = toolbar.currentSet;
toolbar.setAttribute("currentset", currentSet);
var customIndex = toolbar.hasAttribute("customindex");
if (customIndex) {
if (!toolbar.hasChildNodes()) {
// Remove custom toolbars whose contents have been removed.
@@ -193,18 +193,18 @@ function persistCurrentSets()
}
}
/**
* Wraps all items in all customizable toolbars in a toolbox.
*/
function wrapToolbarItems()
{
- forEachCustomizableToolbar(function (toolbar) {
- Array.forEach(toolbar.childNodes, function (item) {
+ forEachCustomizableToolbar(function(toolbar) {
+ Array.forEach(toolbar.childNodes, function(item) {
if (AppConstants.platform == "macosx") {
if (item.firstChild && item.firstChild.localName == "menubar")
return;
}
if (isToolbarItem(item)) {
let wrapper = wrapToolbarItem(item);
cleanupItemForToolbar(item, wrapper);
}
@@ -284,17 +284,17 @@ function wrapToolbarItem(aToolbarItem)
}
/**
* Get the list of ids for the current set of items on each toolbar.
*/
function getCurrentItemIds()
{
var currentItems = {};
- forEachCustomizableToolbar(function (toolbar) {
+ forEachCustomizableToolbar(function(toolbar) {
var child = toolbar.firstChild;
while (child) {
if (isToolbarItem(child))
currentItems[child.id] = 1;
child = child.nextSibling;
}
});
return currentItems;
@@ -531,17 +531,17 @@ function restoreDefaultSet()
thisChild.currentSet = "__empty";
gToolbox.removeChild(thisChild);
} else {
child = child.previousSibling;
}
}
// Restore the defaultset for fixed toolbars.
- forEachCustomizableToolbar(function (toolbar) {
+ forEachCustomizableToolbar(function(toolbar) {
var defaultSet = toolbar.getAttribute("defaultset");
if (defaultSet)
toolbar.currentSet = defaultSet;
});
// Restore the default icon size and mode.
document.getElementById("smallicons").checked = (updateIconSize() == "small");
document.getElementById("modelist").value = updateToolbarMode();
@@ -570,17 +570,17 @@ function updateToolbarMode(aModeValue) {
function updateToolboxProperty(aProp, aValue, aToolkitDefault) {
var toolboxDefault = gToolbox.getAttribute("default" + aProp) ||
aToolkitDefault;
gToolbox.setAttribute(aProp, aValue || toolboxDefault);
gToolboxDocument.persist(gToolbox.id, aProp);
- forEachCustomizableToolbar(function (toolbar) {
+ forEachCustomizableToolbar(function(toolbar) {
var toolbarDefault = toolbar.getAttribute("default" + aProp) ||
toolboxDefault;
if (toolbar.getAttribute("lock" + aProp) == "true" &&
toolbar.getAttribute(aProp) == toolbarDefault)
return;
toolbar.setAttribute(aProp, aValue || toolbarDefault);
gToolboxDocument.persist(toolbar.id, aProp);
--- a/toolkit/content/tests/browser/browser_audioCompeting.js
+++ b/toolkit/content/tests/browser/browser_audioCompeting.js
@@ -9,43 +9,43 @@ function* wait_for_tab_playing_event(tab
is(tab.soundPlaying, expectPlaying, "The tab should " + (expectPlaying ? "" : "not ") + "be playing");
return true;
}
return false;
});
}
}
-function play_audio_from_invisible_tab () {
+function play_audio_from_invisible_tab() {
return new Promise(resolve => {
var autoPlay = content.document.getElementById('autoplay');
if (!autoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.paused, true, "Audio in tab 1 was paused by audio competing.");
autoPlay.play();
autoPlay.onpause = function() {
autoPlay.onpause = null;
ok(true, "Audio in tab 1 can't playback when other tab is playing in foreground.");
resolve();
};
});
}
-function audio_should_keep_playing_even_go_to_background () {
+function audio_should_keep_playing_even_go_to_background() {
var autoPlay = content.document.getElementById('autoplay');
if (!autoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.paused, false, "Audio in tab 2 is still playing in the background.");
}
-function play_non_autoplay_audio () {
+function play_non_autoplay_audio() {
return new Promise(resolve => {
var autoPlay = content.document.getElementById('autoplay');
var nonAutoPlay = content.document.getElementById('nonautoplay');
if (!autoPlay || !nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
is(nonAutoPlay.paused, true, "Non-autoplay audio isn't started playing yet.");
@@ -64,17 +64,17 @@ add_task(function* setup_test_preference
yield new Promise(resolve => {
SpecialPowers.pushPrefEnv({"set": [
["dom.audiochannel.audioCompeting", true],
["dom.ipc.processCount", 1]
]}, resolve);
});
});
-add_task(function* cross_tabs_audio_competing () {
+add_task(function* cross_tabs_audio_competing() {
info("- open tab 1 in foreground -");
let tab1 = yield BrowserTestUtils.openNewForegroundTab(window.gBrowser,
"about:blank");
tab1.linkedBrowser.loadURI(PAGE);
yield wait_for_tab_playing_event(tab1, true);
info("- open tab 2 in foreground -");
let tab2 = yield BrowserTestUtils.openNewForegroundTab(window.gBrowser,
@@ -93,17 +93,17 @@ add_task(function* cross_tabs_audio_comp
play_audio_from_invisible_tab);
info("- remove tabs -");
yield BrowserTestUtils.removeTab(tab1);
yield BrowserTestUtils.removeTab(tab2);
yield BrowserTestUtils.removeTab(tab3);
});
-add_task(function* within_one_tab_audio_competing () {
+add_task(function* within_one_tab_audio_competing() {
info("- open tab and play audio1 -");
let tab = yield BrowserTestUtils.openNewForegroundTab(window.gBrowser,
"about:blank");
tab.linkedBrowser.loadURI(PAGE);
yield wait_for_tab_playing_event(tab, true);
info("- play audio2 in the same tab -");
yield ContentTask.spawn(tab.linkedBrowser, null,
--- a/toolkit/content/tests/browser/browser_default_image_filename.js
+++ b/toolkit/content/tests/browser/browser_default_image_filename.js
@@ -23,17 +23,17 @@ add_task(function* () {
let showFilePickerPromise = new Promise(resolve => {
MockFilePicker.showCallback = function(fp) {
is(fp.defaultString, "index.gif");
resolve();
}
});
- registerCleanupFunction(function () {
+ registerCleanupFunction(function() {
MockFilePicker.cleanup();
});
// Select "Save Image As" option from context menu
var saveImageAsCommand = document.getElementById("context-saveimage");
saveImageAsCommand.doCommand();
yield showFilePickerPromise;
--- a/toolkit/content/tests/browser/browser_mediaPlayback_suspended_multipleAudio.js
+++ b/toolkit/content/tests/browser/browser_mediaPlayback_suspended_multipleAudio.js
@@ -55,37 +55,37 @@ function check_autoplay_audio_pause_stat
if (autoPlay.paused == expectedPauseState) {
if (expectedPauseState) {
ok(true, "Audio is paused correctly.");
} else {
ok(true, "Audio is resumed correctly.");
}
} else if (expectedPauseState) {
- autoPlay.onpause = function () {
+ autoPlay.onpause = function() {
autoPlay.onpause = null;
ok(true, "Audio is paused correctly, checking from onpause.");
}
} else {
- autoPlay.onplay = function () {
+ autoPlay.onplay = function() {
autoPlay.onplay = null;
ok(true, "Audio is resumed correctly, checking from onplay.");
}
}
}
function play_nonautoplay_audio_should_be_paused() {
var nonAutoPlay = content.document.getElementById('nonautoplay');
if (!nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
nonAutoPlay.play();
return new Promise(resolve => {
- nonAutoPlay.onpause = function () {
+ nonAutoPlay.onpause = function() {
nonAutoPlay.onpause = null;
is(nonAutoPlay.ended, false, "Audio can't be playback.");
resolve();
}
});
}
function all_audio_onresume() {
@@ -113,17 +113,17 @@ function all_audio_onpause() {
function play_nonautoplay_audio_should_play_until_ended() {
var nonAutoPlay = content.document.getElementById('nonautoplay');
if (!nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
nonAutoPlay.play();
return new Promise(resolve => {
- nonAutoPlay.onended = function () {
+ nonAutoPlay.onended = function() {
nonAutoPlay.onended = null;
ok(true, "Audio can be playback until ended.");
resolve();
}
});
}
function no_audio_resumed() {
--- a/toolkit/content/tests/browser/browser_save_resend_postdata.js
+++ b/toolkit/content/tests/browser/browser_save_resend_postdata.js
@@ -56,17 +56,17 @@ function test() {
MockFilePicker.returnFiles = [file];
MockFilePicker.showCallback = function(fp) {
MockFilePicker.filterIndex = 1; // kSaveAsType_URL
};
mockTransferCallback = onTransferComplete;
mockTransferRegisterer.register();
- registerCleanupFunction(function () {
+ registerCleanupFunction(function() {
mockTransferRegisterer.unregister();
MockFilePicker.cleanup();
destDir.remove(true);
});
var docToSave = innerFrame.contentDocument;
// We call internalSave instead of saveDocument to bypass the history
// cache.
--- a/toolkit/content/tests/browser/common/mockTransfer.js
+++ b/toolkit/content/tests/browser/common/mockTransfer.js
@@ -32,29 +32,29 @@ MockTransfer.prototype = {
this._downloadIsSuccessful = false;
// If the download is finished
if ((aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) &&
(aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK))
// Continue the test, reporting the success or failure condition.
mockTransferCallback(this._downloadIsSuccessful);
},
- onProgressChange: function () {},
- onLocationChange: function () {},
+ onProgressChange: function() {},
+ onLocationChange: function() {},
onStatusChange: function MTFC_onStatusChange(aWebProgress, aRequest, aStatus,
aMessage) {
// If at least one notification reported an error, the download failed.
if (!Components.isSuccessCode(aStatus))
this._downloadIsSuccessful = false;
},
- onSecurityChange: function () {},
+ onSecurityChange: function() {},
/* nsIWebProgressListener2 */
- onProgressChange64: function () {},
- onRefreshAttempted: function () {},
+ onProgressChange64: function() {},
+ onRefreshAttempted: function() {},
/* nsITransfer */
init: function() {},
setSha256Hash: function() {},
setSignatureInfo: function() {}
};
// Create an instance of a MockObjectRegisterer whose methods can be used to
--- a/toolkit/content/tests/chrome/file_autocomplete_with_composition.js
+++ b/toolkit/content/tests/chrome/file_autocomplete_with_composition.js
@@ -40,20 +40,20 @@ function nsDoTestsForAutoCompleteWithCom
nsDoTestsForAutoCompleteWithComposition.prototype = {
_window: null,
_target: null,
_controller: null,
_DefaultCompleteDefaultIndex: false,
_description: "",
_is: null,
- _getTargetValue: function () { return "not initialized"; },
+ _getTargetValue: function() { return "not initialized"; },
_onFinish: null,
- _doTests: function ()
+ _doTests: function()
{
if (++this._testingIndex == this._tests.length) {
this._controller.input.completeDefaultIndex =
this._DefaultCompleteDefaultIndex;
this._onFinish();
return;
}
@@ -65,17 +65,17 @@ nsDoTestsForAutoCompleteWithComposition.
waitForCondition(() => {
return this._controller.searchStatus >=
Components.interfaces.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH;
},
this._checkResult.bind(this));
},
- _checkResult: function ()
+ _checkResult: function()
{
var test = this._tests[this._testingIndex];
this._is(this._getTargetValue(), test.value,
this._description + ", " + test.description + ": value");
this._is(this._controller.searchString, test.searchString,
this._description + ", " + test.description + ": searchString");
this._is(this._controller.input.popupOpen, test.popup,
this._description + ", " + test.description + ": popupOpen");
@@ -84,155 +84,155 @@ nsDoTestsForAutoCompleteWithComposition.
_testingIndex: -1,
_tests: [
// Simple composition when popup hasn't been shown.
// The autocomplete popup should not be shown during composition, but
// after compositionend, the popup should be shown.
{ description: "compositionstart shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "M",
"clauses":
[
{ "length": 1, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 1, "length": 0 },
"key": { key: "M", code: "KeyM", keyCode: KeyboardEvent.DOM_VK_M,
shiftKey: true },
}, aWindow);
}, popup: false, value: "M", searchString: ""
},
{ description: "modifying composition string shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "Mo",
"clauses":
[
{ "length": 2, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 2, "length": 0 },
"key": { key: "o", code: "KeyO", keyCode: KeyboardEvent.DOM_VK_O },
}, aWindow);
}, popup: false, value: "Mo", searchString: ""
},
{ description: "compositionend should open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeComposition({ type: "compositioncommitasis",
key: { key: "KEY_Enter", code: "Enter" } }, aWindow);
}, popup: true, value: "Mo", searchString: "Mo"
},
// If composition starts when popup is shown, the compositionstart event
// should cause closing the popup.
{ description: "compositionstart should close the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "z",
"clauses":
[
{ "length": 1, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 1, "length": 0 },
"key": { key: "z", code: "KeyZ", keyCode: KeyboardEvent.DOM_VK_Z },
}, aWindow);
}, popup: false, value: "Moz", searchString: "Mo"
},
{ description: "modifying composition string shouldn't reopen the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "zi",
"clauses":
[
{ "length": 2, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 2, "length": 0 },
"key": { key: "i", code: "KeyI", keyCode: KeyboardEvent.DOM_VK_I },
}, aWindow);
}, popup: false, value: "Mozi", searchString: "Mo"
},
{ description: "compositionend should research the result and open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeComposition({ type: "compositioncommitasis",
key: { key: "KEY_Enter", code: "Enter" } }, aWindow);
}, popup: true, value: "Mozi", searchString: "Mozi"
},
// If composition is cancelled, the value shouldn't be changed.
{ description: "compositionstart should reclose the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "l",
"clauses":
[
{ "length": 1, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 1, "length": 0 },
"key": { key: "l", code: "KeyL", keyCode: KeyboardEvent.DOM_VK_L },
}, aWindow);
}, popup: false, value: "Mozil", searchString: "Mozi"
},
{ description: "modifying composition string shouldn't reopen the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "ll",
"clauses":
[
{ "length": 2, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 2, "length": 0 },
"key": { key: "l", code: "KeyL", keyCode: KeyboardEvent.DOM_VK_L },
}, aWindow);
}, popup: false, value: "Mozill", searchString: "Mozi"
},
{ description: "modifying composition string to empty string shouldn't reopen the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "",
"clauses":
[
{ "length": 0, "attr": 0 }
]
},
"caret": { "start": 0, "length": 0 }
}, aWindow);
}, popup: false, value: "Mozi", searchString: "Mozi"
},
{ description: "cancled compositionend should reopen the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeComposition({ type: "compositioncommit", data: "",
key: { key: "KEY_Escape", code: "Escape" } }, aWindow);
}, popup: true, value: "Mozi", searchString: "Mozi"
},
// But if composition replaces some characters and canceled, the search
// string should be the latest value.
{ description: "compositionstart with selected string should close the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeKey("VK_LEFT", { shiftKey: true }, aWindow);
synthesizeKey("VK_LEFT", { shiftKey: true }, aWindow);
synthesizeCompositionChange(
{ "composition":
{ "string": "z",
"clauses":
[
{ "length": 1, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
@@ -240,299 +240,299 @@ nsDoTestsForAutoCompleteWithComposition.
},
"caret": { "start": 1, "length": 0 },
"key": { key: "z", code: "KeyZ", keyCode: KeyboardEvent.DOM_VK_Z },
}, aWindow);
}, popup: false, value: "Moz", searchString: "Mozi"
},
{ description: "modifying composition string shouldn't reopen the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "zi",
"clauses":
[
{ "length": 2, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 2, "length": 0 },
"key": { key: "i", code: "KeyI", keyCode: KeyboardEvent.DOM_VK_I },
}, aWindow);
}, popup: false, value: "Mozi", searchString: "Mozi"
},
{ description: "modifying composition string to empty string shouldn't reopen the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "",
"clauses":
[
{ "length": 0, "attr": 0 }
]
},
"caret": { "start": 0, "length": 0 }
}, aWindow);
}, popup: false, value: "Mo", searchString: "Mozi"
},
{ description: "canceled compositionend should search the result with the latest value",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeComposition({ type: "compositioncommitasis",
key: { key: "KEY_Escape", code: "Escape" } }, aWindow);
}, popup: true, value: "Mo", searchString: "Mo"
},
// If all characters are removed, the popup should be closed.
{ description: "the value becomes empty by backspace, the popup should be closed",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
}, popup: false, value: "", searchString: ""
},
// composition which is canceled shouldn't cause opening the popup.
{ description: "compositionstart shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "M",
"clauses":
[
{ "length": 1, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 1, "length": 0 },
"key": { key: "m", code: "KeyM", keyCode: KeyboardEvent.DOM_VK_M,
shiftKey: true },
}, aWindow);
}, popup: false, value: "M", searchString: ""
},
{ description: "modifying composition string shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "Mo",
"clauses":
[
{ "length": 2, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 2, "length": 0 },
"key": { key: "o", code: "KeyO", keyCode: KeyboardEvent.DOM_VK_O },
}, aWindow);
}, popup: false, value: "Mo", searchString: ""
},
{ description: "modifying composition string to empty string shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "",
"clauses":
[
{ "length": 0, "attr": 0 }
]
},
"caret": { "start": 0, "length": 0 }
}, aWindow);
}, popup: false, value: "", searchString: ""
},
{ description: "canceled compositionend shouldn't open the popup if it was closed",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeComposition({ type: "compositioncommitasis",
key: { key: "KEY_Escape", code: "Escape" } }, aWindow);
}, popup: false, value: "", searchString: ""
},
// Down key should open the popup even if the editor is empty.
{ description: "DOWN key should open the popup even if the value is empty",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeKey("VK_DOWN", {}, aWindow);
}, popup: true, value: "", searchString: ""
},
// If popup is open at starting composition, the popup should be reopened
// after composition anyway.
{ description: "compositionstart shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "M",
"clauses":
[
{ "length": 1, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 1, "length": 0 },
"key": { key: "M", code: "KeyM", keyCode: KeyboardEvent.DOM_VK_M,
shiftKey: true },
}, aWindow);
}, popup: false, value: "M", searchString: ""
},
{ description: "modifying composition string shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "Mo",
"clauses":
[
{ "length": 2, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 2, "length": 0 },
"key": { key: "o", code: "KeyO", keyCode: KeyboardEvent.DOM_VK_O },
}, aWindow);
}, popup: false, value: "Mo", searchString: ""
},
{ description: "modifying composition string to empty string shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "",
"clauses":
[
{ "length": 0, "attr": 0 }
]
},
"caret": { "start": 0, "length": 0 }
}, aWindow);
}, popup: false, value: "", searchString: ""
},
{ description: "canceled compositionend should open the popup if it was opened",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeComposition({ type: "compositioncommitasis",
key: { key: "KEY_Escape", code: "Escape" } }, aWindow);
}, popup: true, value: "", searchString: ""
},
// Type normally, and hit escape, the popup should be closed.
{ description: "ESCAPE should close the popup after typing something",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeKey("M", { shiftKey: true }, aWindow);
synthesizeKey("o", { shiftKey: true }, aWindow);
synthesizeKey("VK_ESCAPE", {}, aWindow);
}, popup: false, value: "Mo", searchString: "Mo"
},
// Even if the popup is closed, composition which is canceled should open
// the popup if the value isn't empty.
// XXX This might not be good behavior, but anyway, this is minor issue...
{ description: "compositionstart shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "z",
"clauses":
[
{ "length": 1, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 1, "length": 0 },
"key": { key: "z", code: "KeyZ", keyCode: KeyboardEvent.DOM_VK_Z },
}, aWindow);
}, popup: false, value: "Moz", searchString: "Mo"
},
{ description: "modifying composition string shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "zi",
"clauses":
[
{ "length": 2, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 2, "length": 0 },
"key": { key: "i", code: "KeyI", keyCode: KeyboardEvent.DOM_VK_I },
}, aWindow);
}, popup: false, value: "Mozi", searchString: "Mo"
},
{ description: "modifying composition string to empty string shouldn't open the popup",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "",
"clauses":
[
{ "length": 0, "attr": 0 }
]
},
"caret": { "start": 0, "length": 0 }
}, aWindow);
}, popup: false, value: "Mo", searchString: "Mo"
},
{ description: "canceled compositionend shouldn't open the popup if the popup was closed",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeComposition({ type: "compositioncommitasis",
key: { key: "KEY_Escape", code: "Escape" } }, aWindow);
}, popup: true, value: "Mo", searchString: "Mo"
},
// House keeping...
{ description: "house keeping for next tests",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
}, popup: false, value: "", searchString: ""
},
// Testing for nsIAutoCompleteInput.completeDefaultIndex being true.
{ description: "compositionstart shouldn't open the popup (completeDefaultIndex is true)",
completeDefaultIndex: true,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "M",
"clauses":
[
{ "length": 1, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 1, "length": 0 },
"key": { key: "M", code: "KeyM", keyCode: KeyboardEvent.DOM_VK_M,
shiftKey: true },
}, aWindow);
}, popup: false, value: "M", searchString: ""
},
{ description: "modifying composition string shouldn't open the popup (completeDefaultIndex is true)",
completeDefaultIndex: true,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeCompositionChange(
{ "composition":
{ "string": "Mo",
"clauses":
[
{ "length": 2, "attr": COMPOSITION_ATTR_RAW_CLAUSE }
]
},
"caret": { "start": 2, "length": 0 },
"key": { key: "o", code: "KeyO", keyCode: KeyboardEvent.DOM_VK_O },
}, aWindow);
}, popup: false, value: "Mo", searchString: ""
},
{ description: "compositionend should open the popup (completeDefaultIndex is true)",
completeDefaultIndex: true,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeComposition({ type: "compositioncommitasis",
key: { key: "KEY_Enter", code: "Enter" } }, aWindow);
}, popup: true, value: "Mozilla", searchString: "Mo"
},
// House keeping...
{ description: "house keeping for next tests",
completeDefaultIndex: false,
- execute: function (aWindow) {
+ execute: function(aWindow) {
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
synthesizeKey("VK_BACK_SPACE", {}, aWindow);
}, popup: false, value: "", searchString: ""
}
--- a/toolkit/content/tests/chrome/popup_trigger.js
+++ b/toolkit/content/tests/chrome/popup_trigger.js
@@ -46,17 +46,17 @@ var popupTests = [
testname: "mouse click on trigger",
events: [ "popupshowing thepopup", "popupshown thepopup" ],
test: function() {
// for menus, no trigger will be set. For non-menus using the popup
// attribute, the trigger will be set to the node with the popup attribute
gExpectedTriggerNode = gIsMenu ? "notset" : gTrigger;
synthesizeMouse(gTrigger, 4, 4, { });
},
- result: function (testname) {
+ result: function(testname) {
gExpectedTriggerNode = null;
// menus are the anchor but non-menus are opened at screen coordinates
is(gMenuPopup.anchorNode, gIsMenu ? gTrigger : null, testname + " anchorNode");
// menus are opened internally, but non-menus have a mouse event which
// triggered them
is(gMenuPopup.triggerNode, gIsMenu ? null : gTrigger, testname + " triggerNode");
is(document.popupNode, gIsMenu ? null : gTrigger, testname + " document.popupNode");
is(document.tooltipNode, null, testname + " document.tooltipNode");
@@ -300,17 +300,17 @@ var popupTests = [
},
{
testname: "popup with unknown step",
events: [ "popupshowing thepopup", "popupshown thepopup" ],
autohide: "thepopup",
test: function() {
gMenuPopup.openPopup(gTrigger, "other", 0, 0, false, false);
},
- result: function (testname) {
+ result: function(testname) {
var triggerrect = gMenuPopup.getBoundingClientRect();
var popuprect = gMenuPopup.getBoundingClientRect();
is(Math.round(popuprect.left), triggerrect.left, testname + " x position ");
is(Math.round(popuprect.top), triggerrect.top, testname + " y position ");
}
},
{
// these tests check to ensure that the position attribute can be used
--- a/toolkit/content/tests/chrome/test_autocomplete_with_composition_on_input.html
+++ b/toolkit/content/tests/chrome/test_autocomplete_with_composition_on_input.html
@@ -36,24 +36,24 @@ function runTests()
target.focus();
target.value = "Mozilla";
synthesizeKey("VK_RETURN", {});
target.value = "";
var test1 = new nsDoTestsForAutoCompleteWithComposition(
"Testing on HTML input (asynchronously search)",
window, target, formFillController.controller, is,
- function () { return target.value; },
- function () {
+ function() { return target.value; },
+ function() {
target.setAttribute("timeout", 0);
var test2 = new nsDoTestsForAutoCompleteWithComposition(
"Testing on HTML input (synchronously search)",
window, target, formFillController.controller, is,
- function () { return target.value; },
- function () {
+ function() { return target.value; },
+ function() {
formFillController.timeout = originalFormFillTimeout;
SpecialPowers.detachFormFillControllerFrom(window);
SimpleTest.finish();
});
});
}
SimpleTest.waitForFocus(runTests);
--- a/toolkit/content/tests/fennec-tile-testapp/chrome/content/WidgetStack.js
+++ b/toolkit/content/tests/fennec-tile-testapp/chrome/content/WidgetStack.js
@@ -54,24 +54,24 @@ var reportError = log;
* Simple container for top,left,bottom,right "border" values
*/
function wsBorder(t, l, b, r) {
this.setBorder(t, l, b, r);
}
wsBorder.prototype = {
- setBorder: function (t, l, b, r) {
+ setBorder: function(t, l, b, r) {
this.top = t;
this.left = l;
this.bottom = b;
this.right = r;
},
- toString: function () {
+ toString: function() {
return "[l:" + this.left + ",t:" + this.top + ",r:" + this.right + ",b:" + this.bottom + "]";
}
};
/*
* wsRect class
*
* Rectangle class, with both x/y/w/h and t/l/b/r accessors.
@@ -375,17 +375,17 @@ WidgetStack.prototype = {
_skipViewportUpdates: 0,
_forceViewportUpdate: false,
//
// init:
// el: the <stack> element whose children are to be managed
//
- init: function (el, ew, eh) {
+ init: function(el, ew, eh) {
this._el = el;
this._widgetState = {};
this._barriers = [];
let rect = this._el.getBoundingClientRect();
let width = rect.width;
let height = rect.height;
@@ -417,17 +417,17 @@ WidgetStack.prototype = {
this._viewportBounds = new wsRect(0, 0, 0, 0);
}
},
// moveWidgetBy: move the widget with the given id by x,y. Should
// not be used on vp-relative or otherwise frozen widgets (using it
// on the x coordinate for x-ignore widgets and similarily for y is
// ok, as long as the other coordinate remains 0.)
- moveWidgetBy: function (wid, x, y) {
+ moveWidgetBy: function(wid, x, y) {
let state = this._getState(wid);
state.rect.x += x;
state.rect.y += y;
this._commitState(state);
},
@@ -467,90 +467,90 @@ WidgetStack.prototype = {
y = this._viewingRect.y;
this.panBy(x - this._viewingRect.x, y - this._viewingRect.y, true);
},
// freeze: set a widget as frozen. A frozen widget won't be moved
// in the stack -- its x,y position will still be tracked in the
// state, but the left/top attributes won't be overwritten. Call unfreeze
// to move the widget back to where the ws thinks it should be.
- freeze: function (wid) {
+ freeze: function(wid) {
let state = this._getState(wid);
state.frozen = true;
},
- unfreeze: function (wid) {
+ unfreeze: function(wid) {
let state = this._getState(wid);
if (!state.frozen)
return;
state.frozen = false;
this._commitState(state);
},
// moveFrozenTo: move a frozen widget with id wid to x, y in the stack.
// can only be used on frozen widgets
- moveFrozenTo: function (wid, x, y) {
+ moveFrozenTo: function(wid, x, y) {
let state = this._getState(wid);
if (!state.frozen)
throw "moveFrozenTo on non-frozen widget " + wid;
state.widget.setAttribute("left", x);
state.widget.setAttribute("top", y);
},
// moveUnfrozenTo: move an unfrozen, pannable widget with id wid to x, y in
// the stack. should only be used on unfrozen widgets when a dynamic change
// in position needs to be made. we basically remove, adjust and re-add
// the widget
- moveUnfrozenTo: function (wid, x, y) {
+ moveUnfrozenTo: function(wid, x, y) {
delete this._widgetState[wid];
let widget = document.getElementById(wid);
if (x) widget.setAttribute("left", x);
if (y) widget.setAttribute("top", y);
this._addNewWidget(widget);
this._updateWidgets();
},
// we're relying on viewportBounds and viewingRect having the same origin
- get viewportVisibleRect () {
+ get viewportVisibleRect() {
let rect = this._viewportBounds.intersect(this._viewingRect);
if (!rect)
rect = new wsRect(0, 0, 0, 0);
return rect;
},
isWidgetFrozen: function isWidgetFrozen(wid) {
return this._getState(wid).frozen;
},
// isWidgetVisible: return true if any portion of widget with id wid is
// visible; otherwise return false.
- isWidgetVisible: function (wid) {
+ isWidgetVisible: function(wid) {
let state = this._getState(wid);
let visibleStackRect = new wsRect(0, 0, this._viewingRect.width, this._viewingRect.height);
return visibleStackRect.intersects(state.rect);
},
// getWidgetVisibility: returns the percentage that the widget is visible
- getWidgetVisibility: function (wid) {
+ getWidgetVisibility: function(wid) {
let state = this._getState(wid);
let visibleStackRect = new wsRect(0, 0, this._viewingRect.width, this._viewingRect.height);
let visibleRect = visibleStackRect.intersect(state.rect);
if (visibleRect)
return [visibleRect.width / state.rect.width, visibleRect.height / state.rect.height]
return [0, 0];
},
// offsetAll: add an offset to all widgets
- offsetAll: function (x, y) {
+ offsetAll: function(x, y) {
this.globalOffsetX += x;
this.globalOffsetY += y;
for (let wid in this._widgetState) {
let state = this._widgetState[wid];
state.rect.x += x;
state.rect.y += y;
@@ -657,26 +657,26 @@ WidgetStack.prototype = {
// setViewportHandler
// uh: A function object
//
// The given function object is called at the end of every drag and viewport
// bounds change, passing in the new rect that's to be displayed in the
// viewport.
//
- setViewportHandler: function (uh) {
+ setViewportHandler: function(uh) {
this._viewportUpdateHandler = uh;
},
// setPanHandler
// uh: A function object
//
// The given functin object is called whenever elements pan; it provides
// the new area of the pannable bounds that's visible in the stack.
- setPanHandler: function (uh) {
+ setPanHandler: function(uh) {
this._panHandler = uh;
},
// dragStart: start a drag, with the current coordinates being clientX,clientY
dragStart: function dragStart(clientX, clientY) {
log("(dragStart)", clientX, clientY);
if (this._dragState) {
@@ -738,17 +738,17 @@ WidgetStack.prototype = {
this._dragCoordsFromClient(clientX, clientY);
let panned = this._dragUpdate();
if (this._viewportUpdateInterval != -1) {
if (this._viewportUpdateTimeout != -1)
clearTimeout(this._viewportUpdateTimeout);
let self = this;
- this._viewportUpdateTimeout = setTimeout(function () { self._viewportDragUpdate(); }, this._viewportUpdateInterval);
+ this._viewportUpdateTimeout = setTimeout(function() { self._viewportDragUpdate(); }, this._viewportUpdateInterval);
}
return panned;
},
// dragBy: process a mouse move by dx,dy for an ongoing drag
dragBy: function dragBy(dx, dy) {
return this.dragMove(this._dragState.outerCurX + dx, this._dragState.outerCurY + dy);
@@ -827,17 +827,17 @@ WidgetStack.prototype = {
rect.right - rect.left,
rect.bottom - rect.top);
if (w.hasAttribute("widgetwidth") && w.hasAttribute("widgetheight")) {
state.rect.width = parseInt(w.getAttribute("widgetwidth"));
state.rect.height = parseInt(w.getAttribute("widgetheight"));
}
},
- _dumpRects: function () {
+ _dumpRects: function() {
dump("WidgetStack:\n");
dump("\tthis._viewportBounds: " + this._viewportBounds + "\n");
dump("\tthis._viewingRect: " + this._viewingRect + "\n");
dump("\tthis._viewport.viewportInnerBounds: " + this._viewport.viewportInnerBounds + "\n");
dump("\tthis._viewport.rect: " + this._viewport.rect + "\n");
dump("\tthis._viewportOverflow: " + this._viewportOverflow + "\n");
dump("\tthis.pannableBounds: " + this.pannableBounds + "\n");
},
@@ -865,17 +865,17 @@ WidgetStack.prototype = {
if (vr.bottom > pb.bottom)
panY = pb.bottom - vr.bottom;
else if (vr.top < pb.top)
panY = pb.top - vr.top;
this.panBy(panX, panY, true);
},
- _getState: function (wid) {
+ _getState: function(wid) {
let w = this._widgetState[wid];
if (!w)
throw "Unknown widget id '" + wid + "'; widget not in stack";
return w;
},
get _dragging() {
return this._dragState && this._dragState.dragging;
@@ -929,28 +929,28 @@ WidgetStack.prototype = {
vwib.left += this._viewport.offsetLeft;
vwib.top += this._viewport.offsetTop;
vwib.right += this._viewport.offsetRight;
vwib.bottom += this._viewport.offsetBottom;
this._viewportUpdateHandler.apply(window, [vwb, vwib, vis, boundsChanged]);
},
- _dragCoordsFromClient: function (cx, cy, t) {
+ _dragCoordsFromClient: function(cx, cy, t) {
this._dragState.curTime = t ? t : Date.now();
this._dragState.outerCurX = cx;
this._dragState.outerCurY = cy;
let dx = this._dragState.outerCurX - this._dragState.outerStartX;
let dy = this._dragState.outerCurY - this._dragState.outerStartY;
this._dragState.outerDX = dx;
this._dragState.outerDY = dy;
},
- _panHandleBarriers: function (dx, dy) {
+ _panHandleBarriers: function(dx, dy) {
// XXX unless the barriers are sorted by position, this will break
// with multiple barriers that are near enough to eachother that a
// drag could cross more than one.
let vr = this._viewingRect;
// XXX this just stops at the first horizontal and vertical barrier it finds
@@ -1142,17 +1142,17 @@ WidgetStack.prototype = {
this._dragState.outerLastUpdateDY = this._dragState.outerDY;
return this.panBy(dx, dy);
},
//
// widget addition/removal
//
- _addNewWidget: function (w) {
+ _addNewWidget: function(w) {
let wid = w.getAttribute("id");
if (!wid) {
reportError("WidgetStack: child widget without id!");
return;
}
if (w.getAttribute("hidden") == "true")
return;
@@ -1219,30 +1219,30 @@ WidgetStack.prototype = {
state.viewportInnerBounds = new wsRect(0, 0, state.rect.width, state.rect.height);
}
this._widgetState[wid] = state;
log("(New widget: " + wid + (state.viewport ? " [viewport]" : "") + " at: " + state.rect + ")");
},
- _removeWidget: function (w) {
+ _removeWidget: function(w) {
let wid = w.getAttribute("id");
delete this._widgetState[wid];
this._updateWidgets();
},
// updateWidgets:
// Go through all the widgets and figure out their viewport-relative offsets.
// If the widget goes to the left or above the viewport widget, then
// vpOffsetXBefore or vpOffsetYBefore is set.
// See setViewportBounds for use of vpOffset* state variables, and for how
// the actual x and y coords of each widget are calculated based on their offsets
// and the viewport bounds.
- _updateWidgets: function () {
+ _updateWidgets: function() {
let vp = this._viewport;
let ofRect = this._viewingRect.clone();
for (let wid in this._widgetState) {
let state = this._widgetState[wid];
if (vp && state.vpRelative) {
// compute the vpOffset from 0,0 assuming that the viewport rect is 0,0
@@ -1297,28 +1297,28 @@ WidgetStack.prototype = {
/* right*/ Math.round(Math.max(ofRect.right - vp.rect.width, 0))
);
// clear the _pannableBounds cache, since it depends on the
// viewportOverflow
this._pannableBounds = null;
},
- _widgetBounds: function () {
+ _widgetBounds: function() {
let r = new wsRect(0, 0, 0, 0);
for (let wid in this._widgetState) {
let state = this._widgetState[wid];
r = r.union(state.rect);
}
return r;
},
- _commitState: function (state) {
+ _commitState: function(state) {
// if the widget is frozen, don't actually update its left/top;
// presumably the caller is managing those directly for now.
if (state.frozen)
return;
let w = state.widget;
let l = state.rect.x + state.offsetLeft;
let t = state.rect.y + state.offsetTop;
@@ -1331,17 +1331,17 @@ WidgetStack.prototype = {
if (state._top != t) {
state._top = t;
w.setAttribute("top", t);
}
},
// constrain translate of rect by dx dy to bounds; return dx dy that can
// be used to bring rect up to the edge of bounds if we'd go over.
- _rectTranslateConstrain: function (dx, dy, rect, bounds) {
+ _rectTranslateConstrain: function(dx, dy, rect, bounds) {
let newX, newY;
// If the rect is larger than the bounds, allow it to increase its overlap
let woverflow = rect.width > bounds.width;
let hoverflow = rect.height > bounds.height;
if (woverflow || hoverflow) {
let intersection = rect.intersect(bounds);
let newIntersection = rect.clone().translate(dx, dy).intersect(bounds);
@@ -1358,17 +1358,17 @@ WidgetStack.prototype = {
newX = Math.min(Math.max(bounds.left, rect.x + dx), bounds.right - rect.width);
if (isNaN(newY))
newY = Math.min(Math.max(bounds.top, rect.y + dy), bounds.bottom - rect.height);
return [newX - rect.x, newY - rect.y];
},
// add a new barrier from a <spacer>
- _addNewBarrierFromSpacer: function (el) {
+ _addNewBarrierFromSpacer: function(el) {
let t = el.getAttribute("barriertype");
// XXX implement these at some point
// t != "lr" && t != "rl" &&
// t != "tb" && t != "bt" &&
if (t != "horizontal" &&
t != "vertical")
--- a/toolkit/content/tests/mochitest/test_mousecapture.xhtml
+++ b/toolkit/content/tests/mochitest/test_mousecapture.xhtml
@@ -100,17 +100,17 @@ function selectionScrollCheck()
synthesizeMouse(document.getElementById("custom"), 2, 2, { type: "mousedown" });
// check to ensure that selection dragging scrolls the right scrollable area
otherWindow = window.open("data:text/html,<html><p>One</p><p style='margin-top: 200px;'>Two</p><p style='margin-top: 4000px'>This is some text</p></html>", "_blank", "width=200,height=200,scrollbars=yes");
SimpleTest.waitForFocus(selectionScrollCheck, otherWindow);
}
}
- SimpleTest.executeSoon(function () {
+ SimpleTest.executeSoon(function() {
disableNonTestMouseEvents(true);
synthesizeMouse(element, 2, 2, { type: "mousedown" }, otherWindow);
synthesizeMouse(element, 100, otherWindow.innerHeight + 20, { type: "mousemove" }, otherWindow);
otherWindow.addEventListener("scroll", selectionScrollDone, false);
});
}
function runTests()
--- a/toolkit/content/tests/widgets/test_videocontrols_standalone.html
+++ b/toolkit/content/tests/widgets/test_videocontrols_standalone.html
@@ -64,21 +64,21 @@ function runTestAudioPre() {
}
})
}
function runTestAudio(aAudio) {
info("User agent (help diagnose bug #943556): " + navigator.userAgent);
var isAndroid = navigator.userAgent.includes("Android");
var expectedHeight = isAndroid ? 103 : 28;
- var condition = function () {
+ var condition = function() {
var boundingRect = aAudio.getBoundingClientRect();
return boundingRect.height == expectedHeight;
};
- waitForCondition(condition, function () {
+ waitForCondition(condition, function() {
var boundingRect = aAudio.getBoundingClientRect();
is(boundingRect.height, expectedHeight,
"Height of audio element should be " + expectedHeight + ", which is equal to the controls bar.");
popup.close();
SimpleTest.finish();
}, "The media element should eventually be resized to match the height of the audio controls.");
}
--- a/toolkit/content/treeUtils.js
+++ b/toolkit/content/treeUtils.js
@@ -1,26 +1,26 @@
// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var gTreeUtils = {
- deleteAll: function (aTree, aView, aItems, aDeletedItems)
+ deleteAll: function(aTree, aView, aItems, aDeletedItems)
{
for (var i = 0; i < aItems.length; ++i)
aDeletedItems.push(aItems[i]);
aItems.splice(0, aItems.length);
var oldCount = aView.rowCount;
aView._rowCount = 0;
aTree.treeBoxObject.rowCountChanged(0, -oldCount);
},
- deleteSelectedItems: function (aTree, aView, aItems, aDeletedItems)
+ deleteSelectedItems: function(aTree, aView, aItems, aDeletedItems)
{
var selection = aTree.view.selection;
selection.selectEventsSuppressed = true;
var rc = selection.getRangeCount();
for (var i = 0; i < rc; ++i) {
var min = { }; var max = { };
selection.getRangeAt(i, min, max);
@@ -46,27 +46,27 @@ var gTreeUtils = {
if (aItems.length) {
selection.select(nextSelection);
aTree.treeBoxObject.ensureRowIsVisible(nextSelection);
aTree.focus();
}
selection.selectEventsSuppressed = false;
},
- sort: function (aTree, aView, aDataSet, aColumn, aComparator,
- aLastSortColumn, aLastSortAscending)
+ sort: function(aTree, aView, aDataSet, aColumn, aComparator,
+ aLastSortColumn, aLastSortAscending)
{
var ascending = (aColumn == aLastSortColumn) ? !aLastSortAscending : true;
if (aDataSet.length == 0)
return ascending;
var numericSort = !isNaN(aDataSet[0][aColumn]);
var sortFunction = null;
if (aComparator) {
- sortFunction = function (a, b) { return aComparator(a[aColumn], b[aColumn]); };
+ sortFunction = function(a, b) { return aComparator(a[aColumn], b[aColumn]); };
}
aDataSet.sort(sortFunction);
if (!ascending)
aDataSet.reverse();
aTree.view.selection.clearSelection();
aTree.view.selection.select(0);
aTree.treeBoxObject.invalidate();
--- a/toolkit/content/widgets/general.xml
+++ b/toolkit/content/widgets/general.xml
@@ -214,17 +214,17 @@
<field name="_dragBindingAlive">true</field>
<constructor>
if (!this._draggableStarted) {
this._draggableStarted = true;
try {
let tmp = {};
Components.utils.import("resource://gre/modules/WindowDraggingUtils.jsm", tmp);
let draghandle = new tmp.WindowDraggingElement(this);
- draghandle.mouseDownCheck = function () {
+ draghandle.mouseDownCheck = function() {
return this._dragBindingAlive;
};
} catch (e) {}
}
</constructor>
</implementation>
</binding>
--- a/toolkit/content/widgets/popup.xml
+++ b/toolkit/content/widgets/popup.xml
@@ -276,17 +276,17 @@
<constructor>
<![CDATA[
if (this.getAttribute("backdrag") == "true" && !this._draggableStarted) {
this._draggableStarted = true;
try {
let tmp = {};
Components.utils.import("resource://gre/modules/WindowDraggingUtils.jsm", tmp);
let draghandle = new tmp.WindowDraggingElement(this);
- draghandle.mouseDownCheck = function () {
+ draghandle.mouseDownCheck = function() {
return this._dragBindingAlive;
}
} catch (e) {}
}
]]>
</constructor>
</implementation>
--- a/toolkit/content/widgets/preferences.xml
+++ b/toolkit/content/widgets/preferences.xml
@@ -764,17 +764,17 @@
this._selector.selectedItem = document.getAnonymousElementByAttribute(this, "pane", aPaneElement.id);
if (!aPaneElement.loaded) {
let OverlayLoadObserver = function(aPane)
{
this._pane = aPane;
}
OverlayLoadObserver.prototype = {
_outer: this,
- observe: function (aSubject, aTopic, aData)
+ observe: function(aSubject, aTopic, aData)
{
this._pane.loaded = true;
this._outer._fireEvent("paneload", this._pane);
this._outer._selectPane(this._pane);
}
};
var obs = new OverlayLoadObserver(aPaneElement);
--- a/toolkit/content/widgets/tabbox.xml
+++ b/toolkit/content/widgets/tabbox.xml
@@ -388,17 +388,17 @@
</getter>
<setter>
<![CDATA[
var tab = this.getItemAtIndex(val);
if (tab) {
var alreadySelected = tab.selected;
- Array.forEach(this.childNodes, function (aTab) {
+ Array.forEach(this.childNodes, function(aTab) {
if (aTab.selected && aTab != tab)
aTab._selected = false;
});
tab._selected = true;
this.setAttribute("value", tab.value);
let linkedPanel = this.getRelatedElement(tab);
--- a/toolkit/content/widgets/toolbar.xml
+++ b/toolkit/content/widgets/toolbar.xml
@@ -132,17 +132,17 @@
<constructor>
<![CDATA[
if (document.readyState == "complete") {
this._init();
} else {
// Need to wait until XUL overlays are loaded. See bug 554279.
let self = this;
- document.addEventListener("readystatechange", function (event) {
+ document.addEventListener("readystatechange", function(event) {
if (document.readyState != "complete")
return;
document.removeEventListener("readystatechange", arguments.callee, false);
self._init();
}, false);
}
]]>
</constructor>
@@ -390,17 +390,17 @@
<parameter name="aCurrentSet"/>
<body><![CDATA[
if (aCurrentSet == "__empty")
return false;
var defaultOrNoninteractive = (this.getAttribute("defaultset") || "")
.split(",")
.concat(["separator", "spacer", "spring"]);
- return aCurrentSet.split(",").some(function (item) {
+ return aCurrentSet.split(",").some(function(item) {
return defaultOrNoninteractive.indexOf(item) == -1;
});
]]></body>
</method>
</implementation>
</binding>
<binding id="toolbar-menubar-autohide"
@@ -414,21 +414,21 @@
</destructor>
<field name="_inactiveTimeout">null</field>
<field name="_contextMenuListener"><![CDATA[({
toolbar: this,
contextMenu: null,
- get active () {
+ get active() {
return !!this.contextMenu;
},
- init: function (event) {
+ init: function(event) {
var node = event.target;
while (node != this.toolbar) {
if (node.localName == "menupopup")
return;
node = node.parentNode;
}
var contextMenuId = this.toolbar.getAttribute("context");
@@ -438,17 +438,17 @@
this.contextMenu = document.getElementById(contextMenuId);
if (!this.contextMenu)
return;
this.contextMenu.addEventListener("popupshown", this, false);
this.contextMenu.addEventListener("popuphiding", this, false);
this.toolbar.addEventListener("mousemove", this, false);
},
- handleEvent: function (event) {
+ handleEvent: function(event) {
switch (event.type) {
case "popupshown":
this.toolbar.removeEventListener("mousemove", this, false);
break;
case "popuphiding":
case "mousemove":
this.toolbar._setInactiveAsync();
this.toolbar.removeEventListener("mousemove", this, false);
@@ -463,17 +463,17 @@
<method name="_setInactive">
<body><![CDATA[
this.setAttribute("inactive", "true");
]]></body>
</method>
<method name="_setInactiveAsync">
<body><![CDATA[
- this._inactiveTimeout = setTimeout(function (self) {
+ this._inactiveTimeout = setTimeout(function(self) {
if (self.getAttribute("autohide") == "true") {
self._inactiveTimeout = null;
self._setInactive();
}
}, 0, this);
]]></body>
</method>
--- a/toolkit/content/widgets/tree.xml
+++ b/toolkit/content/widgets/tree.xml
@@ -1021,17 +1021,17 @@
<children includes="treecol|splitter"/>
</xul:hbox>
<xul:treecolpicker class="treecol-image" fixed="true" xbl:inherits="tooltiptext=pickertooltiptext"/>
</content>
<implementation>
<constructor><![CDATA[
// Set resizeafter="farthest" on the splitters if nothing else has been
// specified.
- Array.forEach(this.getElementsByTagName("splitter"), function (splitter) {
+ Array.forEach(this.getElementsByTagName("splitter"), function(splitter) {
if (!splitter.hasAttribute("resizeafter"))
splitter.setAttribute("resizeafter", "farthest");
});
]]></constructor>
</implementation>
</binding>
<binding id="treerows" extends="chrome://global/content/bindings/tree.xml#tree-base">
--- a/toolkit/content/widgets/videocontrols.xml
+++ b/toolkit/content/widgets/videocontrols.xml
@@ -467,17 +467,17 @@
updateVolumeControls() {
var volume = this.video.muted ? 0 : this.video.volume;
var volumePercentage = Math.round(volume * 100);
this.updateMuteButtonState();
this.volumeControl.value = volumePercentage;
this.volumeForeground.style.paddingRight = (1 - volume) * this._volumeControlWidth + "px";
},
- handleEvent : function (aEvent) {
+ handleEvent : function(aEvent) {
this.log("Got media event ----> " + aEvent.type);
// If the binding is detached (or has been replaced by a
// newer instance of the binding), nuke our event-listeners.
if (this.videocontrols.randomID != this.randomID) {
this.terminateEventListeners();
return;
}
@@ -635,17 +635,17 @@
case "mozinterruptend":
// Nothing to do...
break;
default:
this.log("!!! event " + aEvent.type + " not handled!");
}
},
- terminateEventListeners : function () {
+ terminateEventListeners : function() {
if (this.videoEvents) {
for (let event of this.videoEvents) {
this.video.removeEventListener(event, this, {
capture: true,
mozSystemGroup: true
});
}
}
@@ -657,17 +657,17 @@
}
delete this.controlListeners;
}
this.log("--- videocontrols terminated ---");
},
- hasError : function () {
+ hasError : function() {
// We either have an explicit error, or the resource selection
// algorithm is running and we've tried to load something and failed.
// Note: we don't consider the case where we've tried to load but
// there's no sources to load as an error condition, as sites may
// do this intentionally to work around requires-user-interaction to
// play restrictions, and we don't want to display a debug message
// if that's the case.
return this.video.error != null ||
@@ -685,17 +685,17 @@
child = child.nextElementSibling) {
if (child instanceof HTMLSourceElement) {
return true;
}
}
return false;
},
- updateErrorText : function () {
+ updateErrorText : function() {
let error;
let v = this.video;
// It is possible to have both v.networkState == NETWORK_NO_SOURCE
// as well as v.error being non-null. In this case, we will show
// the v.error.code instead of the v.networkState error.
if (v.error) {
switch (v.error.code) {
case v.error.MEDIA_ERR_ABORTED:
@@ -739,17 +739,17 @@
mins = "0" + mins;
timeString = hours + ":" + mins + ":" + secs;
} else {
timeString = mins + ":" + secs;
}
return timeString;
},
- showDuration : function (duration) {
+ showDuration : function(duration) {
let isInfinite = (duration == Infinity);
this.log("Duration is " + duration + "ms.\n");
if (isNaN(duration) || isInfinite)
duration = this.maxCurrentTimeSeen;
// Format the duration as "h:mm:ss" or "m:ss"
let timeString = isInfinite ? "" : this.formatTime(duration);
@@ -846,34 +846,34 @@
}
this.bufferBar.max = duration;
this.bufferBar.value = endTime;
},
_controlsHiddenByTimeout : false,
_showControlsTimeout : 0,
SHOW_CONTROLS_TIMEOUT_MS: 500,
- _showControlsFn : function () {
+ _showControlsFn : function() {
if (Utils.video.matches("video:hover")) {
Utils.startFadeIn(Utils.controlBar, false);
Utils._showControlsTimeout = 0;
Utils._controlsHiddenByTimeout = false;
}
},
_hideControlsTimeout : 0,
- _hideControlsFn : function () {
+ _hideControlsFn : function() {
if (!Utils.scrubber.isDragging) {
Utils.startFade(Utils.controlBar, false);
Utils._hideControlsTimeout = 0;
Utils._controlsHiddenByTimeout = true;
}
},
HIDE_CONTROLS_TIMEOUT_MS : 2000,
- onMouseMove : function (event) {
+ onMouseMove : function(event) {
// Pause playing video when the mouse is dragging over the control bar.
if (this.scrubber.isDragging) {
this.scrubber.pauseVideoDuringDragging();
}
// If the controls are static, don't change anything.
if (!this.dynamicControls)
return;
@@ -896,17 +896,17 @@
// but above the control bar and if the click-to-play overlay is hidden.
if ((this._controlsHiddenByTimeout ||
event.clientY < this.controlBar.getBoundingClientRect().top) &&
this.clickToPlay.hidden) {
this._hideControlsTimeout = setTimeout(this._hideControlsFn, this.HIDE_CONTROLS_TIMEOUT_MS);
}
},
- onMouseInOut : function (event) {
+ onMouseInOut : function(event) {
// If the controls are static, don't change anything.
if (!this.dynamicControls)
return;
clearTimeout(this._hideControlsTimeout);
// Ignore events caused by transitions between child nodes.
// Note that the videocontrols element is the same
@@ -940,25 +940,25 @@
this.startFadeOut(this.controlBar, false);
this.textTrackList.setAttribute("hidden", "true");
clearTimeout(this._showControlsTimeout);
Utils._controlsHiddenByTimeout = false;
}
},
- startFadeIn : function (element, immediate) {
+ startFadeIn : function(element, immediate) {
this.startFade(element, true, immediate);
},
- startFadeOut : function (element, immediate) {
+ startFadeOut : function(element, immediate) {
this.startFade(element, false, immediate);
},
- startFade : function (element, fadeIn, immediate) {
+ startFade : function(element, fadeIn, immediate) {
if (element.classList.contains("controlBar") && fadeIn) {
// Bug 493523, the scrubber doesn't call valueChanged while hidden,
// so our dependent state (eg, timestamp in the thumb) will be stale.
// As a workaround, update it manually when it first becomes unhidden.
if (element.hidden)
this.scrubber.valueChanged("curpos", this.video.currentTime * 1000, false);
}
@@ -979,40 +979,40 @@
element.setAttribute("fadeout", true);
if (element.classList.contains("controlBar") && !this.hasError() &&
document.mozFullScreenElement == this.video)
this.controlsSpacer.setAttribute("hideCursor", true);
}
},
- onTransitionEnd : function (event) {
+ onTransitionEnd : function(event) {
// Ignore events for things other than opacity changes.
if (event.propertyName != "opacity")
return;
var element = event.originalTarget;
// Nothing to do when a fade *in* finishes.
if (!element.hasAttribute("fadeout"))
return;
this.scrubber.dragStateChanged(false);
element.hidden = true;
},
_triggeredByControls: false,
- startPlay : function () {
+ startPlay : function() {
this._triggeredByControls = true;
this.hideClickToPlay();
this.video.play();
},
- togglePause : function () {
+ togglePause : function() {
if (this.video.paused || this.video.ended) {
this.startPlay();
} else {
this.video.pause();
}
// We'll handle style changes in the event listener for
// the "play" and "pause" events, same as if content
@@ -1020,41 +1020,41 @@
},
isVideoWithoutAudioTrack : function() {
return this.video.readyState >= this.video.HAVE_METADATA &&
!this.isAudioOnly &&
!this.video.mozHasAudio;
},
- toggleMute : function () {
+ toggleMute : function() {
if (this.isVideoWithoutAudioTrack()) {
return;
}
this.video.muted = !this.isEffectivelyMuted();
if (this.video.volume === 0) {
this.video.volume = 0.5;
}
// We'll handle style changes in the event listener for
// the "volumechange" event, same as if content script was
// controlling volume.
},
- isVideoInFullScreen : function () {
+ isVideoInFullScreen : function() {
return document.mozFullScreenElement == this.video;
},
- toggleFullscreen : function () {
+ toggleFullscreen : function() {
this.isVideoInFullScreen() ?
document.mozCancelFullScreen() :
this.video.mozRequestFullScreen();
},
- setFullscreenButtonState : function () {
+ setFullscreenButtonState : function() {
if (this.isAudioOnly || !document.mozFullScreenEnabled) {
this.controlBar.setAttribute("fullscreen-unavailable", true);
this.adjustControlSize();
return;
}
this.controlBar.removeAttribute("fullscreen-unavailable");
this.adjustControlSize();
@@ -1063,17 +1063,17 @@
this.fullscreenButton.setAttribute("aria-label", value);
if (this.isVideoInFullScreen())
this.fullscreenButton.setAttribute("fullscreened", "true");
else
this.fullscreenButton.removeAttribute("fullscreened");
},
- onFullscreenChange: function () {
+ onFullscreenChange: function() {
if (this.isVideoInFullScreen()) {
Utils._hideControlsTimeout = setTimeout(this._hideControlsFn, this.HIDE_CONTROLS_TIMEOUT_MS);
}
this.setFullscreenButtonState();
},
clickToPlayClickHandler : function(e) {
if (e.button != 0)
@@ -1089,17 +1089,17 @@
if (e.defaultPrevented)
return;
if (this.playButton.hasAttribute("paused")) {
this.startPlay();
} else {
this.video.pause();
}
},
- hideClickToPlay : function () {
+ hideClickToPlay : function() {
let videoHeight = this.video.clientHeight;
let videoWidth = this.video.clientWidth;
// The play button will animate to 3x its size. This
// shows the animation unless the video is too small
// to show 2/3 of the animation.
let animationScale = 2;
if (this._overlayPlayButtonHeight * animationScale > (videoHeight - this._controlBarHeight) ||
@@ -1252,27 +1252,27 @@
return textTrack.kind == "subtitles" ||
textTrack.kind == "captions";
},
get overlayableTextTracks() {
return Array.prototype.filter.call(this.video.textTracks, this.isSupportedTextTrack);
},
- isClosedCaptionOn : function () {
+ isClosedCaptionOn : function() {
for (let tt of this.overlayableTextTracks) {
if (tt.mode === "showing") {
return true;
}
}
return false;
},
- setClosedCaptionButtonState : function () {
+ setClosedCaptionButtonState : function() {
if (!this.overlayableTextTracks.length || this.videocontrols.isTouchControl) {
this.closedCaptionButton.setAttribute("hidden", "true");
return;
}
this.closedCaptionButton.removeAttribute("hidden");
if (this.isClosedCaptionOn()) {
@@ -1289,17 +1289,17 @@
if (idx == this.currentTextTrackIndex) {
tti.setAttribute("on", "true");
} else {
tti.removeAttribute("on");
}
}
},
- addNewTextTrack : function (tt) {
+ addNewTextTrack : function(tt) {
if (!this.isSupportedTextTrack(tt)) {
return;
}
if (tt.index && tt.index < this.textTracksCount) {
return;
}
@@ -1307,32 +1307,32 @@
const label = tt.label || "";
const ttText = document.createTextNode(label);
const ttBtn = document.createElement("button");
ttBtn.classList.add("textTrackItem");
ttBtn.setAttribute("index", tt.index);
- ttBtn.addEventListener("click", function (event) {
+ ttBtn.addEventListener("click", function(event) {
event.stopPropagation();
this.changeTextTrack(tt.index);
}.bind(this));
ttBtn.appendChild(ttText);
this.textTrackList.appendChild(ttBtn);
if (tt.mode === "showing" && tt.index) {
this.changeTextTrack(tt.index);
}
},
- changeTextTrack : function (index) {
+ changeTextTrack : function(index) {
for (let tt of this.overlayableTextTracks) {
if (tt.index === index) {
tt.mode = "showing";
this.currentTextTrackIndex = tt.index;
} else {
tt.mode = "disabled";
}
@@ -1342,22 +1342,22 @@
if (this.currentTextTrackIndex !== index) {
this.currentTextTrackIndex = 0;
}
this.textTrackList.setAttribute("hidden", "true");
this.setClosedCaptionButtonState();
},
- onControlBarTransitioned : function () {
+ onControlBarTransitioned : function() {
this.textTrackList.setAttribute("hidden", "true");
this.video.dispatchEvent(new CustomEvent("controlbarchange"));
},
- toggleClosedCaption : function () {
+ toggleClosedCaption : function() {
if (this.overlayableTextTracks.length === 1) {
const lastTTIdx = this.overlayableTextTracks[0].index;
this.changeTextTrack(this.isClosedCaptionOn() ? 0 : lastTTIdx);
return;
}
if (this.textTrackList.hasAttribute("hidden")) {
this.textTrackList.removeAttribute("hidden");
@@ -1377,22 +1377,22 @@
maxButtonWidth = this.video.clientWidth;
}
for (let tti of this.textTrackList.childNodes) {
tti.style.width = maxButtonWidth + "px";
}
},
- onTextTrackAdd : function (trackEvent) {
+ onTextTrackAdd : function(trackEvent) {
this.addNewTextTrack(trackEvent.track);
this.setClosedCaptionButtonState();
},
- onTextTrackRemove : function (trackEvent) {
+ onTextTrackRemove : function(trackEvent) {
const toRemoveIndex = trackEvent.track.index;
const ttItems = this.textTrackList.childNodes;
if (!ttItems) {
return;
}
for (let tti of ttItems) {
@@ -1408,44 +1408,44 @@
this.video.dispatchEvent(new CustomEvent("texttrackchange"));
}
}
this.setClosedCaptionButtonState();
},
- initTextTracks : function () {
+ initTextTracks : function() {
const offLabel = this.textTrackList.getAttribute("offlabel");
this.addNewTextTrack({
label: offLabel,
kind: "subtitles"
});
for (let tt of this.overlayableTextTracks) {
this.addNewTextTrack(tt);
}
this.setClosedCaptionButtonState();
},
- isEventWithin : function (event, parent1, parent2) {
- function isDescendant (node) {
+ isEventWithin : function(event, parent1, parent2) {
+ function isDescendant(node) {
while (node) {
if (node == parent1 || node == parent2)
return true;
node = node.parentNode;
}
return false;
}
return isDescendant(event.target) && isDescendant(event.relatedTarget);
},
- log : function (msg) {
+ log : function(msg) {
if (this.debug)
console.log("videoctl: " + msg + "\n");
},
get isTopLevelSyntheticDocument() {
let doc = this.video.ownerDocument;
let win = doc.defaultView;
return doc.mozSyntheticDocument && win === win.top;
@@ -1524,17 +1524,17 @@
size = "hidden";
else if (videoWidth < minWidthOnlyPlayPause)
size = "hidden";
else if (videoWidth < minWidthAllControls)
size = "small";
this.controlBar.setAttribute("size", size);
},
- init : function (binding) {
+ init : function(binding) {
this.video = binding.parentNode;
this.videocontrols = binding;
this.statusIcon = document.getAnonymousElementByAttribute(binding, "class", "statusIcon");
this.controlBar = document.getAnonymousElementByAttribute(binding, "class", "controlBar");
this.playButton = document.getAnonymousElementByAttribute(binding, "class", "playButton");
this.muteButton = document.getAnonymousElementByAttribute(binding, "class", "muteButton");
this.volumeControl = document.getAnonymousElementByAttribute(binding, "class", "volumeControl");
@@ -1750,71 +1750,71 @@
hideControls : function() {
if (!this.Utils.dynamicControls)
return;
this.Utils.startFadeOut(this.Utils.controlBar);
if (this.firstShow)
this.videocontrols.addEventListener("transitionend", this, false);
},
- handleEvent : function (aEvent) {
+ handleEvent : function(aEvent) {
if (aEvent.type == "transitionend") {
this.firstShow = false;
this.videocontrols.removeEventListener("transitionend", this, false);
return;
}
if (this.videocontrols.randomID != this.Utils.randomID)
this.terminateEventListeners();
},
- terminateEventListeners : function () {
+ terminateEventListeners : function() {
for (var event of this.videoEvents)
this.Utils.video.removeEventListener(event, this, false);
},
- isVideoCasting : function () {
+ isVideoCasting : function() {
if (this.video.mozIsCasting)
return true;
return false;
},
- updateCasting : function (eventDetail) {
+ updateCasting : function(eventDetail) {
let castingData = JSON.parse(eventDetail);
if ("allow" in castingData) {
this.video.mozAllowCasting = !!castingData.allow;
}
if ("active" in castingData) {
this.video.mozIsCasting = !!castingData.active;
}
this.setCastButtonState();
},
- startCasting : function () {
+ startCasting : function() {
this.videocontrols.dispatchEvent(new CustomEvent("VideoBindingCast"));
},
- setCastButtonState : function () {
+ setCastButtonState : function() {
if (this.isAudioOnly || !this.video.mozAllowCasting) {
this.castingButton.hidden = true;
return;
}
if (this.video.mozIsCasting) {
this.castingButton.setAttribute("active", "true");
} else {
this.castingButton.removeAttribute("active");
}
this.castingButton.hidden = false;
},
- init : function (binding) {
+ init : function(binding) {
this.videocontrols = binding;
this.video = binding.parentNode;
let self = this;
this.Utils.playButton.addEventListener("command", function() {
if (!self.video.paused)
self.delayHideControls(0);
else
@@ -1828,17 +1828,17 @@
}, false);
this.Utils.muteButton.addEventListener("click", function() { self.delayHideControls(self.controlsTimeout); }, false);
this.castingButton = document.getAnonymousElementByAttribute(binding, "class", "castingButton");
this.castingButton.addEventListener("command", function() {
self.startCasting();
}, false);
- this.video.addEventListener("media-videoCasting", function (e) {
+ this.video.addEventListener("media-videoCasting", function(e) {
if (!e.isTrusted)
return;
self.updateCasting(e.detail);
}, false, true);
// The first time the controls appear we want to just display
// a play button that does not fade away. The firstShow property
// makes that happen. But because of bug 718107 this init() method
@@ -1911,33 +1911,33 @@
<constructor>
<![CDATA[
this.randomID = 0;
this.Utils = {
randomID : 0,
videoEvents : ["play",
"playing"],
controlListeners: [],
- terminateEventListeners : function () {
+ terminateEventListeners : function() {
for (let event of this.videoEvents)
this.video.removeEventListener(event, this, { mozSystemGroup: true });
for (let element of this.controlListeners) {
element.item.removeEventListener(element.event, element.func,
{ mozSystemGroup: true });
}
delete this.controlListeners;
},
- hasError : function () {
+ hasError : function() {
return (this.video.error != null || this.video.networkState == this.video.NETWORK_NO_SOURCE);
},
- handleEvent : function (aEvent) {
+ handleEvent : function(aEvent) {
// If the binding is detached (or has been replaced by a
// newer instance of the binding), nuke our event-listeners.
if (this.binding.randomID != this.randomID) {
this.terminateEventListeners();
return;
}
switch (aEvent.type) {
@@ -1945,40 +1945,40 @@
this.noControlsOverlay.hidden = true;
break;
case "playing":
this.noControlsOverlay.hidden = true;
break;
}
},
- blockedVideoHandler : function () {
+ blockedVideoHandler : function() {
if (this.binding.randomID != this.randomID) {
this.terminateEventListeners();
return;
} else if (this.hasError()) {
this.noControlsOverlay.hidden = true;
return;
}
this.noControlsOverlay.hidden = false;
},
- clickToPlayClickHandler : function (e) {
+ clickToPlayClickHandler : function(e) {
if (this.binding.randomID != this.randomID) {
this.terminateEventListeners();
return;
} else if (e.button != 0) {
return;
}
this.noControlsOverlay.hidden = true;
this.video.play();
},
- init : function (binding) {
+ init : function(binding) {
this.binding = binding;
this.randomID = Math.random();
this.binding.randomID = this.randomID;
this.video = binding.parentNode;
this.clickToPlay = document.getAnonymousElementByAttribute(binding, "class", "clickToPlay");
this.noControlsOverlay = document.getAnonymousElementByAttribute(binding, "class", "statusOverlay");
let self = this;
--- a/toolkit/crashreporter/test/browser/browser_aboutCrashes.js
+++ b/toolkit/crashreporter/test/browser/browser_aboutCrashes.js
@@ -4,19 +4,19 @@ add_task(function* test() {
crD.append("Crash Reports");
let crashes = add_fake_crashes(crD, 5);
// sanity check
let dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties);
let appDtest = dirSvc.get("UAppData", Components.interfaces.nsILocalFile);
ok(appD.equals(appDtest), "directory service provider registered ok");
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:crashes" }, function (browser) {
+ yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:crashes" }, function(browser) {
info("about:crashes loaded");
- return ContentTask.spawn(browser, crashes, function (crashes) {
+ return ContentTask.spawn(browser, crashes, function(crashes) {
let doc = content.document;
let crashlinks = doc.getElementById("submitted").querySelectorAll(".crashReport");
Assert.equal(crashlinks.length, crashes.length,
"about:crashes lists correct number of crash reports");
for (let i = 0; i < crashes.length; i++) {
Assert.equal(crashlinks[i].firstChild.textContent, crashes[i].id,
i + ": crash ID is correct");
}
--- a/toolkit/crashreporter/test/browser/browser_bug471404.js
+++ b/toolkit/crashreporter/test/browser/browser_bug471404.js
@@ -1,10 +1,10 @@
function check_clear_visible(browser, aVisible) {
- return ContentTask.spawn(browser, aVisible, function (aVisible) {
+ return ContentTask.spawn(browser, aVisible, function(aVisible) {
let doc = content.document;
let visible = false;
let button = doc.getElementById("clear-reports");
if (button) {
let style = doc.defaultView.getComputedStyle(button, "");
if (style.display != "none" &&
style.visibility == "visible")
visible = true;
--- a/toolkit/crashreporter/test/browser/browser_clearReports.js
+++ b/toolkit/crashreporter/test/browser/browser_clearReports.js
@@ -44,17 +44,17 @@ var promptShown = false;
var oldPrompt = Services.prompt;
Services.prompt = {
confirm: function() {
promptShown = true;
return true;
},
};
-registerCleanupFunction(function () {
+registerCleanupFunction(function() {
Services.prompt = oldPrompt;
});
add_task(function* test() {
let appD = make_fake_appdir();
let crD = appD.clone();
crD.append("Crash Reports");
@@ -88,17 +88,17 @@ add_task(function* test() {
let report3 = crD.clone();
report3.append("InstallTimeNew");
report3.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666);
let report4 = crD.clone();
report4.append("InstallTimeOld");
report4.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666);
report4.lastModifiedTime = Date.now() - 63172000000;
- registerCleanupFunction(function () {
+ registerCleanupFunction(function() {
cleanup_fake_appdir();
});
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:crashes" },
function* (browser) {
let dirs = [ submitdir, pendingdir, crD ];
let existing = [ file1.path, file2.path, report1.path, report2.path,
report3.path, submitdir.path, pendingdir.path ];
--- a/toolkit/identity/tests/unit/head_identity.js
+++ b/toolkit/identity/tests/unit/head_identity.js
@@ -140,17 +140,17 @@ function mock_fxa_rp(aIdentity, aOrigin,
// this observer auto-removes itself after the observe function
// is called, so this is meant to observe only ONE event.
function makeObserver(aObserveTopic, aObserveFunc) {
let observer = {
// nsISupports provides type management in C++
// nsIObserver is to be an observer
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIObserver]),
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
if (aTopic == aObserveTopic) {
aObserveFunc(aSubject, aTopic, aData);
Services.obs.removeObserver(observer, aObserveTopic);
}
}
};
Services.obs.addObserver(observer, aObserveTopic, false);
--- a/toolkit/identity/tests/unit/test_authentication.js
+++ b/toolkit/identity/tests/unit/test_authentication.js
@@ -16,17 +16,17 @@ function test_begin_authentication_flow(
// set up a watch, to be consistent
let mockedDoc = mock_doc(null, TEST_URL, function(action, params) {});
IDService.RP.watch(mockedDoc);
// The identity-auth notification is sent up to the UX from the
// _doAuthentication function. Be ready to receive it and call
// beginAuthentication
- makeObserver("identity-auth", function (aSubject, aTopic, aData) {
+ makeObserver("identity-auth", function(aSubject, aTopic, aData) {
do_check_neq(aSubject, null);
do_check_eq(aSubject.wrappedJSObject.provId, _provId);
do_test_finished();
run_next_test();
});
@@ -83,17 +83,17 @@ function test_complete_authentication_fl
));
makeObserver("identity-auth-complete", function(aSubject, aTopic, aData) {
identityAuthComplete = true;
do_test_finished();
run_next_test();
});
- makeObserver("identity-login-state-changed", function (aSubject, aTopic, aData) {
+ makeObserver("identity-login-state-changed", function(aSubject, aTopic, aData) {
do_check_neq(aSubject, null);
do_check_eq(aSubject.wrappedJSObject.rpId, mockedDoc.id);
do_check_eq(aData, id);
// if callbacks in caller doc already fired, test is done.
loginStateChanged = true;
if (callbacksFired && identityAuthComplete) {
--- a/toolkit/identity/tests/unit/test_crypto_service.js
+++ b/toolkit/identity/tests/unit/test_crypto_service.js
@@ -42,50 +42,50 @@ function test_base64_roundtrip() {
let encoded = idService.base64UrlEncode(message);
let decoded = base64UrlDecode(encoded);
do_check_neq(message, encoded);
do_check_eq(decoded, message);
run_next_test();
}
function test_dsa() {
- idService.generateKeyPair(ALG_DSA, function (rv, keyPair) {
+ idService.generateKeyPair(ALG_DSA, function(rv, keyPair) {
log("DSA generateKeyPair finished ", rv);
do_check_true(Components.isSuccessCode(rv));
do_check_eq(typeof keyPair.sign, "function");
do_check_eq(keyPair.keyType, ALG_DSA);
do_check_eq_or_slightly_less(keyPair.hexDSAGenerator.length, 1024 / 8 * 2);
do_check_eq_or_slightly_less(keyPair.hexDSAPrime.length, 1024 / 8 * 2);
do_check_eq_or_slightly_less(keyPair.hexDSASubPrime.length, 160 / 8 * 2);
do_check_eq_or_slightly_less(keyPair.hexDSAPublicValue.length, 1024 / 8 * 2);
// XXX: test that RSA parameters throw the correct error
log("about to sign with DSA key");
- keyPair.sign("foo", function (rv, signature) {
+ keyPair.sign("foo", function(rv, signature) {
log("DSA sign finished ", rv, signature);
do_check_true(Components.isSuccessCode(rv));
do_check_true(signature.length > 1);
// TODO: verify the signature with the public key
run_next_test();
});
});
}
function test_rsa() {
- idService.generateKeyPair(ALG_RSA, function (rv, keyPair) {
+ idService.generateKeyPair(ALG_RSA, function(rv, keyPair) {
log("RSA generateKeyPair finished ", rv);
do_check_true(Components.isSuccessCode(rv));
do_check_eq(typeof keyPair.sign, "function");
do_check_eq(keyPair.keyType, ALG_RSA);
do_check_eq_or_slightly_less(keyPair.hexRSAPublicKeyModulus.length,
2048 / 8);
do_check_true(keyPair.hexRSAPublicKeyExponent.length > 1);
log("about to sign with RSA key");
- keyPair.sign("foo", function (rv, signature) {
+ keyPair.sign("foo", function(rv, signature) {
log("RSA sign finished ", rv, signature);
do_check_true(Components.isSuccessCode(rv));
do_check_true(signature.length > 1);
run_next_test();
});
});
}
--- a/toolkit/identity/tests/unit/test_identity.js
+++ b/toolkit/identity/tests/unit/test_identity.js
@@ -69,17 +69,17 @@ function test_select_identity() {
do_test_finished();
run_next_test();
}));
// register the callbacks
IDService.RP.watch(mockedDoc);
// register the request UX observer
- makeObserver("identity-request", function (aSubject, aTopic, aData) {
+ makeObserver("identity-request", function(aSubject, aTopic, aData) {
// do the select identity
// we expect this to succeed right away because of test_identity
// so we don't mock network requests or otherwise
IDService.selectIdentity(aSubject.wrappedJSObject.rpId, id);
});
// do the request
IDService.RP.request(mockedDoc.id, {});
--- a/toolkit/identity/tests/unit/test_minimalidentity.js
+++ b/toolkit/identity/tests/unit/test_minimalidentity.js
@@ -32,34 +32,34 @@ function test_mock_doc() {
/*
* Test that the "identity-controller-watch" signal is emitted correctly
*/
function test_watch() {
do_test_pending();
let mockedDoc = mock_doc(null, TEST_URL);
- makeObserver("identity-controller-watch", function (aSubject, aTopic, aData) {
+ makeObserver("identity-controller-watch", function(aSubject, aTopic, aData) {
do_check_eq(aSubject.wrappedJSObject.id, mockedDoc.id);
do_check_eq(aSubject.wrappedJSObject.origin, TEST_URL);
do_test_finished();
run_next_test();
});
MinimalIDService.RP.watch(mockedDoc);
}
/*
* Test that the "identity-controller-request" signal is emitted correctly
*/
function test_request() {
do_test_pending();
let mockedDoc = mock_doc(null, TEST_URL);
- makeObserver("identity-controller-request", function (aSubject, aTopic, aData) {
+ makeObserver("identity-controller-request", function(aSubject, aTopic, aData) {
do_check_eq(aSubject.wrappedJSObject.id, mockedDoc.id);
do_check_eq(aSubject.wrappedJSObject.origin, TEST_URL);
do_test_finished();
run_next_test();
});
MinimalIDService.RP.watch(mockedDoc);
MinimalIDService.RP.request(mockedDoc.id, {});
@@ -67,17 +67,17 @@ function test_request() {
/*
* Test that the forceAuthentication flag can be sent
*/
function test_request_forceAuthentication() {
do_test_pending();
let mockedDoc = mock_doc(null, TEST_URL);
- makeObserver("identity-controller-request", function (aSubject, aTopic, aData) {
+ makeObserver("identity-controller-request", function(aSubject, aTopic, aData) {
do_check_eq(aSubject.wrappedJSObject.id, mockedDoc.id);
do_check_eq(aSubject.wrappedJSObject.origin, TEST_URL);
do_check_eq(aSubject.wrappedJSObject.forceAuthentication, true);
do_test_finished();
run_next_test();
});
MinimalIDService.RP.watch(mockedDoc);
@@ -86,17 +86,17 @@ function test_request_forceAuthenticatio
/*
* Test that the issuer can be forced
*/
function test_request_forceIssuer() {
do_test_pending();
let mockedDoc = mock_doc(null, TEST_URL);
- makeObserver("identity-controller-request", function (aSubject, aTopic, aData) {
+ makeObserver("identity-controller-request", function(aSubject, aTopic, aData) {
do_check_eq(aSubject.wrappedJSObject.id, mockedDoc.id);
do_check_eq(aSubject.wrappedJSObject.origin, TEST_URL);
do_check_eq(aSubject.wrappedJSObject.issuer, "https://jed.gov");
do_test_finished();
run_next_test();
});
MinimalIDService.RP.watch(mockedDoc);
@@ -105,17 +105,17 @@ function test_request_forceIssuer() {
/*
* Test that the "identity-controller-logout" signal is emitted correctly
*/
function test_logout() {
do_test_pending();
let mockedDoc = mock_doc(null, TEST_URL);
- makeObserver("identity-controller-logout", function (aSubject, aTopic, aData) {
+ makeObserver("identity-controller-logout", function(aSubject, aTopic, aData) {
do_check_eq(aSubject.wrappedJSObject.id, mockedDoc.id);
do_test_finished();
run_next_test();
});
MinimalIDService.RP.watch(mockedDoc);
MinimalIDService.RP.logout(mockedDoc.id, {});
}
@@ -181,17 +181,17 @@ function test_childProcessShutdown() {
if (action == "child-process-shutdown") {
// since there's no actual dom window connection, we have to
// do this bit manually here.
MinimalIDService.RP.childProcessShutdown(UNIQUE_MESSAGE_MANAGER);
}
});
mockedDoc._mm = UNIQUE_MESSAGE_MANAGER;
- makeObserver("identity-controller-watch", function (aSubject, aTopic, aData) {
+ makeObserver("identity-controller-watch", function(aSubject, aTopic, aData) {
DOMIdentity._childProcessShutdown(UNIQUE_MESSAGE_MANAGER);
});
makeObserver("identity-child-process-shutdown", (aTopic, aSubject, aData) => {
do_check_eq(Object.keys(MinimalIDService.RP._rpFlows).length, initialRPCount);
do_test_finished();
run_next_test();
});
--- a/toolkit/identity/tests/unit/test_observer_topics.js
+++ b/toolkit/identity/tests/unit/test_observer_topics.js
@@ -33,17 +33,17 @@ function test_identity_request() {
// deliberately adding a trailing final slash on the domain
// to test path composition
let mockedDoc = mock_doc(null, "http://jed.gov/", function() {});
// by calling watch() we create an rp flow.
IDService.RP.watch(mockedDoc);
// register the request UX observer
- makeObserver("identity-request", function (aSubject, aTopic, aData) {
+ makeObserver("identity-request", function(aSubject, aTopic, aData) {
do_check_eq(aTopic, "identity-request");
do_check_eq(aData, null);
// check that all the URLs are properly resolved
let subj = aSubject.wrappedJSObject;
do_check_eq(subj.privacyPolicy, "http://jed.gov/pp.html");
do_check_eq(subj.termsOfService, "http://jed.gov/tos.html");
@@ -79,17 +79,17 @@ function test_identity_auth() {
// Create an RP flow
let mockedDoc = mock_doc(null, TEST_URL, function(action, params) {});
IDService.RP.watch(mockedDoc);
// The identity-auth notification is sent up to the UX from the
// _doAuthentication function. Be ready to receive it and call
// beginAuthentication
- makeObserver("identity-auth", function (aSubject, aTopic, aData) {
+ makeObserver("identity-auth", function(aSubject, aTopic, aData) {
do_check_neq(aSubject, null);
do_check_eq(aTopic, "identity-auth");
do_check_eq(aData, "https://myfavoriteflan.com/foo/authenticate.html");
do_check_eq(aSubject.wrappedJSObject.provId, _provId);
do_test_finished();
run_next_test();
});
--- a/toolkit/identity/tests/unit/test_relying_party.js
+++ b/toolkit/identity/tests/unit/test_relying_party.js
@@ -138,17 +138,17 @@ function test_request() {
let mockedDoc = mock_doc(null, TEST_URL, function(action, params) {
// this isn't going to be called for now
// XXX but it is called - is that bad?
});
RelyingParty.watch(mockedDoc);
// be ready for the UX identity-request notification
- makeObserver("identity-request", function (aSubject, aTopic, aData) {
+ makeObserver("identity-request", function(aSubject, aTopic, aData) {
do_check_neq(aSubject, null);
do_check_eq(aSubject.wrappedJSObject.rpId, mockedDoc.id);
do_test_finished();
run_next_test();
});
--- a/toolkit/modules/Battery.jsm
+++ b/toolkit/modules/Battery.jsm
@@ -35,18 +35,18 @@ this.Debugging = {
/**
* If `false`, use the DOM Battery implementation.
* Set it to `true` if you need to fake battery values
* for testing or debugging purposes.
*/
fake: false
}
-this.GetBattery = function () {
- return new Services.appShell.hiddenDOMWindow.Promise(function (resolve, reject) {
+this.GetBattery = function() {
+ return new Services.appShell.hiddenDOMWindow.Promise(function(resolve, reject) {
// Return fake values if spoofing is enabled, otherwise fetch the real values from the BatteryManager API
if (Debugging.fake) {
resolve(gFakeBattery);
return;
}
Services.appShell.hiddenDOMWindow.navigator.getBattery().then(resolve, reject);
});
};
--- a/toolkit/modules/BinarySearch.jsm
+++ b/toolkit/modules/BinarySearch.jsm
@@ -13,31 +13,31 @@ this.BinarySearch = Object.freeze({
/**
* Returns the index of the given target in the given array or -1 if the
* target is not found.
*
* See search() for a description of this function's parameters.
*
* @return The index of `target` in `array` or -1 if `target` is not found.
*/
- indexOf: function (comparator, array, target) {
+ indexOf: function(comparator, array, target) {
let [found, idx] = this.search(comparator, array, target);
return found ? idx : -1;
},
/**
* Returns the index within the given array where the given target may be
* inserted to keep the array ordered.
*
* See search() for a description of this function's parameters.
*
* @return The index in `array` where `target` may be inserted to keep `array`
* ordered.
*/
- insertionIndexOf: function (comparator, array, target) {
+ insertionIndexOf: function(comparator, array, target) {
return this.search(comparator, array, target)[1];
},
/**
* Searches for the given target in the given array.
*
* @param comparator
* A function that takes two arguments and compares them, returning a
@@ -51,17 +51,17 @@ this.BinarySearch = Object.freeze({
* @param target
* The value to search for.
* @return An array with two elements. If `target` is found, the first
* element is true, and the second element is its index in the array.
* If `target` is not found, the first element is false, and the
* second element is the index where it may be inserted to keep the
* array ordered.
*/
- search: function (comparator, array, target) {
+ search: function(comparator, array, target) {
let low = 0;
let high = array.length - 1;
while (low <= high) {
// Thanks to http://jsperf.com/code-review-1480 for this tip.
let mid = (low + high) >> 1;
let cmp = comparator(target, array[mid]);
if (cmp == 0)
return [true, mid];
--- a/toolkit/modules/BrowserUtils.jsm
+++ b/toolkit/modules/BrowserUtils.jsm
@@ -17,17 +17,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
Cu.importGlobalProperties(['URL']);
this.BrowserUtils = {
/**
* Prints arguments separated by a space and appends a new line.
*/
- dumpLn: function (...args) {
+ dumpLn: function(...args) {
for (let a of args)
dump(a + " ");
dump("\n");
},
/**
* restartApplication: Restarts the application, keeping it in
* safe mode if it is already in safe mode.
@@ -226,17 +226,17 @@ this.BrowserUtils = {
},
/**
* Map the plugin's name to a filtered version more suitable for UI.
*
* @param aName The full-length name string of the plugin.
* @return the simplified name string.
*/
- makeNicePluginName: function (aName) {
+ makeNicePluginName: function(aName) {
if (aName == "Shockwave Flash")
return "Adobe Flash";
// Regex checks if aName begins with "Java" + non-letter char
if (/^Java\W/.exec(aName))
return "Java";
// Clean up the plugin name by stripping off parenthetical clauses,
// trailing version numbers or "plugin".
@@ -251,17 +251,17 @@ this.BrowserUtils = {
},
/**
* Return true if linkNode has a rel="noreferrer" attribute.
*
* @param linkNode The <a> element, or null.
* @return a boolean indicating if linkNode has a rel="noreferrer" attribute.
*/
- linkHasNoReferrer: function (linkNode) {
+ linkHasNoReferrer: function(linkNode) {
// A null linkNode typically means that we're checking a link that wasn't
// provided via an <a> link, like a text-selected URL. Don't leak
// referrer information in this case.
if (!linkNode)
return true;
let rel = linkNode.getAttribute("rel");
if (!rel)
--- a/toolkit/modules/ClientID.jsm
+++ b/toolkit/modules/ClientID.jsm
@@ -80,17 +80,17 @@ this.ClientID = Object.freeze({
});
var ClientIDImpl = {
_clientID: null,
_loadClientIdTask: null,
_saveClientIdTask: null,
_logger: null,
- _loadClientID: function () {
+ _loadClientID: function() {
if (this._loadClientIdTask) {
return this._loadClientIdTask;
}
this._loadClientIdTask = this._doLoadClientID();
let clear = () => this._loadClientIdTask = null;
this._loadClientIdTask.then(clear, clear);
return this._loadClientIdTask;
@@ -202,17 +202,17 @@ var ClientIDImpl = {
/**
* Sets the client id to the given value and updates the value cached in
* preferences only if the given id is a valid.
*
* @param {String} id A string containing the client ID.
* @return {Boolean} True when the client ID has valid format, or False
* otherwise.
*/
- updateClientID: function (id) {
+ updateClientID: function(id) {
if (!isValidClientID(id)) {
this._log.error("updateClientID - invalid client ID", id);
return false;
}
this._clientID = id;
Preferences.set(PREF_CACHED_CLIENTID, this._clientID);
return true;
--- a/toolkit/modules/DeferredTask.jsm
+++ b/toolkit/modules/DeferredTask.jsm
@@ -107,17 +107,17 @@ const Timer = Components.Constructor("@m
* task is never re-entered while running.
* @param aDelayMs
* Time between executions, in milliseconds. Multiple attempts to run
* the task before the delay has passed are coalesced. This time of
* inactivity is guaranteed to pass between multiple executions of the
* task, except on finalization, when the task may restart immediately
* after the previous execution finished.
*/
-this.DeferredTask = function (aTaskFn, aDelayMs) {
+this.DeferredTask = function(aTaskFn, aDelayMs) {
this._taskFn = aTaskFn;
this._delayMs = aDelayMs;
}
this.DeferredTask.prototype = {
/**
* Function or generator function to execute.
*/
@@ -156,17 +156,17 @@ this.DeferredTask.prototype = {
* nsITimer used for triggering the task after a delay, or null in case the
* task is running or there is no task scheduled for execution.
*/
_timer: null,
/**
* Actually starts the timer with the delay specified on construction.
*/
- _startTimer: function ()
+ _startTimer: function()
{
this._timer = new Timer(this._timerCallback.bind(this), this._delayMs,
Ci.nsITimer.TYPE_ONE_SHOT);
},
/**
* Requests the execution of the task after the delay specified on
* construction. Multiple calls don't introduce further delays. If the task
@@ -180,17 +180,17 @@ this.DeferredTask.prototype = {
* @note By design, this method doesn't provide a way for the caller to detect
* when the next execution terminates, or collect a result. In fact,
* doing that would often result in duplicate processing or logging. If
* a special operation or error logging is needed on completion, it can
* be better handled from within the task itself, for example using a
* try/catch/finally clause in the task. The "finalize" method can be
* used in the common case of waiting for completion on shutdown.
*/
- arm: function ()
+ arm: function()
{
if (this._finalized) {
throw new Error("Unable to arm timer, the object has been finalized.");
}
this._armed = true;
// In case the timer callback is running, do not create the timer now,
@@ -203,17 +203,17 @@ this.DeferredTask.prototype = {
/**
* Cancels any request for a delayed the execution of the task, though the
* task itself cannot be canceled in case it is already running.
*
* This method stops any currently running timer, thus the delay will restart
* from its original value in case the "arm" method is called again.
*/
- disarm: function () {
+ disarm: function() {
this._armed = false;
if (this._timer) {
// Calling the "cancel" method and discarding the timer reference makes
// sure that the timer callback will not be called later, even if the
// timer thread has already posted the timer event on the main thread.
this._timer.cancel();
this._timer = null;
}
@@ -233,17 +233,17 @@ this.DeferredTask.prototype = {
* execution terminates.
* - If the task is not running and the timer is not armed, the method returns
* a resolved promise.
*
* @return {Promise}
* @resolves After the last execution of the task is finished.
* @rejects Never.
*/
- finalize: function () {
+ finalize: function() {
if (this._finalized) {
throw new Error("The object has been already finalized.");
}
this._finalized = true;
// If the timer is armed, it means that the task is not running but it is
// scheduled for execution. Cancel the timer and run the task immediately.
if (this._timer) {
@@ -257,17 +257,17 @@ this.DeferredTask.prototype = {
}
return Promise.resolve();
},
_finalized: false,
/**
* Timer callback used to run the delayed task.
*/
- _timerCallback: function ()
+ _timerCallback: function()
{
let runningDeferred = Promise.defer();
// All these state changes must occur at the same time directly inside the
// timer callback, to prevent race conditions and to ensure that all the
// methods behave consistently even if called from inside the task. This
// means that the assignment of "this._runningPromise" must complete before
// the task gets a chance to start.
--- a/toolkit/modules/Deprecated.jsm
+++ b/toolkit/modules/Deprecated.jsm
@@ -11,27 +11,27 @@ const Ci = Components.interfaces;
const PREF_DEPRECATION_WARNINGS = "devtools.errorconsole.deprecation_warnings";
Cu.import("resource://gre/modules/Services.jsm");
// A flag that indicates whether deprecation warnings should be logged.
var logWarnings = Services.prefs.getBoolPref(PREF_DEPRECATION_WARNINGS);
Services.prefs.addObserver(PREF_DEPRECATION_WARNINGS,
- function (aSubject, aTopic, aData) {
+ function(aSubject, aTopic, aData) {
logWarnings = Services.prefs.getBoolPref(PREF_DEPRECATION_WARNINGS);
}, false);
/**
* Build a callstack log message.
*
* @param nsIStackFrame aStack
* A callstack to be converted into a string log message.
*/
-function stringifyCallstack (aStack) {
+function stringifyCallstack(aStack) {
// If aStack is invalid, use Components.stack (ignoring the last frame).
if (!aStack || !(aStack instanceof Ci.nsIStackFrame)) {
aStack = Components.stack.caller;
}
let frame = aStack.caller;
let msg = "";
// Get every frame in the callstack.
@@ -52,17 +52,17 @@ this.Deprecated = {
* @param string aUrl
* A URL pointing to documentation describing deprecation
* and the way to address it.
* @param nsIStackFrame aStack
* An optional callstack. If it is not provided a
* snapshot of the current JavaScript callstack will be
* logged.
*/
- warning: function (aText, aUrl, aStack) {
+ warning: function(aText, aUrl, aStack) {
if (!logWarnings) {
return;
}
// If URL is not provided, report an error.
if (!aUrl) {
Cu.reportError("Error in Deprecated.warning: warnings must " +
"provide a URL documenting this deprecation.");
--- a/toolkit/modules/Finder.jsm
+++ b/toolkit/modules/Finder.jsm
@@ -68,26 +68,26 @@ Finder.prototype = {
this._docShell.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebProgress)
.removeProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION);
this._listeners = [];
this._currentFoundRange = this._fastFind = this._docShell = this._previousLink =
this._highlighter = null;
},
- addResultListener: function (aListener) {
+ addResultListener: function(aListener) {
if (this._listeners.indexOf(aListener) === -1)
this._listeners.push(aListener);
},
- removeResultListener: function (aListener) {
+ removeResultListener: function(aListener) {
this._listeners = this._listeners.filter(l => l != aListener);
},
- _notify: function (options) {
+ _notify: function(options) {
if (typeof options.storeResult != "boolean")
options.storeResult = true;
if (options.storeResult) {
this._searchString = options.searchString;
this.clipboardSearchString = options.searchString
}
@@ -182,17 +182,17 @@ Finder.prototype = {
/**
* Used for normal search operations, highlights the first match.
*
* @param aSearchString String to search for.
* @param aLinksOnly Only consider nodes that are links for the search.
* @param aDrawOutline Puts an outline around matched links.
*/
- fastFind: function (aSearchString, aLinksOnly, aDrawOutline) {
+ fastFind: function(aSearchString, aLinksOnly, aDrawOutline) {
this._lastFindResult = this._fastFind.find(aSearchString, aLinksOnly);
let searchString = this._fastFind.searchString;
this._notify({
searchString,
result: this._lastFindResult,
findBackwards: false,
findAgain: false,
drawOutline: aDrawOutline,
@@ -204,17 +204,17 @@ Finder.prototype = {
* Repeat the previous search. Should only be called after a previous
* call to Finder.fastFind.
*
* @param aFindBackwards Controls the search direction:
* true: before current match, false: after current match.
* @param aLinksOnly Only consider nodes that are links for the search.
* @param aDrawOutline Puts an outline around matched links.
*/
- findAgain: function (aFindBackwards, aLinksOnly, aDrawOutline) {
+ findAgain: function(aFindBackwards, aLinksOnly, aDrawOutline) {
this._lastFindResult = this._fastFind.findAgain(aFindBackwards, aLinksOnly);
let searchString = this._fastFind.searchString;
this._notify({
searchString,
result: this._lastFindResult,
findBackwards: aFindBackwards,
findAgain: true,
drawOutline: aDrawOutline,
@@ -346,17 +346,17 @@ Finder.prototype = {
onHighlightAllChange(highlightAll) {
if (this._highlighter)
this._highlighter.onHighlightAllChange(highlightAll);
if (this._iterator)
this._iterator.reset();
},
- keyPress: function (aEvent) {
+ keyPress: function(aEvent) {
let controller = this._getSelectionController(this._getWindow());
switch (aEvent.keyCode) {
case Ci.nsIDOMKeyEvent.DOM_VK_RETURN:
if (this._fastFind.foundLink) {
let view = this._fastFind.foundLink.ownerDocument.defaultView;
this._fastFind.foundLink.dispatchEvent(new view.MouseEvent("click", {
view: view,
@@ -470,25 +470,25 @@ Finder.prototype = {
onIteratorStart() {
this._currentMatchesCountResult = {
total: 0,
current: 0,
_currentFound: false
};
},
- _getWindow: function () {
+ _getWindow: function() {
return this._docShell.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow);
},
/**
* Get the bounding selection rect in CSS px relative to the origin of the
* top-level content document.
*/
- _getResultRect: function () {
+ _getResultRect: function() {
let topWin = this._getWindow();
let win = this._fastFind.currentWindow;
if (!win)
return null;
let selection = win.getSelection();
if (!selection.rangeCount || selection.isCollapsed) {
// The selection can be into an input or a textarea element.
@@ -525,17 +525,17 @@ Finder.prototype = {
let top = frame.getComputedStyle(frame.frameElement, "").borderTopWidth;
scrollX.value += rect.left + parseInt(left, 10);
scrollY.value += rect.top + parseInt(top, 10);
}
let rect = Rect.fromRect(selection.getRangeAt(0).getBoundingClientRect());
return rect.translate(scrollX.value, scrollY.value);
},
- _outlineLink: function (aDrawOutline) {
+ _outlineLink: function(aDrawOutline) {
let foundLink = this._fastFind.foundLink;
// Optimization: We are drawing outlines and we matched
// the same link before, so don't duplicate work.
if (foundLink == this._previousLink && aDrawOutline)
return;
this._restoreOriginalOutline();
@@ -552,17 +552,17 @@ Finder.prototype = {
// Don't set the outline-color, we should always use initial value.
foundLink.style.outline = "1px dotted";
foundLink.style.outlineOffset = "0";
this._previousLink = foundLink;
}
},
- _restoreOriginalOutline: function () {
+ _restoreOriginalOutline: function() {
// Removes the outline around the last found link.
if (this._previousLink) {
this._previousLink.style.outline = this._tmpOutline;
this._previousLink.style.outlineOffset = this._tmpOutlineOffset;
this._previousLink = null;
}
},
--- a/toolkit/modules/Integration.jsm
+++ b/toolkit/modules/Integration.jsm
@@ -135,17 +135,17 @@ this.Integration = new Proxy({}, {
}
return integrationPoint;
},
});
/**
* Individual integration point for which overrides can be registered.
*/
-this.IntegrationPoint = function () {
+this.IntegrationPoint = function() {
this._overrideFns = new Set();
this._combined = {
QueryInterface: function() {
let ex = new Components.Exception(
"Integration objects should not be used with XPCOM because" +
" they change when new overrides are registered.",
Cr.NS_ERROR_NO_INTERFACE);
Cu.reportError(ex);
--- a/toolkit/modules/JSONFile.jsm
+++ b/toolkit/modules/JSONFile.jsm
@@ -44,21 +44,21 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/AsyncShutdown.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "DeferredTask",
"resource://gre/modules/DeferredTask.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
"resource://gre/modules/FileUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
-XPCOMUtils.defineLazyGetter(this, "gTextDecoder", function () {
+XPCOMUtils.defineLazyGetter(this, "gTextDecoder", function() {
return new TextDecoder();
});
-XPCOMUtils.defineLazyGetter(this, "gTextEncoder", function () {
+XPCOMUtils.defineLazyGetter(this, "gTextEncoder", function() {
return new TextEncoder();
});
const FileInputStream =
Components.Constructor("@mozilla.org/network/file-input-stream;1",
"nsIFileInputStream", "init");
/**
--- a/toolkit/modules/LightweightThemeConsumer.jsm
+++ b/toolkit/modules/LightweightThemeConsumer.jsm
@@ -60,49 +60,49 @@ LightweightThemeConsumer.prototype = {
this._enabled = false;
this._lastData = lastData;
},
getData: function() {
return this._enabled ? Cu.cloneInto(this._lastData, this._win) : null;
},
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
if (aTopic != "lightweight-theme-styling-update")
return;
this._update(JSON.parse(aData));
},
- handleEvent: function (aEvent) {
+ handleEvent: function(aEvent) {
let {width, height} = this._win.screen;
if (this._lastScreenWidth != width || this._lastScreenHeight != height) {
this._lastScreenWidth = width;
this._lastScreenHeight = height;
if (!this._active)
return;
this._update(this._lastData);
Services.obs.notifyObservers(this._win, "lightweight-theme-optimized",
JSON.stringify(this._lastData));
}
},
- destroy: function () {
+ destroy: function() {
if (!PrivateBrowsingUtils.isWindowPrivate(this._win) ||
PrivateBrowsingUtils.permanentPrivateBrowsing) {
Services.obs.removeObserver(this, "lightweight-theme-styling-update");
this._win.removeEventListener("resize", this);
}
this._win = this._doc = null;
},
- _update: function (aData) {
+ _update: function(aData) {
if (!aData) {
aData = { headerURL: "", footerURL: "", textcolor: "", accentcolor: "" };
this._lastData = aData;
} else {
this._lastData = aData;
aData = LightweightThemeImageOptimizer.optimize(aData, this._win.screen);
}
if (!this._enabled)
--- a/toolkit/modules/Log.jsm
+++ b/toolkit/modules/Log.jsm
@@ -106,17 +106,17 @@ this.Log = {
}
return interfaces;
},
// Logging helper:
// let logger = Log.repository.getLogger("foo");
// logger.info(Log.enumerateProperties(someObject).join(","));
- enumerateProperties: function (aObject, aExcludeComplexTypes) {
+ enumerateProperties: function(aObject, aExcludeComplexTypes) {
let properties = [];
for (p in aObject) {
try {
if (aExcludeComplexTypes &&
(typeof(aObject[p]) == "object" || typeof(aObject[p]) == "function"))
continue;
properties.push(p + " = " + aObject[p]);
@@ -340,17 +340,17 @@ Logger.prototype = {
* log consumer.
* @param params
* (object) Parameters to be included in the message.
* If _level is included as a key and the corresponding value
* is a number or known level name, the message will be logged
* at the indicated level. If _message is included as a key, the
* value is used as the descriptive text for the message.
*/
- logStructured: function (action, params) {
+ logStructured: function(action, params) {
if (!action) {
throw "An action is required when logging a structured message.";
}
if (!params) {
this.log(this.level, undefined, {"action": action});
return;
}
if (typeof(params) != "object") {
@@ -366,17 +366,17 @@ Logger.prototype = {
} else {
level = this.level;
}
params.action = action;
this.log(level, params._message, params);
},
- log: function (level, string, params) {
+ log: function(level, string, params) {
if (this.level > level)
return;
// Hold off on creating the message object until we actually have
// an appender that's responsible.
let message;
let appenders = this.appenders;
for (let appender of appenders) {
@@ -385,35 +385,35 @@ Logger.prototype = {
}
if (!message) {
message = new LogMessage(this._name, level, string, params);
}
appender.append(message);
}
},
- fatal: function (string, params) {
+ fatal: function(string, params) {
this.log(Log.Level.Fatal, string, params);
},
- error: function (string, params) {
+ error: function(string, params) {
this.log(Log.Level.Error, string, params);
},
- warn: function (string, params) {
+ warn: function(string, params) {
this.log(Log.Level.Warn, string, params);
},
- info: function (string, params) {
+ info: function(string, params) {
this.log(Log.Level.Info, string, params);
},
- config: function (string, params) {
+ config: function(string, params) {
this.log(Log.Level.Config, string, params);
},
- debug: function (string, params) {
+ debug: function(string, params) {
this.log(Log.Level.Debug, string, params);
},
- trace: function (string, params) {
+ trace: function(string, params) {
this.log(Log.Level.Trace, string, params);
}
};
/*
* LoggerRepository
* Implements a hierarchy of Loggers
*/
@@ -467,17 +467,17 @@ LoggerRepository.prototype = {
* Obtain a named Logger.
*
* The returned Logger instance for a particular name is shared among
* all callers. In other words, if two consumers call getLogger("foo"),
* they will both have a reference to the same object.
*
* @return Logger
*/
- getLogger: function (name) {
+ getLogger: function(name) {
if (name in this._loggers)
return this._loggers[name];
this._loggers[name] = new Logger(name, this);
this._updateParents(name);
return this._loggers[name];
},
/**
@@ -492,17 +492,17 @@ LoggerRepository.prototype = {
* up to the original Logger instance. The new prototype has log functions
* that prefix content to each message.
*
* @param name
* (string) The Logger to retrieve.
* @param prefix
* (string) The string to prefix each logged message with.
*/
- getLoggerWithMessagePrefix: function (name, prefix) {
+ getLoggerWithMessagePrefix: function(name, prefix) {
let log = this.getLogger(name);
let proxy = Object.create(log);
proxy.log = (level, string, params) => log.log(level, prefix + string, params);
return proxy;
},
};
@@ -531,17 +531,17 @@ BasicFormatter.prototype = {
/**
* Format the text of a message with optional parameters.
* If the text contains ${identifier}, replace that with
* the value of params[identifier]; if ${}, replace that with
* the entire params object. If no params have been substituted
* into the text, format the entire object and append that
* to the message.
*/
- formatText: function (message) {
+ formatText: function(message) {
let params = message.params;
if (typeof(params) == "undefined") {
return message.message || "";
}
// Defensive handling of non-object params
// We could add a special case for NSRESULT values here...
let pIsObject = (typeof(params) == 'object' || typeof(params) == 'function');
@@ -590,29 +590,29 @@ BasicFormatter.prototype = {
/**
* A formatter that only formats the string message component.
*/
function MessageOnlyFormatter() {
}
MessageOnlyFormatter.prototype = Object.freeze({
__proto__: Formatter.prototype,
- format: function (message) {
+ format: function(message) {
return message.message;
},
});
// Structured formatter that outputs JSON based on message data.
// This formatter will format unstructured messages by supplying
// default values.
function StructuredFormatter() { }
StructuredFormatter.prototype = {
__proto__: Formatter.prototype,
- format: function (logMessage) {
+ format: function(logMessage) {
let output = {
_time: logMessage.time,
_namespace: logMessage.loggerName,
_level: logMessage.levelDesc
};
for (let key in logMessage.params) {
output[key] = logMessage.params[key];
@@ -823,17 +823,17 @@ StorageStreamAppender.prototype = {
if (!this._outputStream) {
return;
}
this.outputStream.close();
this._outputStream = null;
this._ss = null;
},
- doAppend: function (formatted) {
+ doAppend: function(formatted) {
if (!formatted) {
return;
}
try {
this.outputStream.writeString(formatted + "\n");
} catch (ex) {
if (ex.result == Cr.NS_BASE_STREAM_CLOSED) {
// The underlying output stream is closed, so let's open a new one
@@ -863,17 +863,17 @@ function FileAppender(path, formatter) {
// This is a promise exposed for testing/debugging the logger itself.
this._lastWritePromise = null;
}
FileAppender.prototype = {
__proto__: Appender.prototype,
- _openFile: function () {
+ _openFile: function() {
return Task.spawn(function* _openFile() {
try {
this._file = yield OS.File.open(this._path,
{truncate: true});
} catch (err) {
if (err instanceof OS.File.Error) {
this._file = null;
} else {
@@ -886,32 +886,32 @@ FileAppender.prototype = {
_getFile: function() {
if (!this._fileReadyPromise) {
this._fileReadyPromise = this._openFile();
}
return this._fileReadyPromise;
},
- doAppend: function (formatted) {
+ doAppend: function(formatted) {
let array = this._encoder.encode(formatted + "\n");
if (this._file) {
this._lastWritePromise = this._file.write(array);
} else {
this._lastWritePromise = this._getFile().then(_ => {
this._fileReadyPromise = null;
if (this._file) {
return this._file.write(array);
}
return undefined;
});
}
},
- reset: function () {
+ reset: function() {
let fileClosePromise = this._file.close();
return fileClosePromise.then(_ => {
this._file = null;
return OS.File.remove(this._path);
});
}
};
@@ -928,32 +928,32 @@ function BoundedFileAppender(path, forma
this._size = 0;
this._maxSize = maxSize;
this._closeFilePromise = null;
}
BoundedFileAppender.prototype = {
__proto__: FileAppender.prototype,
- doAppend: function (formatted) {
+ doAppend: function(formatted) {
if (!this._removeFilePromise) {
if (this._size < this._maxSize) {
this._size += formatted.length;
return FileAppender.prototype.doAppend.call(this, formatted);
}
this._removeFilePromise = this.reset();
}
this._removeFilePromise.then(_ => {
this._removeFilePromise = null;
this.doAppend(formatted);
});
return undefined;
},
- reset: function () {
+ reset: function() {
let fileClosePromise;
if (this._fileReadyPromise) {
// An attempt to open the file may still be in progress.
fileClosePromise = this._fileReadyPromise.then(_ => {
return this._file.close();
});
} else {
fileClosePromise = this._file.close();
--- a/toolkit/modules/NewTabUtils.jsm
+++ b/toolkit/modules/NewTabUtils.jsm
@@ -18,26 +18,26 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PageThumbs",
"resource://gre/modules/PageThumbs.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "BinarySearch",
"resource://gre/modules/BinarySearch.jsm");
-XPCOMUtils.defineLazyGetter(this, "gPrincipal", function () {
+XPCOMUtils.defineLazyGetter(this, "gPrincipal", function() {
let uri = Services.io.newURI("about:newtab", null, null);
return Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
});
-XPCOMUtils.defineLazyGetter(this, "gCryptoHash", function () {
+XPCOMUtils.defineLazyGetter(this, "gCryptoHash", function() {
return Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
});
-XPCOMUtils.defineLazyGetter(this, "gUnicodeConverter", function () {
+XPCOMUtils.defineLazyGetter(this, "gUnicodeConverter", function() {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = 'utf8';
return converter;
});
// Boolean preferences that control newtab content
const PREF_NEWTAB_ENABLED = "browser.newtabpage.enabled";
@@ -301,30 +301,30 @@ var AllPages = {
this._enabled = null;
break;
case PREF_NEWTAB_ENHANCED:
this._enhanced = null;
break;
}
}
// and all notifications get forwarded to each page.
- this._pages.forEach(function (aPage) {
+ this._pages.forEach(function(aPage) {
aPage.observe(aSubject, aTopic, aData);
}, this);
},
/**
* Adds a preference and new thumbnail observer and turns itself into a
* no-op after the first invokation.
*/
_addObserver: function AllPages_addObserver() {
Services.prefs.addObserver(PREF_NEWTAB_ENABLED, this, true);
Services.prefs.addObserver(PREF_NEWTAB_ENHANCED, this, true);
Services.obs.addObserver(this, "page-thumbnail:create", true);
- this._addObserver = function () {};
+ this._addObserver = function() {};
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference])
};
/**
* Singleton that keeps Grid preferences
@@ -517,17 +517,17 @@ var BlockedLinks = {
/**
* The cached list of blocked links.
*/
_links: null,
/**
* Registers an object that will be notified when the blocked links change.
*/
- addObserver: function (aObserver) {
+ addObserver: function(aObserver) {
this._observers.push(aObserver);
},
/**
* The list of blocked links.
*/
get links() {
if (!this._links)
@@ -643,17 +643,17 @@ var PlacesProvider = {
options.maxResults = this.maxNumLinks;
// Sort by frecency, descending.
options.sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_FRECENCY_DESCENDING
let links = [];
let callback = {
- handleResult: function (aResultSet) {
+ handleResult: function(aResultSet) {
let row;
while ((row = aResultSet.getNextRow())) {
let url = row.getResultByIndex(1);
if (LinkChecker.checkLoadURI(url)) {
let title = row.getResultByIndex(2);
let frecency = row.getResultByIndex(12);
let lastVisitDate = row.getResultByIndex(5);
@@ -663,22 +663,22 @@ var PlacesProvider = {
frecency: frecency,
lastVisitDate: lastVisitDate,
type: "history",
});
}
}
},
- handleError: function (aError) {
+ handleError: function(aError) {
// Should we somehow handle this error?
aCallback([]);
},
- handleCompletion: function (aReason) {
+ handleCompletion: function(aReason) {
// The Places query breaks ties in frecency by place ID descending, but
// that's different from how Links.compareLinks breaks ties, because
// compareLinks doesn't have access to place IDs. It's very important
// that the initial list of links is sorted in the same order imposed by
// compareLinks, because Links uses compareLinks to perform binary
// searches on the list. So, ensure the list is so ordered.
let i = 1;
let outOfOrder = [];
@@ -852,17 +852,17 @@ var Links = {
/**
* A list of objects that are observing links updates.
*/
_observers: [],
/**
* Registers an object that will be notified when links updates.
*/
- addObserver: function (aObserver) {
+ addObserver: function(aObserver) {
this._observers.push(aObserver);
},
/**
* Adds a link provider.
* @param aProvider The link provider.
*/
addProvider: function Links_addProvider(aProvider) {
@@ -929,17 +929,17 @@ var Links = {
let sites = new Set();
for (let link of pinnedLinks) {
if (link)
sites.add(NewTabUtils.extractSite(link.url));
}
// Filter blocked and pinned links and duplicate base domains.
- links = links.filter(function (link) {
+ links = links.filter(function(link) {
let site = NewTabUtils.extractSite(link.url);
if (site == null || sites.has(site))
return false;
sites.add(site);
return !BlockedLinks.isBlocked(link) && !PinnedLinks.isPinned(link);
});
@@ -1053,17 +1053,17 @@ var Links = {
/**
* Calls getLinks on the given provider and populates our cache for it.
* @param aProvider The provider whose cache will be populated.
* @param aCallback The callback to call when finished.
* @param aForce When true, populates the provider's cache even when it's
* already filled.
*/
- _populateProviderCache: function (aProvider, aCallback, aForce) {
+ _populateProviderCache: function(aProvider, aCallback, aForce) {
let cache = this._providers.get(aProvider);
let createCache = !cache;
if (createCache) {
cache = {
// Start with a resolved promise.
populatePromise: new Promise(resolve => resolve()),
};
this._providers.set(aProvider, cache);
@@ -1253,17 +1253,17 @@ var Links = {
/**
* Implements the nsIObserver interface to get notified about browser history
* sanitization.
*/
observe: function Links_observe(aSubject, aTopic, aData) {
// Make sure to update open about:newtab instances. If there are no opened
// pages we can just wait for the next new tab to populate the cache again.
if (AllPages.length && AllPages.enabled)
- this.populateCache(function () { AllPages.update() }, true);
+ this.populateCache(function() { AllPages.update() }, true);
else
this.resetCache();
},
_callObservers(methodName, ...args) {
for (let obs of this._observers) {
if (typeof(obs[methodName]) == "function") {
try {
@@ -1276,17 +1276,17 @@ var Links = {
},
/**
* Adds a sanitization observer and turns itself into a no-op after the first
* invokation.
*/
_addObserver: function Links_addObserver() {
Services.obs.addObserver(this, "browser:purge-session-history", true);
- this._addObserver = function () {};
+ this._addObserver = function() {};
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
Ci.nsISupportsWeakReference])
};
Links.compareLinks = Links.compareLinks.bind(Links);
@@ -1370,17 +1370,17 @@ var ExpirationFilter = {
filterForThumbnailExpiration:
function ExpirationFilter_filterForThumbnailExpiration(aCallback) {
if (!AllPages.enabled) {
aCallback([]);
return;
}
- Links.populateCache(function () {
+ Links.populateCache(function() {
let urls = [];
// Add all URLs to the list that we want to keep thumbnails for.
for (let link of Links.getLinks().slice(0, 25)) {
if (link && link.url)
urls.push(link.url);
}
@@ -1457,17 +1457,17 @@ this.NewTabUtils = {
* Restores all sites that have been removed from the grid.
*/
restore: function NewTabUtils_restore() {
Storage.clear();
Links.resetCache();
PinnedLinks.resetCache();
BlockedLinks.resetCache();
- Links.populateCache(function () {
+ Links.populateCache(function() {
AllPages.update();
}, true);
},
/**
* Undoes all sites that have been removed from the grid and keep the pinned
* tabs.
* @param aCallback the callback method.
--- a/toolkit/modules/PopupNotifications.jsm
+++ b/toolkit/modules/PopupNotifications.jsm
@@ -464,17 +464,17 @@ PopupNotifications.prototype = {
* so that we can update the active notifications accordingly.
*/
locationChange: function PopupNotifications_locationChange(aBrowser) {
if (!aBrowser)
throw "PopupNotifications_locationChange: invalid browser";
let notifications = this._getNotificationsForBrowser(aBrowser);
- notifications = notifications.filter(function (notification) {
+ notifications = notifications.filter(function(notification) {
// The persistWhileVisible option allows an open notification to persist
// across location changes
if (notification.options.persistWhileVisible &&
this.isPanelOpen) {
if ("persistence" in notification.options &&
notification.options.persistence)
notification.options.persistence--;
return true;
@@ -518,33 +518,33 @@ PopupNotifications.prototype = {
this._remove(notification);
if (this._isActiveBrowser(notification.browser)) {
let notifications = this._getNotificationsForBrowser(notification.browser);
this._update(notifications);
}
},
- handleEvent: function (aEvent) {
+ handleEvent: function(aEvent) {
switch (aEvent.type) {
case "popuphidden":
this._onPopupHidden(aEvent);
break;
case "activate":
case "TabSelect":
let self = this;
// This is where we could detect if the panel is dismissed if the page
// was switched. Unfortunately, the user usually has clicked elsewhere
// at this point so this value only gets recorded for programmatic
// reasons, like the "Learn More" link being clicked and resulting in a
// tab switch.
this.nextDismissReason = TELEMETRY_STAT_DISMISSAL_LEAVE_PAGE;
// setTimeout(..., 0) needed, otherwise openPopup from "activate" event
// handler results in the popup being hidden again for some reason...
- this.window.setTimeout(function () {
+ this.window.setTimeout(function() {
self._update();
}, 0);
break;
case "click":
case "keypress":
this._onIconBoxCommand(aEvent);
break;
}
@@ -610,17 +610,17 @@ PopupNotifications.prototype = {
this._ignoreDismissal = deferred;
this.panel.hidePopup();
return deferred.promise;
},
/**
* Removes all notifications from the notification popup.
*/
- _clearPanel: function () {
+ _clearPanel: function() {
let popupnotification;
while ((popupnotification = this.panel.lastChild)) {
this.panel.removeChild(popupnotification);
// If this notification was provided by the chrome document rather than
// created ad hoc, move it back to where we got it from.
let originalParent = gNotificationParents.get(popupnotification);
if (originalParent) {
@@ -646,17 +646,17 @@ PopupNotifications.prototype = {
}
},
_refreshPanel: function PopupNotifications_refreshPanel(notificationsToShow) {
this._clearPanel();
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
- notificationsToShow.forEach(function (n) {
+ notificationsToShow.forEach(function(n) {
let doc = this.window.document;
// Append "-notification" to the ID to try to avoid ID conflicts with other stuff
// in the document.
let popupnotificationID = n.id + "-notification";
// If the chrome document provides a popupnotification with this id, use
// that. Otherwise create it ad-hoc.
@@ -716,17 +716,17 @@ PopupNotifications.prototype = {
} else
popupnotification.removeAttribute("origin");
popupnotification.notification = n;
if (n.secondaryActions) {
let telemetryStatId = TELEMETRY_STAT_ACTION_2;
- n.secondaryActions.forEach(function (a) {
+ n.secondaryActions.forEach(function(a) {
let item = doc.createElementNS(XUL_NS, "menuitem");
item.setAttribute("label", a.label);
item.setAttribute("accesskey", a.accessKey);
item.notification = n;
item.action = a;
popupnotification.appendChild(item);
@@ -811,17 +811,17 @@ PopupNotifications.prototype = {
});
if (!notificationsToShow.length)
return;
let notificationIds = notificationsToShow.map(n => n.id);
this._refreshPanel(notificationsToShow);
if (this.isPanelOpen && this._currentAnchorElement == anchorElement) {
- notificationsToShow.forEach(function (n) {
+ notificationsToShow.forEach(function(n) {
this._fireCallback(n, NOTIFICATION_EVENT_SHOWN);
}, this);
// Let tests know that the panel was updated and what notifications it was
// updated with so that tests can wait for the correct notifications to be
// added.
let event = new this.window.CustomEvent("PanelUpdated",
{"detail": notificationIds});
this.panel.dispatchEvent(event);
@@ -844,17 +844,17 @@ PopupNotifications.prototype = {
anchorElement = selectedTab; // null
}
this._currentAnchorElement = anchorElement;
// On OS X and Linux we need a different panel arrow color for
// click-to-play plugins, so copy the popupid and use css.
this.panel.setAttribute("popupid", this.panel.firstChild.getAttribute("popupid"));
- notificationsToShow.forEach(function (n) {
+ notificationsToShow.forEach(function(n) {
// Record that the notification was actually displayed on screen.
// Notifications that were opened a second time or that were originally
// shown with "options.dismissed" will be recorded in a separate bucket.
n._recordTelemetryStat(TELEMETRY_STAT_OFFERED);
// Remember the time the notification was shown for the security delay.
n.timeShown = this.window.performance.now();
}, this);
@@ -871,21 +871,21 @@ PopupNotifications.prototype = {
// By targeting the panel's parent and using a capturing listener, we
// can have our listener called before others waiting for the panel to
// be shown (which probably expect the panel to be fully initialized)
target = target.parentNode;
}
if (this._popupshownListener) {
target.removeEventListener("popupshown", this._popupshownListener, true);
}
- this._popupshownListener = function (e) {
+ this._popupshownListener = function(e) {
target.removeEventListener("popupshown", this._popupshownListener, true);
this._popupshownListener = null;
- notificationsToShow.forEach(function (n) {
+ notificationsToShow.forEach(function(n) {
this._fireCallback(n, NOTIFICATION_EVENT_SHOWN);
}, this);
// These notifications are used by tests to know when all the processing
// required to display the panel has happened.
this.panel.dispatchEvent(new this.window.CustomEvent("Shown"));
let event = new this.window.CustomEvent("PanelUpdated",
{"detail": notificationIds});
this.panel.dispatchEvent(event);
@@ -927,28 +927,28 @@ PopupNotifications.prototype = {
if (anchor.parentNode == this.iconBox)
continue;
useIconBox = false;
break;
}
}
// Filter out notifications that have been dismissed.
- let notificationsToShow = notifications.filter(function (n) {
+ let notificationsToShow = notifications.filter(function(n) {
return !n.dismissed && !n.options.neverShow;
});
if (useIconBox) {
// Hide icons of the previous tab.
this._hideIcons();
}
if (haveNotifications) {
// Also filter out notifications that are for a different anchor.
- notificationsToShow = notificationsToShow.filter(function (n) {
+ notificationsToShow = notificationsToShow.filter(function(n) {
return anchors.has(n.anchorElement);
});
if (useIconBox) {
this._showIcons(notifications);
this.iconBox.hidden = false;
// Make sure that panels can only be attached to anchors of shown
// notifications inside an iconBox.
@@ -1055,17 +1055,17 @@ PopupNotifications.prototype = {
if (notification.anchorElement)
anchors.add(notification.anchorElement)
}
if (defaultAnchor && !anchors.size)
anchors.add(defaultAnchor);
return anchors;
},
- _isActiveBrowser: function (browser) {
+ _isActiveBrowser: function(browser) {
// We compare on frameLoader instead of just comparing the
// selectedBrowser and browser directly because browser tabs in
// Responsive Design Mode put the actual web content into a
// mozbrowser iframe and proxy property read/write and method
// calls from the tab to that iframe. This is so that attempts
// to reload the tab end up reloading the content in
// Responsive Design Mode, and not the Responsive Design Mode
// viewer itself.
@@ -1115,17 +1115,17 @@ PopupNotifications.prototype = {
this._reshowNotifications(anchor);
},
_reshowNotifications: function PopupNotifications_reshowNotifications(anchor, browser) {
// Mark notifications anchored to this anchor as un-dismissed
browser = browser || this.tabbrowser.selectedBrowser;
let notifications = this._getNotificationsForBrowser(browser);
- notifications.forEach(function (n) {
+ notifications.forEach(function(n) {
if (n.anchorElement == anchor)
n.dismissed = false;
});
if (this._isActiveBrowser(browser)) {
// ...and then show them.
this._update(notifications, anchor);
}
@@ -1210,17 +1210,17 @@ PopupNotifications.prototype = {
_dismissOrRemoveCurrentNotifications: function() {
let browser = this.panel.firstChild &&
this.panel.firstChild.notification.browser;
if (!browser)
return;
let notifications = this._getNotificationsForBrowser(browser);
// Mark notifications as dismissed and call dismissal callbacks
- Array.forEach(this.panel.childNodes, function (nEl) {
+ Array.forEach(this.panel.childNodes, function(nEl) {
let notificationObj = nEl.notification;
// Never call a dismissal handler on a notification that's been removed.
if (notifications.indexOf(notificationObj) == -1)
return;
// Record the time of the first notification dismissal if the main action
// was not triggered in the meantime.
let timeSinceShown = this.window.performance.now() - notificationObj.timeShown;
--- a/toolkit/modules/ProfileAge.jsm
+++ b/toolkit/modules/ProfileAge.jsm
@@ -19,17 +19,17 @@ Cu.import("resource://services-common/ut
* This is separate from the provider to simplify testing and enable extraction
* to a shared location in the future.
*/
this.ProfileAge = function(profile, log) {
this.profilePath = profile || OS.Constants.Path.profileDir;
if (!this.profilePath) {
throw new Error("No profile directory.");
}
- this._log = log || {"debug": function (s) { dump(s + "\n"); }};
+ this._log = log || {"debug": function(s) { dump(s + "\n"); }};
}
this.ProfileAge.prototype = {
/**
* There are three ways we can get our creation time:
*
* 1. From our own saved value (to avoid redundant work).
* 2. From the on-disk JSON file.
* 3. By calculating it from the filesystem.
@@ -58,56 +58,56 @@ this.ProfileAge.prototype = {
.then(onSuccess.bind(this),
onFailure.bind(this));
},
/**
* Explicitly make `file`, a filename, a full path
* relative to our profile path.
*/
- getPath: function (file) {
+ getPath: function(file) {
return OS.Path.join(this.profilePath, file);
},
/**
* Return a promise which resolves to the JSON contents
* of the time file, using the already read value if possible.
*/
- getTimes: function (file = "times.json") {
+ getTimes: function(file = "times.json") {
if (this._times) {
return Promise.resolve(this._times);
}
return this.readTimes(file).then(
times => {
return this.times = times || {};
}
);
},
/**
* Return a promise which resolves to the JSON contents
* of the time file in this accessor's profile.
*/
- readTimes: function (file = "times.json") {
+ readTimes: function(file = "times.json") {
return CommonUtils.readJSON(this.getPath(file));
},
/**
* Return a promise representing the writing of `contents`
* to `file` in the specified profile.
*/
- writeTimes: function (contents, file = "times.json") {
+ writeTimes: function(contents, file = "times.json") {
return CommonUtils.writeJSON(contents, this.getPath(file));
},
/**
* Merge existing contents with a 'created' field, writing them
* to the specified file. Promise, naturally.
*/
- computeAndPersistCreated: function (existingContents, file = "times.json") {
+ computeAndPersistCreated: function(existingContents, file = "times.json") {
let path = this.getPath(file);
function onOldest(oldest) {
let contents = existingContents || {};
contents.created = oldest;
this._times = contents;
return this.writeTimes(contents, path)
.then(function onSuccess() {
return oldest;
@@ -117,17 +117,17 @@ this.ProfileAge.prototype = {
return this.getOldestProfileTimestamp()
.then(onOldest.bind(this));
},
/**
* Traverse the contents of the profile directory, finding the oldest file
* and returning its creation timestamp.
*/
- getOldestProfileTimestamp: function () {
+ getOldestProfileTimestamp: function() {
let self = this;
let oldest = Date.now() + 1000;
let iterator = new OS.File.DirectoryIterator(this.profilePath);
self._log.debug("Iterating over profile " + this.profilePath);
if (!iterator) {
throw new Error("Unable to fetch oldest profile entry: no profile iterator.");
}
@@ -180,17 +180,17 @@ this.ProfileAge.prototype = {
/**
* Record (and persist) when a profile reset happened. We just store a
* single value - the timestamp of the most recent reset - but there is scope
* to keep a list of reset times should our health-reporter successor
* be able to make use of that.
* Returns a promise that is resolved once the file has been written.
*/
- recordProfileReset: function (time = Date.now(), file = "times.json") {
+ recordProfileReset: function(time = Date.now(), file = "times.json") {
return this.getTimes(file).then(
times => {
times.reset = time;
return this.writeTimes(times, file);
}
);
},
--- a/toolkit/modules/Promise-backend.js
+++ b/toolkit/modules/Promise-backend.js
@@ -427,17 +427,17 @@ this.Promise = function Promise(aExecuto
* - If the callback returns a promise, the new promise will
* eventually assume the same state as the returned promise.
*
* @note If the aOnResolve callback throws an exception, the aOnReject
* callback is not invoked. You can register a rejection callback on
* the returned promise instead, to process any exception occurred in
* either of the callbacks registered on this promise.
*/
-Promise.prototype.then = function (aOnResolve, aOnReject)
+Promise.prototype.then = function(aOnResolve, aOnReject)
{
let handler = new Handler(this, aOnResolve, aOnReject);
this[N_INTERNALS].handlers.push(handler);
// Ensure the handler is scheduled for processing if this promise is already
// resolved or rejected.
if (this[N_INTERNALS].status != STATUS_PENDING) {
@@ -461,46 +461,46 @@ Promise.prototype.then = function (aOnRe
*
* @param aOnReject
* The rejection handler.
*
* @return A new pending promise returned.
*
* @see Promise.prototype.then
*/
-Promise.prototype.catch = function (aOnReject)
+Promise.prototype.catch = function(aOnReject)
{
return this.then(undefined, aOnReject);
};
/**
* Creates a new pending promise and provides methods to resolve or reject it.
*
* @return A new object, containing the new promise in the "promise" property,
* and the methods to change its state in the "resolve" and "reject"
* properties. See the Deferred documentation for details.
*/
-Promise.defer = function ()
+Promise.defer = function()
{
return new Deferred();
};
/**
* Creates a new promise resolved with the specified value, or propagates the
* state of an existing promise.
*
* @param aValue
* If this value is not a promise, including "undefined", it becomes
* the resolution value of the returned promise. If this value is a
* promise, then the returned promise will eventually assume the same
* state as the provided promise.
*
* @return A promise that can be pending, resolved, or rejected.
*/
-Promise.resolve = function (aValue)
+Promise.resolve = function(aValue)
{
if (aValue && typeof(aValue) == "function" && aValue.isAsyncFunction) {
throw new TypeError(
"Cannot resolve a promise with an async function. " +
"You should either invoke the async function first " +
"or use 'Task.spawn' instead of 'Task.async' to start " +
"the Task and return its promise.");
}
@@ -521,17 +521,17 @@ Promise.resolve = function (aValue)
* exception handling.
*
* @return A rejected promise.
*
* @note The aReason argument should not be a promise. Using a rejected
* promise for the value of aReason would make the rejection reason
* equal to the rejected promise itself, and not its rejection reason.
*/
-Promise.reject = function (aReason)
+Promise.reject = function(aReason)
{
return new Promise((_, aReject) => aReject(aReason));
};
/**
* Returns a promise that is resolved or rejected when all values are
* resolved or any is rejected.
*
@@ -542,17 +542,17 @@ Promise.reject = function (aReason)
*
* @return A new promise that is fulfilled when all values are resolved or
* that is rejected when any of the values are rejected. Its
* resolution value will be an array of all resolved values in the
* given order, or undefined if aValues is an empty array. The reject
* reason will be forwarded from the first promise in the list of
* given promises to be rejected.
*/
-Promise.all = function (aValues)
+Promise.all = function(aValues)
{
if (aValues == null || typeof(aValues[Symbol.iterator]) != "function") {
throw new Error("Promise.all() expects an iterable.");
}
return new Promise((resolve, reject) => {
let values = Array.isArray(aValues) ? aValues : [...aValues];
let countdown = values.length;
@@ -593,17 +593,17 @@ Promise.all = function (aValues)
* Iterable of values or promises that may be pending, resolved, or
* rejected. When any is resolved or rejected, the returned promise will
* be resolved or rejected as to the given value or reason.
*
* @return A new promise that is fulfilled when any values are resolved or
* rejected. Its resolution value will be forwarded from the resolution
* value or rejection reason.
*/
-Promise.race = function (aValues)
+Promise.race = function(aValues)
{
if (aValues == null || typeof(aValues[Symbol.iterator]) != "function") {
throw new Error("Promise.race() expects an iterable.");
}
return new Promise((resolve, reject) => {
for (let value of aValues) {
Promise.resolve(value).then(resolve, reject);
@@ -683,17 +683,17 @@ this.PromiseWalker = {
* @param aPromise
* Promise that needs to change state. If this is already resolved or
* rejected, this method has no effect.
* @param aStatus
* New desired status, either STATUS_RESOLVED or STATUS_REJECTED.
* @param aValue
* Associated resolution value or rejection reason.
*/
- completePromise: function (aPromise, aStatus, aValue)
+ completePromise: function(aPromise, aStatus, aValue)
{
// Do nothing if the promise is already resolved or rejected.
if (aPromise[N_INTERNALS].status != STATUS_PENDING) {
return;
}
// Resolving with another promise will cause this promise to eventually
// assume the state of the provided promise.
@@ -758,17 +758,17 @@ this.PromiseWalker = {
/**
* Schedules the resolution or rejection handlers registered on the provided
* promise for processing.
*
* @param aPromise
* Resolved or rejected promise whose handlers should be processed. It
* is expected that this promise has at least one handler to process.
*/
- schedulePromise: function (aPromise)
+ schedulePromise: function(aPromise)
{
// Migrate the handlers from the provided promise to the global list.
for (let handler of aPromise[N_INTERNALS].handlers) {
this.handlers.push(handler);
}
aPromise[N_INTERNALS].handlers.length = 0;
// Schedule the walker loop on the next tick of the event loop.
@@ -785,17 +785,17 @@ this.PromiseWalker = {
/**
* Processes all the known handlers during this tick of the event loop. This
* eager processing is done to avoid unnecessarily exiting and re-entering the
* JavaScript context for each handler on a resolved or rejected promise.
*
* This function is called with "this" bound to the PromiseWalker object.
*/
- walkerLoop: function ()
+ walkerLoop: function()
{
// If there is more than one handler waiting, reschedule the walker loop
// immediately. Otherwise, use walkerLoopScheduled to tell schedulePromise()
// to reschedule the loop if it adds more handlers to the queue. This makes
// this walker resilient to the case where one handler does not return, but
// starts a nested event loop. In that case, the newly scheduled walker will
// take over. In the common case, the newly scheduled walker will be invoked
// after this one has returned, with no actual handler to process. This
--- a/toolkit/modules/PropertyListUtils.jsm
+++ b/toolkit/modules/PropertyListUtils.jsm
@@ -780,17 +780,17 @@ XMLPropertyListReader.prototype = {
* Target object. (dict/Map)
* @param name
* Name of operation to be invoked on target.
* @param key
* Key to be set, retrieved or deleted. Keys are checked for laziness.
* @return Returns value of "name" property of target by default. Otherwise returns
* updated target.
*/
-function LazyMapProxyHandler () {
+function LazyMapProxyHandler() {
return {
_lazyGetters: new Set(),
get: function(target, name) {
switch (name) {
case "setAsLazyGetter":
return (key, value) => {
this._lazyGetters.add(key);
target.set(key, value);
--- a/toolkit/modules/RemoteController.jsm
+++ b/toolkit/modules/RemoteController.jsm
@@ -68,17 +68,17 @@ RemoteController.prototype = {
this._browser.messageManager.sendAsyncMessage(
"ControllerCommands:DoWithParams", cmd);
},
getSupportedCommands: function(aCount, aCommands) {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
},
- onEvent: function () {},
+ onEvent: function() {},
// This is intended to be called from the remote-browser binding to update
// the enabled and disabled commands.
enableDisableCommands: function(aAction,
aEnabledLength, aEnabledCommands,
aDisabledLength, aDisabledCommands) {
// Clear the list first
this._supportedCommands = { };
--- a/toolkit/modules/RemoteFinder.jsm
+++ b/toolkit/modules/RemoteFinder.jsm
@@ -46,25 +46,25 @@ RemoteFinder.prototype = {
this._messageManager.addMessageListener("Finder:CurrentSelectionResult", this);
this._messageManager.addMessageListener("Finder:HighlightFinished", this);
// Ideally listeners would have removed themselves but that doesn't happen
// right now
this._listeners.clear();
},
- addResultListener: function (aListener) {
+ addResultListener: function(aListener) {
this._listeners.add(aListener);
},
- removeResultListener: function (aListener) {
+ removeResultListener: function(aListener) {
this._listeners.delete(aListener);
},
- receiveMessage: function (aMessage) {
+ receiveMessage: function(aMessage) {
// Only Finder:Result messages have the searchString field.
let callback;
let params;
switch (aMessage.name) {
case "Finder:Result":
this._searchString = aMessage.data.searchString;
// The rect stops being a Geometry.jsm:Rect over IPC.
if (aMessage.data.rect) {
@@ -121,91 +121,91 @@ RemoteFinder.prototype = {
this._browser.messageManager.sendAsyncMessage("Finder:EntireWord",
{ entireWord: aEntireWord });
},
getInitialSelection: function() {
this._browser.messageManager.sendAsyncMessage("Finder:GetInitialSelection", {});
},
- fastFind: function (aSearchString, aLinksOnly, aDrawOutline) {
+ fastFind: function(aSearchString, aLinksOnly, aDrawOutline) {
this._browser.messageManager.sendAsyncMessage("Finder:FastFind",
{ searchString: aSearchString,
linksOnly: aLinksOnly,
drawOutline: aDrawOutline });
},
- findAgain: function (aFindBackwards, aLinksOnly, aDrawOutline) {
+ findAgain: function(aFindBackwards, aLinksOnly, aDrawOutline) {
this._browser.messageManager.sendAsyncMessage("Finder:FindAgain",
{ findBackwards: aFindBackwards,
linksOnly: aLinksOnly,
drawOutline: aDrawOutline });
},
- highlight: function (aHighlight, aWord, aLinksOnly) {
+ highlight: function(aHighlight, aWord, aLinksOnly) {
this._browser.messageManager.sendAsyncMessage("Finder:Highlight",
{ highlight: aHighlight,
linksOnly: aLinksOnly,
word: aWord });
},
- enableSelection: function () {
+ enableSelection: function() {
this._browser.messageManager.sendAsyncMessage("Finder:EnableSelection");
},
- removeSelection: function () {
+ removeSelection: function() {
this._browser.messageManager.sendAsyncMessage("Finder:RemoveSelection");
},
- focusContent: function () {
+ focusContent: function() {
// Allow Finder listeners to cancel focusing the content.
for (let l of this._listeners) {
try {
if ("shouldFocusContent" in l &&
!l.shouldFocusContent())
return;
} catch (ex) {
Cu.reportError(ex);
}
}
this._browser.focus();
this._browser.messageManager.sendAsyncMessage("Finder:FocusContent");
},
- onFindbarClose: function () {
+ onFindbarClose: function() {
this._browser.messageManager.sendAsyncMessage("Finder:FindbarClose");
},
- onFindbarOpen: function () {
+ onFindbarOpen: function() {
this._browser.messageManager.sendAsyncMessage("Finder:FindbarOpen");
},
onModalHighlightChange: function(aUseModalHighlight) {
this._browser.messageManager.sendAsyncMessage("Finder:ModalHighlightChange", {
useModalHighlight: aUseModalHighlight
});
},
onHighlightAllChange: function(aHighlightAll) {
this._browser.messageManager.sendAsyncMessage("Finder:HighlightAllChange", {
highlightAll: aHighlightAll
});
},
- keyPress: function (aEvent) {
+ keyPress: function(aEvent) {
this._browser.messageManager.sendAsyncMessage("Finder:KeyPress",
{ keyCode: aEvent.keyCode,
ctrlKey: aEvent.ctrlKey,
metaKey: aEvent.metaKey,
altKey: aEvent.altKey,
shiftKey: aEvent.shiftKey });
},
- requestMatchesCount: function (aSearchString, aLinksOnly) {
+ requestMatchesCount: function(aSearchString, aLinksOnly) {
this._browser.messageManager.sendAsyncMessage("Finder:MatchesCount",
{ searchString: aSearchString,
linksOnly: aLinksOnly });
}
}
function RemoteFinderListener(global) {
let {Finder} = Cu.import("resource://gre/modules/Finder.jsm", {});
@@ -233,31 +233,31 @@ RemoteFinderListener.prototype = {
"Finder:FocusContent",
"Finder:FindbarClose",
"Finder:FindbarOpen",
"Finder:KeyPress",
"Finder:MatchesCount",
"Finder:ModalHighlightChange"
],
- onFindResult: function (aData) {
+ onFindResult: function(aData) {
this._global.sendAsyncMessage("Finder:Result", aData);
},
// When the child receives messages with results of requestMatchesCount,
// it passes them forward to the parent.
- onMatchesCountResult: function (aData) {
+ onMatchesCountResult: function(aData) {
this._global.sendAsyncMessage("Finder:MatchesResult", aData);
},
onHighlightFinished: function(aData) {
this._global.sendAsyncMessage("Finder:HighlightFinished", aData);
},
- receiveMessage: function (aMessage) {
+ receiveMessage: function(aMessage) {
let data = aMessage.data;
switch (aMessage.name) {
case "Finder:CaseSensitive":
this._finder.caseSensitive = data.caseSensitive;
break;
case "Finder:EntireWord":
--- a/toolkit/modules/RemoteSecurityUI.jsm
+++ b/toolkit/modules/RemoteSecurityUI.jsm
@@ -22,13 +22,13 @@ RemoteSecurityUI.prototype = {
// nsISSLStatusProvider
get SSLStatus() { return this._SSLStatus; },
// nsISecureBrowserUI
get state() { return this._state; },
get tooltipText() { return ""; },
- _update: function (aStatus, aState) {
+ _update: function(aStatus, aState) {
this._SSLStatus = aStatus;
this._state = aState;
}
};
--- a/toolkit/modules/RemoteWebProgress.jsm
+++ b/toolkit/modules/RemoteWebProgress.jsm
@@ -59,26 +59,26 @@ RemoteWebProgress.prototype = {
NOTIFY_ALL: 0x000001ff,
get isLoadingDocument() { return this._isLoadingDocument },
get DOMWindow() { return this._DOMWindow; },
get DOMWindowID() { return this._DOMWindowID; },
get isTopLevel() { return this._isTopLevel },
get loadType() { return this._loadType; },
- addProgressListener: function (aListener) {
+ addProgressListener: function(aListener) {
this._manager.addProgressListener(aListener);
},
- removeProgressListener: function (aListener) {
+ removeProgressListener: function(aListener) {
this._manager.removeProgressListener(aListener);
}
};
-function RemoteWebProgressManager (aBrowser) {
+function RemoteWebProgressManager(aBrowser) {
this._topLevelWebProgress = new RemoteWebProgress(this, true);
this._progressListeners = [];
this.swapBrowser(aBrowser);
}
RemoteWebProgressManager.argumentsForAddonListener = function(kind, args) {
function checkType(arg, typ) {
@@ -129,40 +129,40 @@ RemoteWebProgressManager.prototype = {
this._messageManager.addMessageListener("Content:ProgressChange", this);
this._messageManager.addMessageListener("Content:LoadURIResult", this);
},
get topLevelWebProgress() {
return this._topLevelWebProgress;
},
- addProgressListener: function (aListener) {
+ addProgressListener: function(aListener) {
let listener = aListener.QueryInterface(Ci.nsIWebProgressListener);
this._progressListeners.push(listener);
},
- removeProgressListener: function (aListener) {
+ removeProgressListener: function(aListener) {
this._progressListeners =
this._progressListeners.filter(l => l != aListener);
},
- _fixSSLStatusAndState: function (aStatus, aState) {
+ _fixSSLStatusAndState: function(aStatus, aState) {
let deserialized = null;
if (aStatus) {
let helper = Cc["@mozilla.org/network/serialization-helper;1"]
.getService(Components.interfaces.nsISerializationHelper);
deserialized = helper.deserializeObject(aStatus)
deserialized.QueryInterface(Ci.nsISSLStatus);
}
return [deserialized, aState];
},
- setCurrentURI: function (aURI) {
+ setCurrentURI: function(aURI) {
// This function is simpler than nsDocShell::SetCurrentURI since
// it doesn't have to deal with child docshells.
let remoteWebNav = this._browser._remoteWebNavigationImpl;
remoteWebNav._currentURI = aURI;
let webProgress = this.topLevelWebProgress;
for (let p of this._progressListeners) {
p.onLocationChange(webProgress, null, aURI);
@@ -176,17 +176,17 @@ RemoteWebProgressManager.prototype = {
p[methodName].apply(p, args);
} catch (ex) {
Cu.reportError("RemoteWebProgress failed to call " + methodName + ": " + ex + "\n");
}
}
}
},
- receiveMessage: function (aMessage) {
+ receiveMessage: function(aMessage) {
let json = aMessage.json;
let objects = aMessage.objects;
// This message is a custom one we send as a result of a loadURI call.
// It shouldn't go through the same processing as all the forwarded
// webprogresslistener messages.
if (aMessage.name == "Content:LoadURIResult") {
this._browser.inLoadURI = false;
return;
--- a/toolkit/modules/SelectContentHelper.jsm
+++ b/toolkit/modules/SelectContentHelper.jsm
@@ -25,17 +25,17 @@ const kStateHover = 0x00000004; // NS_EV
// entirely within this module, and is read-only accessible
// via SelectContentHelper.open.
var gOpen = false;
this.EXPORTED_SYMBOLS = [
"SelectContentHelper"
];
-this.SelectContentHelper = function (aElement, aOptions, aGlobal) {
+this.SelectContentHelper = function(aElement, aOptions, aGlobal) {
this.element = aElement;
this.initialSelection = aElement[aElement.selectedIndex] || null;
this.global = aGlobal;
this.closedWithEnter = false;
this.isOpenedViaTouch = aOptions.isOpenedViaTouch;
this.init();
this.showDropDown();
this._updateTimer = new DeferredTask(this._update.bind(this), 0);
--- a/toolkit/modules/Services.jsm
+++ b/toolkit/modules/Services.jsm
@@ -8,37 +8,37 @@ const Ci = Components.interfaces;
const Cc = Components.classes;
const Cr = Components.results;
Components.utils.import("resource://gre/modules/AppConstants.jsm");
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
this.Services = {};
-XPCOMUtils.defineLazyGetter(Services, "prefs", function () {
+XPCOMUtils.defineLazyGetter(Services, "prefs", function() {
return Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService)
.QueryInterface(Ci.nsIPrefBranch);
});
-XPCOMUtils.defineLazyGetter(Services, "appinfo", function () {
+XPCOMUtils.defineLazyGetter(Services, "appinfo", function() {
let appinfo = Cc["@mozilla.org/xre/app-info;1"]
.getService(Ci.nsIXULRuntime);
try {
appinfo.QueryInterface(Ci.nsIXULAppInfo);
} catch (ex) {
// Not all applications implement nsIXULAppInfo (e.g. xpcshell doesn't).
if (!(ex instanceof Components.Exception) || ex.result != Cr.NS_NOINTERFACE) {
throw ex;
}
}
return appinfo;
});
-XPCOMUtils.defineLazyGetter(Services, "dirsvc", function () {
+XPCOMUtils.defineLazyGetter(Services, "dirsvc", function() {
return Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIDirectoryService)
.QueryInterface(Ci.nsIProperties);
});
if (AppConstants.MOZ_CRASHREPORTER) {
XPCOMUtils.defineLazyGetter(Services, "crashmanager", () => {
let ns = {};
--- a/toolkit/modules/SessionRecorder.jsm
+++ b/toolkit/modules/SessionRecorder.jsm
@@ -53,17 +53,17 @@ const LOGGER_PREFIX = "SessionRecorder::
* 1) An "idle-daily" observer which delete sessions older than
* MAX_SESSION_AGE_MS.
* 2) The creator of this instance explicitly calling
* `pruneOldSessions`.
*
* @param branch
* (string) Preferences branch on which to record state.
*/
-this.SessionRecorder = function (branch) {
+this.SessionRecorder = function(branch) {
if (!branch) {
throw new Error("branch argument must be defined.");
}
if (!branch.endsWith(".")) {
throw new Error("branch argument must end with '.': " + branch);
}
@@ -110,30 +110,30 @@ SessionRecorder.prototype = Object.freez
set _startDate(value) {
CommonUtils.setDatePref(this._prefs, "current.startTime", value);
},
get activeTicks() {
return this._prefs.get("current.activeTicks", 0);
},
- incrementActiveTicks: function () {
+ incrementActiveTicks: function() {
this._prefs.set("current.activeTicks", ++this._activeTicks);
},
/**
* Total time of this session in integer seconds.
*
* See also fineTotalTime for the time in milliseconds.
*/
get totalTime() {
return this._prefs.get("current.totalTime", 0);
},
- updateTotalTime: function () {
+ updateTotalTime: function() {
// We store millisecond precision internally to prevent drift from
// repeated rounding.
this.fineTotalTime = Date.now() - this.startDate;
this._prefs.set("current.totalTime", Math.floor(this.fineTotalTime / 1000));
},
get main() {
return this._prefs.get("current.main", -1);
@@ -166,57 +166,57 @@ SessionRecorder.prototype = Object.freez
set _sessionRestored(value) {
if (!Number.isInteger(value)) {
throw new Error("sessionRestored must be an integer.");
}
this._prefs.set("current.sessionRestored", value);
},
- getPreviousSessions: function () {
+ getPreviousSessions: function() {
let result = {};
for (let i = this._prunedIndex; i < this._currentIndex; i++) {
let s = this.getPreviousSession(i);
if (!s) {
continue;
}
result[i] = s;
}
return result;
},
- getPreviousSession: function (index) {
+ getPreviousSession: function(index) {
return this._deserialize(this._prefs.get("previous." + index));
},
/**
* Prunes old, completed sessions that started earlier than the
* specified date.
*/
- pruneOldSessions: function (date) {
+ pruneOldSessions: function(date) {
for (let i = this._prunedIndex; i < this._currentIndex; i++) {
let s = this.getPreviousSession(i);
if (!s) {
continue;
}
if (s.startDate >= date) {
continue;
}
this._log.debug("Pruning session #" + i + ".");
this._prefs.reset("previous." + i);
this._prunedIndex = i;
}
},
- recordStartupFields: function () {
+ recordStartupFields: function() {
let si = this._getStartupInfo();
if (!si.process) {
throw new Error("Startup info not available.");
}
let missing = false;
@@ -242,29 +242,29 @@ SessionRecorder.prototype = Object.freez
if (!this._timer) {
this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this._timer.initWithCallback({
notify: this.recordStartupFields.bind(this),
}, this.STARTUP_RETRY_INTERVAL_MS, this._timer.TYPE_REPEATING_SLACK);
}
},
- _clearStartupTimer: function () {
+ _clearStartupTimer: function() {
if (this._timer) {
this._timer.cancel();
delete this._timer;
}
},
/**
* Perform functionality on application startup.
*
* This is typically called in a "profile-do-change" handler.
*/
- onStartup: function () {
+ onStartup: function() {
if (this._started) {
throw new Error("onStartup has already been called.");
}
let si = this._getStartupInfo();
if (!si.process) {
throw new Error("Process information not available. Misconfigured app?");
}
@@ -284,28 +284,28 @@ SessionRecorder.prototype = Object.freez
this.updateTotalTime();
this.recordStartupFields();
},
/**
* Record application activity.
*/
- onActivity: function (active) {
+ onActivity: function(active) {
let updateActive = active && !this._lastActivityWasInactive;
this._lastActivityWasInactive = !active;
this.updateTotalTime();
if (updateActive) {
this.incrementActiveTicks();
}
},
- onShutdown: function () {
+ onShutdown: function() {
this._log.info("Recording clean session shutdown.");
this._prefs.set("current.clean", true);
this.updateTotalTime();
this._clearStartupTimer();
this._os.removeObserver(this, "profile-before-change");
this._os.removeObserver(this, "user-interaction-active");
this._os.removeObserver(this, "user-interaction-inactive");
@@ -318,17 +318,17 @@ SessionRecorder.prototype = Object.freez
"current.totalTime",
"current.main",
"current.firstPaint",
"current.sessionRestored",
"current.clean",
],
// This is meant to be called only during onStartup().
- _moveCurrentToPrevious: function () {
+ _moveCurrentToPrevious: function() {
try {
if (!this.startDate.getTime()) {
this._log.info("No previous session. Is this first app run?");
return;
}
let clean = this._prefs.get("current.clean", false);
@@ -350,17 +350,17 @@ SessionRecorder.prototype = Object.freez
} finally {
this._log.debug("Resetting prefs from last session.");
for (let pref of this._CURRENT_PREFS) {
this._prefs.reset(pref);
}
}
},
- _deserialize: function (s) {
+ _deserialize: function(s) {
let o;
try {
o = JSON.parse(s);
} catch (ex) {
return null;
}
return {
@@ -370,23 +370,23 @@ SessionRecorder.prototype = Object.freez
clean: !!o.c,
main: o.m,
firstPaint: o.fp,
sessionRestored: o.sr,
};
},
// Implemented as a function to allow for monkeypatching in tests.
- _getStartupInfo: function () {
+ _getStartupInfo: function() {
return Cc["@mozilla.org/toolkit/app-startup;1"]
.getService(Ci.nsIAppStartup)
.getStartupInfo();
},
- observe: function (subject, topic, data) {
+ observe: function(subject, topic, data) {
switch (topic) {
case "profile-before-change":
this.onShutdown();
break;
case "user-interaction-active":
this.onActivity(true);
break;
--- a/toolkit/modules/Sntp.jsm
+++ b/toolkit/modules/Sntp.jsm
@@ -321,14 +321,14 @@ Sntp.prototype = {
_retryPeriodInMS: 0,
// Timer used for retries & daily updates.
_updateTimer: null
};
var debug;
if (DEBUG) {
- debug = function (s) {
+ debug = function(s) {
dump("-*- Sntp: " + s + "\n");
};
} else {
- debug = function (s) {};
+ debug = function(s) {};
}
--- a/toolkit/modules/SpatialNavigation.jsm
+++ b/toolkit/modules/SpatialNavigation.jsm
@@ -18,17 +18,17 @@
*/
"use strict";
this.EXPORTED_SYMBOLS = ["SpatialNavigation"];
var SpatialNavigation = {
init: function(browser, callback) {
- browser.addEventListener("keydown", function (event) {
+ browser.addEventListener("keydown", function(event) {
_onInputKeyPress(event, callback);
}, true);
}
};
// Private stuff
const Cc = Components.classes;
@@ -63,17 +63,17 @@ function dumpNodeCoord(desc, node) {
// modifier values
const kAlt = "alt";
const kShift = "shift";
const kCtrl = "ctrl";
const kNone = "none";
-function _onInputKeyPress (event, callback) {
+function _onInputKeyPress(event, callback) {
// If Spatial Navigation isn't enabled, return.
if (!PrefObserver['enabled']) {
return;
}
// Use whatever key value is available (either keyCode or charCode).
// It might be useful for addons or whoever wants to set different
// key to be used here (e.g. "a", "F1", "arrowUp", ...).
--- a/toolkit/modules/Sqlite.jsm
+++ b/toolkit/modules/Sqlite.jsm
@@ -127,17 +127,17 @@ XPCOMUtils.defineLazyGetter(this, "Barri
/**
* Observer for the event which is broadcasted when the finalization
* witness `_witness` of `OpenedConnection` is garbage collected.
*
* The observer is passed the connection identifier of the database
* connection that is being finalized.
*/
- let finalizationObserver = function (subject, topic, identifier) {
+ let finalizationObserver = function(subject, topic, identifier) {
let connectionData = ConnectionData.byId.get(identifier);
if (connectionData === undefined) {
logScriptError("Error: Attempt to finalize unknown Sqlite connection: " +
identifier + "\n");
return;
}
@@ -384,17 +384,17 @@ ConnectionData.prototype = Object.freeze
return Task.spawn(function*() {
try {
return (yield promiseResult);
} finally {
this._barrier.client.removeBlocker(key, promiseComplete)
}
}.bind(this));
},
- close: function () {
+ close: function() {
this._closeRequested = true;
if (!this._dbConn) {
return this._deferredClose.promise;
}
this._log.debug("Request to close connection.");
this._clearIdleShrinkTimer();
@@ -402,34 +402,34 @@ ConnectionData.prototype = Object.freeze
return this._barrier.wait().then(() => {
if (!this._dbConn) {
return undefined;
}
return this._finalize();
});
},
- clone: function (readOnly = false) {
+ clone: function(readOnly = false) {
this.ensureOpen();
this._log.debug("Request to clone connection.");
let options = {
connection: this._dbConn,
readOnly: readOnly,
};
if (this._idleShrinkMS)
options.shrinkMemoryOnConnectionIdleMS = this._idleShrinkMS;
return cloneStorageConnection(options);
},
_getOperationId: function() {
return this._operationsCounter++;
},
- _finalize: function () {
+ _finalize: function() {
this._log.debug("Finalizing connection.");
// Cancel any pending statements.
for (let [k, statement] of this._pendingStatements) {
statement.cancel();
}
this._pendingStatements.clear();
// We no longer need to track these.
@@ -466,17 +466,17 @@ ConnectionData.prototype = Object.freeze
} else {
this._log.debug("Calling asyncClose().");
this._dbConn.asyncClose(markAsClosed);
this._dbConn = null;
}
return this._deferredClose.promise;
},
- executeCached: function (sql, params = null, onRow = null) {
+ executeCached: function(sql, params = null, onRow = null) {
this.ensureOpen();
if (!sql) {
throw new Error("sql argument is empty.");
}
let statement = this._cachedStatements.get(sql);
if (!statement) {
@@ -500,17 +500,17 @@ ConnectionData.prototype = Object.freeze
);
} catch (ex) {
this._startIdleShrinkTimer();
throw ex;
}
});
},
- execute: function (sql, params = null, onRow = null) {
+ execute: function(sql, params = null, onRow = null) {
if (typeof(sql) != "string") {
throw new Error("Must define SQL to execute as a string: " + sql);
}
this.ensureOpen();
let statement = this._dbConn.createAsyncStatement(sql);
let index = this._anonymousCounter++;
@@ -542,17 +542,17 @@ ConnectionData.prototype = Object.freeze
}
});
},
get transactionInProgress() {
return this._open && this._hasInProgressTransaction;
},
- executeTransaction: function (func, type) {
+ executeTransaction: function(func, type) {
if (typeof type == "undefined") {
throw new Error("Internal error: expected a type");
}
this.ensureOpen();
this._log.debug("Beginning transaction");
let promise = this._transactionQueue.then(() => {
@@ -648,38 +648,38 @@ ConnectionData.prototype = Object.freeze
this._transactionQueue = promise.catch(ex => { console.error(ex) });
// Make sure that we do not shutdown the connection during a transaction.
this._barrier.client.addBlocker(`Transaction (${this._getOperationId()})`,
this._transactionQueue);
return promise;
},
- shrinkMemory: function () {
+ shrinkMemory: function() {
this._log.info("Shrinking memory usage.");
let onShrunk = this._clearIdleShrinkTimer.bind(this);
return this.execute("PRAGMA shrink_memory").then(onShrunk, onShrunk);
},
- discardCachedStatements: function () {
+ discardCachedStatements: function() {
let count = 0;
for (let [k, statement] of this._cachedStatements) {
++count;
statement.finalize();
}
this._cachedStatements.clear();
this._log.debug("Discarded " + count + " cached statements.");
return count;
},
/**
* Helper method to bind parameters of various kinds through
* reflection.
*/
- _bindParameters: function (statement, params) {
+ _bindParameters: function(statement, params) {
if (!params) {
return;
}
if (Array.isArray(params)) {
// It's an array of separate params.
if (params.length && (typeof(params[0]) == "object")) {
let paramsArray = statement.newBindingParamsArray();
@@ -709,17 +709,17 @@ ConnectionData.prototype = Object.freeze
}
return;
}
throw new Error("Invalid type for bound parameters. Expected Array or " +
"object. Got: " + params);
},
- _executeStatement: function (sql, statement, params, onRow) {
+ _executeStatement: function(sql, statement, params, onRow) {
if (statement.state != statement.MOZ_STORAGE_STATEMENT_READY) {
throw new Error("Statement is not ready for execution.");
}
if (onRow && typeof(onRow) != "function") {
throw new Error("onRow must be a function. Got: " + onRow);
}
@@ -743,17 +743,17 @@ ConnectionData.prototype = Object.freeze
}
this._log.trace(msg);
} else {
this._log.debug("Stmt #" + index + " starting");
}
let self = this;
let pending = statement.executeAsync({
- handleResult: function (resultSet) {
+ handleResult: function(resultSet) {
// .cancel() may not be immediate and handleResult() could be called
// after a .cancel().
for (let row = resultSet.getNextRow(); row && !userCancelled; row = resultSet.getNextRow()) {
if (!onRow) {
rows.push(row);
continue;
}
@@ -768,23 +768,23 @@ ConnectionData.prototype = Object.freeze
break;
}
self._log.warn("Exception when calling onRow callback", e);
}
}
},
- handleError: function (error) {
+ handleError: function(error) {
self._log.info("Error when executing SQL (" +
error.result + "): " + error.message);
errors.push(error);
},
- handleCompletion: function (reason) {
+ handleCompletion: function(reason) {
self._log.debug("Stmt #" + index + " finished.");
self._pendingStatements.delete(index);
switch (reason) {
case Ci.mozIStorageStatementCallback.REASON_FINISHED:
// If there is an onRow handler, we always instead resolve to a
// boolean indicating whether the onRow handler was called or not.
let result = onRow ? handledRow : rows;
@@ -816,31 +816,31 @@ ConnectionData.prototype = Object.freeze
}
},
});
this._pendingStatements.set(index, pending);
return deferred.promise;
},
- ensureOpen: function () {
+ ensureOpen: function() {
if (!this._open) {
throw new Error("Connection is not open.");
}
},
- _clearIdleShrinkTimer: function () {
+ _clearIdleShrinkTimer: function() {
if (!this._idleShrinkTimer) {
return;
}
this._idleShrinkTimer.cancel();
},
- _startIdleShrinkTimer: function () {
+ _startIdleShrinkTimer: function() {
if (!this._idleShrinkTimer) {
return;
}
this._idleShrinkTimer.initWithCallback(this.shrinkMemory.bind(this),
this._idleShrinkMS,
this._idleShrinkTimer.TYPE_ONE_SHOT);
}
@@ -1203,17 +1203,17 @@ OpenedConnection.prototype = Object.free
* The returned promise will be resolved once the connection is closed.
* Successive calls to close() return the same promise.
*
* IMPROVEMENT: Resolve the promise to a closed connection which can be
* reopened.
*
* @return Promise<>
*/
- close: function () {
+ close: function() {
// Unless cleanup has already been done by a previous call to
// `close`, delete the database entry from map and tell the
// finalization witness to forget.
if (ConnectionData.byId.has(this._connectionData._identifier)) {
ConnectionData.byId.delete(this._connectionData._identifier);
this._witness.forget();
}
return this._connectionData.close();
@@ -1228,17 +1228,17 @@ OpenedConnection.prototype = Object.free
* (boolean) - If true the clone will be read-only. If the original
* connection is already read-only, the clone will be, regardless of
* this option. If the original connection is using the shared cache,
* this parameter will be ignored and the clone will be as privileged as
* the original connection.
*
* @return Promise<OpenedConnection>
*/
- clone: function (readOnly = false) {
+ clone: function(readOnly = false) {
return this._connectionData.clone(readOnly);
},
executeBeforeShutdown: function(name, task) {
return this._connectionData.executeBeforeShutdown(this, name, task);
},
/**
@@ -1294,17 +1294,17 @@ OpenedConnection.prototype = Object.free
*
* @param name
* (string) The name of the registered statement to execute.
* @param params optional
* (Array or object) Parameters to bind.
* @param onRow optional
* (function) Callback to receive each row from result.
*/
- executeCached: function (sql, params = null, onRow = null) {
+ executeCached: function(sql, params = null, onRow = null) {
if (isInvalidBoundLikeQuery(sql)) {
throw new Error("Please enter a LIKE clause with bindings");
}
return this._connectionData.executeCached(sql, params, onRow);
},
/**
* Execute a one-shot SQL statement.
@@ -1316,17 +1316,17 @@ OpenedConnection.prototype = Object.free
*
* @param sql
* (string) SQL to execute.
* @param params optional
* (Array or Object) Parameters to bind to the statement.
* @param onRow optional
* (function) Callback to receive result of a single row.
*/
- execute: function (sql, params = null, onRow = null) {
+ execute: function(sql, params = null, onRow = null) {
if (isInvalidBoundLikeQuery(sql)) {
throw new Error("Please enter a LIKE clause with bindings");
}
return this._connectionData.execute(sql, params, onRow);
},
/**
* Whether a transaction is currently in progress.
@@ -1368,33 +1368,33 @@ OpenedConnection.prototype = Object.free
* be resolved to whatever value the supplied function resolves to. If
* the transaction is rolled back, the promise is rejected.
*
* @param func
* (function) What to perform as part of the transaction.
* @param type optional
* One of the TRANSACTION_* constants attached to this type.
*/
- executeTransaction: function (func, type = this.TRANSACTION_DEFERRED) {
+ executeTransaction: function(func, type = this.TRANSACTION_DEFERRED) {
if (this.TRANSACTION_TYPES.indexOf(type) == -1) {
throw new Error("Unknown transaction type: " + type);
}
return this._connectionData.executeTransaction(() => func(this), type);
},
/**
* Whether a table exists in the database (both persistent and temporary tables).
*
* @param name
* (string) Name of the table.
*
* @return Promise<bool>
*/
- tableExists: function (name) {
+ tableExists: function(name) {
return this.execute(
"SELECT name FROM (SELECT * FROM sqlite_master UNION ALL " +
"SELECT * FROM sqlite_temp_master) " +
"WHERE type = 'table' AND name=?",
[name])
.then(function onResult(rows) {
return Promise.resolve(rows.length > 0);
}
@@ -1404,48 +1404,48 @@ OpenedConnection.prototype = Object.free
/**
* Whether a named index exists (both persistent and temporary tables).
*
* @param name
* (string) Name of the index.
*
* @return Promise<bool>
*/
- indexExists: function (name) {
+ indexExists: function(name) {
return this.execute(
"SELECT name FROM (SELECT * FROM sqlite_master UNION ALL " +
"SELECT * FROM sqlite_temp_master) " +
"WHERE type = 'index' AND name=?",
[name])
.then(function onResult(rows) {
return Promise.resolve(rows.length > 0);
}
);
},
/**
* Free up as much memory from the underlying database connection as possible.
*
* @return Promise<>
*/
- shrinkMemory: function () {
+ shrinkMemory: function() {
return this._connectionData.shrinkMemory();
},
/**
* Discard all cached statements.
*
* Note that this relies on us being non-interruptible between
* the insertion or retrieval of a statement in the cache and its
* execution: we finalize all statements, which is only safe if
* they will not be executed again.
*
* @return (integer) the number of statements discarded.
*/
- discardCachedStatements: function () {
+ discardCachedStatements: function() {
return this._connectionData.discardCachedStatements();
},
});
this.Sqlite = {
openConnection: openConnection,
cloneStorageConnection: cloneStorageConnection,
wrapStorageConnection: wrapStorageConnection,
--- a/toolkit/modules/Task.jsm
+++ b/toolkit/modules/Task.jsm
@@ -220,17 +220,17 @@ this.Task = {
* Example: throw new Task.Result("Value");
*/
Result: function Task_Result(aValue) {
this.value = aValue;
}
};
function createAsyncFunction(aTask) {
- let asyncFunction = function () {
+ let asyncFunction = function() {
let result = aTask;
if (aTask && typeof(aTask) == "function") {
if (aTask.isAsyncFunction) {
throw new TypeError(
"Cannot use an async function in place of a promise. " +
"You should either invoke the async function first " +
"or use 'Task.spawn' instead of 'Task.async' to start " +
"the Task and return its promise.");
--- a/toolkit/modules/Troubleshoot.jsm
+++ b/toolkit/modules/Troubleshoot.jsm
@@ -233,34 +233,34 @@ var dataProviders = {
} catch (e) {
data.autoStartStatus = -1;
}
done(data);
},
extensions: function extensions(done) {
- AddonManager.getAddonsByTypes(["extension"], function (extensions) {
- extensions.sort(function (a, b) {
+ AddonManager.getAddonsByTypes(["extension"], function(extensions) {
+ extensions.sort(function(a, b) {
if (a.isActive != b.isActive)
return b.isActive ? 1 : -1;
// In some unfortunate cases addon names can be null.
let aname = a.name || null;
let bname = b.name || null;
let lc = aname.localeCompare(bname);
if (lc != 0)
return lc;
if (a.version != b.version)
return a.version > b.version ? 1 : -1;
return 0;
});
let props = ["name", "version", "isActive", "id"];
- done(extensions.map(function (ext) {
- return props.reduce(function (extData, prop) {
+ done(extensions.map(function(ext) {
+ return props.reduce(function(extData, prop) {
extData[prop] = ext[prop];
return extData;
}, {});
}));
});
},
experiments: function experiments(done) {
--- a/toolkit/modules/UpdateUtils.jsm
+++ b/toolkit/modules/UpdateUtils.jsm
@@ -39,17 +39,17 @@ this.UpdateUtils = {
// use default value when pref not found
}
if (aIncludePartners) {
try {
let partners = Services.prefs.getChildList("app.partner.").sort();
if (partners.length) {
channel += "-cck";
- partners.forEach(function (prefName) {
+ partners.forEach(function(prefName) {
channel += "-" + Services.prefs.getCharPref(prefName);
});
}
} catch (e) {
Cu.reportError(e);
}
}
--- a/toolkit/modules/WebChannel.jsm
+++ b/toolkit/modules/WebChannel.jsm
@@ -26,17 +26,17 @@ Cu.import("resource://gre/modules/Servic
var WebChannelBroker = Object.create({
/**
* Register a new channel that callbacks messages
* based on proper origin and channel name
*
* @param channel {WebChannel}
*/
- registerChannel: function (channel) {
+ registerChannel: function(channel) {
if (!this._channelMap.has(channel)) {
this._channelMap.set(channel);
} else {
Cu.reportError("Failed to register the channel. Channel already exists.");
}
// attach the global message listener if needed
if (!this._messageListenerAttached) {
@@ -48,28 +48,28 @@ var WebChannelBroker = Object.create({
/**
* Unregister a channel
*
* @param channelToRemove {WebChannel}
* WebChannel to remove from the channel map
*
* Removes the specified channel from the channel map
*/
- unregisterChannel: function (channelToRemove) {
+ unregisterChannel: function(channelToRemove) {
if (!this._channelMap.delete(channelToRemove)) {
Cu.reportError("Failed to unregister the channel. Channel not found.");
}
},
/**
* @param event {Event}
* Message Manager event
* @private
*/
- _listener: function (event) {
+ _listener: function(event) {
let data = event.data;
let sendingContext = {
browser: event.target,
eventTarget: event.objects.eventTarget,
principal: event.principal,
};
// data must be a string except for a few legacy origins allowed by browser-content.js.
if (typeof data == "string") {
@@ -122,17 +122,17 @@ var WebChannelBroker = Object.create({
* @param id {String}
* The WebChannel id to include in the message
* @param sendingContext {Object}
* Message sending context
* @param [errorMsg] {String}
* Error message
* @private
*/
- _sendErrorEventToContent: function (id, sendingContext, errorMsg) {
+ _sendErrorEventToContent: function(id, sendingContext, errorMsg) {
let { browser: targetBrowser, eventTarget, principal: targetPrincipal } = sendingContext;
errorMsg = errorMsg || "Web Channel Broker error";
if (targetBrowser && targetBrowser.messageManager) {
targetBrowser.messageManager.sendAsyncMessage("WebChannelMessageToContent", {
id: id,
error: errorMsg,
@@ -235,32 +235,32 @@ this.WebChannel.prototype = {
* The <browser> object that captured the
* WebChannelMessageToChrome.
* @param sendingContext.eventTarget {EventTarget}
* The <EventTarget> where the message was sent.
* @param sendingContext.principal {Principal}
* The <Principal> of the EventTarget where the
* message was sent.
*/
- listen: function (callback) {
+ listen: function(callback) {
if (this._deliverCallback) {
throw new Error("Failed to listen. Listener already attached.");
} else if (!callback) {
throw new Error("Failed to listen. Callback argument missing.");
} else {
this._deliverCallback = callback;
this._broker.registerChannel(this);
}
},
/**
* Resets the callback for messages on this channel
* Removes the channel from the WebChannelBroker
*/
- stopListening: function () {
+ stopListening: function() {
this._broker.unregisterChannel(this);
this._deliverCallback = null;
},
/**
* Sends messages over the WebChannel id using the "WebChannelMessageToContent" event
*
* @param message {Object}
@@ -273,17 +273,17 @@ this.WebChannel.prototype = {
* @param target.principal {Principal}
* Principal of the target. Prevents messages from
* being dispatched to unexpected origins. The system principal
* can be specified to send to any target.
* @param [target.eventTarget] {EventTarget}
* Optional eventTarget within the browser, use to send to a
* specific element, e.g., an iframe.
*/
- send: function (message, target) {
+ send: function(message, target) {
let { browser, principal, eventTarget } = target;
if (message && browser && browser.messageManager && principal) {
browser.messageManager.sendAsyncMessage("WebChannelMessageToContent", {
id: this.id,
message: message
}, { eventTarget }, principal);
} else if (!message) {
--- a/toolkit/modules/secondscreen/SimpleServiceDiscovery.jsm
+++ b/toolkit/modules/secondscreen/SimpleServiceDiscovery.jsm
@@ -10,17 +10,17 @@ this.EXPORTED_SYMBOLS = ["SimpleServiceD
const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Timer.jsm");
var log = Cu.reportError;
-XPCOMUtils.defineLazyGetter(this, "converter", function () {
+XPCOMUtils.defineLazyGetter(this, "converter", function() {
let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
conv.charset = "utf8";
return conv;
});
// Spec information:
// https://tools.ietf.org/html/draft-cai-ssdp-v1-03
// http://www.dial-multiscreen.org/dial-protocol-specification
--- a/toolkit/modules/sessionstore/FormData.jsm
+++ b/toolkit/modules/sessionstore/FormData.jsm
@@ -77,21 +77,21 @@ function isValidCCNumber(value) {
return total % 10 == 0;
}
/**
* The public API exported by this module that allows to collect
* and restore form data for a document and its subframes.
*/
this.FormData = Object.freeze({
- collect: function (frame) {
+ collect: function(frame) {
return FormDataInternal.collect(frame);
},
- restoreTree: function (root, data) {
+ restoreTree: function(root, data) {
FormDataInternal.restoreTree(root, data);
}
});
/**
* This module's internal API.
*/
var FormDataInternal = {
@@ -113,17 +113,17 @@ var FormDataInternal = {
* }
* }
*
* @param doc
* DOMDocument instance to obtain form data for.
* @return object
* Form data encoded in an object.
*/
- collect: function ({document: doc}) {
+ collect: function({document: doc}) {
let formNodes = doc.evaluate(
XPathGenerator.restorableFormNodes,
doc,
XPathGenerator.resolveNS,
Ci.nsIDOMXPathResult.UNORDERED_NODE_ITERATOR_TYPE, null
);
let node;
@@ -227,17 +227,17 @@ var FormDataInternal = {
* Restores form |data| for the given frame. The data is expected to be in
* the same format that FormData.collect() returns.
*
* @param frame (DOMWindow)
* The frame to restore form data to.
* @param data (object)
* An object holding form data.
*/
- restore: function ({document: doc}, data) {
+ restore: function({document: doc}, data) {
// Don't restore any data for the given frame if the URL
// stored in the form data doesn't match its current URL.
if (!data.url || data.url != getDocumentURI(doc)) {
return;
}
// For about:{sessionrestore,welcomeback} we saved the field as JSON to
// avoid nested instances causing humongous sessionstore.js files.
@@ -270,17 +270,17 @@ var FormDataInternal = {
*
* @param data (object)
* A subset of the form data as collected by FormData.collect(). This
* is either data stored under "id" or under "xpath".
* @param retrieve (function)
* The function used to retrieve the input field belonging to a key
* in the given |data| object.
*/
- restoreManyInputValues: function (data, retrieve) {
+ restoreManyInputValues: function(data, retrieve) {
for (let key of Object.keys(data)) {
let input = retrieve(key);
if (input) {
this.restoreSingleInputValue(input, data[key]);
}
}
},
@@ -288,17 +288,17 @@ var FormDataInternal = {
* Restores a given form value to a given DOMNode and takes care of firing
* the appropriate DOM event should the input's value change.
*
* @param aNode
* DOMNode to set form value on.
* @param aValue
* Value to set form element to.
*/
- restoreSingleInputValue: function (aNode, aValue) {
+ restoreSingleInputValue: function(aNode, aValue) {
let eventType;
if (typeof aValue == "string" && aNode.type != "file") {
// Don't dispatch an input event if there is no change.
if (aNode.value == aValue) {
return;
}
@@ -354,17 +354,17 @@ var FormDataInternal = {
},
/**
* Dispatches an event of type |type| to the given |node|.
*
* @param node (DOMNode)
* @param type (string)
*/
- fireEvent: function (node, type) {
+ fireEvent: function(node, type) {
let doc = node.ownerDocument;
let event = doc.createEvent("UIEvents");
event.initUIEvent(type, true, true, doc.defaultView, 0);
node.dispatchEvent(event);
},
/**
* Restores form data for the current frame hierarchy starting at |root|
@@ -382,17 +382,17 @@ var FormDataInternal = {
* formdata: {id: {input1: "value1"}},
* children: [
* {formdata: {id: {input2: "value2"}}},
* null,
* {formdata: {xpath: { ... }}, children: [ ... ]}
* ]
* }
*/
- restoreTree: function (root, data) {
+ restoreTree: function(root, data) {
// Don't restore any data for the root frame and its subframes if there
// is a URL stored in the form data and it doesn't match its current URL.
if (data.url && data.url != getDocumentURI(root.document)) {
return;
}
if (data.url) {
this.restore(root, data);
--- a/toolkit/modules/sessionstore/ScrollPosition.jsm
+++ b/toolkit/modules/sessionstore/ScrollPosition.jsm
@@ -32,17 +32,17 @@ var ScrollPositionInternal = {
* Collects scroll position data for any given |frame| in the frame hierarchy.
*
* @param frame (DOMWindow)
*
* @return {scroll: "x,y"} e.g. {scroll: "100,200"}
* Returns null when there is no scroll data we want to store for the
* given |frame|.
*/
- collect: function (frame) {
+ collect: function(frame) {
let ifreq = frame.QueryInterface(Ci.nsIInterfaceRequestor);
let utils = ifreq.getInterface(Ci.nsIDOMWindowUtils);
let scrollX = {}, scrollY = {};
utils.getScrollXY(false /* no layout flush */, scrollX, scrollY);
if (scrollX.value || scrollY.value) {
return {scroll: scrollX.value + "," + scrollY.value};
}
@@ -51,17 +51,17 @@ var ScrollPositionInternal = {
},
/**
* Restores scroll position data for any given |frame| in the frame hierarchy.
*
* @param frame (DOMWindow)
* @param value (object, see collect())
*/
- restore: function (frame, value) {
+ restore: function(frame, value) {
let match;
if (value && (match = /(\d+),(\d+)/.exec(value))) {
frame.scrollTo(match[1], match[2]);
}
},
/**
@@ -79,17 +79,17 @@ var ScrollPositionInternal = {
* scroll: "100,200",
* children: [
* {scroll: "100,200"},
* null,
* {scroll: "200,300", children: [ ... ]}
* ]
* }
*/
- restoreTree: function (root, data) {
+ restoreTree: function(root, data) {
if (data.hasOwnProperty("scroll")) {
this.restore(root, data.scroll);
}
if (!data.hasOwnProperty("children")) {
return;
}
--- a/toolkit/modules/sessionstore/Utils.jsm
+++ b/toolkit/modules/sessionstore/Utils.jsm
@@ -13,34 +13,34 @@ const Ci = Components.interfaces;
Cu.import("resource://gre/modules/Services.jsm", this);
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
XPCOMUtils.defineLazyServiceGetter(this, "serializationHelper",
"@mozilla.org/network/serialization-helper;1",
"nsISerializationHelper");
this.Utils = Object.freeze({
- makeURI: function (url) {
+ makeURI: function(url) {
return Services.io.newURI(url, null, null);
},
- makeInputStream: function (aString) {
+ makeInputStream: function(aString) {
let stream = Cc["@mozilla.org/io/string-input-stream;1"].
createInstance(Ci.nsISupportsCString);
stream.data = aString;
return stream; // XPConnect will QI this to nsIInputStream for us.
},
/**
* Returns true if the |url| passed in is part of the given root |domain|.
* For example, if |url| is "www.mozilla.org", and we pass in |domain| as
* "mozilla.org", this will return true. It would return false the other way
* around.
*/
- hasRootDomain: function (url, domain) {
+ hasRootDomain: function(url, domain) {
let host;
try {
host = this.makeURI(url).host;
} catch (e) {
// The given URL probably doesn't have a host.
return false;
}
@@ -52,17 +52,17 @@ this.Utils = Object.freeze({
if (host == domain)
return true;
let prevChar = host[index - 1];
return (index == (host.length - domain.length)) &&
(prevChar == "." || prevChar == "/");
},
- shallowCopy: function (obj) {
+ shallowCopy: function(obj) {
let retval = {};
for (let key of Object.keys(obj)) {
retval[key] = obj[key];
}
return retval;
},
--- a/toolkit/modules/tests/browser/browser_Battery.js
+++ b/toolkit/modules/tests/browser/browser_Battery.js
@@ -5,27 +5,27 @@
var imported = Components.utils.import("resource://gre/modules/Battery.jsm", this);
Cu.import("resource://gre/modules/Services.jsm", this);
function test() {
waitForExplicitFinish();
is(imported.Debugging.fake, false, "Battery spoofing is initially false")
- GetBattery().then(function (battery) {
+ GetBattery().then(function(battery) {
for (let k of ["charging", "chargingTime", "dischargingTime", "level"]) {
let backup = battery[k];
battery[k] = "__magic__";
is(battery[k], backup, "Setting battery " + k + "preference without spoofing enabled should fail");
}
imported.Debugging.fake = true;
// reload again to get the fake one
- GetBattery().then(function (battery) {
+ GetBattery().then(function(battery) {
battery.charging = true;
battery.chargingTime = 100;
battery.level = 0.5;
ok(battery.charging, "Test for charging setter");
is(battery.chargingTime, 100, "Test for chargingTime setter");
is(battery.level, 0.5, "Test for level setter");
battery.charging = false;
--- a/toolkit/modules/tests/browser/browser_Deprecated.js
+++ b/toolkit/modules/tests/browser/browser_Deprecated.js
@@ -6,80 +6,80 @@ var Ci = Components.interfaces;
var Cu = Components.utils;
const PREF_DEPRECATION_WARNINGS = "devtools.errorconsole.deprecation_warnings";
Cu.import("resource://gre/modules/Services.jsm", this);
Cu.import("resource://gre/modules/Deprecated.jsm", this);
// Using this named functions to test deprecation and the properly logged
// callstacks.
-function basicDeprecatedFunction () {
+function basicDeprecatedFunction() {
Deprecated.warning("this method is deprecated.", "http://example.com");
return true;
}
-function deprecationFunctionBogusCallstack () {
+function deprecationFunctionBogusCallstack() {
Deprecated.warning("this method is deprecated.", "http://example.com", {
caller: {}
});
return true;
}
-function deprecationFunctionCustomCallstack () {
+function deprecationFunctionCustomCallstack() {
// Get the nsIStackFrame that will contain the name of this function.
- function getStack () {
+ function getStack() {
return Components.stack;
}
Deprecated.warning("this method is deprecated.", "http://example.com",
getStack());
return true;
}
var tests = [
// Test deprecation warning without passing the callstack.
{
deprecatedFunction: basicDeprecatedFunction,
- expectedObservation: function (aMessage) {
+ expectedObservation: function(aMessage) {
testAMessage(aMessage);
ok(aMessage.errorMessage.indexOf("basicDeprecatedFunction") > 0,
"Callstack is correctly logged.");
}
},
// Test a reported error when URL to documentation is not passed.
{
- deprecatedFunction: function () {
+ deprecatedFunction: function() {
Deprecated.warning("this method is deprecated.");
return true;
},
- expectedObservation: function (aMessage) {
+ expectedObservation: function(aMessage) {
ok(aMessage.errorMessage.indexOf("must provide a URL") > 0,
"Deprecation warning logged an empty URL argument.");
}
},
// Test deprecation with a bogus callstack passed as an argument (it will be
// replaced with the current call stack).
{
deprecatedFunction: deprecationFunctionBogusCallstack,
- expectedObservation: function (aMessage) {
+ expectedObservation: function(aMessage) {
testAMessage(aMessage);
ok(aMessage.errorMessage.indexOf("deprecationFunctionBogusCallstack") > 0,
"Callstack is correctly logged.");
}
},
// When pref is unset Deprecated.warning should not log anything.
{
deprecatedFunction: basicDeprecatedFunction,
expectedObservation: null,
// Set pref to false.
logWarnings: false
},
// Test deprecation with a valid custom callstack passed as an argument.
{
deprecatedFunction: deprecationFunctionCustomCallstack,
- expectedObservation: function (aMessage) {
+ expectedObservation: function(aMessage) {
testAMessage(aMessage);
ok(aMessage.errorMessage.indexOf("deprecationFunctionCustomCallstack") > 0,
"Callstack is correctly logged.");
},
// Set pref to true.
logWarnings: true
}];
@@ -91,17 +91,17 @@ function test() {
// Check if Deprecated is loaded.
ok(Deprecated, "Deprecated object exists");
nextTest();
}
// Test Consle Message attributes.
-function testAMessage (aMessage) {
+function testAMessage(aMessage) {
ok(aMessage.errorMessage.indexOf("DEPRECATION WARNING: " +
"this method is deprecated.") === 0,
"Deprecation is correctly logged.");
ok(aMessage.errorMessage.indexOf("http://example.com") > 0,
"URL is correctly logged.");
}
function nextTest() {
@@ -117,17 +117,17 @@ function nextTest() {
// Deprecation warnings will be logged only when the preference is set.
if (typeof test.logWarnings !== "undefined") {
Services.prefs.setBoolPref(PREF_DEPRECATION_WARNINGS, test.logWarnings);
}
// Create a console listener.
let consoleListener = {
- observe: function (aMessage) {
+ observe: function(aMessage) {
// Ignore unexpected messages.
if (!(aMessage instanceof Ci.nsIScriptError)) {
return;
}
if (aMessage.errorMessage.indexOf("DEPRECATION WARNING: ") < 0 &&
aMessage.errorMessage.indexOf("must provide a URL") < 0) {
return;
}
--- a/toolkit/modules/tests/browser/browser_Finder.js
+++ b/toolkit/modules/tests/browser/browser_Finder.js
@@ -7,20 +7,20 @@ var Ci = Components.interfaces;
add_task(function* () {
const url = "data:text/html;base64," +
btoa("<body><iframe srcdoc=\"content\"/></iframe>" +
"<a href=\"http://test.com\">test link</a>");
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
let finder = tab.linkedBrowser.finder;
let listener = {
- onFindResult: function () {
+ onFindResult: function() {
ok(false, "onFindResult callback wasn't replaced");
},
- onHighlightFinished: function () {
+ onHighlightFinished: function() {
ok(false, "onHighlightFinished callback wasn't replaced");
}
};
finder.addResultListener(listener);
function waitForFind(which = "onFindResult") {
return new Promise(resolve => {
listener[which] = resolve;
--- a/toolkit/modules/tests/browser/browser_Finder_hidden_textarea.js
+++ b/toolkit/modules/tests/browser/browser_Finder_hidden_textarea.js
@@ -8,17 +8,17 @@ add_task(function* test_bug1174036() {
function* (browser) {
// Hide the first textarea.
yield ContentTask.spawn(browser, null, function() {
content.document.getElementsByTagName("textarea")[0].style.display = "none";
});
let finder = browser.finder;
let listener = {
- onFindResult: function () {
+ onFindResult: function() {
ok(false, "callback wasn't replaced");
}
};
finder.addResultListener(listener);
function waitForFind() {
return new Promise(resolve => {
listener.onFindResult = resolve;
--- a/toolkit/modules/tests/browser/browser_Troubleshoot.js
+++ b/toolkit/modules/tests/browser/browser_Troubleshoot.js
@@ -17,26 +17,26 @@ function test() {
finish();
return;
}
tests.shift()(doNextTest);
}
doNextTest();
}
-registerCleanupFunction(function () {
+registerCleanupFunction(function() {
// Troubleshoot.jsm is imported into the global scope -- the window -- above.
// If it's not deleted, it outlives the test and is reported as a leak.
delete window.Troubleshoot;
});
var tests = [
function snapshotSchema(done) {
- Troubleshoot.snapshot(function (snapshot) {
+ Troubleshoot.snapshot(function(snapshot) {
try {
validateObject(snapshot, SNAPSHOT_SCHEMA);
ok(true, "The snapshot should conform to the schema.");
}
catch (err) {
ok(false, "Schema mismatch, " + err);
}
done();
@@ -45,21 +45,21 @@ var tests = [
function modifiedPreferences(done) {
let prefs = [
"javascript.troubleshoot",
"troubleshoot.foo",
"javascript.print_to_filename",
"network.proxy.troubleshoot",
];
- prefs.forEach(function (p) {
+ prefs.forEach(function(p) {
Services.prefs.setBoolPref(p, true);
is(Services.prefs.getBoolPref(p), true, "The pref should be set: " + p);
});
- Troubleshoot.snapshot(function (snapshot) {
+ Troubleshoot.snapshot(function(snapshot) {
let p = snapshot.modifiedPreferences;
is(p["javascript.troubleshoot"], true,
"The pref should be present because it's whitelisted " +
"but not blacklisted.");
ok(!("troubleshoot.foo" in p),
"The pref should be absent because it's not in the whitelist.");
ok(!("javascript.print_to_filename" in p),
"The pref should be absent because it's blacklisted.");
@@ -73,17 +73,17 @@ var tests = [
function unicodePreferences(done) {
let name = "font.name.sans-serif.x-western";
let utf8Value = "\xc4\x8capk\xc5\xafv Krasopis"
let unicodeValue = "\u010Capk\u016Fv Krasopis";
// set/getCharPref work with 8bit strings (utf8)
Services.prefs.setCharPref(name, utf8Value);
- Troubleshoot.snapshot(function (snapshot) {
+ Troubleshoot.snapshot(function(snapshot) {
let p = snapshot.modifiedPreferences;
is(p[name], unicodeValue, "The pref should have correct Unicode value.");
Services.prefs.deleteBranch(name);
done();
});
}
];
--- a/toolkit/modules/tests/xpcshell/test_DeferredTask.js
+++ b/toolkit/modules/tests/xpcshell/test_DeferredTask.js
@@ -52,22 +52,22 @@ add_test(function test_arm_simple()
/**
* Checks that the delay set for the task is respected.
*/
add_test(function test_arm_delay_respected()
{
let executed1 = false;
let executed2 = false;
- new DeferredTask(function () {
+ new DeferredTask(function() {
executed1 = true;
do_check_false(executed2);
}, 1 * T).arm();
- new DeferredTask(function () {
+ new DeferredTask(function() {
executed2 = true;
do_check_true(executed1);
run_next_test();
}, 2 * T).arm();
});
/**
* Checks that calling "arm" again does not introduce further delay.
@@ -79,30 +79,30 @@ add_test(function test_arm_delay_notrest
// Create a task that will run later.
let deferredTask = new DeferredTask(() => { executed = true; }, 4 * T);
deferredTask.arm();
// Before the task starts, call "arm" again.
do_timeout(2 * T, () => deferredTask.arm());
// The "arm" call should not have introduced further delays.
- do_timeout(5 * T, function () {
+ do_timeout(5 * T, function() {
do_check_true(executed);
run_next_test();
});
});
/**
* Checks that a task runs only once when armed multiple times synchronously.
*/
add_test(function test_arm_coalesced()
{
let executed = false;
- let deferredTask = new DeferredTask(function () {
+ let deferredTask = new DeferredTask(function() {
do_check_false(executed);
executed = true;
run_next_test();
}, 50);
deferredTask.arm();
deferredTask.arm();
});
@@ -110,34 +110,34 @@ add_test(function test_arm_coalesced()
/**
* Checks that a task runs only once when armed multiple times synchronously,
* even when it has been created with a delay of zero milliseconds.
*/
add_test(function test_arm_coalesced_nodelay()
{
let executed = false;
- let deferredTask = new DeferredTask(function () {
+ let deferredTask = new DeferredTask(function() {
do_check_false(executed);
executed = true;
run_next_test();
}, 0);
deferredTask.arm();
deferredTask.arm();
});
/**
* Checks that a task can be armed again while running.
*/
add_test(function test_arm_recursive()
{
let executed = false;
- let deferredTask = new DeferredTask(function () {
+ let deferredTask = new DeferredTask(function() {
if (!executed) {
executed = true;
deferredTask.arm();
} else {
run_next_test();
}
}, 50);
@@ -162,50 +162,50 @@ add_test(function test_arm_async()
finishedExecutionAgain = true;
}
}, 2 * T);
deferredTask.arm();
// While the task is running, call "arm" again. This will result in a wait
// of 2*T until the task finishes, then another 2*T for the normal task delay
// specified on construction.
- do_timeout(4 * T, function () {
+ do_timeout(4 * T, function() {
do_check_true(deferredTask.isRunning);
do_check_false(finishedExecution);
deferredTask.arm();
});
// This will fail in case the task was started without waiting 2*T after it
// has finished.
- do_timeout(7 * T, function () {
+ do_timeout(7 * T, function() {
do_check_false(deferredTask.isRunning);
do_check_true(finishedExecution);
});
// This is in the middle of the second execution.
- do_timeout(10 * T, function () {
+ do_timeout(10 * T, function() {
do_check_true(deferredTask.isRunning);
do_check_false(finishedExecutionAgain);
});
// Wait enough time to verify that the task was executed as expected.
- do_timeout(13 * T, function () {
+ do_timeout(13 * T, function() {
do_check_false(deferredTask.isRunning);
do_check_true(finishedExecutionAgain);
run_next_test();
});
});
/**
* Checks that an armed task can be disarmed.
*/
add_test(function test_disarm()
{
// Create a task that will run later.
- let deferredTask = new DeferredTask(function () {
+ let deferredTask = new DeferredTask(function() {
do_throw("This task should not run.");
}, 2 * T);
deferredTask.arm();
// Disable execution later, but before the task starts.
do_timeout(1 * T, () => deferredTask.disarm());
// Wait enough time to verify that the task did not run.
@@ -217,26 +217,26 @@ add_test(function test_disarm()
*/
add_test(function test_disarm_delay_restarted()
{
let executed = false;
let deferredTask = new DeferredTask(() => { executed = true; }, 4 * T);
deferredTask.arm();
- do_timeout(2 * T, function () {
+ do_timeout(2 * T, function() {
deferredTask.disarm();
deferredTask.arm();
});
- do_timeout(5 * T, function () {
+ do_timeout(5 * T, function() {
do_check_false(executed);
});
- do_timeout(7 * T, function () {
+ do_timeout(7 * T, function() {
do_check_true(executed);
run_next_test();
});
});
/**
* Checks that calling "disarm" while an asynchronous task is running does not
* prevent the task to finish.
@@ -247,24 +247,24 @@ add_test(function test_disarm_async()
let deferredTask = new DeferredTask(function* () {
deferredTask.arm();
yield promiseTimeout(2 * T);
finishedExecution = true;
}, 1 * T);
deferredTask.arm();
- do_timeout(2 * T, function () {
+ do_timeout(2 * T, function() {
do_check_true(deferredTask.isRunning);
do_check_true(deferredTask.isArmed);
do_check_false(finishedExecution);
deferredTask.disarm();
});
- do_timeout(4 * T, function () {
+ do_timeout(4 * T, function() {
do_check_false(deferredTask.isRunning);
do_check_false(deferredTask.isArmed);
do_check_true(finishedExecution);
run_next_test();
});
});
/**
@@ -277,37 +277,37 @@ add_test(function test_disarm_immediate_
let deferredTask = new DeferredTask(function* () {
do_check_false(executed);
executed = true;
yield promiseTimeout(2 * T);
}, 1 * T);
deferredTask.arm();
- do_timeout(2 * T, function () {
+ do_timeout(2 * T, function() {
do_check_true(deferredTask.isRunning);
do_check_false(deferredTask.isArmed);
deferredTask.arm();
deferredTask.disarm();
});
- do_timeout(4 * T, function () {
+ do_timeout(4 * T, function() {
do_check_true(executed);
do_check_false(deferredTask.isRunning);
do_check_false(deferredTask.isArmed);
run_next_test();
});
});
/**
* Checks the isArmed and isRunning properties with a synchronous task.
*/
add_test(function test_isArmed_isRunning()
{
- let deferredTask = new DeferredTask(function () {
+ let deferredTask = new DeferredTask(function() {
do_check_true(deferredTask.isRunning);
do_check_false(deferredTask.isArmed);
deferredTask.arm();
do_check_true(deferredTask.isArmed);
deferredTask.disarm();
do_check_false(deferredTask.isArmed);
run_next_test();
}, 50);
@@ -321,26 +321,26 @@ add_test(function test_isArmed_isRunning
/**
* Checks that the "finalize" method executes a synchronous task.
*/
add_test(function test_finalize()
{
let executed = false;
let timePassed = false;
- let deferredTask = new DeferredTask(function () {
+ let deferredTask = new DeferredTask(function() {
do_check_false(timePassed);
executed = true;
}, 2 * T);
deferredTask.arm();
do_timeout(1 * T, () => { timePassed = true; });
// This should trigger the immediate execution of the task.
- deferredTask.finalize().then(function () {
+ deferredTask.finalize().then(function() {
do_check_true(executed);
run_next_test();
});
});
/**
* Checks that the "finalize" method executes the task again from start to
* finish in case it is already running.
@@ -353,17 +353,17 @@ add_test(function test_finalize_executes
let deferredTask = new DeferredTask(function* () {
// The first time, we arm the timer again and set up the finalization.
if (!executed) {
deferredTask.arm();
do_check_true(deferredTask.isArmed);
do_check_true(deferredTask.isRunning);
- deferredTask.finalize().then(function () {
+ deferredTask.finalize().then(function() {
// When we reach this point, the task must be finished.
do_check_true(executedAgain);
do_check_false(timePassed);
do_check_false(deferredTask.isArmed);
do_check_false(deferredTask.isRunning);
run_next_test();
});
--- a/toolkit/modules/tests/xpcshell/test_FileUtils.js
+++ b/toolkit/modules/tests/xpcshell/test_FileUtils.js
@@ -27,17 +27,17 @@ add_test(function test_getFile() {
let other = gProfD.clone();
other.append("foobar");
do_check_true(file.equals(other));
run_next_test();
});
add_test(function test_getFile_nonexistentDir() {
- do_check_throws(function () {
+ do_check_throws(function() {
let file = FileUtils.getFile("NonexistentD", ["foobar"]);
}, Components.results.NS_ERROR_FAILURE);
run_next_test();
});
add_test(function test_getFile_createDirs() {
let file = FileUtils.getFile("ProfD", ["a", "b", "foobar"]);
@@ -63,17 +63,17 @@ add_test(function test_getDir() {
let other = gProfD.clone();
other.append("foodir");
do_check_true(dir.equals(other));
run_next_test();
});
add_test(function test_getDir_nonexistentDir() {
- do_check_throws(function () {
+ do_check_throws(function() {
let file = FileUtils.getDir("NonexistentD", ["foodir"]);
}, Components.results.NS_ERROR_FAILURE);
run_next_test();
});
add_test(function test_getDir_shouldCreate() {
let dir = FileUtils.getDir("ProfD", ["c", "d", "foodir"], true);
@@ -86,17 +86,17 @@ add_test(function test_getDir_shouldCrea
other.append("d");
do_check_true(other.isDirectory());
other.append("foodir");
do_check_true(dir.equals(other));
run_next_test();
});
-var openFileOutputStream_defaultFlags = function (aKind, aFileName) {
+var openFileOutputStream_defaultFlags = function(aKind, aFileName) {
let file = FileUtils.getFile("ProfD", [aFileName]);
let fos;
do_check_true(aKind == "atomic" || aKind == "safe" || aKind == "");
if (aKind == "atomic") {
fos = FileUtils.openAtomicFileOutputStream(file);
} else if (aKind == "safe") {
fos = FileUtils.openSafeFileOutputStream(file);
} else {
@@ -134,17 +134,17 @@ var openFileOutputStream_modeFlags = fun
if (aKind == "atomic") {
fos = FileUtils.openAtomicFileOutputStream(file, FileUtils.MODE_WRONLY);
} else if (aKind == "safe") {
fos = FileUtils.openSafeFileOutputStream(file, FileUtils.MODE_WRONLY);
} else {
fos = FileUtils.openFileOutputStream(file, FileUtils.MODE_WRONLY);
}
let data = "test_modeFlags";
- do_check_throws(function () {
+ do_check_throws(function() {
fos.write(data, data.length);
}, Components.results.NS_ERROR_FILE_NOT_FOUND);
do_check_false(file.exists());
run_next_test();
};
var closeFileOutputStream = function(aKind, aFileName) {
@@ -162,17 +162,17 @@ var closeFileOutputStream = function(aKi
fos.write(data, data.length);
// But once we close it, we can't anymore.
if (aKind == "atomic") {
FileUtils.closeAtomicFileOutputStream(fos);
} else if (aKind == "safe") {
FileUtils.closeSafeFileOutputStream(fos);
}
- do_check_throws(function () {
+ do_check_throws(function() {
fos.write(data, data.length);
}, Components.results.NS_BASE_STREAM_CLOSED);
run_next_test();
};
add_test(function test_openFileOutputStream_defaultFlags() {
openFileOutputStream_defaultFlags("", "george");
});
--- a/toolkit/modules/tests/xpcshell/test_JSONFile.js
+++ b/toolkit/modules/tests/xpcshell/test_JSONFile.js
@@ -41,17 +41,17 @@ function getTempFile(aLeafName)
let [base, ext] = DownloadPaths.splitBaseNameAndExtension(aLeafName);
let leafName = base + "-" + gFileCounter + ext;
gFileCounter++;
// Get a file reference under the temporary directory for this test file.
let file = FileUtils.getFile("TmpD", [leafName]);
do_check_false(file.exists());
- do_register_cleanup(function () {
+ do_register_cleanup(function() {
if (file.exists()) {
file.remove(false);
}
});
return file;
}
--- a/toolkit/modules/tests/xpcshell/test_NewTabUtils.js
+++ b/toolkit/modules/tests/xpcshell/test_NewTabUtils.js
@@ -321,26 +321,26 @@ add_task(function* extractSite() {
});
function TestProvider(getLinksFn) {
this.getLinks = getLinksFn;
this._observers = new Set();
}
TestProvider.prototype = {
- addObserver: function (observer) {
+ addObserver: function(observer) {
this._observers.add(observer);
},
- notifyLinkChanged: function (link, index = -1, deleted = false) {
+ notifyLinkChanged: function(link, index = -1, deleted = false) {
this._notifyObservers("onLinkChanged", link, index, deleted);
},
- notifyManyLinksChanged: function () {
+ notifyManyLinksChanged: function() {
this._notifyObservers("onManyLinksChanged");
},
- _notifyObservers: function () {
+ _notifyObservers: function() {
let observerMethodName = arguments[0];
let args = Array.prototype.slice.call(arguments, 1);
args.unshift(this);
for (let obs of this._observers) {
if (obs[observerMethodName])
obs[observerMethodName].apply(NewTabUtils.links, args);
}
},
--- a/toolkit/modules/tests/xpcshell/test_session_recorder.js
+++ b/toolkit/modules/tests/xpcshell/test_session_recorder.js
@@ -96,17 +96,17 @@ add_task(function* test_current_availabi
Object.defineProperty(recorder, "STARTUP_RETRY_INTERVAL_MS", {
value: 100,
});
let oldRecord = recorder.recordStartupFields;
let recordCount = 0;
Object.defineProperty(recorder, "recordStartupFields", {
- value: function () {
+ value: function() {
recordCount++;
return oldRecord.call(recorder);
}
});
do_check_null(recorder._timer);
recorder.onStartup();
do_check_eq(recordCount, 1);
--- a/toolkit/modules/tests/xpcshell/test_sqlite.js
+++ b/toolkit/modules/tests/xpcshell/test_sqlite.js
@@ -21,17 +21,17 @@ Cu.import("resource://services-common/as
function sleep(ms) {
let deferred = Promise.defer();
let timer = Cc["@mozilla.org/timer;1"]
.createInstance(Ci.nsITimer);
timer.initWithCallback({
- notify: function () {
+ notify: function() {
deferred.resolve();
},
}, ms, timer.TYPE_ONE_SHOT);
return deferred.promise;
}
// When testing finalization, use this to tell Sqlite.jsm to not throw
@@ -492,17 +492,17 @@ add_task(function* test_shrink_memory()
add_task(function* test_no_shrink_on_init() {
let c = yield getConnection("no_shrink_on_init",
{shrinkMemoryOnConnectionIdleMS: 200});
let oldShrink = c._connectionData.shrinkMemory;
let count = 0;
Object.defineProperty(c._connectionData, "shrinkMemory", {
- value: function () {
+ value: function() {
count++;
},
});
// We should not shrink until a statement has been executed.
yield sleep(220);
do_check_eq(count, 0);
@@ -518,17 +518,17 @@ add_task(function* test_idle_shrink_fire
{shrinkMemoryOnConnectionIdleMS: 200});
c._connectionData._clearIdleShrinkTimer();
let oldShrink = c._connectionData.shrinkMemory;
let shrinkPromises = [];
let count = 0;
Object.defineProperty(c._connectionData, "shrinkMemory", {
- value: function () {
+ value: function() {
count++;
let promise = oldShrink.call(c._connectionData);
shrinkPromises.push(promise);
return promise;
},
});
// We reset the idle shrink timer after monkeypatching because otherwise the
@@ -562,17 +562,17 @@ add_task(function* test_idle_shrink_rese
c._connectionData._clearIdleShrinkTimer();
let oldShrink = c._connectionData.shrinkMemory;
let shrinkPromises = [];
let count = 0;
Object.defineProperty(c._connectionData, "shrinkMemory", {
- value: function () {
+ value: function() {
count++;
let promise = oldShrink.call(c._connectionData);
shrinkPromises.push(promise);
return promise;
},
});
let now = new Date();
@@ -833,60 +833,60 @@ add_task(function* test_direct() {
params.addParams(two);
print("Beginning transaction.");
let begin = db.createAsyncStatement("BEGIN DEFERRED TRANSACTION");
let end = db.createAsyncStatement("COMMIT TRANSACTION");
let deferred = Promise.defer();
begin.executeAsync({
- handleCompletion: function (reason) {
+ handleCompletion: function(reason) {
deferred.resolve();
}
});
yield deferred.promise;
statement.bindParameters(params);
deferred = Promise.defer();
print("Executing async.");
statement.executeAsync({
- handleResult: function (resultSet) {
+ handleResult: function(resultSet) {
},
- handleError: function (error) {
+ handleError: function(error) {
print("Error when executing SQL (" + error.result + "): " +
error.message);
print("Original error: " + error.error);
errors.push(error);
deferred.reject();
},
- handleCompletion: function (reason) {
+ handleCompletion: function(reason) {
print("Completed.");
deferred.resolve();
}
});
yield deferred.promise;
deferred = Promise.defer();
end.executeAsync({
- handleCompletion: function (reason) {
+ handleCompletion: function(reason) {
deferred.resolve();
}
});
yield deferred.promise;
statement.finalize();
begin.finalize();
end.finalize();
deferred = Promise.defer();
- db.asyncClose(function () {
+ db.asyncClose(function() {
deferred.resolve()
});
yield deferred.promise;
});
// Test Sqlite.cloneStorageConnection.
add_task(function* test_cloneStorageConnection() {
let file = new FileUtils.File(OS.Path.join(OS.Constants.Path.profileDir,
@@ -1046,17 +1046,17 @@ add_task(function* test_error_message_on
});
add_task(function* test_forget_witness_on_close() {
let c = yield getDummyDatabase("forget_witness_on_close");
let forgetCalled = false;
let oldWitness = c._witness;
c._witness = {
- forget: function () {
+ forget: function() {
forgetCalled = true;
oldWitness.forget();
},
};
yield c.close();
// After close, witness should have forgotten the connection
do_check_true(forgetCalled);
--- a/toolkit/modules/tests/xpcshell/test_sqlite_shutdown.js
+++ b/toolkit/modules/tests/xpcshell/test_sqlite_shutdown.js
@@ -44,17 +44,17 @@ function* getDummyDatabase(name, extraOp
function sleep(ms) {
let deferred = Promise.defer();
let timer = Cc["@mozilla.org/timer;1"]
.createInstance(Ci.nsITimer);
timer.initWithCallback({
- notify: function () {
+ notify: function() {
deferred.resolve();
},
}, ms, timer.TYPE_ONE_SHOT);
return deferred.promise;
}
function run_test() {
--- a/toolkit/modules/tests/xpcshell/test_web_channel.js
+++ b/toolkit/modules/tests/xpcshell/test_web_channel.js
@@ -16,17 +16,17 @@ const TEST_PERMISSION_NAME = "test-webch
var MockWebChannelBroker = {
_channelMap: new Map(),
registerChannel: function(channel) {
if (!this._channelMap.has(channel)) {
this._channelMap.set(channel);
}
},
- unregisterChannel: function (channelToRemove) {
+ unregisterChannel: function(channelToRemove) {
this._channelMap.delete(channelToRemove)
}
};
function run_test() {
run_next_test();
}
--- a/toolkit/mozapps/downloads/DownloadLastDir.jsm
+++ b/toolkit/mozapps/downloads/DownloadLastDir.jsm
@@ -30,24 +30,24 @@ const nsIFile = Components.interfaces.ns
this.EXPORTED_SYMBOLS = [ "DownloadLastDir" ];
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
var observer = {
- QueryInterface: function (aIID) {
+ QueryInterface: function(aIID) {
if (aIID.equals(Components.interfaces.nsIObserver) ||
aIID.equals(Components.interfaces.nsISupports) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference))
return this;
throw Components.results.NS_NOINTERFACE;
},
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
switch (aTopic) {
case "last-pb-context-exited":
gDownloadLastDirFile = null;
break;
case "browser:purge-session-history":
gDownloadLastDirFile = null;
if (Services.prefs.prefHasUserValue(LAST_DIR_PREF))
Services.prefs.clearUserPref(LAST_DIR_PREF);
@@ -104,22 +104,22 @@ this.DownloadLastDir = function Download
DownloadLastDir.prototype = {
isPrivate: function DownloadLastDir_isPrivate() {
return this.fakeContext.usePrivateBrowsing;
},
// compat shims
get file() { return this._getLastFile(); },
set file(val) { this.setFile(null, val); },
- cleanupPrivateFile: function () {
+ cleanupPrivateFile: function() {
gDownloadLastDirFile = null;
},
// This function is now deprecated as it uses the sync nsIContentPrefService
// interface. New consumers should use the getFileAsync function.
- getFile: function (aURI) {
+ getFile: function(aURI) {
let Deprecated = Components.utils.import("resource://gre/modules/Deprecated.jsm", {}).Deprecated;
Deprecated.warning("DownloadLastDir.getFile is deprecated. Please use getFileAsync instead.",
"https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/DownloadLastDir.jsm",
Components.stack.caller);
if (aURI && isContentPrefEnabled()) {
let lastDir = Services.contentPrefs.getPref(aURI, LAST_DIR_PREF, this.fakeContext);
if (lastDir) {
@@ -127,17 +127,17 @@ DownloadLastDir.prototype = {
.createInstance(Components.interfaces.nsIFile);
lastDirFile.initWithPath(lastDir);
return lastDirFile;
}
}
return this._getLastFile();
},
- _getLastFile: function () {
+ _getLastFile: function() {
if (gDownloadLastDirFile && !gDownloadLastDirFile.exists())
gDownloadLastDirFile = null;
if (this.isPrivate()) {
if (!gDownloadLastDirFile)
gDownloadLastDirFile = readLastDirPref();
return gDownloadLastDirFile;
}
@@ -166,17 +166,17 @@ DownloadLastDir.prototype = {
.createInstance(Components.interfaces.nsIFile);
file.initWithPath(result.value);
}
aCallback(file);
}
});
},
- setFile: function (aURI, aFile) {
+ setFile: function(aURI, aFile) {
if (aURI && isContentPrefEnabled()) {
let uri = aURI instanceof Components.interfaces.nsIURI ? aURI.spec : aURI;
let cps2 = Components.classes["@mozilla.org/content-pref/service;1"]
.getService(Components.interfaces.nsIContentPrefService2);
if (aFile instanceof Components.interfaces.nsIFile)
cps2.set(uri, LAST_DIR_PREF, aFile.path, this.fakeContext);
else
cps2.removeByDomainAndName(uri, LAST_DIR_PREF, this.fakeContext);
--- a/toolkit/mozapps/downloads/DownloadTaskbarProgress.jsm
+++ b/toolkit/mozapps/downloads/DownloadTaskbarProgress.jsm
@@ -191,17 +191,17 @@ var DownloadTaskbarProgressUpdater =
QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIXULWindow).docShell;
let taskbarProgress = this._taskbar.getTaskbarProgress(docShell);
this._activeTaskbarProgress = taskbarProgress;
this._updateTaskbar();
// _onActiveWindowUnload is idempotent, so we don't need to check whether
// we've already set this before or not.
- aWindow.addEventListener("unload", function () {
+ aWindow.addEventListener("unload", function() {
DownloadTaskbarProgressUpdater._onActiveWindowUnload(taskbarProgress);
}, false);
}
else {
this._activeTaskbarProgress = null;
}
}
},
--- a/toolkit/mozapps/downloads/content/downloads.js
+++ b/toolkit/mozapps/downloads/content/downloads.js
@@ -629,17 +629,17 @@ function buildContextMenu(aEvent)
return true;
}
return false;
}
// Drag and Drop
var gDownloadDNDObserver =
{
- onDragStart: function (aEvent)
+ onDragStart: function(aEvent)
{
if (!gDownloadsView.selectedItem)
return;
var dl = gDownloadsView.selectedItem;
var f = getLocalFileFromNativePathOrUrl(dl.getAttribute("file"));
if (!f.exists())
return;
@@ -647,17 +647,17 @@ var gDownloadDNDObserver =
dt.mozSetDataAt("application/x-moz-file", f, 0);
var url = Services.io.newFileURI(f).spec;
dt.setData("text/uri-list", url);
dt.setData("text/plain", url);
dt.effectAllowed = "copyMove";
dt.addElement(dl);
},
- onDragOver: function (aEvent)
+ onDragOver: function(aEvent)
{
var types = aEvent.dataTransfer.types;
if (types.includes("text/uri-list") ||
types.includes("text/x-moz-url") ||
types.includes("text/plain"))
aEvent.preventDefault();
},
--- a/toolkit/mozapps/extensions/AddonManager.jsm
+++ b/toolkit/mozapps/extensions/AddonManager.jsm
@@ -2614,21 +2614,19 @@ var AddonManagerInternal = {
if (typeof aCallback != "function")
throw Components.Exception("aCallback must be a function",
Cr.NS_ERROR_INVALID_ARG);
let addons = [];
new AsyncObjectCaller(this.providers, "getAddonsWithOperationsByTypes", {
- nextObject: function getAddonsWithOperationsByTypes_nextObject
- (aCaller, aProvider) {
+ nextObject: function getAddonsWithOperationsByTypes_nextObject(aCaller, aProvider) {
callProviderAsync(aProvider, "getAddonsWithOperationsByTypes", aTypes,
- function getAddonsWithOperationsByTypes_concatAddons
- (aProviderAddons) {
+ function getAddonsWithOperationsByTypes_concatAddons(aProviderAddons) {
if (aProviderAddons) {
addons = addons.concat(aProviderAddons);
}
aCaller.callNext();
});
},
noMoreObjects: function(caller) {
--- a/toolkit/mozapps/extensions/LightweightThemeManager.jsm
+++ b/toolkit/mozapps/extensions/LightweightThemeManager.jsm
@@ -99,57 +99,57 @@ this.LightweightThemeManager = {
get name() {
return "LightweightThemeManager";
},
// Themes that can be added for an application. They can't be removed, and
// will always show up at the top of the list.
_builtInThemes: new Map(),
- get usedThemes () {
+ get usedThemes() {
let themes = [];
try {
themes = JSON.parse(_prefs.getComplexValue("usedThemes",
Ci.nsISupportsString).data);
} catch (e) { }
themes.push(...this._builtInThemes.values());
return themes;
},
- get currentTheme () {
+ get currentTheme() {
let selectedThemeID = null;
try {
selectedThemeID = _prefs.getCharPref("selectedThemeID");
} catch (e) {}
let data = null;
if (selectedThemeID) {
data = this.getUsedTheme(selectedThemeID);
}
return data;
},
- get currentThemeForDisplay () {
+ get currentThemeForDisplay() {
var data = this.currentTheme;
if (data && PERSIST_ENABLED) {
for (let key in PERSIST_FILES) {
try {
if (data[key] && _prefs.getBoolPref("persisted." + key))
data[key] = _getLocalImageURI(PERSIST_FILES[key]).spec
+ "?" + data.id + ";" + _version(data);
} catch (e) {}
}
}
return data;
},
- set currentTheme (aData) {
+ set currentTheme(aData) {
return _setCurrentTheme(aData, false);
},
setLocalTheme: function(aData) {
_setCurrentTheme(aData, true);
},
getUsedTheme: function(aId) {
@@ -823,17 +823,17 @@ function _prefObserver(aSubject, aTopic,
// Update the theme list to remove any themes over the number we keep
_updateUsedThemes(LightweightThemeManager.usedThemes);
break;
}
}
function _persistImages(aData, aCallback) {
function onSuccess(key) {
- return function () {
+ return function() {
let current = LightweightThemeManager.currentTheme;
if (current && current.id == aData.id) {
_prefs.setBoolPref("persisted." + key, true);
}
if (--numFilesToPersist == 0 && aCallback) {
aCallback();
}
};
--- a/toolkit/mozapps/extensions/content/update.js
+++ b/toolkit/mozapps/extensions/content/update.js
@@ -71,17 +71,17 @@ var gUpdateWizard = {
}
if (Services.io.offline)
document.documentElement.currentPage = document.getElementById("offline");
else
document.documentElement.currentPage = document.getElementById("versioninfo");
},
- onWizardFinish: function gUpdateWizard_onWizardFinish ()
+ onWizardFinish: function gUpdateWizard_onWizardFinish()
{
if (this.shouldSuggestAutoChecking)
Services.prefs.setBoolPref(PREF_UPDATE_EXTENSIONS_ENABLED, this.shouldAutoCheck);
},
_setUpButton: function(aButtonID, aButtonKey, aDisabled)
{
var strings = document.getElementById("updateStrings");
--- a/toolkit/mozapps/extensions/nsBlocklistService.js
+++ b/toolkit/mozapps/extensions/nsBlocklistService.js
@@ -1104,17 +1104,17 @@ Blocklist.prototype = {
// <driverVersion> 8.52.322.2202 </driverVersion>
// <driverVersionMax> 8.52.322.2202 </driverVersionMax>
// <driverVersionComparator> LESS_THAN_OR_EQUAL </driverVersionComparator>
// <model>foo</model>
// <product>foo</product>
// <manufacturer>foo</manufacturer>
// <hardware>foo</hardware>
// </gfxBlacklistEntry>
- _handleGfxBlacklistNode: function (blocklistElement, result) {
+ _handleGfxBlacklistNode: function(blocklistElement, result) {
const blockEntry = {};
// The blockID attribute is always present in the actual data produced on server
// (see https://github.com/mozilla/addons-server/blob/2016.05.05/src/olympia/blocklist/templates/blocklist/blocklist.xml#L74)
// But it is sometimes missing in test fixtures.
if (blocklistElement.hasAttribute("blockID")) {
blockEntry.blockID = blocklistElement.getAttribute("blockID");
}
@@ -1295,17 +1295,17 @@ Blocklist.prototype = {
let {entry: blockEntry, version: blockEntryVersion} = r;
if (!blockEntry.blockID) {
return null;
}
return blockEntry.infoURL;
},
- _notifyObserversBlocklistGFX: function () {
+ _notifyObserversBlocklistGFX: function() {
// Notify `GfxInfoBase`, by passing a string serialization.
// This way we avoid spreading XML structure logics there.
const payload = this._gfxEntries.map((r) => {
return Object.keys(r).sort().filter((k) => !/id|last_modified/.test(k)).map((key) => {
let value = r[key];
if (Array.isArray(value)) {
value = value.join(",");
} else if (value.hasOwnProperty("minVersion")) {
--- a/toolkit/mozapps/extensions/test/AddonManagerTesting.jsm
+++ b/toolkit/mozapps/extensions/test/AddonManagerTesting.jsm
@@ -21,59 +21,59 @@ XPCOMUtils.defineLazyModuleGetter(this,
this.AddonManagerTesting = {
/**
* Get the add-on that is specified by its ID.
*
* @return {Promise<Object>} A promise that resolves returning the found addon or null
* if it is not found.
*/
- getAddonById: function (id) {
+ getAddonById: function(id) {
return new Promise(resolve => AddonManager.getAddonByID(id, addon => resolve(addon)));
},
/**
* Uninstall an add-on that is specified by its ID.
*
* The returned promise resolves on successful uninstall and rejects
* if the add-on is not unknown.
*
* @return Promise<restartRequired>
*/
- uninstallAddonByID: function (id) {
+ uninstallAddonByID: function(id) {
let deferred = Promise.defer();
AddonManager.getAddonByID(id, (addon) => {
if (!addon) {
deferred.reject(new Error("Add-on is not known: " + id));
return;
}
let listener = {
- onUninstalling: function (addon, needsRestart) {
+ onUninstalling: function(addon, needsRestart) {
if (addon.id != id) {
return;
}
if (needsRestart) {
AddonManager.removeAddonListener(listener);
deferred.resolve(true);
}
},
- onUninstalled: function (addon) {
+ onUninstalled: function(addon) {
if (addon.id != id) {
return;
}
AddonManager.removeAddonListener(listener);
deferred.resolve(false);
},
- onOperationCancelled: function (addon) {
+ onOperationCancelled: function(addon) {
if (addon.id != id) {
return;
}
AddonManager.removeAddonListener(listener);
deferred.reject(new Error("Uninstall cancelled."));
},
};
@@ -85,28 +85,28 @@ this.AddonManagerTesting = {
return deferred.promise;
},
/**
* Install an XPI add-on from a URL.
*
* @return Promise<addon>
*/
- installXPIFromURL: function (url, hash, name, iconURL, version) {
+ installXPIFromURL: function(url, hash, name, iconURL, version) {
let deferred = Promise.defer();
AddonManager.getInstallForURL(url, (install) => {
let fail = () => { deferred.reject(new Error("Add-on install failed.")) };
let listener = {
onDownloadCancelled: fail,
onDownloadFailed: fail,
onInstallCancelled: fail,
onInstallFailed: fail,
- onInstallEnded: function (install, addon) {
+ onInstallEnded: function(install, addon) {
deferred.resolve(addon);
},
};
install.addListener(listener);
install.install();
}, "application/x-xpinstall", hash, name, iconURL, version);
--- a/toolkit/mozapps/extensions/test/browser/addons/browser_inlinesettings1/bootstrap.js
+++ b/toolkit/mozapps/extensions/test/browser/addons/browser_inlinesettings1/bootstrap.js
@@ -1,8 +1,8 @@
-function install (params, aReason) {
+function install(params, aReason) {
}
-function uninstall (params, aReason) {
+function uninstall(params, aReason) {
}
-function startup (params, aReason) {
+function startup(params, aReason) {
}
-function shutdown (params, aReason) {
+function shutdown(params, aReason) {
}
--- a/toolkit/mozapps/extensions/test/browser/addons/browser_inlinesettings1_custom/bootstrap.js
+++ b/toolkit/mozapps/extensions/test/browser/addons/browser_inlinesettings1_custom/bootstrap.js
@@ -1,8 +1,8 @@
-function install (params, aReason) {
+function install(params, aReason) {
}
-function uninstall (params, aReason) {
+function uninstall(params, aReason) {
}
-function startup (params, aReason) {
+function startup(params, aReason) {
}
-function shutdown (params, aReason) {
+function shutdown(params, aReason) {
}
--- a/toolkit/mozapps/extensions/test/browser/addons/browser_inlinesettings1_info/bootstrap.js
+++ b/toolkit/mozapps/extensions/test/browser/addons/browser_inlinesettings1_info/bootstrap.js
@@ -1,8 +1,8 @@
-function install (params, aReason) {
+function install(params, aReason) {
}
-function uninstall (params, aReason) {
+function uninstall(params, aReason) {
}
-function startup (params, aReason) {
+function startup(params, aReason) {
}
-function shutdown (params, aReason) {
+function shutdown(params, aReason) {
}
--- a/toolkit/mozapps/extensions/test/browser/browser_bug557956.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_bug557956.js
@@ -195,17 +195,17 @@ function check_telemetry({disabled, meta
is(am.appUpdate_upgradeFailed, failed, failed + " upgrades failed");
if (declined !== undefined)
is(am.appUpdate_upgradeDeclined, declined, declined + " upgrades declined");
}
add_test(function test_setup() {
let oldCanRecord = Services.telemetry.canRecordExtended;
Services.telemetry.canRecordExtended = true;
- registerCleanupFunction(function () {
+ registerCleanupFunction(function() {
Services.telemetry.canRecordExtended = oldCanRecord;
});
run_next_test();
});
// Tests that the right add-ons show up in the mismatch dialog and updates can
// be installed
add_test(function basic_mismatch() {
--- a/toolkit/mozapps/extensions/test/browser/browser_bug562992.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_bug562992.js
@@ -16,45 +16,45 @@ var gInstall;
const EXTENSION_NAME = "Wunderbar";
function test() {
waitForExplicitFinish();
gProvider = new MockProvider();
- open_manager("addons://list/extension", function (aWindow) {
+ open_manager("addons://list/extension", function(aWindow) {
gManagerWindow = aWindow;
run_next_test();
});
}
function end_test() {
- close_manager(gManagerWindow, function () {
+ close_manager(gManagerWindow, function() {
finish();
});
}
// Create a MockInstall with a MockAddon payload and add it to the provider,
// causing the onNewInstall event to fire, which in turn will cause a new
// "installing" item to appear in the list of extensions.
-add_test(function () {
+add_test(function() {
let addon = new MockAddon(undefined, EXTENSION_NAME, "extension", true);
gInstall = new MockInstall(undefined, undefined, addon);
gInstall.addTestListener({
onNewInstall: run_next_test
});
gProvider.addInstall(gInstall);
});
// Finish the install, which will cause the "installing" item to be converted
// to an "installed" item, which should have the correct add-on name.
-add_test(function () {
+add_test(function() {
gInstall.addTestListener({
- onInstallEnded: function () {
+ onInstallEnded: function() {
let list = gManagerWindow.document.getElementById("addon-list");
// To help prevent future breakage, don't assume the item is the only one
// in the list, or that it's first in the list. Find it by name.
for (let i = 0; i < list.itemCount; i++) {
let item = list.getItemAtIndex(i);
if (item.getAttribute("name") === EXTENSION_NAME) {
ok(true, "Item with correct name found");
--- a/toolkit/mozapps/extensions/test/browser/browser_inlinesettings.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_inlinesettings.js
@@ -98,17 +98,17 @@ function test() {
optionsType: AddonManager.OPTIONS_TYPE_INLINE
}, {
id: "noninlinesettings@tests.mozilla.org",
name: "Non-Inline Settings",
version: "1",
optionsURL: CHROMEROOT + "addon_prefs.xul"
}]);
- installAddon(function () {
+ installAddon(function() {
open_manager("addons://list/extension", function(aWindow) {
gManagerWindow = aWindow;
gCategoryUtilities = new CategoryUtilities(gManagerWindow);
Services.obs.addObserver(observer,
AddonManager.OPTIONS_NOTIFICATION_DISPLAYED,
false);
Services.obs.addObserver(observer,
--- a/toolkit/mozapps/extensions/test/browser/browser_inlinesettings_custom.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_inlinesettings_custom.js
@@ -17,17 +17,17 @@ function installAddon(aCallback) {
});
aInstall.install();
}, "application/x-xpinstall");
}
function test() {
waitForExplicitFinish();
- installAddon(function () {
+ installAddon(function() {
open_manager("addons://list/extension", function(aWindow) {
gManagerWindow = aWindow;
gCategoryUtilities = new CategoryUtilities(gManagerWindow);
run_next_test();
});
});
}
--- a/toolkit/mozapps/extensions/test/browser/browser_inlinesettings_info.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_inlinesettings_info.js
@@ -98,17 +98,17 @@ function test() {
optionsType: AddonManager.OPTIONS_TYPE_INLINE_INFO
}, {
id: "noninlinesettings@tests.mozilla.org",
name: "Non-Inline Settings",
version: "1",
optionsURL: CHROMEROOT + "addon_prefs.xul"
}]);
- installAddon(function () {
+ installAddon(function() {
open_manager("addons://list/extension", function(aWindow) {
gManagerWindow = aWindow;
gCategoryUtilities = new CategoryUtilities(gManagerWindow);
Services.obs.addObserver(observer,
AddonManager.OPTIONS_NOTIFICATION_DISPLAYED,
false);
Services.obs.addObserver(observer,
--- a/toolkit/mozapps/extensions/test/browser/browser_openDialog.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_openDialog.js
@@ -111,23 +111,23 @@ function test() {
return null;
}
function observer(aSubject, aTopic, aData) {
switch (aTopic) {
case "domwindowclosed":
// Give the preference window a chance to finish closing before
// closing the add-ons manager.
- waitForFocus(function () {
+ waitForFocus(function() {
test_next_addon();
});
break;
case "domwindowopened":
let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
- waitForFocus(function () {
+ waitForFocus(function() {
// If the openDialog privileges are wrong a new browser window
// will open, let the test proceed (and fail) rather than timeout.
if (win.location != currentAddon.optionsURL &&
win.location != "chrome://browser/content/browser.xul")
return;
is(win.location, currentAddon.optionsURL,
"The correct addon pref window should have opened");
--- a/toolkit/mozapps/extensions/test/browser/browser_tabsettings.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_tabsettings.js
@@ -58,24 +58,24 @@ add_test(function() {
let instantApply = Services.prefs.getBoolPref("browser.preferences.instantApply");
function observer(aSubject, aTopic, aData) {
switch (aTopic) {
case "domwindowclosed":
// Give the preference window a chance to finish closing before
// closing the add-ons manager.
- waitForFocus(function () {
+ waitForFocus(function() {
Services.ww.unregisterNotification(observer);
run_next_test();
});
break;
case "domwindowopened":
let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
- waitForFocus(function () {
+ waitForFocus(function() {
// If the openDialog privileges are wrong a new browser window
// will open, let the test proceed (and fail) rather than timeout.
if (win.location != addon.mAddon.optionsURL &&
win.location != "chrome://browser/content/browser.xul")
return;
is(win.location, addon.mAddon.optionsURL,
"The correct addon pref window should have opened");
--- a/toolkit/mozapps/extensions/test/browser/browser_webapi_install.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_webapi_install.js
@@ -280,17 +280,17 @@ add_task(makeInstallTest(function* (brow
is(addons[0], null, "The addon was not installed");
ok(AddonManager.webAPI.installs.size > 0, "webAPI is tracking the AddonInstall");
}));
add_task(function* test_permissions() {
function testBadUrl(url, pattern, successMessage) {
return BrowserTestUtils.withNewTab(TESTPAGE, function* (browser) {
- let result = yield ContentTask.spawn(browser, {url, pattern}, function (opts) {
+ let result = yield ContentTask.spawn(browser, {url, pattern}, function(opts) {
return new Promise(resolve => {
content.navigator.mozAddonManager.createInstall({url: opts.url})
.then(() => {
resolve({success: false, message: "createInstall should not have succeeded"});
}, err => {
if (err.message.match(new RegExp(opts.pattern))) {
resolve({success: true});
}
--- a/toolkit/mozapps/extensions/test/browser/head.js
+++ b/toolkit/mozapps/extensions/test/browser/head.js
@@ -408,30 +408,30 @@ function open_manager(aView, aCallback,
resolve(aManagerWindow);
}, null, aLongerTimeout);
});
}, aManagerWindow);
}
if (gUseInContentUI) {
info("Loading manager window in tab");
- Services.obs.addObserver(function (aSubject, aTopic, aData) {
+ Services.obs.addObserver(function(aSubject, aTopic, aData) {
Services.obs.removeObserver(arguments.callee, aTopic);
if (aSubject.location.href != MANAGER_URI) {
info("Ignoring load event for " + aSubject.location.href);
return;
}
setup_manager(aSubject);
}, "EM-loaded", false);
gBrowser.selectedTab = gBrowser.addTab();
switchToTabHavingURI(MANAGER_URI, true);
} else {
info("Loading manager window in dialog");
- Services.obs.addObserver(function (aSubject, aTopic, aData) {
+ Services.obs.addObserver(function(aSubject, aTopic, aData) {
Services.obs.removeObserver(arguments.callee, aTopic);
setup_manager(aSubject);
}, "EM-loaded", false);
openDialog(MANAGER_URI);
}
});
@@ -643,30 +643,30 @@ function CertOverrideListener(host, bits
this.host = host;
this.bits = bits;
}
CertOverrideListener.prototype = {
host: null,
bits: null,
- getInterface: function (aIID) {
+ getInterface: function(aIID) {
return this.QueryInterface(aIID);
},
QueryInterface: function(aIID) {
if (aIID.equals(Ci.nsIBadCertListener2) ||
aIID.equals(Ci.nsIInterfaceRequestor) ||
aIID.equals(Ci.nsISupports))
return this;
throw Components.Exception("No interface", Components.results.NS_ERROR_NO_INTERFACE);
},
- notifyCertProblem: function (socketInfo, sslStatus, targetHost) {
+ notifyCertProblem: function(socketInfo, sslStatus, targetHost) {
var cert = sslStatus.QueryInterface(Components.interfaces.nsISSLStatus)
.serverCert;
var cos = Cc["@mozilla.org/security/certoverride;1"].
getService(Ci.nsICertOverrideService);
cos.rememberValidityOverride(this.host, -1, cert, this.bits, false);
return true;
}
}
--- a/toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository_cache.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository_cache.js
@@ -195,23 +195,23 @@ const WITHOUT_CACHE = [{
version: "1.2",
sourceURI: NetUtil.newURI(ADDON_FILES[1]).spec,
icons: {}
}, {
id: ADDON_IDS[2],
type: "theme",
name: "XPI Add-on 3",
version: "1.3",
- get iconURL () {
+ get iconURL() {
return get_subfile_uri(ADDON_IDS[2], "icon.png");
},
- get icons () {
+ get icons() {
return { "32": get_subfile_uri(ADDON_IDS[2], "icon.png") };
},
- screenshots: [{ get url () { return get_subfile_uri(ADDON_IDS[2], "preview.png"); } }],
+ screenshots: [{ get url() { return get_subfile_uri(ADDON_IDS[2], "preview.png"); } }],
sourceURI: NetUtil.newURI(ADDON_FILES[2]).spec
}];
// Expected add-ons when using cache
const WITH_CACHE = [{
id: ADDON_IDS[0],
type: "extension",
@@ -305,20 +305,20 @@ const WITH_CACHE = [{
dailyUsers: 4442,
sourceURI: NetUtil.newURI(ADDON_FILES[1]).spec,
repositoryStatus: 9
}, {
id: ADDON_IDS[2],
type: "theme",
name: "XPI Add-on 3",
version: "1.3",
- get iconURL () {
+ get iconURL() {
return get_subfile_uri(ADDON_IDS[2], "icon.png");
},
- get icons () {
+ get icons() {
return { "32": get_subfile_uri(ADDON_IDS[2], "icon.png") };
},
screenshots: [{
url: BASE_URL + "/repo/3/firstFull.png",
thumbnailURL: BASE_URL + "/repo/3/firstThumbnail.png",
caption: "Repo Add-on 3 - First Caption"
}, {
url: BASE_URL + "/repo/3/secondFull.png",
@@ -386,23 +386,23 @@ const WITH_EXTENSION_CACHE = [{
version: "1.2",
sourceURI: NetUtil.newURI(ADDON_FILES[1]).spec,
icons: {}
}, {
id: ADDON_IDS[2],
type: "theme",
name: "XPI Add-on 3",
version: "1.3",
- get iconURL () {
+ get iconURL() {
return get_subfile_uri(ADDON_IDS[2], "icon.png");
},
- get icons () {
+ get icons() {
return { "32": get_subfile_uri(ADDON_IDS[2], "icon.png") };
},
- screenshots: [{ get url () { return get_subfile_uri(ADDON_IDS[2], "preview.png"); } }],
+ screenshots: [{ get url() { return get_subfile_uri(ADDON_IDS[2], "preview.png"); } }],
sourceURI: NetUtil.newURI(ADDON_FILES[2]).spec
}];
var gDBFile = gProfD.clone();
gDBFile.append(FILE_DATABASE);
/*
* Check the actual add-on results against the expected add-on results
--- a/toolkit/mozapps/extensions/test/xpcshell/test_LightweightThemeManager.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_LightweightThemeManager.js
@@ -201,110 +201,110 @@ function run_test() {
data.unknownProperty = "Foo";
do_check_eq(typeof roundtrip(data).unknownProperty, "undefined");
data = dummy();
data.unknownURL = "http://lwttest.invalid/";
do_check_eq(typeof roundtrip(data).unknownURL, "undefined");
function roundtripSet(props, modify, test, secure) {
- props.forEach(function (prop) {
+ props.forEach(function(prop) {
var data = dummy();
modify(data, prop);
test(roundtrip(data, secure), prop, data);
});
}
- roundtripSet(MANDATORY, function (data, prop) {
+ roundtripSet(MANDATORY, function(data, prop) {
delete data[prop];
- }, function (after) {
+ }, function(after) {
do_check_eq(after, null);
});
- roundtripSet(OPTIONAL, function (data, prop) {
+ roundtripSet(OPTIONAL, function(data, prop) {
delete data[prop];
- }, function (after) {
+ }, function(after) {
do_check_neq(after, null);
});
- roundtripSet(MANDATORY, function (data, prop) {
+ roundtripSet(MANDATORY, function(data, prop) {
data[prop] = "";
- }, function (after) {
+ }, function(after) {
do_check_eq(after, null);
});
- roundtripSet(OPTIONAL, function (data, prop) {
+ roundtripSet(OPTIONAL, function(data, prop) {
data[prop] = "";
- }, function (after, prop) {
+ }, function(after, prop) {
do_check_eq(typeof after[prop], "undefined");
});
- roundtripSet(MANDATORY, function (data, prop) {
+ roundtripSet(MANDATORY, function(data, prop) {
data[prop] = " ";
- }, function (after) {
+ }, function(after) {
do_check_eq(after, null);
});
- roundtripSet(OPTIONAL, function (data, prop) {
+ roundtripSet(OPTIONAL, function(data, prop) {
data[prop] = " ";
- }, function (after, prop) {
+ }, function(after, prop) {
do_check_neq(after, null);
do_check_eq(typeof after[prop], "undefined");
});
function non_urls(props) {
return props.filter(prop => !/URL$/.test(prop));
}
function urls(props) {
return props.filter(prop => /URL$/.test(prop));
}
- roundtripSet(non_urls(MANDATORY.concat(OPTIONAL)), function (data, prop) {
+ roundtripSet(non_urls(MANDATORY.concat(OPTIONAL)), function(data, prop) {
data[prop] = prop;
- }, function (after, prop, before) {
+ }, function(after, prop, before) {
do_check_eq(after[prop], before[prop]);
});
- roundtripSet(non_urls(MANDATORY.concat(OPTIONAL)), function (data, prop) {
+ roundtripSet(non_urls(MANDATORY.concat(OPTIONAL)), function(data, prop) {
data[prop] = " " + prop + " ";
- }, function (after, prop, before) {
+ }, function(after, prop, before) {
do_check_eq(after[prop], before[prop].trim());
});
- roundtripSet(urls(MANDATORY.concat(OPTIONAL)), function (data, prop) {
+ roundtripSet(urls(MANDATORY.concat(OPTIONAL)), function(data, prop) {
data[prop] = Math.random().toString();
- }, function (after, prop, before) {
+ }, function(after, prop, before) {
if (prop == "updateURL")
do_check_eq(typeof after[prop], "undefined");
else
do_check_eq(after[prop], "http://lwttest.invalid/" + before[prop]);
});
- roundtripSet(urls(MANDATORY.concat(OPTIONAL)), function (data, prop) {
+ roundtripSet(urls(MANDATORY.concat(OPTIONAL)), function(data, prop) {
data[prop] = Math.random().toString();
- }, function (after, prop, before) {
+ }, function(after, prop, before) {
do_check_eq(after[prop], "https://lwttest.invalid/" + before[prop]);
}, true);
- roundtripSet(urls(MANDATORY.concat(OPTIONAL)), function (data, prop) {
+ roundtripSet(urls(MANDATORY.concat(OPTIONAL)), function(data, prop) {
data[prop] = "https://sub.lwttest.invalid/" + Math.random().toString();
- }, function (after, prop, before) {
+ }, function(after, prop, before) {
do_check_eq(after[prop], before[prop]);
});
- roundtripSet(urls(MANDATORY), function (data, prop) {
+ roundtripSet(urls(MANDATORY), function(data, prop) {
data[prop] = "ftp://lwttest.invalid/" + Math.random().toString();
- }, function (after) {
+ }, function(after) {
do_check_eq(after, null);
});
- roundtripSet(urls(OPTIONAL), function (data, prop) {
+ roundtripSet(urls(OPTIONAL), function(data, prop) {
data[prop] = "ftp://lwttest.invalid/" + Math.random().toString();
- }, function (after, prop) {
+ }, function(after, prop) {
do_check_eq(typeof after[prop], "undefined");
});
do_check_eq(ltm.usedThemes.length, 0);
do_check_eq(ltm.currentTheme, null);
data = dummy();
delete data.name;
--- a/toolkit/mozapps/extensions/test/xpcshell/test_XPIcancel.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_XPIcancel.js
@@ -9,17 +9,17 @@ var XPIProvider = scope.XPIProvider;
function run_test() {
// Check that cancelling with nothing in progress doesn't blow up
XPIProvider.cancelAll();
// Check that a basic object gets cancelled
let getsCancelled = {
isCancelled: false,
- cancel: function () {
+ cancel: function() {
if (this.isCancelled)
do_throw("Already cancelled");
this.isCancelled = true;
}
};
XPIProvider.doing(getsCancelled);
XPIProvider.cancelAll();
do_check_true(getsCancelled.isCancelled);
@@ -31,33 +31,33 @@ function run_test() {
XPIProvider.doing(doesntGetCancelled);
do_check_true(XPIProvider.done(doesntGetCancelled));
XPIProvider.cancelAll();
// A cancellable that adds a cancellable
getsCancelled.isCancelled = false;
let addsAnother = {
isCancelled: false,
- cancel: function () {
+ cancel: function() {
if (this.isCancelled)
do_throw("Already cancelled");
this.isCancelled = true;
XPIProvider.doing(getsCancelled);
}
}
XPIProvider.doing(addsAnother);
XPIProvider.cancelAll();
do_check_true(addsAnother.isCancelled);
do_check_true(getsCancelled.isCancelled);
// A cancellable that removes another. This assumes that Set() iterates in the
// order that members were added
let removesAnother = {
isCancelled: false,
- cancel: function () {
+ cancel: function() {
if (this.isCancelled)
do_throw("Already cancelled");
this.isCancelled = true;
XPIProvider.done(doesntGetCancelled);
}
}
XPIProvider.doing(removesAnother);
XPIProvider.doing(doesntGetCancelled);
--- a/toolkit/mozapps/extensions/test/xpcshell/test_isDebuggable.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_isDebuggable.js
@@ -18,17 +18,17 @@ var IDS = [
function run_test() {
do_test_pending();
createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "2", "2");
startupManager();
AddonManager.checkCompatibility = false;
- installAllFiles(ADDONS.map(do_get_addon), function () {
+ installAllFiles(ADDONS.map(do_get_addon), function() {
restartManager();
AddonManager.getAddonsByIDs(IDS, function([a1, a2, a3]) {
do_check_eq(a1.isDebuggable, false);
do_check_eq(a2.isDebuggable, true);
do_check_eq(a3.isDebuggable, true);
do_test_finished();
});
--- a/toolkit/mozapps/extensions/test/xpcshell/test_migrateAddonRepository.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_migrateAddonRepository.js
@@ -75,17 +75,17 @@ function run_test() {
stmt.execute();
stmt.finalize();
db.schemaVersion = 1;
db.close();
Services.prefs.setBoolPref("extensions.getAddons.cache.enabled", true);
- AddonRepository.getCachedAddonByID("test1@tests.mozilla.org", function (aAddon) {
+ AddonRepository.getCachedAddonByID("test1@tests.mozilla.org", function(aAddon) {
do_check_neq(aAddon, null);
do_check_eq(aAddon.screenshots.length, 1);
do_check_true(aAddon.screenshots[0].width === null);
do_check_true(aAddon.screenshots[0].height === null);
do_check_true(aAddon.screenshots[0].thumbnailWidth === null);
do_check_true(aAddon.screenshots[0].thumbnailHeight === null);
do_check_eq(aAddon.iconURL, undefined);
do_check_eq(JSON.stringify(aAddon.icons), "{}");
--- a/toolkit/mozapps/extensions/test/xpcshell/test_migrate_max_version.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_migrate_max_version.js
@@ -61,17 +61,17 @@ function run_test() {
db.close();
startupManager();
run_next_test();
}
add_test(function before_rebuild() {
AddonManager.getAddonByID("addon1@tests.mozilla.org",
- function check_before_rebuild (a1) {
+ function check_before_rebuild(a1) {
// First check that it migrated OK once
// addon1 was disabled in the database
do_check_neq(a1, null);
do_check_true(a1.userDisabled);
do_check_false(a1.appDisabled);
do_check_false(a1.isActive);
do_check_false(a1.strictCompatibility);
do_check_false(a1.foreignInstall);
--- a/toolkit/mozapps/extensions/test/xpcshell/test_syncGUID.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_syncGUID.js
@@ -1,16 +1,16 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
Components.utils.import("resource://gre/modules/Services.jsm");
// restartManager() mucks with XPIProvider.jsm importing, so we hack around.
-this.__defineGetter__("XPIProvider", function () {
+this.__defineGetter__("XPIProvider", function() {
let scope = {};
return Components.utils.import("resource://gre/modules/addons/XPIProvider.jsm", scope)
.XPIProvider;
});
const addonId = "addon1@tests.mozilla.org";
function run_test() {
--- a/toolkit/mozapps/extensions/test/xpcshell/test_update.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_update.js
@@ -1280,17 +1280,17 @@ function check_test_7() {
gInstallDate = p1.installDate.getTime();
run_next_test();
});
}
// Test that background update checks for lightweight themes do not use the cache
// The update body from test 7 shouldn't be used since the cache should be bypassed.
-add_test(function () {
+add_test(function() {
// XXX The lightweight theme manager strips non-https updateURLs so hack it
// back in.
let themes = JSON.parse(Services.prefs.getCharPref("lightweightThemes.usedThemes"));
do_check_eq(themes.length, 1);
themes[0].updateURL = "http://localhost:" + gPort + "/data/lwtheme.js";
Services.prefs.setCharPref("lightweightThemes.usedThemes", JSON.stringify(themes));
testserver.registerPathHandler("/data/lwtheme.js", function(request, response) {
--- a/toolkit/mozapps/extensions/test/xpcshell/test_update_ignorecompat.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_update_ignorecompat.js
@@ -31,17 +31,17 @@ let testParams = [
appId: "toolkit@mozilla.org" },
];
for (let test of testParams) {
let { updateFile, appId } = test;
// Test that the update check correctly observes the
// extensions.strictCompatibility pref and compatibility overrides.
- add_test(function () {
+ add_test(function() {
writeInstallRDFForExtension({
id: "addon9@tests.mozilla.org",
version: "1.0",
updateURL: "http://localhost:" + gPort + "/data/" + updateFile,
targetApplications: [{
id: appId,
minVersion: "0.1",
maxVersion: "0.2"
@@ -66,17 +66,17 @@ for (let test of testParams) {
"http://localhost:" + gPort + "/data/" + updateFile);
Services.prefs.setBoolPref(PREF_GETADDONS_CACHE_ENABLED, true);
AddonManagerInternal.backgroundUpdateCheck();
});
// Test that the update check correctly observes when an addon opts-in to
// strict compatibility checking.
- add_test(function () {
+ add_test(function() {
writeInstallRDFForExtension({
id: "addon11@tests.mozilla.org",
version: "1.0",
updateURL: "http://localhost:" + gPort + "/data/" + updateFile,
targetApplications: [{
id: appId,
minVersion: "0.1",
maxVersion: "0.2"
--- a/toolkit/mozapps/extensions/test/xpinstall/browser_enabled.js
+++ b/toolkit/mozapps/extensions/test/xpinstall/browser_enabled.js
@@ -1,16 +1,16 @@
// ----------------------------------------------------------------------------
// Test whether an InstallTrigger.enabled is working
function test() {
waitForExplicitFinish();
gBrowser.selectedTab = gBrowser.addTab();
- ContentTask.spawn(gBrowser.selectedBrowser, TESTROOT + "enabled.html", function (url) {
+ ContentTask.spawn(gBrowser.selectedBrowser, TESTROOT + "enabled.html", function(url) {
return new Promise(resolve => {
function page_loaded() {
content.removeEventListener("PageLoaded", page_loaded, false);
resolve(content.document.getElementById("enabled").textContent);
}
function load_listener() {
removeEventListener("load", load_listener, true);
--- a/toolkit/mozapps/extensions/test/xpinstall/browser_enabled2.js
+++ b/toolkit/mozapps/extensions/test/xpinstall/browser_enabled2.js
@@ -2,17 +2,17 @@
// Test whether an InstallTrigger.enabled is working
function test() {
waitForExplicitFinish();
Services.prefs.setBoolPref("xpinstall.enabled", false);
gBrowser.selectedTab = gBrowser.addTab();
- ContentTask.spawn(gBrowser.selectedBrowser, TESTROOT + "enabled.html", function (url) {
+ ContentTask.spawn(gBrowser.selectedBrowser, TESTROOT + "enabled.html", function(url) {
return new Promise(resolve => {
function page_loaded() {
content.removeEventListener("PageLoaded", page_loaded, false);
resolve(content.document.getElementById("enabled").textContent);
}
function load_listener() {
removeEventListener("load", load_listener, true);
--- a/toolkit/mozapps/preferences/fontbuilder.js
+++ b/toolkit/mozapps/preferences/fontbuilder.js
@@ -1,28 +1,28 @@
// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var FontBuilder = {
_enumerator: null,
- get enumerator ()
+ get enumerator()
{
if (!this._enumerator) {
this._enumerator = Components.classes["@mozilla.org/gfx/fontenumerator;1"]
.createInstance(Components.interfaces.nsIFontEnumerator);
}
return this._enumerator;
},
_allFonts: null,
_langGroupSupported: false,
- buildFontList: function (aLanguage, aFontType, aMenuList)
+ buildFontList: function(aLanguage, aFontType, aMenuList)
{
// Reset the list
while (aMenuList.hasChildNodes())
aMenuList.removeChild(aMenuList.firstChild);
var defaultFont = null;
// Load Font Lists
var fonts = this.enumerator.EnumerateFonts(aLanguage, aFontType, { } );
--- a/toolkit/mozapps/preferences/removemp.js
+++ b/toolkit/mozapps/preferences/removemp.js
@@ -5,17 +5,17 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var gRemovePasswordDialog = {
_token : null,
_bundle : null,
_prompt : null,
_okButton : null,
_password : null,
- init: function ()
+ init: function()
{
this._prompt = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
this._bundle = document.getElementById("bundlePreferences");
this._okButton = document.documentElement.getButton("accept");
this._okButton.label = this._bundle.getString("pw_remove_button");
@@ -25,22 +25,22 @@ var gRemovePasswordDialog = {
.getService(Components.interfaces.nsIPK11TokenDB);
this._token = pk11db.getInternalKeyToken();
// Initialize the enabled state of the Remove button by checking the
// initial value of the password ("" should be incorrect).
this.validateInput();
},
- validateInput: function ()
+ validateInput: function()
{
this._okButton.disabled = !this._token.checkPassword(this._password.value);
},
- removePassword: function ()
+ removePassword: function()
{
if (this._token.checkPassword(this._password.value)) {
this._token.changePassword(this._password.value, "");
this._prompt.alert(window,
this._bundle.getString("pw_change_success_title"),
this._bundle.getString("pw_erased_ok")
+ " " + this._bundle.getString("pw_empty_warning"));
}
--- a/toolkit/mozapps/update/content/updates.js
+++ b/toolkit/mozapps/update/content/updates.js
@@ -226,17 +226,17 @@ var gUpdates = {
},
getAUSString: function(key, strings) {
if (strings)
return this.strings.getFormattedString(key, strings);
return this.strings.getString(key);
},
- never: function () {
+ never: function() {
// If the user clicks "No Thanks", we should not prompt them to update to
// this version again unless they manually select "Check for Updates..."
// which will clear all of the "never" prefs. There are currently two
// "never" prefs: the older PREFBRANCH_APP_UPDATE_NEVER as well as the
// OSX-only PREF_APP_UPDATE_ELEVATE_NEVER. We set both of these prefs (if
// applicable) to ensure that we don't prompt the user regardless of which
// pref is checked.
let neverPrefName = PREFBRANCH_APP_UPDATE_NEVER + this.update.appVersion;
@@ -303,17 +303,17 @@ var gUpdates = {
* the user has the app.update.auto preference set to false.
*/
sourceEvent: SRCEVT_FOREGROUND,
/**
* Helper function for onLoad
* Saves default button label & accesskey for use by _setButton
*/
- _cacheButtonStrings: function (buttonName) {
+ _cacheButtonStrings: function(buttonName) {
var button = this.wiz.getButton(buttonName);
button.defaultLabel = button.label;
button.defaultAccesskey = button.getAttribute("accesskey");
},
/**
* Called when the wizard UI is loaded.
*/
@@ -1277,17 +1277,17 @@ var gFinishedPage = {
document.getElementById("finishedBackgroundMoreElevatedLinkLabel");
let manualURL = Services.urlFormatter.formatURLPref(PREF_APP_UPDATE_URL_MANUAL);
moreElevatedLinkLabel.value = manualURL;
moreElevatedLinkLabel.setAttribute("url", manualURL);
moreElevatedLinkLabel.setAttribute("hidden", "false");
}
if (getPref("getBoolPref", PREF_APP_UPDATE_TEST_LOOP, false)) {
- setTimeout(function () { gUpdates.wiz.getButton("finish").click(); },
+ setTimeout(function() { gUpdates.wiz.getButton("finish").click(); },
UPDATE_TEST_LOOP_INTERVAL);
}
},
/**
* Called when the wizard finishes, i.e. the "Restart Now" button is
* clicked.
*/
--- a/toolkit/mozapps/update/nsUpdateService.js
+++ b/toolkit/mozapps/update/nsUpdateService.js
@@ -1788,17 +1788,17 @@ Update.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdate,
Ci.nsIPropertyBag,
Ci.nsIWritablePropertyBag])
};
const UpdateServiceFactory = {
_instance: null,
- createInstance: function (outer, iid) {
+ createInstance: function(outer, iid) {
if (outer != null)
throw Cr.NS_ERROR_NO_AGGREGATION;
return this._instance == null ? this._instance = new UpdateService() :
this._instance;
}
};
/**
@@ -4422,25 +4422,25 @@ UpdatePrompt.prototype = {
* Can be null
*/
_showUnobtrusiveUI: function UP__showUnobUI(parent, uri, features, name, page,
update) {
var observer = {
updatePrompt: this,
service: null,
timer: null,
- notify: function () {
+ notify: function() {
// the user hasn't restarted yet => prompt when idle
this.service.removeObserver(this, "quit-application");
// If the update window is already open skip showing the UI
if (this.updatePrompt._getUpdateWindow())
return;
this.updatePrompt._showUIWhenIdle(parent, uri, features, name, page, update);
},
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
switch (aTopic) {
case "quit-application":
if (this.timer)
this.timer.cancel();
this.service.removeObserver(this, "quit-application");
break;
}
}
@@ -4498,17 +4498,17 @@ UpdatePrompt.prototype = {
// Don't allow the preference to set a value greater than 600 seconds for the idle time.
const IDLE_TIME = Math.min(getPref("getIntPref", PREF_APP_UPDATE_IDLETIME, 60), 600);
if (idleService.idleTime / 1000 >= IDLE_TIME) {
this._showUI(parent, uri, features, name, page, update);
} else {
var observer = {
updatePrompt: this,
- observe: function (aSubject, aTopic, aData) {
+ observe: function(aSubject, aTopic, aData) {
switch (aTopic) {
case "idle":
// If the update window is already open skip showing the UI
if (!this.updatePrompt._getUpdateWindow())
this.updatePrompt._showUI(parent, uri, features, name, page, update);
// fall thru
case "quit-application":
idleService.removeIdleObserver(this, IDLE_TIME);