Bug 1398329 - Convert uses of defer to new Promise in client/shared (except in test/, vendor/ and widgets/ subdirs). r=Honza, r=nchevobbe

This commit is contained in:
Mark Collins 2017-09-08 23:32:47 +02:00
Родитель bb17178a61
Коммит f3b3075513
7 изменённых файлов: 429 добавлений и 450 удалений

Просмотреть файл

@ -35,7 +35,6 @@ var { require } = Cu.import("resource://devtools/shared/Loader.jsm", {});
var { gDevTools } = require("devtools/client/framework/devtools");
var Services = require("Services");
var promise = require("promise");
var defer = require("devtools/shared/defer");
this.EXPORTED_SYMBOLS = ["AppCacheUtils"];
@ -58,196 +57,194 @@ AppCacheUtils.prototype = {
},
validateManifest: function ACU_validateManifest() {
let deferred = defer();
this.errors = [];
// Check for missing manifest.
this._getManifestURI().then(manifestURI => {
this.manifestURI = manifestURI;
return new Promise((resolve, reject) => {
this.errors = [];
// Check for missing manifest.
this._getManifestURI().then(manifestURI => {
this.manifestURI = manifestURI;
if (!this.manifestURI) {
this._addError(0, "noManifest");
deferred.resolve(this.errors);
}
if (!this.manifestURI) {
this._addError(0, "noManifest");
resolve(this.errors);
}
this._getURIInfo(this.manifestURI).then(uriInfo => {
this._parseManifest(uriInfo).then(() => {
// Sort errors by line number.
this.errors.sort(function (a, b) {
return a.line - b.line;
this._getURIInfo(this.manifestURI).then(uriInfo => {
this._parseManifest(uriInfo).then(() => {
// Sort errors by line number.
this.errors.sort(function (a, b) {
return a.line - b.line;
});
resolve(this.errors);
});
deferred.resolve(this.errors);
});
});
});
return deferred.promise;
},
_parseManifest: function ACU__parseManifest(uriInfo) {
let deferred = defer();
let manifestName = uriInfo.name;
let manifestLastModified = new Date(uriInfo.responseHeaders["last-modified"]);
return new Promise((resolve, reject) => {
let manifestName = uriInfo.name;
let manifestLastModified = new Date(uriInfo.responseHeaders["last-modified"]);
if (uriInfo.charset.toLowerCase() != "utf-8") {
this._addError(0, "notUTF8", uriInfo.charset);
}
if (uriInfo.mimeType != "text/cache-manifest") {
this._addError(0, "badMimeType", uriInfo.mimeType);
}
let parser = new ManifestParser(uriInfo.text, this.manifestURI);
let parsed = parser.parse();
if (parsed.errors.length > 0) {
this.errors.push.apply(this.errors, parsed.errors);
}
// Check for duplicate entries.
let dupes = {};
for (let parsedUri of parsed.uris) {
dupes[parsedUri.uri] = dupes[parsedUri.uri] || [];
dupes[parsedUri.uri].push({
line: parsedUri.line,
section: parsedUri.section,
original: parsedUri.original
});
}
for (let [uri, value] of Object.entries(dupes)) {
if (value.length > 1) {
this._addError(0, "duplicateURI", uri, JSON.stringify(value));
if (uriInfo.charset.toLowerCase() != "utf-8") {
this._addError(0, "notUTF8", uriInfo.charset);
}
}
// Loop through network entries making sure that fallback and cache don't
// contain uris starting with the network uri.
for (let neturi of parsed.uris) {
if (neturi.section == "NETWORK") {
if (uriInfo.mimeType != "text/cache-manifest") {
this._addError(0, "badMimeType", uriInfo.mimeType);
}
let parser = new ManifestParser(uriInfo.text, this.manifestURI);
let parsed = parser.parse();
if (parsed.errors.length > 0) {
this.errors.push.apply(this.errors, parsed.errors);
}
// Check for duplicate entries.
let dupes = {};
for (let parsedUri of parsed.uris) {
dupes[parsedUri.uri] = dupes[parsedUri.uri] || [];
dupes[parsedUri.uri].push({
line: parsedUri.line,
section: parsedUri.section,
original: parsedUri.original
});
}
for (let [uri, value] of Object.entries(dupes)) {
if (value.length > 1) {
this._addError(0, "duplicateURI", uri, JSON.stringify(value));
}
}
// Loop through network entries making sure that fallback and cache don't
// contain uris starting with the network uri.
for (let neturi of parsed.uris) {
if (neturi.section == "NETWORK") {
for (let parsedUri of parsed.uris) {
if (parsedUri.section !== "NETWORK" &&
parsedUri.uri.startsWith(neturi.uri)) {
this._addError(neturi.line, "networkBlocksURI", neturi.line,
neturi.original, parsedUri.line, parsedUri.original,
parsedUri.section);
}
}
}
}
// Loop through fallback entries making sure that fallback and cache don't
// contain uris starting with the network uri.
for (let fb of parsed.fallbacks) {
for (let parsedUri of parsed.uris) {
if (parsedUri.section !== "NETWORK" &&
parsedUri.uri.startsWith(neturi.uri)) {
this._addError(neturi.line, "networkBlocksURI", neturi.line,
neturi.original, parsedUri.line, parsedUri.original,
if (parsedUri.uri.startsWith(fb.namespace)) {
this._addError(fb.line, "fallbackBlocksURI", fb.line,
fb.original, parsedUri.line, parsedUri.original,
parsedUri.section);
}
}
}
}
// Loop through fallback entries making sure that fallback and cache don't
// contain uris starting with the network uri.
for (let fb of parsed.fallbacks) {
for (let parsedUri of parsed.uris) {
if (parsedUri.uri.startsWith(fb.namespace)) {
this._addError(fb.line, "fallbackBlocksURI", fb.line,
fb.original, parsedUri.line, parsedUri.original,
parsedUri.section);
}
}
}
// Check that all resources exist and that their cach-control headers are
// not set to no-store.
let current = -1;
for (let i = 0, len = parsed.uris.length; i < len; i++) {
let parsedUri = parsed.uris[i];
this._getURIInfo(parsedUri.uri).then(uriInfo => {
current++;
// Check that all resources exist and that their cach-control headers are
// not set to no-store.
let current = -1;
for (let i = 0, len = parsed.uris.length; i < len; i++) {
let parsedUri = parsed.uris[i];
this._getURIInfo(parsedUri.uri).then(uriInfo => {
current++;
if (uriInfo.success) {
// Check that the resource was not modified after the manifest was last
// modified. If it was then the manifest file should be refreshed.
let resourceLastModified =
new Date(uriInfo.responseHeaders["last-modified"]);
if (uriInfo.success) {
// Check that the resource was not modified after the manifest was last
// modified. If it was then the manifest file should be refreshed.
let resourceLastModified =
new Date(uriInfo.responseHeaders["last-modified"]);
if (manifestLastModified < resourceLastModified) {
this._addError(parsedUri.line, "fileChangedButNotManifest",
uriInfo.name, manifestName, parsedUri.line);
}
if (manifestLastModified < resourceLastModified) {
this._addError(parsedUri.line, "fileChangedButNotManifest",
uriInfo.name, manifestName, parsedUri.line);
}
// If cache-control: no-store the file will not be added to the
// appCache.
if (uriInfo.nocache) {
this._addError(parsedUri.line, "cacheControlNoStore",
// If cache-control: no-store the file will not be added to the
// appCache.
if (uriInfo.nocache) {
this._addError(parsedUri.line, "cacheControlNoStore",
parsedUri.original, parsedUri.line);
}
} else if (parsedUri.original !== "*") {
this._addError(parsedUri.line, "notAvailable",
parsedUri.original, parsedUri.line);
}
} else if (parsedUri.original !== "*") {
this._addError(parsedUri.line, "notAvailable",
parsedUri.original, parsedUri.line);
}
if (current == len - 1) {
deferred.resolve();
}
});
}
return deferred.promise;
if (current == len - 1) {
resolve();
}
});
}
});
},
_getURIInfo: function ACU__getURIInfo(uri) {
let inputStream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
let deferred = defer();
let buffer = "";
var channel = NetUtil.newChannel({
uri: uri,
loadUsingSystemPrincipal: true,
securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL
});
return new Promise((resolve, reject) => {
let inputStream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
let buffer = "";
var channel = NetUtil.newChannel({
uri: uri,
loadUsingSystemPrincipal: true,
securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL
});
// Avoid the cache:
channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
channel.loadFlags |= Ci.nsIRequest.INHIBIT_CACHING;
// Avoid the cache:
channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
channel.loadFlags |= Ci.nsIRequest.INHIBIT_CACHING;
channel.asyncOpen2({
onStartRequest: function (request, context) {
// This empty method is needed in order for onDataAvailable to be
// called.
},
channel.asyncOpen2({
onStartRequest: function (request, context) {
// This empty method is needed in order for onDataAvailable to be
// called.
},
onDataAvailable: function (request, context, stream, offset, count) {
request.QueryInterface(Ci.nsIHttpChannel);
inputStream.init(stream);
buffer = buffer.concat(inputStream.read(count));
},
onStopRequest: function onStartRequest(request, context, statusCode) {
if (statusCode === 0) {
onDataAvailable: function (request, context, stream, offset, count) {
request.QueryInterface(Ci.nsIHttpChannel);
inputStream.init(stream);
buffer = buffer.concat(inputStream.read(count));
},
let result = {
name: request.name,
success: request.requestSucceeded,
status: request.responseStatus + " - " + request.responseStatusText,
charset: request.contentCharset || "utf-8",
mimeType: request.contentType,
contentLength: request.contentLength,
nocache: request.isNoCacheResponse() || request.isNoStoreResponse(),
prePath: request.URI.prePath + "/",
text: buffer
};
onStopRequest: function onStartRequest(request, context, statusCode) {
if (statusCode === 0) {
request.QueryInterface(Ci.nsIHttpChannel);
result.requestHeaders = {};
request.visitRequestHeaders(function (header, value) {
result.requestHeaders[header.toLowerCase()] = value;
});
let result = {
name: request.name,
success: request.requestSucceeded,
status: request.responseStatus + " - " + request.responseStatusText,
charset: request.contentCharset || "utf-8",
mimeType: request.contentType,
contentLength: request.contentLength,
nocache: request.isNoCacheResponse() || request.isNoStoreResponse(),
prePath: request.URI.prePath + "/",
text: buffer
};
result.responseHeaders = {};
request.visitResponseHeaders(function (header, value) {
result.responseHeaders[header.toLowerCase()] = value;
});
result.requestHeaders = {};
request.visitRequestHeaders(function (header, value) {
result.requestHeaders[header.toLowerCase()] = value;
});
deferred.resolve(result);
} else {
deferred.resolve({
name: request.name,
success: false
});
result.responseHeaders = {};
request.visitResponseHeaders(function (header, value) {
result.responseHeaders[header.toLowerCase()] = value;
});
resolve(result);
} else {
resolve({
name: request.name,
success: false
});
}
}
}
});
});
return deferred.promise;
},
listEntries: function ACU_show(searchTerm) {
@ -313,43 +310,42 @@ AppCacheUtils.prototype = {
},
_getManifestURI: function ACU__getManifestURI() {
let deferred = defer();
return new Promise((resolve, reject) => {
let getURI = () => {
let htmlNode = this.doc.querySelector("html[manifest]");
if (htmlNode) {
let pageUri = this.doc.location ? this.doc.location.href : this.uri;
let origin = pageUri.substr(0, pageUri.lastIndexOf("/") + 1);
let manifestURI = htmlNode.getAttribute("manifest");
let getURI = () => {
let htmlNode = this.doc.querySelector("html[manifest]");
if (htmlNode) {
let pageUri = this.doc.location ? this.doc.location.href : this.uri;
let origin = pageUri.substr(0, pageUri.lastIndexOf("/") + 1);
let manifestURI = htmlNode.getAttribute("manifest");
if (manifestURI.startsWith("/")) {
manifestURI = manifestURI.substr(1);
}
if (manifestURI.startsWith("/")) {
manifestURI = manifestURI.substr(1);
return origin + manifestURI;
}
};
return origin + manifestURI;
if (this.doc) {
let uri = getURI();
return resolve(uri);
} else {
this._getURIInfo(this.uri).then(uriInfo => {
if (uriInfo.success) {
let html = uriInfo.text;
let parser = _DOMParser;
this.doc = parser.parseFromString(html, "text/html");
let uri = getURI();
resolve(uri);
} else {
this.errors.push({
line: 0,
msg: l10n.GetStringFromName("invalidURI")
});
}
});
}
};
if (this.doc) {
let uri = getURI();
return promise.resolve(uri);
} else {
this._getURIInfo(this.uri).then(uriInfo => {
if (uriInfo.success) {
let html = uriInfo.text;
let parser = _DOMParser;
this.doc = parser.parseFromString(html, "text/html");
let uri = getURI();
deferred.resolve(uri);
} else {
this.errors.push({
line: 0,
msg: l10n.GetStringFromName("invalidURI")
});
}
});
}
return deferred.promise;
});
},
_addError: function ACU__addError(line, l10nString, ...params) {

Просмотреть файл

@ -6,7 +6,6 @@
const { Ci } = require("chrome");
const promise = require("promise");
const defer = require("devtools/shared/defer");
const Services = require("Services");
const { TargetFactory } = require("devtools/client/framework/target");
const Telemetry = require("devtools/client/shared/telemetry");
@ -309,25 +308,23 @@ DeveloperToolbar.prototype.focus = function () {
if (this.visible) {
// If the toolbar was just inserted, the <textbox> may still have
// its binding in process of being applied and not be focusable yet
let waitForBinding = defer();
let checkBinding = () => {
// Bail out if the toolbar has been destroyed in the meantime
if (!this._input) {
waitForBinding.reject();
return;
}
// mInputField is a xbl field of <xul:textbox>
if (typeof this._input.mInputField != "undefined") {
this._input.focus();
waitForBinding.resolve();
} else {
this._input.ownerDocument.defaultView.setTimeout(checkBinding, 50);
}
};
checkBinding();
return waitForBinding.promise;
return new Promise((resolve, reject) => {
let checkBinding = () => {
// Bail out if the toolbar has been destroyed in the meantime
if (!this._input) {
reject();
return;
}
// mInputField is a xbl field of <xul:textbox>
if (typeof this._input.mInputField != "undefined") {
this._input.focus();
resolve();
} else {
this._input.ownerDocument.defaultView.setTimeout(checkBinding, 50);
}
};
checkBinding();
});
}
return this.show(true);
@ -817,77 +814,76 @@ OutputPanel.create = function (devtoolbar) {
* @private See OutputPanel.create
*/
OutputPanel.prototype._init = function (devtoolbar) {
this._devtoolbar = devtoolbar;
this._input = this._devtoolbar._input;
this._toolbar = this._devtoolbar._doc.getElementById("developer-toolbar");
return new Promise((resolve, reject) => {
this._devtoolbar = devtoolbar;
this._input = this._devtoolbar._input;
this._toolbar = this._devtoolbar._doc.getElementById("developer-toolbar");
/*
<tooltip|panel id="gcli-output"
noautofocus="true"
noautohide="true"
class="gcli-panel">
<html:iframe xmlns:html="http://www.w3.org/1999/xhtml"
id="gcli-output-frame"
src="chrome://devtools/content/commandline/commandlineoutput.xhtml"
sandbox="allow-same-origin"/>
</tooltip|panel>
*/
/*
<tooltip|panel id="gcli-output"
noautofocus="true"
noautohide="true"
class="gcli-panel">
<html:iframe xmlns:html="http://www.w3.org/1999/xhtml"
id="gcli-output-frame"
src="chrome://devtools/content/commandline/commandlineoutput.xhtml"
sandbox="allow-same-origin"/>
</tooltip|panel>
*/
// TODO: Switch back from tooltip to panel when metacity focus issue is fixed:
// https://bugzilla.mozilla.org/show_bug.cgi?id=780102
this._panel = this._devtoolbar._doc.createElement(isLinux ? "tooltip" : "panel");
// TODO: Switch back from tooltip to panel when metacity focus issue is fixed:
// https://bugzilla.mozilla.org/show_bug.cgi?id=780102
this._panel = this._devtoolbar._doc.createElement(isLinux ? "tooltip" : "panel");
this._panel.id = "gcli-output";
this._panel.classList.add("gcli-panel");
this._panel.id = "gcli-output";
this._panel.classList.add("gcli-panel");
if (isLinux) {
this.canHide = false;
this._onpopuphiding = this._onpopuphiding.bind(this);
this._panel.addEventListener("popuphiding", this._onpopuphiding, true);
} else {
this._panel.setAttribute("noautofocus", "true");
this._panel.setAttribute("noautohide", "true");
if (isLinux) {
this.canHide = false;
this._onpopuphiding = this._onpopuphiding.bind(this);
this._panel.addEventListener("popuphiding", this._onpopuphiding, true);
} else {
this._panel.setAttribute("noautofocus", "true");
this._panel.setAttribute("noautohide", "true");
// Bug 692348: On Windows and OSX if a panel has no content and no height
// openPopup fails to display it. Setting the height to 1px alows the panel
// to be displayed before has content or a real height i.e. the first time
// it is displayed.
this._panel.setAttribute("height", "1px");
}
// Bug 692348: On Windows and OSX if a panel has no content and no height
// openPopup fails to display it. Setting the height to 1px alows the panel
// to be displayed before has content or a real height i.e. the first time
// it is displayed.
this._panel.setAttribute("height", "1px");
}
this._toolbar.parentElement.insertBefore(this._panel, this._toolbar);
this._toolbar.parentElement.insertBefore(this._panel, this._toolbar);
this._frame = this._devtoolbar._doc.createElementNS(NS_XHTML, "iframe");
this._frame.id = "gcli-output-frame";
this._frame.setAttribute("src", "chrome://devtools/content/commandline/commandlineoutput.xhtml");
this._frame.setAttribute("sandbox", "allow-same-origin");
this._panel.appendChild(this._frame);
this._frame = this._devtoolbar._doc.createElementNS(NS_XHTML, "iframe");
this._frame.id = "gcli-output-frame";
this._frame.setAttribute("src", "chrome://devtools/content/commandline/commandlineoutput.xhtml");
this._frame.setAttribute("sandbox", "allow-same-origin");
this._panel.appendChild(this._frame);
this.displayedOutput = undefined;
this.displayedOutput = undefined;
this._update = this._update.bind(this);
this._update = this._update.bind(this);
// Wire up the element from the iframe, and resolve the promise
let deferred = defer();
let onload = () => {
this._frame.removeEventListener("load", onload, true);
// Wire up the element from the iframe, and resolve the promise
let onload = () => {
this._frame.removeEventListener("load", onload, true);
this.document = this._frame.contentDocument;
this._copyTheme();
this.document = this._frame.contentDocument;
this._copyTheme();
this._div = this.document.getElementById("gcli-output-root");
this._div.classList.add("gcli-row-out");
this._div.setAttribute("aria-live", "assertive");
this._div = this.document.getElementById("gcli-output-root");
this._div.classList.add("gcli-row-out");
this._div.setAttribute("aria-live", "assertive");
let styles = this._toolbar.ownerDocument.defaultView
.getComputedStyle(this._toolbar);
this._div.setAttribute("dir", styles.direction);
let styles = this._toolbar.ownerDocument.defaultView
.getComputedStyle(this._toolbar);
this._div.setAttribute("dir", styles.direction);
deferred.resolve(this);
};
this._frame.addEventListener("load", onload, true);
return deferred.promise;
resolve(this);
};
this._frame.addEventListener("load", onload, true);
});
};
/* Copy the current devtools theme attribute into the iframe,
@ -1136,78 +1132,76 @@ TooltipPanel.create = function (devtoolbar) {
* @private See TooltipPanel.create
*/
TooltipPanel.prototype._init = function (devtoolbar) {
let deferred = defer();
return new Promise((resolve, reject) => {
this._devtoolbar = devtoolbar;
this._input = devtoolbar._doc.querySelector(".gclitoolbar-input-node");
this._toolbar = devtoolbar._doc.querySelector("#developer-toolbar");
this._dimensions = { start: 0, end: 0 };
this._devtoolbar = devtoolbar;
this._input = devtoolbar._doc.querySelector(".gclitoolbar-input-node");
this._toolbar = devtoolbar._doc.querySelector("#developer-toolbar");
this._dimensions = { start: 0, end: 0 };
/*
<tooltip|panel id="gcli-tooltip"
type="arrow"
noautofocus="true"
noautohide="true"
class="gcli-panel">
<html:iframe xmlns:html="http://www.w3.org/1999/xhtml"
id="gcli-tooltip-frame"
src="chrome://devtools/content/commandline/commandlinetooltip.xhtml"
flex="1"
sandbox="allow-same-origin"/>
</tooltip|panel>
*/
/*
<tooltip|panel id="gcli-tooltip"
type="arrow"
noautofocus="true"
noautohide="true"
class="gcli-panel">
<html:iframe xmlns:html="http://www.w3.org/1999/xhtml"
id="gcli-tooltip-frame"
src="chrome://devtools/content/commandline/commandlinetooltip.xhtml"
flex="1"
sandbox="allow-same-origin"/>
</tooltip|panel>
*/
// TODO: Switch back from tooltip to panel when metacity focus issue is fixed:
// https://bugzilla.mozilla.org/show_bug.cgi?id=780102
this._panel = devtoolbar._doc.createElement(isLinux ? "tooltip" : "panel");
// TODO: Switch back from tooltip to panel when metacity focus issue is fixed:
// https://bugzilla.mozilla.org/show_bug.cgi?id=780102
this._panel = devtoolbar._doc.createElement(isLinux ? "tooltip" : "panel");
this._panel.id = "gcli-tooltip";
this._panel.classList.add("gcli-panel");
this._panel.id = "gcli-tooltip";
this._panel.classList.add("gcli-panel");
if (isLinux) {
this.canHide = false;
this._onpopuphiding = this._onpopuphiding.bind(this);
this._panel.addEventListener("popuphiding", this._onpopuphiding, true);
} else {
this._panel.setAttribute("noautofocus", "true");
this._panel.setAttribute("noautohide", "true");
if (isLinux) {
this.canHide = false;
this._onpopuphiding = this._onpopuphiding.bind(this);
this._panel.addEventListener("popuphiding", this._onpopuphiding, true);
} else {
this._panel.setAttribute("noautofocus", "true");
this._panel.setAttribute("noautohide", "true");
// Bug 692348: On Windows and OSX if a panel has no content and no height
// openPopup fails to display it. Setting the height to 1px alows the panel
// to be displayed before has content or a real height i.e. the first time
// it is displayed.
this._panel.setAttribute("height", "1px");
}
// Bug 692348: On Windows and OSX if a panel has no content and no height
// openPopup fails to display it. Setting the height to 1px alows the panel
// to be displayed before has content or a real height i.e. the first time
// it is displayed.
this._panel.setAttribute("height", "1px");
}
this._toolbar.parentElement.insertBefore(this._panel, this._toolbar);
this._toolbar.parentElement.insertBefore(this._panel, this._toolbar);
this._frame = devtoolbar._doc.createElementNS(NS_XHTML, "iframe");
this._frame.id = "gcli-tooltip-frame";
this._frame.setAttribute("src", "chrome://devtools/content/commandline/commandlinetooltip.xhtml");
this._frame.setAttribute("flex", "1");
this._frame.setAttribute("sandbox", "allow-same-origin");
this._panel.appendChild(this._frame);
this._frame = devtoolbar._doc.createElementNS(NS_XHTML, "iframe");
this._frame.id = "gcli-tooltip-frame";
this._frame.setAttribute("src", "chrome://devtools/content/commandline/commandlinetooltip.xhtml");
this._frame.setAttribute("flex", "1");
this._frame.setAttribute("sandbox", "allow-same-origin");
this._panel.appendChild(this._frame);
/**
* Wire up the element from the iframe, and resolve the promise.
*/
let onload = () => {
this._frame.removeEventListener("load", onload, true);
/**
* Wire up the element from the iframe, and resolve the promise.
*/
let onload = () => {
this._frame.removeEventListener("load", onload, true);
this.document = this._frame.contentDocument;
this._copyTheme();
this.hintElement = this.document.getElementById("gcli-tooltip-root");
this._connector = this.document.getElementById("gcli-tooltip-connector");
this.document = this._frame.contentDocument;
this._copyTheme();
this.hintElement = this.document.getElementById("gcli-tooltip-root");
this._connector = this.document.getElementById("gcli-tooltip-connector");
let styles = this._toolbar.ownerDocument.defaultView
.getComputedStyle(this._toolbar);
this.hintElement.setAttribute("dir", styles.direction);
let styles = this._toolbar.ownerDocument.defaultView
.getComputedStyle(this._toolbar);
this.hintElement.setAttribute("dir", styles.direction);
deferred.resolve(this);
};
this._frame.addEventListener("load", onload, true);
return deferred.promise;
resolve(this);
};
this._frame.addEventListener("load", onload, true);
});
};
/* Copy the current devtools theme attribute into the iframe,

Просмотреть файл

@ -7,7 +7,6 @@
const Services = require("Services");
const { DOMHelpers } = require("resource://devtools/client/shared/DOMHelpers.jsm");
const { Task } = require("devtools/shared/task");
const defer = require("devtools/shared/defer");
const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
const DEV_EDITION_PROMO_URL = "chrome://devtools/content/framework/dev-edition-promo/dev-edition-promo.xul";
@ -132,20 +131,18 @@ function setDoorhangerStyle(panel, frame) {
}
function onFrameLoad(frame) {
let { resolve, promise } = defer();
if (frame.contentWindow) {
let domHelper = new DOMHelpers(frame.contentWindow);
domHelper.onceDOMReady(resolve);
} else {
let callback = () => {
frame.removeEventListener("DOMContentLoaded", callback);
resolve();
};
frame.addEventListener("DOMContentLoaded", callback);
}
return promise;
return new Promise((resolve, reject) => {
if (frame.contentWindow) {
let domHelper = new DOMHelpers(frame.contentWindow);
domHelper.onceDOMReady(resolve);
} else {
let callback = () => {
frame.removeEventListener("DOMContentLoaded", callback);
resolve();
};
frame.addEventListener("DOMContentLoaded", callback);
}
});
}
function getGBrowser() {
@ -153,7 +150,7 @@ function getGBrowser() {
}
function wait(n) {
let { resolve, promise } = defer();
setTimeout(resolve, n);
return promise;
return new Promise((resolve, reject) => {
setTimeout(resolve, n);
});
}

Просмотреть файл

@ -7,7 +7,6 @@
"use strict";
var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
const {require, loader} = Cu.import("resource://devtools/shared/Loader.jsm", {});
const defer = require("devtools/shared/defer");
const { Task } = require("devtools/shared/task");
loader.lazyGetter(this, "nsIProfilerModule", () => {
@ -51,32 +50,32 @@ addMessageListener("devtools:test:console", function ({ data }) {
*
*/
function promiseXHR(data) {
let xhr = new content.XMLHttpRequest();
return new Promise((resolve, reject) => {
let xhr = new content.XMLHttpRequest();
let method = data.method || "GET";
let url = data.url || content.location.href;
let body = data.body || "";
let method = data.method || "GET";
let url = data.url || content.location.href;
let body = data.body || "";
if (data.nocache) {
url += "?devtools-cachebust=" + Math.random();
}
if (data.nocache) {
url += "?devtools-cachebust=" + Math.random();
}
let deferred = defer();
xhr.addEventListener("loadend", function (event) {
deferred.resolve({ status: xhr.status, response: xhr.response });
}, {once: true});
xhr.addEventListener("loadend", function (event) {
resolve({ status: xhr.status, response: xhr.response });
}, {once: true});
xhr.open(method, url);
xhr.open(method, url);
// Set request headers
if (data.requestHeaders) {
data.requestHeaders.forEach(header => {
xhr.setRequestHeader(header.name, header.value);
});
}
// Set request headers
if (data.requestHeaders) {
data.requestHeaders.forEach(header => {
xhr.setRequestHeader(header.name, header.value);
});
}
xhr.send(body);
return deferred.promise;
xhr.send(body);
});
}
/**

Просмотреть файл

@ -5,8 +5,6 @@
"use strict";
const {CC} = require("chrome");
const defer = require("devtools/shared/defer");
const promise = require("promise");
const Services = require("Services");
loader.lazyRequireGetter(this, "asyncStorage", "devtools/shared/async-storage");
@ -25,52 +23,51 @@ const XMLHttpRequest = CC("@mozilla.org/xmlextras/xmlhttprequest;1");
* - Rejected with an error message in case of failure
*/
exports.getJSON = function (prefName) {
let deferred = defer();
let xhr = new XMLHttpRequest();
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
// We used to store cached data in preferences, but now we use asyncStorage
// Migration step: if it still exists, move this now useless preference in its
// new location and clear it
if (Services.prefs.prefHasUserValue(prefName + "_cache")) {
let json = Services.prefs.getCharPref(prefName + "_cache");
asyncStorage.setItem(prefName + "_cache", json).catch(function (e) {
// Could not move the cache, let's log the error but continue
console.error(e);
});
Services.prefs.clearUserPref(prefName + "_cache");
}
function readFromStorage(networkError) {
asyncStorage.getItem(prefName + "_cache").then(function (json) {
if (!json) {
return promise.reject("Empty cache for " + prefName);
}
return deferred.resolve(json);
}).catch(function (e) {
deferred.reject("JSON not available, CDN error: " + networkError +
", storage error: " + e);
});
}
xhr.onload = () => {
try {
let json = JSON.parse(xhr.responseText);
// We used to store cached data in preferences, but now we use asyncStorage
// Migration step: if it still exists, move this now useless preference in its
// new location and clear it
if (Services.prefs.prefHasUserValue(prefName + "_cache")) {
let json = Services.prefs.getCharPref(prefName + "_cache");
asyncStorage.setItem(prefName + "_cache", json).catch(function (e) {
// Could not update cache, let's log the error but continue
// Could not move the cache, let's log the error but continue
console.error(e);
});
deferred.resolve(json);
} catch (e) {
readFromStorage(e);
Services.prefs.clearUserPref(prefName + "_cache");
}
};
xhr.onerror = (e) => {
readFromStorage(e);
};
function readFromStorage(networkError) {
asyncStorage.getItem(prefName + "_cache").then(function (json) {
if (!json) {
return reject("Empty cache for " + prefName);
}
return resolve(json);
}).catch(function (e) {
reject("JSON not available, CDN error: " + networkError +
", storage error: " + e);
});
}
xhr.open("get", Services.prefs.getCharPref(prefName));
xhr.send();
xhr.onload = () => {
try {
let json = JSON.parse(xhr.responseText);
asyncStorage.setItem(prefName + "_cache", json).catch(function (e) {
// Could not update cache, let's log the error but continue
console.error(e);
});
resolve(json);
} catch (e) {
readFromStorage(e);
}
};
return deferred.promise;
xhr.onerror = (e) => {
readFromStorage(e);
};
xhr.open("get", Services.prefs.getCharPref(prefName));
xhr.send();
});
};

Просмотреть файл

@ -3,8 +3,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
loader.lazyRequireGetter(this, "defer",
"promise", true);
/**
* @constructor Poller
@ -63,20 +61,20 @@ Poller.prototype.on = function pollerOn() {
* @return {Promise}
*/
Poller.prototype.off = function pollerOff() {
let { resolve, promise } = defer();
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
return new Promise((resolve, reject) => {
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
// Settle an inflight poll call before resolving
// if using a promise-backed poll function
if (this._inflight) {
this._inflight.then(resolve);
} else {
resolve();
}
return promise;
// Settle an inflight poll call before resolving
// if using a promise-backed poll function
if (this._inflight) {
this._inflight.then(resolve);
} else {
resolve();
}
});
};
/**

Просмотреть файл

@ -4,7 +4,6 @@
"use strict";
const { generateUUID } = require("devtools/shared/generate-uuid");
const defer = require("devtools/shared/defer");
const {
entries, toObject, executeSoon
} = require("devtools/shared/DevToolsUtils");
@ -15,39 +14,38 @@ function promiseMiddleware({ dispatch, getState }) {
if (!(PROMISE in action)) {
return next(action);
}
const promiseInst = action[PROMISE];
const seqId = generateUUID().toString();
// Create a new action that doesn't have the promise field and has
// the `seqId` field that represents the sequence id
action = Object.assign(
toObject(entries(action).filter(pair => pair[0] !== PROMISE)), { seqId }
);
dispatch(Object.assign({}, action, { status: "start" }));
// Return the promise so action creators can still compose if they
// want to.
const deferred = defer();
promiseInst.then(value => {
executeSoon(() => {
dispatch(Object.assign({}, action, {
status: "done",
value: value
}));
deferred.resolve(value);
});
}, error => {
executeSoon(() => {
dispatch(Object.assign({}, action, {
status: "error",
error: error.message || error
}));
deferred.reject(error);
return new Promise((resolve, reject) => {
const promiseInst = action[PROMISE];
const seqId = generateUUID().toString();
// Create a new action that doesn't have the promise field and has
// the `seqId` field that represents the sequence id
action = Object.assign(
toObject(entries(action).filter(pair => pair[0] !== PROMISE)), { seqId }
);
dispatch(Object.assign({}, action, { status: "start" }));
promiseInst.then(value => {
executeSoon(() => {
dispatch(Object.assign({}, action, {
status: "done",
value: value
}));
resolve(value);
});
}, error => {
executeSoon(() => {
dispatch(Object.assign({}, action, {
status: "error",
error: error.message || error
}));
reject(error);
});
});
});
return deferred.promise;
};
}