Bug 1346009 - Convert 'defer' to 'new Promise' in client/webide; r=tromey

MozReview-Commit-ID: 1adrD8A96Dx

--HG--
extra : rebase_source : 9c616dfa39a4d80697e59073d1d8a3b796d51355
This commit is contained in:
Matt R 2017-05-20 13:31:10 +01:00
Родитель 4d43775859
Коммит 7ae37aa776
18 изменённых файлов: 567 добавлений и 604 удалений

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

@ -4,7 +4,6 @@
"use strict"; "use strict";
const promise = require("promise");
const {AddonManager} = require("resource://gre/modules/AddonManager.jsm"); const {AddonManager} = require("resource://gre/modules/AddonManager.jsm");
const Services = require("Services"); const Services = require("Services");
const {getJSON} = require("devtools/client/shared/getjson"); const {getJSON} = require("devtools/client/shared/getjson");
@ -51,24 +50,24 @@ AddonManager.addAddonListener(addonsListener);
var GetAvailableAddons_promise = null; var GetAvailableAddons_promise = null;
var GetAvailableAddons = exports.GetAvailableAddons = function () { var GetAvailableAddons = exports.GetAvailableAddons = function () {
if (!GetAvailableAddons_promise) { if (!GetAvailableAddons_promise) {
let deferred = promise.defer(); GetAvailableAddons_promise = new Promise((resolve, reject) => {
GetAvailableAddons_promise = deferred.promise; let addons = {
let addons = { simulators: [],
simulators: [], adb: null
adb: null };
}; getJSON(ADDONS_URL).then(json => {
getJSON(ADDONS_URL).then(json => { for (let stability in json) {
for (let stability in json) { for (let version of json[stability]) {
for (let version of json[stability]) { addons.simulators.push(new SimulatorAddon(stability, version));
addons.simulators.push(new SimulatorAddon(stability, version)); }
} }
} addons.adb = new ADBAddon();
addons.adb = new ADBAddon(); addons.adapters = new AdaptersAddon();
addons.adapters = new AdaptersAddon(); resolve(addons);
deferred.resolve(addons); }, e => {
}, e => { GetAvailableAddons_promise = null;
GetAvailableAddons_promise = null; reject(e);
deferred.reject(e); });
}); });
} }
return GetAvailableAddons_promise; return GetAvailableAddons_promise;

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

@ -4,7 +4,6 @@
const {Cu} = require("chrome"); const {Cu} = require("chrome");
const promise = require("promise");
const {TargetFactory} = require("devtools/client/framework/target"); const {TargetFactory} = require("devtools/client/framework/target");
const Services = require("Services"); const Services = require("Services");
const {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm", {}); const {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm", {});
@ -277,7 +276,7 @@ var AppManager = exports.AppManager = {
reloadTab: function () { reloadTab: function () {
if (this.selectedProject && this.selectedProject.type != "tab") { if (this.selectedProject && this.selectedProject.type != "tab") {
return promise.reject("tried to reload non-tab project"); return Promise.reject("tried to reload non-tab project");
} }
return this.getTarget().then(target => { return this.getTarget().then(target => {
target.activeTab.reload(); target.activeTab.reload();
@ -313,7 +312,7 @@ var AppManager = exports.AppManager = {
let app = this._getProjectFront(this.selectedProject); let app = this._getProjectFront(this.selectedProject);
if (!app) { if (!app) {
return promise.reject("Can't find app front for selected project"); return Promise.reject("Can't find app front for selected project");
} }
return Task.spawn(function* () { return Task.spawn(function* () {
@ -325,9 +324,9 @@ var AppManager = exports.AppManager = {
try { try {
return yield app.getTarget(); return yield app.getTarget();
} catch (e) {} } catch (e) {}
let deferred = promise.defer(); return new Promise(resolve => {
setTimeout(deferred.resolve, 500); setTimeout(resolve, 500);
yield deferred.promise; });
} }
AppManager.reportError("error_cantConnectToApp", app.manifest.manifestURL); AppManager.reportError("error_cantConnectToApp", app.manifest.manifestURL);
@ -460,36 +459,36 @@ var AppManager = exports.AppManager = {
if (this.connected && this.selectedRuntime === runtime) { if (this.connected && this.selectedRuntime === runtime) {
// Already connected // Already connected
return promise.resolve(); return Promise.resolve();
} }
let deferred = promise.defer(); let deferred = new Promise((resolve, reject) => {
this.disconnectRuntime().then(() => {
this.selectedRuntime = runtime;
this.disconnectRuntime().then(() => { let onConnectedOrDisconnected = () => {
this.selectedRuntime = runtime; this.connection.off(Connection.Events.CONNECTED, onConnectedOrDisconnected);
this.connection.off(Connection.Events.DISCONNECTED, onConnectedOrDisconnected);
let onConnectedOrDisconnected = () => { if (this.connected) {
this.connection.off(Connection.Events.CONNECTED, onConnectedOrDisconnected); resolve();
this.connection.off(Connection.Events.DISCONNECTED, onConnectedOrDisconnected); } else {
if (this.connected) { reject();
deferred.resolve(); }
} else { };
deferred.reject(); this.connection.on(Connection.Events.CONNECTED, onConnectedOrDisconnected);
this.connection.on(Connection.Events.DISCONNECTED, onConnectedOrDisconnected);
try {
// Reset the connection's state to defaults
this.connection.resetOptions();
// Only watch for errors here. Final resolution occurs above, once
// we've reached the CONNECTED state.
this.selectedRuntime.connect(this.connection)
.then(null, e => reject(e));
} catch (e) {
reject(e);
} }
}; }, reject);
this.connection.on(Connection.Events.CONNECTED, onConnectedOrDisconnected); });
this.connection.on(Connection.Events.DISCONNECTED, onConnectedOrDisconnected);
try {
// Reset the connection's state to defaults
this.connection.resetOptions();
// Only watch for errors here. Final resolution occurs above, once
// we've reached the CONNECTED state.
this.selectedRuntime.connect(this.connection)
.then(null, e => deferred.reject(e));
} catch (e) {
deferred.reject(e);
}
}, deferred.reject);
// Record connection result in telemetry // Record connection result in telemetry
let logResult = result => { let logResult = result => {
@ -499,10 +498,10 @@ var AppManager = exports.AppManager = {
"_CONNECTION_RESULT", result); "_CONNECTION_RESULT", result);
} }
}; };
deferred.promise.then(() => logResult(true), () => logResult(false)); deferred.then(() => logResult(true), () => logResult(false));
// If successful, record connection time in telemetry // If successful, record connection time in telemetry
deferred.promise.then(() => { deferred.then(() => {
const timerId = "DEVTOOLS_WEBIDE_CONNECTION_TIME_SECONDS"; const timerId = "DEVTOOLS_WEBIDE_CONNECTION_TIME_SECONDS";
this._telemetry.startTimer(timerId); this._telemetry.startTimer(timerId);
this.connection.once(Connection.Events.STATUS_CHANGED, () => { this.connection.once(Connection.Events.STATUS_CHANGED, () => {
@ -514,7 +513,7 @@ var AppManager = exports.AppManager = {
// Bug 1121100 may find a better way to silence these. // Bug 1121100 may find a better way to silence these.
}); });
return deferred.promise; return deferred;
}, },
_recordRuntimeInfo: Task.async(function* () { _recordRuntimeInfo: Task.async(function* () {
@ -570,17 +569,18 @@ var AppManager = exports.AppManager = {
disconnectRuntime: function () { disconnectRuntime: function () {
if (!this.connected) { if (!this.connected) {
return promise.resolve(); return Promise.resolve();
} }
let deferred = promise.defer();
this.connection.once(Connection.Events.DISCONNECTED, () => deferred.resolve()); return new Promise(resolve => {
this.connection.disconnect(); this.connection.once(Connection.Events.DISCONNECTED, () => resolve());
return deferred.promise; this.connection.disconnect();
});
}, },
launchRuntimeApp: function () { launchRuntimeApp: function () {
if (this.selectedProject && this.selectedProject.type != "runtimeApp") { if (this.selectedProject && this.selectedProject.type != "runtimeApp") {
return promise.reject("attempting to launch a non-runtime app"); return Promise.reject("attempting to launch a non-runtime app");
} }
let app = this._getProjectFront(this.selectedProject); let app = this._getProjectFront(this.selectedProject);
return app.launch(); return app.launch();
@ -588,7 +588,7 @@ var AppManager = exports.AppManager = {
launchOrReloadRuntimeApp: function () { launchOrReloadRuntimeApp: function () {
if (this.selectedProject && this.selectedProject.type != "runtimeApp") { if (this.selectedProject && this.selectedProject.type != "runtimeApp") {
return promise.reject("attempting to launch / reload a non-runtime app"); return Promise.reject("attempting to launch / reload a non-runtime app");
} }
let app = this._getProjectFront(this.selectedProject); let app = this._getProjectFront(this.selectedProject);
if (!app.running) { if (!app.running) {
@ -607,17 +607,17 @@ var AppManager = exports.AppManager = {
if (!project || (project.type != "packaged" && project.type != "hosted")) { if (!project || (project.type != "packaged" && project.type != "hosted")) {
console.error("Can't install project. Unknown type of project."); console.error("Can't install project. Unknown type of project.");
return promise.reject("Can't install"); return Promise.reject("Can't install");
} }
if (!this._listTabsResponse) { if (!this._listTabsResponse) {
this.reportError("error_cantInstallNotFullyConnected"); this.reportError("error_cantInstallNotFullyConnected");
return promise.reject("Can't install"); return Promise.reject("Can't install");
} }
if (!this._appsFront) { if (!this._appsFront) {
console.error("Runtime doesn't have a webappsActor"); console.error("Runtime doesn't have a webappsActor");
return promise.reject("Can't install"); return Promise.reject("Can't install");
} }
return Task.spawn(function* () { return Task.spawn(function* () {
@ -635,7 +635,7 @@ var AppManager = exports.AppManager = {
let installPromise; let installPromise;
if (project.type != "packaged" && project.type != "hosted") { if (project.type != "packaged" && project.type != "hosted") {
return promise.reject("Don't know how to install project"); return Promise.reject("Don't know how to install project");
} }
let response; let response;
@ -674,15 +674,16 @@ var AppManager = exports.AppManager = {
let {app} = response; let {app} = response;
if (!app.running) { if (!app.running) {
let deferred = promise.defer(); let deferred = new Promise(resolve => {
self.on("app-manager-update", function onUpdate(event, what) { self.on("app-manager-update", function onUpdate(event, what) {
if (what == "project-started") { if (what == "project-started") {
self.off("app-manager-update", onUpdate); self.off("app-manager-update", onUpdate);
deferred.resolve(); resolve();
} }
});
}); });
yield app.launch(); yield app.launch();
yield deferred.promise; yield deferred;
} else { } else {
yield app.reload(); yield app.reload();
} }
@ -698,7 +699,7 @@ var AppManager = exports.AppManager = {
validateAndUpdateProject: function (project) { validateAndUpdateProject: function (project) {
if (!project) { if (!project) {
return promise.reject(); return Promise.reject();
} }
return Task.spawn(function* () { return Task.spawn(function* () {
@ -823,7 +824,7 @@ var AppManager = exports.AppManager = {
writeManifest: function (project) { writeManifest: function (project) {
if (project.type != "packaged") { if (project.type != "packaged") {
return promise.reject("Not a packaged app"); return Promise.reject("Not a packaged app");
} }
if (!project.manifest) { if (!project.manifest) {

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

@ -3,7 +3,6 @@
* 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 {Cc, Ci, Cu, Cr} = require("chrome"); const {Cc, Ci, Cu, Cr} = require("chrome");
const promise = require("promise");
const EventEmitter = require("devtools/shared/event-emitter"); const EventEmitter = require("devtools/shared/event-emitter");
const {generateUUID} = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator); const {generateUUID} = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
@ -21,145 +20,135 @@ const IDB = {
databaseName: "AppProjects", databaseName: "AppProjects",
open: function () { open: function () {
let deferred = promise.defer(); return new Promise((resolve, reject) => {
let request = indexedDB.open(IDB.databaseName, 5);
request.onerror = function (event) {
reject("Unable to open AppProjects indexedDB: " +
this.error.name + " - " + this.error.message);
};
request.onupgradeneeded = function (event) {
let db = event.target.result;
db.createObjectStore("projects", { keyPath: "location" });
};
let request = indexedDB.open(IDB.databaseName, 5); request.onsuccess = function () {
request.onerror = function (event) { let db = IDB._db = request.result;
deferred.reject("Unable to open AppProjects indexedDB: " + let objectStore = db.transaction("projects").objectStore("projects");
this.error.name + " - " + this.error.message); let projects = [];
}; let toRemove = [];
request.onupgradeneeded = function (event) { objectStore.openCursor().onsuccess = function (event) {
let db = event.target.result; let cursor = event.target.result;
db.createObjectStore("projects", { keyPath: "location" }); if (cursor) {
}; if (cursor.value.location) {
request.onsuccess = function () { // We need to make sure this object has a `.location` property.
let db = IDB._db = request.result; // The UI depends on this property.
let objectStore = db.transaction("projects").objectStore("projects"); // This should not be needed as we make sure to register valid
let projects = []; // projects, but in the past (before bug 924568), we might have
let toRemove = []; // registered invalid objects.
objectStore.openCursor().onsuccess = function (event) {
let cursor = event.target.result;
if (cursor) {
if (cursor.value.location) {
// We need to make sure this object has a `.location` property.
// The UI depends on this property.
// This should not be needed as we make sure to register valid
// projects, but in the past (before bug 924568), we might have
// registered invalid objects.
// We also want to make sure the location is valid. // We also want to make sure the location is valid.
// If the location doesn't exist, we remove the project. // If the location doesn't exist, we remove the project.
try { try {
let file = FileUtils.File(cursor.value.location); let file = FileUtils.File(cursor.value.location);
if (file.exists()) { if (file.exists()) {
projects.push(cursor.value); projects.push(cursor.value);
} else { } else {
toRemove.push(cursor.value.location); toRemove.push(cursor.value.location);
} }
} catch (e) { } catch (e) {
if (e.result == Cr.NS_ERROR_FILE_UNRECOGNIZED_PATH) { if (e.result == Cr.NS_ERROR_FILE_UNRECOGNIZED_PATH) {
// A URL // A URL
projects.push(cursor.value); projects.push(cursor.value);
}
} }
} }
cursor.continue();
} else {
let removePromises = [];
for (let location of toRemove) {
removePromises.push(IDB.remove(location));
}
Promise.all(removePromises).then(() => {
resolve(projects);
});
} }
cursor.continue(); };
} else {
let removePromises = [];
for (let location of toRemove) {
removePromises.push(IDB.remove(location));
}
promise.all(removePromises).then(() => {
deferred.resolve(projects);
});
}
}; };
}; });
return deferred.promise;
}, },
add: function (project) { add: function (project) {
let deferred = promise.defer(); return new Promise((resolve, reject) => {
if (!project.location) {
if (!project.location) { // We need to make sure this object has a `.location` property.
// We need to make sure this object has a `.location` property. reject("Missing location property on project object.");
deferred.reject("Missing location property on project object."); } else {
} else { let transaction = IDB._db.transaction(["projects"], "readwrite");
let transaction = IDB._db.transaction(["projects"], "readwrite"); let objectStore = transaction.objectStore("projects");
let objectStore = transaction.objectStore("projects"); let request = objectStore.add(project);
let request = objectStore.add(project); request.onerror = function (event) {
request.onerror = function (event) { reject("Unable to add project to the AppProjects indexedDB: " +
deferred.reject("Unable to add project to the AppProjects indexedDB: " + this.error.name + " - " + this.error.message);
this.error.name + " - " + this.error.message); };
}; request.onsuccess = function () {
request.onsuccess = function () { resolve();
deferred.resolve(); };
}; }
} });
return deferred.promise;
}, },
update: function (project) { update: function (project) {
let deferred = promise.defer(); return new Promise((resolve, reject) => {
var transaction = IDB._db.transaction(["projects"], "readwrite");
var transaction = IDB._db.transaction(["projects"], "readwrite"); var objectStore = transaction.objectStore("projects");
var objectStore = transaction.objectStore("projects"); var request = objectStore.put(project);
var request = objectStore.put(project); request.onerror = function (event) {
request.onerror = function (event) { reject("Unable to update project to the AppProjects indexedDB: " +
deferred.reject("Unable to update project to the AppProjects indexedDB: " + this.error.name + " - " + this.error.message);
this.error.name + " - " + this.error.message); };
}; request.onsuccess = function () {
request.onsuccess = function () { resolve();
deferred.resolve(); };
}; });
return deferred.promise;
}, },
remove: function (location) { remove: function (location) {
let deferred = promise.defer(); return new Promise((resolve, reject) => {
let request = IDB._db.transaction(["projects"], "readwrite")
let request = IDB._db.transaction(["projects"], "readwrite")
.objectStore("projects") .objectStore("projects")
.delete(location); .delete(location);
request.onsuccess = function (event) { request.onsuccess = function (event) {
deferred.resolve(); resolve();
}; };
request.onerror = function () { request.onerror = function () {
deferred.reject("Unable to delete project to the AppProjects indexedDB: " + reject("Unable to delete project to the AppProjects indexedDB: " +
this.error.name + " - " + this.error.message); this.error.name + " - " + this.error.message);
}; };
});
return deferred.promise;
} }
}; };
var loadDeferred = promise.defer(); var loadDeferred = IDB.open().then(function (projects) {
loadDeferred.resolve(IDB.open().then(function (projects) {
AppProjects.projects = projects; AppProjects.projects = projects;
AppProjects.emit("ready", projects); AppProjects.emit("ready", projects);
})); });
const AppProjects = { const AppProjects = {
load: function () { load: function () {
return loadDeferred.promise; return loadDeferred;
}, },
addPackaged: function (folder) { addPackaged: function (folder) {
let file = FileUtils.File(folder.path); let file = FileUtils.File(folder.path);
if (!file.exists()) { if (!file.exists()) {
return promise.reject("path doesn't exist"); return Promise.reject("path doesn't exist");
} }
let existingProject = this.get(folder.path); let existingProject = this.get(folder.path);
if (existingProject) { if (existingProject) {
return promise.reject("Already added"); return Promise.reject("Already added");
} }
let project = { let project = {
type: "packaged", type: "packaged",
@ -182,7 +171,7 @@ const AppProjects = {
addHosted: function (manifestURL) { addHosted: function (manifestURL) {
let existingProject = this.get(manifestURL); let existingProject = this.get(manifestURL);
if (existingProject) { if (existingProject) {
return promise.reject("Already added"); return Promise.reject("Already added");
} }
let project = { let project = {
type: "hosted", type: "hosted",

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

@ -4,7 +4,6 @@
"use strict"; "use strict";
var {Ci, Cu, CC} = require("chrome"); var {Ci, Cu, CC} = require("chrome");
const promise = require("promise");
const {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm", {}); const {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm", {});
const Services = require("Services"); const Services = require("Services");
@ -64,46 +63,44 @@ AppValidator.prototype._getPackagedManifestURL = function () {
}; };
AppValidator.checkManifest = function (manifestURL) { AppValidator.checkManifest = function (manifestURL) {
let deferred = promise.defer(); return new Promise((resolve, reject) => {
let error; let error;
let req = new XMLHttpRequest(); let req = new XMLHttpRequest();
req.overrideMimeType("text/plain"); req.overrideMimeType("text/plain");
try {
req.open("GET", manifestURL, true);
req.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_CACHING;
} catch (e) {
error = strings.formatStringFromName("validator.invalidManifestURL", [manifestURL], 1);
deferred.reject(error);
return deferred.promise;
}
req.onload = function () {
let manifest = null;
try { try {
manifest = JSON.parse(req.responseText); req.open("GET", manifestURL, true);
req.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_CACHING;
} catch (e) { } catch (e) {
error = strings.formatStringFromName("validator.invalidManifestJSON", [e, manifestURL], 2); error = strings.formatStringFromName("validator.invalidManifestURL", [manifestURL], 1);
deferred.reject(error); return reject(error);
} }
deferred.resolve({manifest, manifestURL}); req.onload = function () {
}; let manifest = null;
try {
manifest = JSON.parse(req.responseText);
} catch (e) {
error = strings.formatStringFromName("validator.invalidManifestJSON", [e, manifestURL], 2);
reject(error);
}
req.onerror = function () { resolve({manifest, manifestURL});
error = strings.formatStringFromName("validator.noAccessManifestURL", [req.statusText, manifestURL], 2); };
deferred.reject(error);
};
try { req.onerror = function () {
req.send(null); error = strings.formatStringFromName("validator.noAccessManifestURL", [req.statusText, manifestURL], 2);
} catch (e) { reject(error);
error = strings.formatStringFromName("validator.noAccessManifestURL", [e, manifestURL], 2); };
deferred.reject(error);
}
return deferred.promise; try {
req.send(null);
} catch (e) {
error = strings.formatStringFromName("validator.noAccessManifestURL", [e, manifestURL], 2);
reject(error);
}
});
}; };
AppValidator.findManifestAtOrigin = function (manifestURL) { AppValidator.findManifestAtOrigin = function (manifestURL) {
@ -112,16 +109,14 @@ AppValidator.findManifestAtOrigin = function (manifestURL) {
}; };
AppValidator.findManifestPath = function (manifestURL) { AppValidator.findManifestPath = function (manifestURL) {
let deferred = promise.defer(); return new Promise((resolve, reject) => {
if (manifestURL.endsWith("manifest.webapp")) {
if (manifestURL.endsWith("manifest.webapp")) { reject();
deferred.reject(); } else {
} else { let fixedManifest = manifestURL + "/manifest.webapp";
let fixedManifest = manifestURL + "/manifest.webapp"; resolve(AppValidator.checkManifest(fixedManifest));
deferred.resolve(AppValidator.checkManifest(fixedManifest)); }
} });
return deferred.promise;
}; };
AppValidator.checkAlternateManifest = function (manifestURL) { AppValidator.checkAlternateManifest = function (manifestURL) {
@ -138,24 +133,23 @@ AppValidator.checkAlternateManifest = function (manifestURL) {
}; };
AppValidator.prototype._fetchManifest = function (manifestURL) { AppValidator.prototype._fetchManifest = function (manifestURL) {
let deferred = promise.defer(); return new Promise(resolve => {
this.manifestURL = manifestURL; this.manifestURL = manifestURL;
AppValidator.checkManifest(manifestURL) AppValidator.checkManifest(manifestURL)
.then(({manifest, manifestURL}) => { .then(({manifest, manifestURL}) => {
deferred.resolve(manifest); resolve(manifest);
}, error => { }, error => {
AppValidator.checkAlternateManifest(manifestURL) AppValidator.checkAlternateManifest(manifestURL)
.then(({manifest, manifestURL}) => { .then(({manifest, manifestURL}) => {
this.manifestURL = manifestURL; this.manifestURL = manifestURL;
deferred.resolve(manifest); resolve(manifest);
}, () => { }, () => {
this.error(error); this.error(error);
deferred.resolve(null); resolve(null);
}); });
}); });
});
return deferred.promise;
}; };
AppValidator.prototype._getManifest = function () { AppValidator.prototype._getManifest = function () {
@ -163,18 +157,18 @@ AppValidator.prototype._getManifest = function () {
if (this.type == "packaged") { if (this.type == "packaged") {
manifestURL = this._getPackagedManifestURL(); manifestURL = this._getPackagedManifestURL();
if (!manifestURL) if (!manifestURL)
return promise.resolve(null); return Promise.resolve(null);
} else if (this.type == "hosted") { } else if (this.type == "hosted") {
manifestURL = this.location; manifestURL = this.location;
try { try {
Services.io.newURI(manifestURL); Services.io.newURI(manifestURL);
} catch (e) { } catch (e) {
this.error(strings.formatStringFromName("validator.invalidHostedManifestURL", [manifestURL, e.message], 2)); this.error(strings.formatStringFromName("validator.invalidHostedManifestURL", [manifestURL, e.message], 2));
return promise.resolve(null); return Promise.resolve(null);
} }
} else { } else {
this.error(strings.formatStringFromName("validator.invalidProjectType", [this.type], 1)); this.error(strings.formatStringFromName("validator.invalidProjectType", [this.type], 1));
return promise.resolve(null); return Promise.resolve(null);
} }
return this._fetchManifest(manifestURL); return this._fetchManifest(manifestURL);
}; };
@ -201,57 +195,53 @@ AppValidator.prototype._getOriginURL = function () {
}; };
AppValidator.prototype.validateLaunchPath = function (manifest) { AppValidator.prototype.validateLaunchPath = function (manifest) {
let deferred = promise.defer(); return new Promise(resolve => {
// The launch_path field has to start with a `/` // The launch_path field has to start with a `/`
if (manifest.launch_path && manifest.launch_path[0] !== "/") { if (manifest.launch_path && manifest.launch_path[0] !== "/") {
this.error(strings.formatStringFromName("validator.nonAbsoluteLaunchPath", [manifest.launch_path], 1)); this.error(strings.formatStringFromName("validator.nonAbsoluteLaunchPath", [manifest.launch_path], 1));
deferred.resolve(); resolve();
return deferred.promise; }
} let origin = this._getOriginURL();
let origin = this._getOriginURL(); let path;
let path; if (this.type == "packaged") {
if (this.type == "packaged") { path = "." + (manifest.launch_path || "/index.html");
path = "." + (manifest.launch_path || "/index.html"); } else if (this.type == "hosted") {
} else if (this.type == "hosted") { path = manifest.launch_path || "/";
path = manifest.launch_path || "/"; }
} let indexURL;
let indexURL; try {
try { indexURL = Services.io.newURI(path, null, Services.io.newURI(origin)).spec;
indexURL = Services.io.newURI(path, null, Services.io.newURI(origin)).spec; } catch (e) {
} catch (e) { this.error(strings.formatStringFromName("validator.accessFailedLaunchPath", [origin + path], 1));
this.error(strings.formatStringFromName("validator.accessFailedLaunchPath", [origin + path], 1)); return resolve();
deferred.resolve(); }
return deferred.promise;
}
let req = new XMLHttpRequest(); let req = new XMLHttpRequest();
req.overrideMimeType("text/plain"); req.overrideMimeType("text/plain");
try { try {
req.open("HEAD", indexURL, true); req.open("HEAD", indexURL, true);
req.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_CACHING; req.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_CACHING;
} catch (e) { } catch (e) {
this.error(strings.formatStringFromName("validator.accessFailedLaunchPath", [indexURL], 1)); this.error(strings.formatStringFromName("validator.accessFailedLaunchPath", [indexURL], 1));
deferred.resolve(); return resolve();
return deferred.promise; }
} req.onload = () => {
req.onload = () => { if (req.status >= 400)
if (req.status >= 400) this.error(strings.formatStringFromName("validator.accessFailedLaunchPathBadHttpCode", [indexURL, req.status], 2));
this.error(strings.formatStringFromName("validator.accessFailedLaunchPathBadHttpCode", [indexURL, req.status], 2)); resolve();
deferred.resolve(); };
}; req.onerror = () => {
req.onerror = () => { this.error(strings.formatStringFromName("validator.accessFailedLaunchPath", [indexURL], 1));
this.error(strings.formatStringFromName("validator.accessFailedLaunchPath", [indexURL], 1)); resolve();
deferred.resolve(); };
};
try { try {
req.send(null); req.send(null);
} catch (e) { } catch (e) {
this.error(strings.formatStringFromName("validator.accessFailedLaunchPath", [indexURL], 1)); this.error(strings.formatStringFromName("validator.accessFailedLaunchPath", [indexURL], 1));
deferred.resolve(); resolve();
} }
});
return deferred.promise;
}; };
AppValidator.prototype.validateType = function (manifest) { AppValidator.prototype.validateType = function (manifest) {
@ -279,7 +269,7 @@ AppValidator.prototype.validate = function () {
// Skip validations for add-ons // Skip validations for add-ons
if (manifest.role === "addon" || manifest.manifest_version) { if (manifest.role === "addon" || manifest.manifest_version) {
return promise.resolve(); return Promise.resolve();
} }
this.validateManifest(manifest); this.validateManifest(manifest);

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

@ -4,7 +4,6 @@
const {Cu, Cc, Ci} = require("chrome"); const {Cu, Cc, Ci} = require("chrome");
const promise = require("promise");
const { Task } = require("devtools/shared/task"); const { Task } = require("devtools/shared/task");
const { OS } = Cu.import("resource://gre/modules/osfile.jsm", {}); const { OS } = Cu.import("resource://gre/modules/osfile.jsm", {});
const Subprocess = require("sdk/system/child_process/subprocess"); const Subprocess = require("sdk/system/child_process/subprocess");
@ -149,31 +148,30 @@ const ProjectBuilding = exports.ProjectBuilding = {
// Subprocess changes CWD, we have to save and restore it. // Subprocess changes CWD, we have to save and restore it.
let originalCwd = yield OS.File.getCurrentDirectory(); let originalCwd = yield OS.File.getCurrentDirectory();
try { try {
let defer = promise.defer(); yield new Promise((resolve, reject) => {
Subprocess.call({ Subprocess.call({
command: shell, command: shell,
arguments: args, arguments: args,
environment: env, environment: env,
workdir: cwd, workdir: cwd,
stdout: data => stdout: data =>
logger(data), logger(data),
stderr: data => stderr: data =>
logger(data), logger(data),
done: result => { done: result => {
logger("Terminated with error code: " + result.exitCode); logger("Terminated with error code: " + result.exitCode);
if (result.exitCode == 0) { if (result.exitCode == 0) {
defer.resolve(); resolve();
} else { } else {
defer.reject("pre-package command failed with error code " + result.exitCode); reject("pre-package command failed with error code " + result.exitCode);
}
} }
} });
}); }).then(() => {
defer.promise.then(() => {
OS.File.setCurrentDirectory(originalCwd); OS.File.setCurrentDirectory(originalCwd);
}); });
yield defer.promise;
} catch (e) { } catch (e) {
throw new Error("Unable to run pre-package command '" + command + "' " + throw new Error("Unable to run pre-package command '" + command + "' " +
args.join(" ") + ":\n" + (e.message || e)); args.join(" ") + ":\n" + (e.message || e));

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

@ -7,7 +7,6 @@ const {Cu} = require("chrome");
const Services = require("Services"); const Services = require("Services");
const {AppProjects} = require("devtools/client/webide/modules/app-projects"); const {AppProjects} = require("devtools/client/webide/modules/app-projects");
const {AppManager} = require("devtools/client/webide/modules/app-manager"); const {AppManager} = require("devtools/client/webide/modules/app-manager");
const promise = require("promise");
const EventEmitter = require("devtools/shared/event-emitter"); const EventEmitter = require("devtools/shared/event-emitter");
const {Task} = require("devtools/shared/task"); const {Task} = require("devtools/shared/task");
const utils = require("devtools/client/webide/modules/utils"); const utils = require("devtools/client/webide/modules/utils");
@ -200,7 +199,7 @@ ProjectList.prototype = {
}, true); }, true);
} }
return promise.resolve(); return Promise.resolve();
}, },
updateApps: function () { updateApps: function () {
@ -263,7 +262,7 @@ ProjectList.prototype = {
}, true); }, true);
} }
return promise.resolve(); return Promise.resolve();
}, },
updateCommands: function () { updateCommands: function () {
@ -299,69 +298,67 @@ ProjectList.prototype = {
* what is updated to only those sections. * what is updated to only those sections.
*/ */
update: function (options) { update: function (options) {
let deferred = promise.defer();
if (options && options.type === "apps") { if (options && options.type === "apps") {
return this.updateApps(); return this.updateApps();
} else if (options && options.type === "tabs") { } else if (options && options.type === "tabs") {
return this.updateTabs(); return this.updateTabs();
} }
let doc = this._doc; return new Promise((resolve, reject) => {
let projectsNode = doc.querySelector("#project-panel-projects"); let doc = this._doc;
let projectsNode = doc.querySelector("#project-panel-projects");
while (projectsNode.hasChildNodes()) { while (projectsNode.hasChildNodes()) {
projectsNode.firstChild.remove(); projectsNode.firstChild.remove();
}
AppProjects.load().then(() => {
let projects = AppProjects.projects;
for (let i = 0; i < projects.length; i++) {
let project = projects[i];
let panelItemNode = doc.createElement(this._panelNodeEl);
panelItemNode.className = "panel-item";
projectsNode.appendChild(panelItemNode);
if (!project.validationStatus) {
// The result of the validation process (storing names, icons, …) is not stored in
// the IndexedDB database when App Manager v1 is used.
// We need to run the validation again and update the name and icon of the app.
AppManager.validateAndUpdateProject(project).then(() => {
this._renderProjectItem({
panel: panelItemNode,
name: project.name,
icon: project.icon
});
});
} else {
this._renderProjectItem({
panel: panelItemNode,
name: project.name || AppManager.DEFAULT_PROJECT_NAME,
icon: project.icon || AppManager.DEFAULT_PROJECT_ICON
});
}
panelItemNode.addEventListener("click", () => {
AppManager.selectedProject = project;
}, true);
} }
deferred.resolve(); AppProjects.load().then(() => {
}, deferred.reject); let projects = AppProjects.projects;
for (let i = 0; i < projects.length; i++) {
let project = projects[i];
let panelItemNode = doc.createElement(this._panelNodeEl);
panelItemNode.className = "panel-item";
projectsNode.appendChild(panelItemNode);
if (!project.validationStatus) {
// The result of the validation process (storing names, icons, …) is not stored in
// the IndexedDB database when App Manager v1 is used.
// We need to run the validation again and update the name and icon of the app.
AppManager.validateAndUpdateProject(project).then(() => {
this._renderProjectItem({
panel: panelItemNode,
name: project.name,
icon: project.icon
});
});
} else {
this._renderProjectItem({
panel: panelItemNode,
name: project.name || AppManager.DEFAULT_PROJECT_NAME,
icon: project.icon || AppManager.DEFAULT_PROJECT_ICON
});
}
panelItemNode.addEventListener("click", () => {
AppManager.selectedProject = project;
}, true);
}
// List remote apps and the main process, if they exist resolve();
this.updateApps(); }, reject);
// Build the tab list right now, so it's fast... // List remote apps and the main process, if they exist
this.updateTabs(); this.updateApps();
// But re-list them and rebuild, in case any tabs navigated since the last // Build the tab list right now, so it's fast...
// time they were listed. this.updateTabs();
if (AppManager.connected) {
AppManager.listTabs().then(() => {
this.updateTabs();
}).catch(console.error);
}
return deferred.promise; // But re-list them and rebuild, in case any tabs navigated since the last
// time they were listed.
if (AppManager.connected) {
AppManager.listTabs().then(() => {
this.updateTabs();
}).catch(console.error);
}
});
}, },
destroy: function () { destroy: function () {

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

@ -9,7 +9,6 @@ const { Cc, Ci, Cu } = require("chrome");
const Environment = require("sdk/system/environment").env; const Environment = require("sdk/system/environment").env;
const EventEmitter = require("devtools/shared/event-emitter"); const EventEmitter = require("devtools/shared/event-emitter");
const promise = require("promise");
const Subprocess = require("sdk/system/child_process/subprocess"); const Subprocess = require("sdk/system/child_process/subprocess");
const Services = require("Services"); const Services = require("Services");
@ -104,21 +103,21 @@ SimulatorProcess.prototype = {
// Request a B2G instance kill. // Request a B2G instance kill.
kill() { kill() {
let deferred = promise.defer(); return new Promise(resolve => {
if (this.process) { if (this.process) {
this.once("exit", (e, exitCode) => { this.once("exit", (e, exitCode) => {
this.shuttingDown = false; this.shuttingDown = false;
deferred.resolve(exitCode); resolve(exitCode);
}); });
if (!this.shuttingDown) { if (!this.shuttingDown) {
this.shuttingDown = true; this.shuttingDown = true;
this.emit("kill", null); this.emit("kill", null);
this.process.kill(); this.process.kill();
}
} else {
return resolve(undefined);
} }
return deferred.promise; });
} else {
return promise.resolve(undefined);
}
}, },
// Maybe log output messages. // Maybe log output messages.

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

@ -12,7 +12,6 @@ loader.lazyRequireGetter(this, "OldAddonSimulatorProcess", "devtools/client/webi
loader.lazyRequireGetter(this, "CustomSimulatorProcess", "devtools/client/webide/modules/simulator-process", true); loader.lazyRequireGetter(this, "CustomSimulatorProcess", "devtools/client/webide/modules/simulator-process", true);
const asyncStorage = require("devtools/shared/async-storage"); const asyncStorage = require("devtools/shared/async-storage");
const EventEmitter = require("devtools/shared/event-emitter"); const EventEmitter = require("devtools/shared/event-emitter");
const promise = require("promise");
const Services = require("Services"); const Services = require("Services");
const SimulatorRegExp = new RegExp(Services.prefs.getCharPref("devtools.webide.simulatorAddonRegExp")); const SimulatorRegExp = new RegExp(Services.prefs.getCharPref("devtools.webide.simulatorAddonRegExp"));
@ -46,18 +45,19 @@ var Simulators = {
// If the simulator had a reference to an addon, fix it. // If the simulator had a reference to an addon, fix it.
if (options.addonID) { if (options.addonID) {
let deferred = promise.defer(); let deferred = new Promise(resolve => {
AddonManager.getAddonByID(options.addonID, addon => { AddonManager.getAddonByID(options.addonID, addon => {
simulator.addon = addon; simulator.addon = addon;
delete simulator.options.addonID; delete simulator.options.addonID;
deferred.resolve(); resolve();
});
}); });
jobs.push(deferred.promise); jobs.push(deferred);
} }
}); });
} }
yield promise.all(jobs); yield Promise.all(jobs);
yield Simulators._addUnusedAddons(); yield Simulators._addUnusedAddons();
Simulators.emitUpdated(); Simulators.emitUpdated();
return Simulators._simulators; return Simulators._simulators;
@ -79,7 +79,7 @@ var Simulators = {
jobs.push(Simulators.addIfUnusedAddon(addon, true)); jobs.push(Simulators.addIfUnusedAddon(addon, true));
}); });
yield promise.all(jobs); yield Promise.all(jobs);
}), }),
/** /**
@ -117,19 +117,19 @@ var Simulators = {
* @return Promised addon list. * @return Promised addon list.
*/ */
findSimulatorAddons() { findSimulatorAddons() {
let deferred = promise.defer(); return new Promise(resolve => {
AddonManager.getAllAddons(all => { AddonManager.getAllAddons(all => {
let addons = []; let addons = [];
for (let addon of all) { for (let addon of all) {
if (Simulators.isSimulatorAddon(addon)) { if (Simulators.isSimulatorAddon(addon)) {
addons.push(addon); addons.push(addon);
}
} }
} // Sort simulator addons by name.
// Sort simulator addons by name. addons.sort(LocaleCompare);
addons.sort(LocaleCompare); resolve(addons);
deferred.resolve(addons); });
}); });
return deferred.promise;
}, },
/** /**
@ -139,7 +139,7 @@ var Simulators = {
let simulators = this._simulators; let simulators = this._simulators;
let matching = simulators.filter(s => s.addon && s.addon.id == addon.id); let matching = simulators.filter(s => s.addon && s.addon.id == addon.id);
if (matching.length > 0) { if (matching.length > 0) {
return promise.resolve(); return Promise.resolve();
} }
let options = {}; let options = {};
options.name = addon.name.replace(" Simulator", ""); options.name = addon.name.replace(" Simulator", "");
@ -176,7 +176,7 @@ var Simulators = {
if (!silently) { if (!silently) {
this.emitUpdated(); this.emitUpdated();
} }
return promise.resolve(simulator); return Promise.resolve(simulator);
}, },
/** /**
@ -332,13 +332,13 @@ Simulator.prototype = {
} }
this.process.run(); this.process.run();
return promise.resolve(this.options.port); return Promise.resolve(this.options.port);
}, },
kill() { kill() {
let process = this.process; let process = this.process;
if (!process) { if (!process) {
return promise.resolve(); return Promise.resolve();
} }
this.process = null; this.process = null;
return process.kill(); return process.kill();

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

@ -7,7 +7,6 @@ const { Cu } = require("chrome");
const { TargetFactory } = require("devtools/client/framework/target"); const { TargetFactory } = require("devtools/client/framework/target");
const EventEmitter = require("devtools/shared/event-emitter"); const EventEmitter = require("devtools/shared/event-emitter");
const { Connection } = require("devtools/shared/client/connection-manager"); const { Connection } = require("devtools/shared/client/connection-manager");
const promise = require("promise");
const { Task } = require("devtools/shared/task"); const { Task } = require("devtools/shared/task");
const _knownTabStores = new WeakMap(); const _knownTabStores = new WeakMap();
@ -95,25 +94,26 @@ TabStore.prototype = {
listTabs: function () { listTabs: function () {
if (!this._connection || !this._connection.client) { if (!this._connection || !this._connection.client) {
return promise.reject(new Error("Can't listTabs, not connected.")); return Promise.reject(new Error("Can't listTabs, not connected."));
} }
let deferred = promise.defer();
this._connection.client.listTabs(response => { return new Promise((resolve, reject) => {
if (response.error) { this._connection.client.listTabs(response => {
this._connection.disconnect(); if (response.error) {
deferred.reject(response.error); this._connection.disconnect();
return; reject(response.error);
} return;
let tabsChanged = JSON.stringify(this.tabs) !== JSON.stringify(response.tabs); }
this.response = response; let tabsChanged = JSON.stringify(this.tabs) !== JSON.stringify(response.tabs);
this.tabs = response.tabs; this.response = response;
this._checkSelectedTab(); this.tabs = response.tabs;
if (tabsChanged) { this._checkSelectedTab();
this.emit("tab-list"); if (tabsChanged) {
} this.emit("tab-list");
deferred.resolve(response); }
resolve(response);
});
}); });
return deferred.promise;
}, },
// TODO: Tab "selection" should really take place by creating a TabProject // TODO: Tab "selection" should really take place by creating a TabProject

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

@ -64,12 +64,12 @@ function test() {
} }
function connectToLocal(win, docRuntime) { function connectToLocal(win, docRuntime) {
let deferred = promise.defer(); return new Promise(resolve => {
win.AppManager.connection.once( win.AppManager.connection.once(
win.Connection.Events.CONNECTED, win.Connection.Events.CONNECTED,
() => deferred.resolve()); resolve);
docRuntime.querySelectorAll(".runtime-panel-item-other")[1].click(); docRuntime.querySelectorAll(".runtime-panel-item-other")[1].click();
return deferred.promise; });
} }
function selectTabProject(win, docProject) { function selectTabProject(win, docProject) {

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

@ -8,7 +8,6 @@ var {utils: Cu, classes: Cc, interfaces: Ci} = Components;
const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {}); const { require } = Cu.import("resource://devtools/shared/Loader.jsm", {});
const { FileUtils } = require("resource://gre/modules/FileUtils.jsm"); const { FileUtils } = require("resource://gre/modules/FileUtils.jsm");
const { gDevTools } = require("devtools/client/framework/devtools"); const { gDevTools } = require("devtools/client/framework/devtools");
const promise = require("promise");
const Services = require("Services"); const Services = require("Services");
const { Task } = require("devtools/shared/task"); const { Task } = require("devtools/shared/task");
const { AppProjects } = require("devtools/client/webide/modules/app-projects"); const { AppProjects } = require("devtools/client/webide/modules/app-projects");
@ -71,18 +70,14 @@ var openWebIDE = Task.async(function* (autoInstallAddons) {
function closeWebIDE(win) { function closeWebIDE(win) {
info("Closing WebIDE"); info("Closing WebIDE");
let deferred = promise.defer(); return new Promise(resolve => {
win.addEventListener("unload", function () {
info("WebIDE closed");
SimpleTest.executeSoon(resolve);
}, {once: true});
win.addEventListener("unload", function () { win.close();
info("WebIDE closed"); });
SimpleTest.executeSoon(() => {
deferred.resolve();
});
}, {once: true});
win.close();
return deferred.promise;
} }
function removeAllProjects() { function removeAllProjects() {
@ -98,93 +93,87 @@ function removeAllProjects() {
} }
function nextTick() { function nextTick() {
let deferred = promise.defer(); return new Promise(resolve => {
SimpleTest.executeSoon(() => { SimpleTest.executeSoon(resolve);
deferred.resolve();
}); });
return deferred.promise;
} }
function waitForUpdate(win, update) { function waitForUpdate(win, update) {
info("Wait: " + update); info("Wait: " + update);
let deferred = promise.defer(); return new Promise(resolve => {
win.AppManager.on("app-manager-update", function onUpdate(e, what) { win.AppManager.on("app-manager-update", function onUpdate(e, what) {
info("Got: " + what); info("Got: " + what);
if (what !== update) { if (what !== update) {
return; return;
} }
win.AppManager.off("app-manager-update", onUpdate); win.AppManager.off("app-manager-update", onUpdate);
deferred.resolve(win.UI._updatePromise); resolve(win.UI._updatePromise);
});
}); });
return deferred.promise;
} }
function waitForTime(time) { function waitForTime(time) {
let deferred = promise.defer(); return new Promise(resolve => {
setTimeout(() => { setTimeout(resolve, time);
deferred.resolve(); });
}, time);
return deferred.promise;
} }
function documentIsLoaded(doc) { function documentIsLoaded(doc) {
let deferred = promise.defer(); return new Promise(resolve => {
if (doc.readyState == "complete") { if (doc.readyState == "complete") {
deferred.resolve(); resolve();
} else { } else {
doc.addEventListener("readystatechange", function onChange() { doc.addEventListener("readystatechange", function onChange() {
if (doc.readyState == "complete") { if (doc.readyState == "complete") {
doc.removeEventListener("readystatechange", onChange); doc.removeEventListener("readystatechange", onChange);
deferred.resolve(); resolve();
} }
}); });
} }
return deferred.promise; });
} }
function lazyIframeIsLoaded(iframe) { function lazyIframeIsLoaded(iframe) {
let deferred = promise.defer(); return new Promise(resolve => {
iframe.addEventListener("load", function () { iframe.addEventListener("load", function () {
deferred.resolve(nextTick()); resolve(nextTick());
}, {capture: true, once: true}); }, {capture: true, once: true});
return deferred.promise; });
} }
function addTab(aUrl, aWindow) { function addTab(aUrl, aWindow) {
info("Adding tab: " + aUrl); info("Adding tab: " + aUrl);
let deferred = promise.defer(); return new Promise(resolve => {
let targetWindow = aWindow || window; let targetWindow = aWindow || window;
let targetBrowser = targetWindow.gBrowser; let targetBrowser = targetWindow.gBrowser;
targetWindow.focus(); targetWindow.focus();
let tab = targetBrowser.selectedTab = targetBrowser.addTab(aUrl); let tab = targetBrowser.selectedTab = targetBrowser.addTab(aUrl);
let linkedBrowser = tab.linkedBrowser; let linkedBrowser = tab.linkedBrowser;
BrowserTestUtils.browserLoaded(linkedBrowser).then(function () { BrowserTestUtils.browserLoaded(linkedBrowser).then(function () {
info("Tab added and finished loading: " + aUrl); info("Tab added and finished loading: " + aUrl);
deferred.resolve(tab); resolve(tab);
});
}); });
return deferred.promise;
} }
function removeTab(aTab, aWindow) { function removeTab(aTab, aWindow) {
info("Removing tab."); info("Removing tab.");
let deferred = promise.defer(); return new Promise(resolve => {
let targetWindow = aWindow || window; let targetWindow = aWindow || window;
let targetBrowser = targetWindow.gBrowser; let targetBrowser = targetWindow.gBrowser;
let tabContainer = targetBrowser.tabContainer; let tabContainer = targetBrowser.tabContainer;
tabContainer.addEventListener("TabClose", function (aEvent) { tabContainer.addEventListener("TabClose", function (aEvent) {
info("Tab removed and finished closing."); info("Tab removed and finished closing.");
deferred.resolve(); resolve();
}, {once: true}); }, {once: true});
targetBrowser.removeTab(aTab); targetBrowser.removeTab(aTab);
return deferred.promise; });
} }
function getRuntimeDocument(win) { function getRuntimeDocument(win) {

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

@ -22,30 +22,26 @@
const {Devices} = Cu.import("resource://devtools/shared/apps/Devices.jsm"); const {Devices} = Cu.import("resource://devtools/shared/apps/Devices.jsm");
const {Simulators} = require("devtools/client/webide/modules/simulators"); const {Simulators} = require("devtools/client/webide/modules/simulators");
let adbAddonsInstalled = promise.defer(); let adbAddonsInstalled;
Devices.on("addon-status-updated", function onUpdate1() {
Devices.off("addon-status-updated", onUpdate1);
adbAddonsInstalled.resolve();
});
function getVersion(name) { function getVersion(name) {
return name.match(/(\d+\.\d+)/)[0]; return name.match(/(\d+\.\d+)/)[0];
} }
function onSimulatorInstalled(name) { function onSimulatorInstalled(name) {
let deferred = promise.defer(); return new Promise(resolve => {
Simulators.on("updated", function onUpdate() { Simulators.on("updated", function onUpdate() {
Simulators.findSimulatorAddons().then(addons => { Simulators.findSimulatorAddons().then(addons => {
for (let addon of addons) { for (let addon of addons) {
if (name == addon.name.replace(" Simulator", "")) { if (name == addon.name.replace(" Simulator", "")) {
Simulators.off("updated", onUpdate); Simulators.off("updated", onUpdate);
nextTick().then(deferred.resolve); nextTick().then(resolve);
return; return;
}
} }
} });
}); });
}); });
return deferred.promise;
} }
function installSimulatorFromUI(doc, name) { function installSimulatorFromUI(doc, name) {
@ -55,39 +51,39 @@
} }
function uninstallSimulatorFromUI(doc, name) { function uninstallSimulatorFromUI(doc, name) {
let deferred = promise.defer(); return new Promise((resolve, reject) => {
Simulators.on("updated", function onUpdate() { Simulators.on("updated", function onUpdate() {
nextTick().then(() => { nextTick().then(() => {
let li = doc.querySelector('[status="uninstalled"][addon="simulator-' + getVersion(name) + '"]'); let li = doc.querySelector('[status="uninstalled"][addon="simulator-' + getVersion(name) + '"]');
if (li) { if (li) {
Simulators.off("updated", onUpdate); Simulators.off("updated", onUpdate);
deferred.resolve(); resolve();
} else { } else {
deferred.reject("Can't find item"); reject("Can't find item");
} }
});
}); });
let li = doc.querySelector('[status="installed"][addon="simulator-' + getVersion(name) + '"]');
li.querySelector(".uninstall-button").click();
}); });
let li = doc.querySelector('[status="installed"][addon="simulator-' + getVersion(name) + '"]');
li.querySelector(".uninstall-button").click();
return deferred.promise;
} }
function uninstallADBFromUI(doc) { function uninstallADBFromUI(doc) {
let deferred = promise.defer(); return new Promise((resolve, reject) => {
Devices.on("addon-status-updated", function onUpdate() { Devices.on("addon-status-updated", function onUpdate() {
nextTick().then(() => { nextTick().then(() => {
let li = doc.querySelector('[status="uninstalled"][addon="adb"]'); let li = doc.querySelector('[status="uninstalled"][addon="adb"]');
if (li) { if (li) {
Devices.off("addon-status-updated", onUpdate); Devices.off("addon-status-updated", onUpdate);
deferred.resolve(); resolve();
} else { } else {
deferred.reject("Can't find item"); reject("Can't find item");
} }
}) })
});
let li = doc.querySelector('[status="installed"][addon="adb"]');
li.querySelector(".uninstall-button").click();
}); });
let li = doc.querySelector('[status="installed"][addon="adb"]');
li.querySelector(".uninstall-button").click();
return deferred.promise;
} }
Task.spawn(function*() { Task.spawn(function*() {
@ -97,7 +93,12 @@
let win = yield openWebIDE(true); let win = yield openWebIDE(true);
let docRuntime = getRuntimeDocument(win); let docRuntime = getRuntimeDocument(win);
yield adbAddonsInstalled.promise; adbAddonsInstalled = new Promise(resolve => {
Devices.on("addon-status-updated", function onUpdate1() {
Devices.off("addon-status-updated", onUpdate1);
resolve();
});
});
ok(Devices.helperAddonInstalled, "Helper has been auto-installed"); ok(Devices.helperAddonInstalled, "Helper has been auto-installed");

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

@ -33,7 +33,7 @@
is(connection, win.AppManager.connection, "connection is valid"); is(connection, win.AppManager.connection, "connection is valid");
connection.host = null; // force connectPipe connection.host = null; // force connectPipe
connection.connect(); connection.connect();
return promise.resolve(); return Promise.resolve();
}, },
get id() { get id() {

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

@ -35,12 +35,13 @@
let nbox = win.document.querySelector("#notificationbox"); let nbox = win.document.querySelector("#notificationbox");
let notification = nbox.getNotificationWithValue("webide:errornotification"); let notification = nbox.getNotificationWithValue("webide:errornotification");
ok(!notification, "No notification yet"); ok(!notification, "No notification yet");
let deferred = promise.defer(); let deferred = new Promise((resolve, reject) => {
nextTick().then(() => { nextTick().then(() => {
deferred.reject("BOOM!"); reject("BOOM!");
});
}); });
try { try {
yield win.UI.busyUntil(deferred.promise, "xx"); yield win.UI.busyUntil(deferred, "xx");
} catch(e) {/* This *will* fail */} } catch(e) {/* This *will* fail */}
notification = nbox.getNotificationWithValue("webide:errornotification"); notification = nbox.getNotificationWithValue("webide:errornotification");
ok(notification, "Error has been reported"); ok(notification, "Error has been reported");

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

@ -16,12 +16,12 @@
<script type="application/javascript"> <script type="application/javascript">
function connectToLocal(win, docRuntime) { function connectToLocal(win, docRuntime) {
let deferred = promise.defer(); return new Promise(resolve => {
win.AppManager.connection.once( win.AppManager.connection.once(
win.Connection.Events.CONNECTED, win.Connection.Events.CONNECTED,
() => deferred.resolve()); resolve);
docRuntime.querySelectorAll(".runtime-panel-item-other")[1].click(); docRuntime.querySelectorAll(".runtime-panel-item-other")[1].click();
return deferred.promise; });
} }
window.onload = function() { window.onload = function() {
@ -33,7 +33,7 @@
let docRuntime = getRuntimeDocument(win); let docRuntime = getRuntimeDocument(win);
win.AppManager.update("runtime-list"); win.AppManager.update("runtime-list");
yield connectToLocal(win, docRuntime); connectToLocal(win, docRuntime);
// Select main process // Select main process
yield waitForUpdate(win, "runtime-targets"); yield waitForUpdate(win, "runtime-targets");

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

@ -62,7 +62,7 @@
is(connection, win.AppManager.connection, "connection is valid"); is(connection, win.AppManager.connection, "connection is valid");
connection.host = null; // force connectPipe connection.host = null; // force connectPipe
connection.connect(); connection.connect();
return promise.resolve(); return Promise.resolve();
}, },
get name() { get name() {
@ -72,8 +72,7 @@
win.AppManager.runtimeList.usb.push({ win.AppManager.runtimeList.usb.push({
connect: function(connection) { connect: function(connection) {
let deferred = promise.defer(); return new Promise(() => {});
return deferred.promise;
}, },
get name() { get name() {
@ -83,8 +82,7 @@
win.AppManager.runtimeList.usb.push({ win.AppManager.runtimeList.usb.push({
connect: function(connection) { connect: function(connection) {
let deferred = promise.defer(); return new Promise(() => {});
return deferred.promise;
}, },
prolongedConnection: true, prolongedConnection: true,
@ -164,36 +162,35 @@
Services.prefs.setIntPref("devtools.webide.busyTimeout", 100); Services.prefs.setIntPref("devtools.webide.busyTimeout", 100);
// Wait for error message since connection never completes
let errorDeferred = promise.defer();
win.UI.reportError = errorName => {
if (errorName === "error_operationTimeout") {
errorDeferred.resolve();
}
};
// Click the infinite runtime // Click the infinite runtime
items[1].click(); items[1].click();
ok(win.document.querySelector("window").className, "busy", "UI is busy"); ok(win.document.querySelector("window").className, "busy", "UI is busy");
yield errorDeferred.promise;
// Check for unexpected error message since this is prolonged // Wait for error message since connection never completes
let noErrorDeferred = promise.defer(); let errorDeferred = new Promise(resolve => {
win.UI.reportError = errorName => { win.UI.reportError = errorName => {
if (errorName === "error_operationTimeout") { if (errorName === "error_operationTimeout") {
noErrorDeferred.reject(); resolve();
} }
}; };
});
// Click the prolonged runtime // Click the prolonged runtime
items[2].click(); items[2].click();
ok(win.document.querySelector("window").className, "busy", "UI is busy"); ok(win.document.querySelector("window").className, "busy", "UI is busy");
setTimeout(() => { // Check for unexpected error message since this is prolonged
noErrorDeferred.resolve(); let noErrorDeferred = new Promise((resolve, reject) => {
}, 1000); win.UI.reportError = errorName => {
if (errorName === "error_operationTimeout") {
reject();
}
};
yield noErrorDeferred.promise; setTimeout(() => {
resolve();
}, 1000);
});
SimpleTest.finish(); SimpleTest.finish();
}); });

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

@ -29,31 +29,31 @@
function addonStatus(addon, status) { function addonStatus(addon, status) {
if (addon.status == status) { if (addon.status == status) {
return promise.resolve(); return Promise.resolve();
} }
let deferred = promise.defer(); return new Promise(resolve => {
addon.on("update", function onUpdate() { addon.on("update", function onUpdate() {
if (addon.status == status) { if (addon.status == status) {
addon.off("update", onUpdate); addon.off("update", onUpdate);
nextTick().then(() => deferred.resolve()); nextTick().then(() => resolve());
} }
});
}); });
return deferred.promise;
} }
function waitForUpdate(length) { function waitForUpdate(length) {
info(`Wait for update with length ${length}`); info(`Wait for update with length ${length}`);
let deferred = promise.defer(); return new Promise(resolve => {
let handler = (_, data) => { let handler = (_, data) => {
if (data.length != length) { if (data.length != length) {
return; return;
} }
info(`Got update with length ${length}`); info(`Got update with length ${length}`);
Simulators.off("updated", handler); Simulators.off("updated", handler);
deferred.resolve(); resolve();
}; };
Simulators.on("updated", handler); Simulators.on("updated", handler);
return deferred.promise; });
} }
Task.spawn(function* () { Task.spawn(function* () {
@ -70,9 +70,9 @@
// Hack SimulatorProcesses to spy on simulation parameters. // Hack SimulatorProcesses to spy on simulation parameters.
let runPromise; let resolver;
function fakeRun() { function fakeRun() {
runPromise.resolve({ resolver({
path: this.b2gBinary.path, path: this.b2gBinary.path,
args: this.args args: this.args
}); });
@ -85,9 +85,10 @@
CustomSimulatorProcess.prototype.run = fakeRun; CustomSimulatorProcess.prototype.run = fakeRun;
function runSimulator(i) { function runSimulator(i) {
runPromise = promise.defer(); return new Promise(resolve => {
findAll(".runtime-panel-item-simulator")[i].click(); resolver = resolve;
return runPromise.promise; findAll(".runtime-panel-item-simulator")[i].click();
});
} }
// Install fake "Firefox OS 1.0" simulator addon. // Install fake "Firefox OS 1.0" simulator addon.

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

@ -42,10 +42,11 @@
win.AppManager.update("runtime-list"); win.AppManager.update("runtime-list");
let deferred = promise.defer(); let deferred = new Promise(resolve => {
win.AppManager.connection.once( win.AppManager.connection.once(
win.Connection.Events.CONNECTED, win.Connection.Events.CONNECTED,
() => deferred.resolve()); resolve);
});
docRuntime.querySelectorAll(".runtime-panel-item-other")[1].click(); docRuntime.querySelectorAll(".runtime-panel-item-other")[1].click();