Bug 1556849 - Enable ESLint for dom/base/. r=Standard8,mccr8

# ignore-this-changeset

These are all automatic changes via ESLint/prettier.

Differential Revision: https://phabricator.services.mozilla.com/D37978

--HG--
extra : moz-landing-system : lando
This commit is contained in:
soniasingla 2019-07-15 17:22:45 +00:00
parent 790ab483b4
commit f52cea06ac
6 changed files with 270 additions and 159 deletions

View file

@ -12,7 +12,6 @@
obj*/** obj*/**
# dom/ exclusions which should be removed (aka ESLint enabled) # dom/ exclusions which should be removed (aka ESLint enabled)
dom/base/*.*
dom/media/test/** dom/media/test/**
!dom/media/test/marionette/yttest/*.js !dom/media/test/marionette/yttest/*.js
dom/xhr/** dom/xhr/**

View file

@ -2,8 +2,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm"); const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm");
// This component is used for handling dragover and drop of urls. // This component is used for handling dragover and drop of urls.
// //
@ -12,20 +12,17 @@ const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm");
// access the uri. This prevents, for example, a source document from tricking // access the uri. This prevents, for example, a source document from tricking
// the user into dragging a chrome url. // the user into dragging a chrome url.
function ContentAreaDropListener() { }; function ContentAreaDropListener() {}
ContentAreaDropListener.prototype = ContentAreaDropListener.prototype = {
{ classID: Components.ID("{1f34bc80-1bc7-11d6-a384-d705dd0746fc}"),
classID: Components.ID("{1f34bc80-1bc7-11d6-a384-d705dd0746fc}"), QueryInterface: ChromeUtils.generateQI([Ci.nsIDroppedLinkHandler]),
QueryInterface: ChromeUtils.generateQI([Ci.nsIDroppedLinkHandler]),
_addLink : function(links, url, name, type) _addLink: function(links, url, name, type) {
{
links.push({ url, name, type }); links.push({ url, name, type });
}, },
_addLinksFromItem: function(links, dt, i) _addLinksFromItem: function(links, dt, i) {
{
let types = dt.mozTypesAt(i); let types = dt.mozTypesAt(i);
let type, data; let type, data;
@ -36,8 +33,9 @@ ContentAreaDropListener.prototype =
let urls = data.split("\n"); let urls = data.split("\n");
for (let url of urls) { for (let url of urls) {
// lines beginning with # are comments // lines beginning with # are comments
if (url.startsWith("#")) if (url.startsWith("#")) {
continue; continue;
}
url = url.replace(/^\s+|\s+$/g, ""); url = url.replace(/^\s+|\s+$/g, "");
this._addLink(links, url, url, type); this._addLink(links, url, url, type);
} }
@ -61,7 +59,7 @@ ContentAreaDropListener.prototype =
if (types.contains(type)) { if (types.contains(type)) {
data = dt.mozGetDataAt(type, i); data = dt.mozGetDataAt(type, i);
if (data) { if (data) {
let lines = data.replace(/^\s+|\s+$/mg, "").split("\n"); let lines = data.replace(/^\s+|\s+$/gm, "").split("\n");
if (!lines.length) { if (!lines.length) {
return; return;
} }
@ -74,8 +72,9 @@ ContentAreaDropListener.prototype =
// Add the entire text as a single entry, so that the entire // Add the entire text as a single entry, so that the entire
// text is searched. // text is searched.
let hasURI = false; let hasURI = false;
let flags = Ci.nsIURIFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS | let flags =
Ci.nsIURIFixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP; Ci.nsIURIFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS |
Ci.nsIURIFixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP;
for (let line of lines) { for (let line of lines) {
let info = Services.uriFixup.getFixupURIInfo(line, flags); let info = Services.uriFixup.getFixupURIInfo(line, flags);
if (info.fixedURI) { if (info.fixedURI) {
@ -99,13 +98,16 @@ ContentAreaDropListener.prototype =
// type, which points to the actual file. // type, which points to the actual file.
let files = dt.files; let files = dt.files;
if (files && i < files.length) { if (files && i < files.length) {
this._addLink(links, OS.Path.toFileURI(files[i].mozFullPath), this._addLink(
files[i].name, "application/x-moz-file"); links,
OS.Path.toFileURI(files[i].mozFullPath),
files[i].name,
"application/x-moz-file"
);
} }
}, },
_getDropLinks : function (dt) _getDropLinks: function(dt) {
{
let links = []; let links = [];
for (let i = 0; i < dt.mozItemCount; i++) { for (let i = 0; i < dt.mozItemCount; i++) {
this._addLinksFromItem(links, dt, i); this._addLinksFromItem(links, dt, i);
@ -113,23 +115,28 @@ ContentAreaDropListener.prototype =
return links; return links;
}, },
_validateURI: function(dataTransfer, uriString, disallowInherit, _validateURI: function(
triggeringPrincipal) dataTransfer,
{ uriString,
if (!uriString) disallowInherit,
triggeringPrincipal
) {
if (!uriString) {
return ""; return "";
}
// Strip leading and trailing whitespace, then try to create a // Strip leading and trailing whitespace, then try to create a
// URI from the dropped string. If that succeeds, we're // URI from the dropped string. If that succeeds, we're
// dropping a URI and we need to do a security check to make // dropping a URI and we need to do a security check to make
// sure the source document can load the dropped URI. // sure the source document can load the dropped URI.
uriString = uriString.replace(/^\s*|\s*$/g, ''); uriString = uriString.replace(/^\s*|\s*$/g, "");
// Apply URI fixup so that this validation prevents bad URIs even if the // Apply URI fixup so that this validation prevents bad URIs even if the
// similar fixup is applied later, especialy fixing typos up will convert // similar fixup is applied later, especialy fixing typos up will convert
// non-URI to URI. // non-URI to URI.
let fixupFlags = Ci.nsIURIFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS | let fixupFlags =
Ci.nsIURIFixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP; Ci.nsIURIFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS |
Ci.nsIURIFixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP;
let info = Services.uriFixup.getFixupURIInfo(uriString, fixupFlags); let info = Services.uriFixup.getFixupURIInfo(uriString, fixupFlags);
if (!info.fixedURI || info.keywordProviderName) { if (!info.fixedURI || info.keywordProviderName) {
// Loading a keyword search should always be fine for all cases. // Loading a keyword search should always be fine for all cases.
@ -137,11 +144,13 @@ ContentAreaDropListener.prototype =
} }
let uri = info.fixedURI; let uri = info.fixedURI;
let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"]. let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
let flags = secMan.STANDARD; let flags = secMan.STANDARD;
if (disallowInherit) if (disallowInherit) {
flags |= secMan.DISALLOW_INHERIT_PRINCIPAL; flags |= secMan.DISALLOW_INHERIT_PRINCIPAL;
}
secMan.checkLoadURIWithPrincipal(triggeringPrincipal, uri, flags); secMan.checkLoadURIWithPrincipal(triggeringPrincipal, uri, flags);
@ -150,13 +159,17 @@ ContentAreaDropListener.prototype =
return uri.spec; return uri.spec;
}, },
_getTriggeringPrincipalFromDataTransfer: function(aDataTransfer, _getTriggeringPrincipalFromDataTransfer: function(
fallbackToSystemPrincipal) aDataTransfer,
{ fallbackToSystemPrincipal
) {
let sourceNode = aDataTransfer.mozSourceNode; let sourceNode = aDataTransfer.mozSourceNode;
if (sourceNode && if (
(sourceNode.localName !== "browser" || sourceNode &&
sourceNode.namespaceURI !== "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul")) { (sourceNode.localName !== "browser" ||
sourceNode.namespaceURI !==
"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul")
) {
// Use sourceNode's principal only if the sourceNode is not browser. // Use sourceNode's principal only if the sourceNode is not browser.
// //
// If sourceNode is browser, the actual triggering principal may be // If sourceNode is browser, the actual triggering principal may be
@ -179,33 +192,39 @@ ContentAreaDropListener.prototype =
// TODO: Investigate and describe the difference between them, // TODO: Investigate and describe the difference between them,
// or use only one principal. (Bug 1367038) // or use only one principal. (Bug 1367038)
if (fallbackToSystemPrincipal) { if (fallbackToSystemPrincipal) {
let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"]. let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
getService(Ci.nsIScriptSecurityManager); Ci.nsIScriptSecurityManager
);
return secMan.getSystemPrincipal(); return secMan.getSystemPrincipal();
} else { } else {
principalURISpec = "file:///"; principalURISpec = "file:///";
} }
} }
let ioService = Cc["@mozilla.org/network/io-service;1"] let ioService = Cc["@mozilla.org/network/io-service;1"].getService(
.getService(Ci.nsIIOService); Ci.nsIIOService
let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"]. );
getService(Ci.nsIScriptSecurityManager); let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(
return secMan.createContentPrincipal(ioService.newURI(principalURISpec), {}); Ci.nsIScriptSecurityManager
);
return secMan.createContentPrincipal(
ioService.newURI(principalURISpec),
{}
);
}, },
getTriggeringPrincipal: function(aEvent) getTriggeringPrincipal: function(aEvent) {
{
let dataTransfer = aEvent.dataTransfer; let dataTransfer = aEvent.dataTransfer;
return this._getTriggeringPrincipalFromDataTransfer(dataTransfer, true); return this._getTriggeringPrincipalFromDataTransfer(dataTransfer, true);
}, },
getCSP: function(aEvent) getCSP: function(aEvent) {
{
let sourceNode = aEvent.dataTransfer.mozSourceNode; let sourceNode = aEvent.dataTransfer.mozSourceNode;
if (sourceNode && if (
(sourceNode.localName !== "browser" || sourceNode &&
sourceNode.namespaceURI !== "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul")) { (sourceNode.localName !== "browser" ||
sourceNode.namespaceURI !==
"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul")
) {
// Use sourceNode's csp only if the sourceNode is not browser. // Use sourceNode's csp only if the sourceNode is not browser.
// //
// If sourceNode is browser, the actual triggering csp may be differ than sourceNode's csp, // If sourceNode is browser, the actual triggering csp may be differ than sourceNode's csp,
@ -216,74 +235,89 @@ ContentAreaDropListener.prototype =
return null; return null;
}, },
canDropLink: function(aEvent, aAllowSameDocument) canDropLink: function(aEvent, aAllowSameDocument) {
{ if (this._eventTargetIsDisabled(aEvent)) {
if (this._eventTargetIsDisabled(aEvent))
return false; return false;
}
let dataTransfer = aEvent.dataTransfer; let dataTransfer = aEvent.dataTransfer;
let types = dataTransfer.types; let types = dataTransfer.types;
if (!types.includes("application/x-moz-file") && if (
!types.includes("text/x-moz-url") && !types.includes("application/x-moz-file") &&
!types.includes("text/uri-list") && !types.includes("text/x-moz-url") &&
!types.includes("text/x-moz-text-internal") && !types.includes("text/uri-list") &&
!types.includes("text/plain")) !types.includes("text/x-moz-text-internal") &&
!types.includes("text/plain")
) {
return false; return false;
}
if (aAllowSameDocument) if (aAllowSameDocument) {
return true; return true;
}
let sourceNode = dataTransfer.mozSourceNode; let sourceNode = dataTransfer.mozSourceNode;
if (!sourceNode) if (!sourceNode) {
return true; return true;
}
// don't allow a drop of a node from the same document onto this one // don't allow a drop of a node from the same document onto this one
let sourceDocument = sourceNode.ownerDocument; let sourceDocument = sourceNode.ownerDocument;
let eventDocument = aEvent.originalTarget.ownerDocument; let eventDocument = aEvent.originalTarget.ownerDocument;
if (sourceDocument == eventDocument) if (sourceDocument == eventDocument) {
return false; return false;
}
// also check for nodes in other child or sibling frames by checking // also check for nodes in other child or sibling frames by checking
// if both have the same top window. // if both have the same top window.
if (sourceDocument && eventDocument) { if (sourceDocument && eventDocument) {
if (sourceDocument.defaultView == null) if (sourceDocument.defaultView == null) {
return true; return true;
}
let sourceRoot = sourceDocument.defaultView.top; let sourceRoot = sourceDocument.defaultView.top;
if (sourceRoot && sourceRoot == eventDocument.defaultView.top) if (sourceRoot && sourceRoot == eventDocument.defaultView.top) {
return false; return false;
}
} }
return true; return true;
}, },
dropLink: function(aEvent, aName, aDisallowInherit) dropLink: function(aEvent, aName, aDisallowInherit) {
{
aName.value = ""; aName.value = "";
let links = this.dropLinks(aEvent, aDisallowInherit); let links = this.dropLinks(aEvent, aDisallowInherit);
let url = ""; let url = "";
if (links.length > 0) { if (links.length > 0) {
url = links[0].url; url = links[0].url;
let name = links[0].name; let name = links[0].name;
if (name) if (name) {
aName.value = name; aName.value = name;
}
} }
return url; return url;
}, },
dropLinks: function(aEvent, aDisallowInherit) dropLinks: function(aEvent, aDisallowInherit) {
{ if (aEvent && this._eventTargetIsDisabled(aEvent)) {
if (aEvent && this._eventTargetIsDisabled(aEvent))
return []; return [];
}
let dataTransfer = aEvent.dataTransfer; let dataTransfer = aEvent.dataTransfer;
let links = this._getDropLinks(dataTransfer); let links = this._getDropLinks(dataTransfer);
let triggeringPrincipal = this._getTriggeringPrincipalFromDataTransfer(dataTransfer, false); let triggeringPrincipal = this._getTriggeringPrincipalFromDataTransfer(
dataTransfer,
false
);
for (let link of links) { for (let link of links) {
try { try {
link.url = this._validateURI(dataTransfer, link.url, aDisallowInherit, link.url = this._validateURI(
triggeringPrincipal); dataTransfer,
link.url,
aDisallowInherit,
triggeringPrincipal
);
} catch (ex) { } catch (ex) {
// Prevent the drop entirely if any of the links are invalid even if // Prevent the drop entirely if any of the links are invalid even if
// one of them is valid. // one of them is valid.
@ -296,32 +330,37 @@ ContentAreaDropListener.prototype =
return links; return links;
}, },
validateURIsForDrop: function(aEvent, aURIs, aDisallowInherit) validateURIsForDrop: function(aEvent, aURIs, aDisallowInherit) {
{
let dataTransfer = aEvent.dataTransfer; let dataTransfer = aEvent.dataTransfer;
let triggeringPrincipal = this._getTriggeringPrincipalFromDataTransfer(dataTransfer, false); let triggeringPrincipal = this._getTriggeringPrincipalFromDataTransfer(
dataTransfer,
false
);
for (let uri of aURIs) { for (let uri of aURIs) {
this._validateURI(dataTransfer, uri, aDisallowInherit, this._validateURI(
triggeringPrincipal); dataTransfer,
uri,
aDisallowInherit,
triggeringPrincipal
);
} }
}, },
queryLinks: function(aDataTransfer) queryLinks: function(aDataTransfer) {
{
return this._getDropLinks(aDataTransfer); return this._getDropLinks(aDataTransfer);
}, },
_eventTargetIsDisabled: function(aEvent) _eventTargetIsDisabled: function(aEvent) {
{
let ownerDoc = aEvent.originalTarget.ownerDocument; let ownerDoc = aEvent.originalTarget.ownerDocument;
if (!ownerDoc || !ownerDoc.defaultView) if (!ownerDoc || !ownerDoc.defaultView) {
return false; return false;
}
return ownerDoc.defaultView return ownerDoc.defaultView.windowUtils.isNodeDisabledForEvents(
.windowUtils aEvent.originalTarget
.isNodeDisabledForEvents(aEvent.originalTarget); );
} },
}; };
var EXPORTED_SYMBOLS = ["ContentAreaDropListener"]; var EXPORTED_SYMBOLS = ["ContentAreaDropListener"];

View file

@ -18,7 +18,7 @@
*/ */
var EXPORTED_SYMBOLS = ["DOMRequestIpcHelper"]; var EXPORTED_SYMBOLS = ["DOMRequestIpcHelper"];
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
function DOMRequestIpcHelper() { function DOMRequestIpcHelper() {
// _listeners keeps a list of messages for which we added a listener and the // _listeners keeps a list of messages for which we added a listener and the
@ -41,10 +41,12 @@ DOMRequestIpcHelper.prototype = {
* An object which "inherits" from DOMRequestIpcHelper and declares its own * An object which "inherits" from DOMRequestIpcHelper and declares its own
* queryInterface method MUST implement Ci.nsISupportsWeakReference. * queryInterface method MUST implement Ci.nsISupportsWeakReference.
*/ */
QueryInterface: ChromeUtils.generateQI([Ci.nsISupportsWeakReference, QueryInterface: ChromeUtils.generateQI([
Ci.nsIObserver]), Ci.nsISupportsWeakReference,
Ci.nsIObserver,
]),
/** /**
* 'aMessages' is expected to be an array of either: * 'aMessages' is expected to be an array of either:
* - objects of this form: * - objects of this form:
* { * {
@ -70,7 +72,7 @@ DOMRequestIpcHelper.prototype = {
aMessages = [aMessages]; aMessages = [aMessages];
} }
aMessages.forEach((aMsg) => { aMessages.forEach(aMsg => {
let name = aMsg.name || aMsg; let name = aMsg.name || aMsg;
// If the listener is already set and it is of the same type we just // If the listener is already set and it is of the same type we just
// increase the count and bail out. If it is not of the same type, // increase the count and bail out. If it is not of the same type,
@ -84,11 +86,12 @@ DOMRequestIpcHelper.prototype = {
} }
} }
aMsg.weakRef ? Services.cpmm.addWeakMessageListener(name, this) aMsg.weakRef
: Services.cpmm.addMessageListener(name, this); ? Services.cpmm.addWeakMessageListener(name, this)
: Services.cpmm.addMessageListener(name, this);
this._listeners[name] = { this._listeners[name] = {
weakRef: !!aMsg.weakRef, weakRef: !!aMsg.weakRef,
count: 1 count: 1,
}; };
}); });
}, },
@ -106,7 +109,7 @@ DOMRequestIpcHelper.prototype = {
aMessages = [aMessages]; aMessages = [aMessages];
} }
aMessages.forEach((aName) => { aMessages.forEach(aName => {
if (this._listeners[aName] == undefined) { if (this._listeners[aName] == undefined) {
return; return;
} }
@ -114,8 +117,8 @@ DOMRequestIpcHelper.prototype = {
// Only remove the listener really when we don't have anybody that could // Only remove the listener really when we don't have anybody that could
// be waiting on a message. // be waiting on a message.
if (!--this._listeners[aName].count) { if (!--this._listeners[aName].count) {
this._listeners[aName].weakRef ? this._listeners[aName].weakRef
Services.cpmm.removeWeakMessageListener(aName, this) ? Services.cpmm.removeWeakMessageListener(aName, this)
: Services.cpmm.removeMessageListener(aName, this); : Services.cpmm.removeMessageListener(aName, this);
delete this._listeners[aName]; delete this._listeners[aName];
} }
@ -160,8 +163,11 @@ DOMRequestIpcHelper.prototype = {
this._destroyed = false; this._destroyed = false;
Services.obs.addObserver(this, "inner-window-destroyed", Services.obs.addObserver(
/* weak-ref */ true); this,
"inner-window-destroyed",
/* weak-ref */ true
);
}, },
destroyDOMRequestHelper: function() { destroyDOMRequestHelper: function() {
@ -174,9 +180,9 @@ DOMRequestIpcHelper.prototype = {
Services.obs.removeObserver(this, "inner-window-destroyed"); Services.obs.removeObserver(this, "inner-window-destroyed");
if (this._listeners) { if (this._listeners) {
Object.keys(this._listeners).forEach((aName) => { Object.keys(this._listeners).forEach(aName => {
this._listeners[aName].weakRef ? this._listeners[aName].weakRef
Services.cpmm.removeWeakMessageListener(aName, this) ? Services.cpmm.removeWeakMessageListener(aName, this)
: Services.cpmm.removeMessageListener(aName, this); : Services.cpmm.removeMessageListener(aName, this);
}); });
} }
@ -262,13 +268,17 @@ DOMRequestIpcHelper.prototype = {
_getRandomId: function() { _getRandomId: function() {
return Cc["@mozilla.org/uuid-generator;1"] return Cc["@mozilla.org/uuid-generator;1"]
.getService(Ci.nsIUUIDGenerator).generateUUID().toString(); .getService(Ci.nsIUUIDGenerator)
.generateUUID()
.toString();
}, },
createRequest: function() { createRequest: function() {
// If we don't have a valid window object, throw. // If we don't have a valid window object, throw.
if (!this._window) { if (!this._window) {
Cu.reportError("DOMRequestHelper trying to create a DOMRequest without a valid window, failing."); Cu.reportError(
"DOMRequestHelper trying to create a DOMRequest without a valid window, failing."
);
throw Cr.NS_ERROR_FAILURE; throw Cr.NS_ERROR_FAILURE;
} }
return Services.DOMRequest.createRequest(this._window); return Services.DOMRequest.createRequest(this._window);
@ -282,7 +292,9 @@ DOMRequestIpcHelper.prototype = {
createPromise: function(aPromiseInit) { createPromise: function(aPromiseInit) {
// If we don't have a valid window object, throw. // If we don't have a valid window object, throw.
if (!this._window) { if (!this._window) {
Cu.reportError("DOMRequestHelper trying to create a Promise without a valid window, failing."); Cu.reportError(
"DOMRequestHelper trying to create a Promise without a valid window, failing."
);
throw Cr.NS_ERROR_FAILURE; throw Cr.NS_ERROR_FAILURE;
} }
return new this._window.Promise(aPromiseInit); return new this._window.Promise(aPromiseInit);
@ -294,7 +306,10 @@ DOMRequestIpcHelper.prototype = {
*/ */
createPromiseWithId: function(aCallback) { createPromiseWithId: function(aCallback) {
return this.createPromise((aResolve, aReject) => { return this.createPromise((aResolve, aReject) => {
let resolverId = this.getPromiseResolverId({ resolve: aResolve, reject: aReject }); let resolverId = this.getPromiseResolverId({
resolve: aResolve,
reject: aReject,
});
aCallback(resolverId); aCallback(resolverId);
}); });
}, },
@ -304,7 +319,7 @@ DOMRequestIpcHelper.prototype = {
return; return;
} }
Object.keys(this._requests).forEach((aKey) => { Object.keys(this._requests).forEach(aKey => {
if (this.getRequest(aKey) instanceof this._window.DOMRequest) { if (this.getRequest(aKey) instanceof this._window.DOMRequest) {
aCallback(aKey); aCallback(aKey);
} }
@ -316,11 +331,13 @@ DOMRequestIpcHelper.prototype = {
return; return;
} }
Object.keys(this._requests).forEach((aKey) => { Object.keys(this._requests).forEach(aKey => {
if ("resolve" in this.getPromiseResolver(aKey) && if (
"reject" in this.getPromiseResolver(aKey)) { "resolve" in this.getPromiseResolver(aKey) &&
"reject" in this.getPromiseResolver(aKey)
) {
aCallback(aKey); aCallback(aKey);
} }
}); });
}, },
} };

View file

@ -7,24 +7,28 @@
var DEBUG = 0; var DEBUG = 0;
var debug; var debug;
if (DEBUG) { if (DEBUG) {
debug = function (s) { dump("-*- IndexedDBHelper: " + s + "\n"); } debug = function(s) {
dump("-*- IndexedDBHelper: " + s + "\n");
};
} else { } else {
debug = function (s) {} debug = function(s) {};
} }
var EXPORTED_SYMBOLS = ["IndexedDBHelper"]; var EXPORTED_SYMBOLS = ["IndexedDBHelper"];
Cu.importGlobalProperties(["indexedDB"]); Cu.importGlobalProperties(["indexedDB"]);
ChromeUtils.defineModuleGetter(this, 'Services', ChromeUtils.defineModuleGetter(
'resource://gre/modules/Services.jsm'); this,
"Services",
"resource://gre/modules/Services.jsm"
);
function getErrorName(err) { function getErrorName(err) {
return err && err.name || "UnknownError"; return (err && err.name) || "UnknownError";
} }
function IndexedDBHelper() { function IndexedDBHelper() {}
}
IndexedDBHelper.prototype = { IndexedDBHelper.prototype = {
// Close the database // Close the database
@ -60,39 +64,64 @@ IndexedDBHelper.prototype = {
self._waitForOpenCallbacks.clear(); self._waitForOpenCallbacks.clear();
}; };
if (DEBUG) debug("Try to open database:" + self.dbName + " " + self.dbVersion); if (DEBUG) {
debug("Try to open database:" + self.dbName + " " + self.dbVersion);
}
let req; let req;
try { try {
req = indexedDB.open(this.dbName, this.dbVersion); req = indexedDB.open(this.dbName, this.dbVersion);
} catch (e) { } catch (e) {
if (DEBUG) debug("Error opening database: " + self.dbName); if (DEBUG) {
debug("Error opening database: " + self.dbName);
}
Services.tm.dispatchToMainThread(() => invokeCallbacks(getErrorName(e))); Services.tm.dispatchToMainThread(() => invokeCallbacks(getErrorName(e)));
return; return;
} }
req.onsuccess = function (event) { req.onsuccess = function(event) {
if (DEBUG) debug("Opened database:" + self.dbName + " " + self.dbVersion); if (DEBUG) {
debug("Opened database:" + self.dbName + " " + self.dbVersion);
}
self._db = event.target.result; self._db = event.target.result;
self._db.onversionchange = function(event) { self._db.onversionchange = function(event) {
if (DEBUG) debug("WARNING: DB modified from a different window."); if (DEBUG) {
} debug("WARNING: DB modified from a different window.");
}
};
invokeCallbacks(); invokeCallbacks();
}; };
req.onupgradeneeded = function (aEvent) { req.onupgradeneeded = function(aEvent) {
if (DEBUG) { if (DEBUG) {
debug("Database needs upgrade:" + self.dbName + aEvent.oldVersion + aEvent.newVersion); debug(
debug("Correct new database version:" + (aEvent.newVersion == this.dbVersion)); "Database needs upgrade:" +
self.dbName +
aEvent.oldVersion +
aEvent.newVersion
);
debug(
"Correct new database version:" +
(aEvent.newVersion == this.dbVersion)
);
} }
let _db = aEvent.target.result; let _db = aEvent.target.result;
self.upgradeSchema(req.transaction, _db, aEvent.oldVersion, aEvent.newVersion); self.upgradeSchema(
req.transaction,
_db,
aEvent.oldVersion,
aEvent.newVersion
);
}; };
req.onerror = function (aEvent) { req.onerror = function(aEvent) {
if (DEBUG) debug("Failed to open database: " + self.dbName); if (DEBUG) {
debug("Failed to open database: " + self.dbName);
}
invokeCallbacks(getErrorName(aEvent.target.error)); invokeCallbacks(getErrorName(aEvent.target.error));
}; };
req.onblocked = function (aEvent) { req.onblocked = function(aEvent) {
if (DEBUG) debug("Opening database request is blocked."); if (DEBUG) {
debug("Opening database request is blocked.");
}
}; };
}, },
@ -106,7 +135,9 @@ IndexedDBHelper.prototype = {
*/ */
ensureDB: function ensureDB(aSuccessCb, aFailureCb) { ensureDB: function ensureDB(aSuccessCb, aFailureCb) {
if (this._db) { if (this._db) {
if (DEBUG) debug("ensureDB: already have a database, returning early."); if (DEBUG) {
debug("ensureDB: already have a database, returning early.");
}
if (aSuccessCb) { if (aSuccessCb) {
Services.tm.dispatchToMainThread(aSuccessCb); Services.tm.dispatchToMainThread(aSuccessCb);
} }
@ -137,18 +168,33 @@ IndexedDBHelper.prototype = {
* @param failureCb * @param failureCb
* Error callback to call when an error is encountered. * Error callback to call when an error is encountered.
*/ */
newTxn: function newTxn(txn_type, store_name, callback, successCb, failureCb) { newTxn: function newTxn(
txn_type,
store_name,
callback,
successCb,
failureCb
) {
this.ensureDB(() => { this.ensureDB(() => {
if (DEBUG) debug("Starting new transaction" + txn_type); if (DEBUG) {
debug("Starting new transaction" + txn_type);
}
let txn; let txn;
try { try {
txn = this._db.transaction(Array.isArray(store_name) ? store_name : this.dbStoreNames, txn_type); txn = this._db.transaction(
Array.isArray(store_name) ? store_name : this.dbStoreNames,
txn_type
);
} catch (e) { } catch (e) {
if (DEBUG) debug("Error starting transaction: " + this.dbName); if (DEBUG) {
debug("Error starting transaction: " + this.dbName);
}
failureCb(getErrorName(e)); failureCb(getErrorName(e));
return; return;
} }
if (DEBUG) debug("Retrieving object store: " + this.dbName); if (DEBUG) {
debug("Retrieving object store: " + this.dbName);
}
let stores; let stores;
if (Array.isArray(store_name)) { if (Array.isArray(store_name)) {
stores = []; stores = [];
@ -159,8 +205,10 @@ IndexedDBHelper.prototype = {
stores = txn.objectStore(store_name); stores = txn.objectStore(store_name);
} }
txn.oncomplete = function () { txn.oncomplete = function() {
if (DEBUG) debug("Transaction complete. Returning to callback."); if (DEBUG) {
debug("Transaction complete. Returning to callback.");
}
/* /*
* txn.result property is not part of the transaction object returned * txn.result property is not part of the transaction object returned
* by this._db.transaction method called above. * by this._db.transaction method called above.
@ -178,8 +226,10 @@ IndexedDBHelper.prototype = {
} }
}; };
txn.onabort = function () { txn.onabort = function() {
if (DEBUG) debug("Caught error on transaction"); if (DEBUG) {
debug("Caught error on transaction");
}
/* /*
* txn.error property is part of the transaction object returned by * txn.error property is part of the transaction object returned by
* this._db.transaction method called above. * this._db.transaction method called above.
@ -211,5 +261,5 @@ IndexedDBHelper.prototype = {
// Cache the database. // Cache the database.
this._db = null; this._db = null;
this._waitForOpenCallbacks = new Set(); this._waitForOpenCallbacks = new Set();
} },
} };

View file

@ -4,12 +4,11 @@
// Fills up aProcesses until max and then selects randomly from the available // Fills up aProcesses until max and then selects randomly from the available
// ones. // ones.
function RandomSelector() { function RandomSelector() {}
}
RandomSelector.prototype = { RandomSelector.prototype = {
classID: Components.ID("{c616fcfd-9737-41f1-aa74-cee72a38f91b}"), classID: Components.ID("{c616fcfd-9737-41f1-aa74-cee72a38f91b}"),
QueryInterface: ChromeUtils.generateQI([Ci.nsIContentProcessProvider]), QueryInterface: ChromeUtils.generateQI([Ci.nsIContentProcessProvider]),
provideProcess(aType, aOpener, aProcesses, aMaxCount) { provideProcess(aType, aOpener, aProcesses, aMaxCount) {
if (aProcesses.length < aMaxCount) { if (aProcesses.length < aMaxCount) {
@ -33,12 +32,11 @@ RandomSelector.prototype = {
// Fills up aProcesses until max and then selects one from the available // Fills up aProcesses until max and then selects one from the available
// ones that host the least number of tabs. // ones that host the least number of tabs.
function MinTabSelector() { function MinTabSelector() {}
}
MinTabSelector.prototype = { MinTabSelector.prototype = {
classID: Components.ID("{2dc08eaf-6eef-4394-b1df-a3a927c1290b}"), classID: Components.ID("{2dc08eaf-6eef-4394-b1df-a3a927c1290b}"),
QueryInterface: ChromeUtils.generateQI([Ci.nsIContentProcessProvider]), QueryInterface: ChromeUtils.generateQI([Ci.nsIContentProcessProvider]),
provideProcess(aType, aOpener, aProcesses, aMaxCount) { provideProcess(aType, aOpener, aProcesses, aMaxCount) {
if (aProcesses.length < aMaxCount) { if (aProcesses.length < aMaxCount) {
@ -66,4 +64,4 @@ MinTabSelector.prototype = {
}, },
}; };
var EXPORTED_SYMBOLS = ["RandomSelector", "MinTabSelector"] var EXPORTED_SYMBOLS = ["RandomSelector", "MinTabSelector"];

View file

@ -4,17 +4,25 @@
"use strict"; "use strict";
function SlowScriptDebug() { } function SlowScriptDebug() {}
SlowScriptDebug.prototype = { SlowScriptDebug.prototype = {
classDescription: "Slow script debug handler", classDescription: "Slow script debug handler",
QueryInterface: ChromeUtils.generateQI([Ci.nsISlowScriptDebug]), QueryInterface: ChromeUtils.generateQI([Ci.nsISlowScriptDebug]),
get activationHandler() { return this._activationHandler; }, get activationHandler() {
set activationHandler(cb) { return this._activationHandler = cb; }, return this._activationHandler;
},
set activationHandler(cb) {
return (this._activationHandler = cb);
},
get remoteActivationHandler() { return this._remoteActivationHandler; }, get remoteActivationHandler() {
set remoteActivationHandler(cb) { return this._remoteActivationHandler = cb; }, return this._remoteActivationHandler;
},
set remoteActivationHandler(cb) {
return (this._remoteActivationHandler = cb);
},
}; };
var EXPORTED_SYMBOLS = ["SlowScriptDebug"]; var EXPORTED_SYMBOLS = ["SlowScriptDebug"];