--- a/toolkit/content/about.js
+++ b/toolkit/content/about.js
@@ -1,32 +1,31 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+var Cu = Components.utils;
+Cu.import("resource://gre/modules/Services.jsm");
+
// get release notes and vendor URL from prefs
-var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
- .getService(Components.interfaces.nsIURLFormatter);
-var releaseNotesURL = formatter.formatURLPref("app.releaseNotesURL");
+var releaseNotesURL = Services.urlFormatter.formatURLPref("app.releaseNotesURL");
if (releaseNotesURL != "about:blank") {
var relnotes = document.getElementById("releaseNotesURL");
relnotes.setAttribute("href", releaseNotesURL);
relnotes.parentNode.removeAttribute("hidden");
}
-var vendorURL = formatter.formatURLPref("app.vendorURL");
+var vendorURL = Services.urlFormatter.formatURLPref("app.vendorURL");
if (vendorURL != "about:blank") {
var vendor = document.getElementById("vendorURL");
vendor.setAttribute("href", vendorURL);
}
// insert the version of the XUL application (!= XULRunner platform version)
-var versionNum = Components.classes["@mozilla.org/xre/app-info;1"]
- .getService(Components.interfaces.nsIXULAppInfo)
- .version;
+var versionNum = Services.appinfo.version;
var version = document.getElementById("version");
version.textContent += " " + versionNum;
// append user agent
var ua = navigator.userAgent;
if (ua) {
document.getElementById("buildID").textContent += " " + ua;
}
--- a/toolkit/content/aboutAbout.js
+++ b/toolkit/content/aboutAbout.js
@@ -1,31 +1,33 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var Cc = Components.classes;
var Ci = Components.interfaces;
+var Cu = Components.utils;
+Cu.import("resource://gre/modules/Services.jsm");
+
var gProtocols = [];
var gContainer;
window.onload = function() {
gContainer = document.getElementById("abouts");
findAbouts();
};
function findAbouts() {
- var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
for (var cid in Cc) {
var result = cid.match(/@mozilla.org\/network\/protocol\/about;1\?what\=(.*)$/);
if (result) {
var aboutType = result[1];
var contract = "@mozilla.org/network/protocol/about;1?what=" + aboutType;
try {
var am = Cc[contract].getService(Ci.nsIAboutModule);
- var uri = ios.newURI("about:" + aboutType);
+ var uri = Services.io.newURI("about:" + aboutType);
var flags = am.getURIFlags(uri);
if (!(flags & Ci.nsIAboutModule.HIDE_FROM_ABOUTABOUT)) {
gProtocols.push(aboutType);
}
} catch (e) {
// getService might have thrown if the component doesn't actually
// implement nsIAboutModule
}
--- a/toolkit/content/aboutProfiles.js
+++ b/toolkit/content/aboutProfiles.js
@@ -22,19 +22,17 @@ const bundle = Services.strings.createBu
// nsIToolkitProfileService.selectProfile can be used only during the selection
// of the profile in the ProfileManager. If we are showing about:profiles in a
// tab, the selectedProfile returns the default profile.
// In this function we use the ProfD to find the current profile.
function findCurrentProfile() {
let cpd;
try {
- cpd = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("ProfD", Ci.nsIFile);
+ cpd = Services.dirsvc.get("ProfD", Ci.nsIFile);
} catch (e) {}
if (cpd) {
let itr = ProfileService.profiles;
while (itr.hasMoreElements()) {
let profile = itr.getNext().QueryInterface(Ci.nsIToolkitProfile);
if (profile.rootDir.path == cpd.path) {
return profile;
--- a/toolkit/content/aboutSupport.js
+++ b/toolkit/content/aboutSupport.js
@@ -896,19 +896,17 @@ function copyRawDataToClipboard(button)
let str = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
str.data = JSON.stringify(snapshot, undefined, 2);
let transferable = Cc["@mozilla.org/widget/transferable;1"].
createInstance(Ci.nsITransferable);
transferable.init(getLoadContext());
transferable.addDataFlavor("text/unicode");
transferable.setTransferData("text/unicode", str, str.data.length * 2);
- Cc["@mozilla.org/widget/clipboard;1"].
- getService(Ci.nsIClipboard).
- setData(transferable, null, Ci.nsIClipboard.kGlobalClipboard);
+ Services.clipboard.setData(transferable, null, Ci.nsIClipboard.kGlobalClipboard);
if (AppConstants.platform == "android") {
// Present a toast notification.
let message = {
type: "Toast:Show",
message: stringBundle().GetStringFromName("rawDataCopied"),
duration: "short"
};
Services.androidBridge.handleGeckoMessage(message);
@@ -948,19 +946,17 @@ function copyContentsToClipboard() {
transferable.setTransferData("text/html", ssHtml, dataHtml.length * 2);
// Add the plain text flavor.
transferable.addDataFlavor("text/unicode");
ssText.data = dataText;
transferable.setTransferData("text/unicode", ssText, dataText.length * 2);
// Store the data into the clipboard.
- let clipboard = Cc["@mozilla.org/widget/clipboard;1"]
- .getService(Ci.nsIClipboard);
- clipboard.setData(transferable, null, clipboard.kGlobalClipboard);
+ Services.clipboard.setData(transferable, null, Services.clipboard.kGlobalClipboard);
if (AppConstants.platform == "android") {
// Present a toast notification.
let message = {
type: "Toast:Show",
message: stringBundle().GetStringFromName("textCopied"),
duration: "short"
};
--- a/toolkit/content/globalOverlay.js
+++ b/toolkit/content/globalOverlay.js
@@ -3,19 +3,17 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function closeWindow(aClose, aPromptFunction) {
let { AppConstants } = Components.utils.import("resource://gre/modules/AppConstants.jsm", {});
// Closing the last window doesn't quit the application on OS X.
if (AppConstants.platform != "macosx") {
var windowCount = 0;
- var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
- .getService(Components.interfaces.nsIWindowMediator);
- var e = wm.getEnumerator(null);
+ var e = Services.wm.getEnumerator(null);
while (e.hasMoreElements()) {
var w = e.getNext();
if (w.closed) {
continue;
}
if (++windowCount == 2)
break;
@@ -34,40 +32,33 @@ function closeWindow(aClose, aPromptFunc
window.close();
return window.closed;
}
return true;
}
function canQuitApplication(aData) {
- var os = Components.classes["@mozilla.org/observer-service;1"]
- .getService(Components.interfaces.nsIObserverService);
- if (!os) return true;
-
try {
var cancelQuit = Components.classes["@mozilla.org/supports-PRBool;1"]
.createInstance(Components.interfaces.nsISupportsPRBool);
- os.notifyObservers(cancelQuit, "quit-application-requested", aData || null);
+ Services.obs.notifyObservers(cancelQuit, "quit-application-requested", aData || null);
// Something aborted the quit process.
if (cancelQuit.data)
return false;
} catch (ex) { }
return true;
}
function goQuitApplication() {
if (!canQuitApplication())
return false;
- var appStartup = Components.classes["@mozilla.org/toolkit/app-startup;1"].
- getService(Components.interfaces.nsIAppStartup);
-
- appStartup.quit(Components.interfaces.nsIAppStartup.eAttemptQuit);
+ Services.startup.quit(Components.interfaces.nsIAppStartup.eAttemptQuit);
return true;
}
//
// Command Updater functions
//
function goUpdateCommand(aCommand) {
try {
--- a/toolkit/content/plugins.html
+++ b/toolkit/content/plugins.html
@@ -7,16 +7,19 @@
<html>
<head>
<script type="application/javascript">
"use strict";
Components.utils.import("resource://gre/modules/Services.jsm");
var Ci = Components.interfaces;
+ // XXX Bug 1418959 - For some reason, using Services.strings here causes
+ // about:plugins to leak when running browser_aboutURLs.js.
+ // eslint-disable-next-line mozilla/use-services
var strBundleService = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
var pluginsbundle = strBundleService.createBundle("chrome://global/locale/plugins.properties");
// eslint-disable-next-line no-unsanitized/method
document.writeln("<title>" + pluginsbundle.GetStringFromName("title_label") + "<\/title>");
</script>
<link rel="stylesheet" type="text/css" href="chrome://global/content/plugins.css">
<link rel="stylesheet" type="text/css" href="chrome://global/skin/plugins.css">
--- a/toolkit/content/tests/browser/browser_save_resend_postdata.js
+++ b/toolkit/content/tests/browser/browser_save_resend_postdata.js
@@ -93,25 +93,21 @@ function test() {
isnot(fileContents.indexOf("inputfield=inner"), -1,
"The saved inner frame was generated using the correct POST data");
finish();
}
}
/* import-globals-from common/mockTransfer.js */
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
+Services.scriptloader.loadSubScript("chrome://mochitests/content/browser/toolkit/content/tests/browser/common/mockTransfer.js",
this);
function createTemporarySaveDirectory() {
- var saveDir = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("TmpD", Ci.nsIFile);
+ var saveDir = Services.dirsvc.get("TmpD", Ci.nsIFile);
saveDir.append("testsavedir");
if (!saveDir.exists())
saveDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
return saveDir;
}
/**
* Reads the contents of the provided short file (up to 1 MiB).
--- a/toolkit/content/tests/browser/common/mockTransfer.js
+++ b/toolkit/content/tests/browser/common/mockTransfer.js
@@ -1,15 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://mochikit/content/tests/SimpleTest/MockObjects.js", this);
+Services.scriptloader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/MockObjects.js", this);
var mockTransferCallback;
/**
* This "transfer" object implementation continues the currently running test
* when the download is completed, reporting true for success or false for
* failure as the first argument of the testRunner.continueTest function.
*/
--- a/toolkit/content/tests/chrome/RegisterUnregisterChrome.js
+++ b/toolkit/content/tests/chrome/RegisterUnregisterChrome.js
@@ -1,40 +1,37 @@
/* This code is mostly copied from chrome/test/unit/head_crtestutils.js */
const NS_CHROME_MANIFESTS_FILE_LIST = "ChromeML";
const XUL_CACHE_PREF = "nglayout.debug.disable_xul_cache";
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cr = Components.results;
+var Cu = Components.utils;
-var gDirSvc = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIDirectoryService).QueryInterface(Ci.nsIProperties);
+Cu.import("resource://gre/modules/Services.jsm");
+
var gChromeReg = Cc["@mozilla.org/chrome/chrome-registry;1"].
getService(Ci.nsIXULChromeRegistry);
-var gPrefs = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
// Create the temporary file in the profile, instead of in TmpD, because
// we know the mochitest harness kills off the profile when it's done.
function copyToTemporaryFile(f) {
- let tmpd = gDirSvc.get("ProfD", Ci.nsIFile);
+ let tmpd = Services.dirsvc.get("ProfD", Ci.nsIFile);
let tmpf = tmpd.clone();
tmpf.append("temp.manifest");
tmpf.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
tmpf.remove(false);
f.copyTo(tmpd, tmpf.leafName);
return tmpf;
}
function* dirIter(directory) {
- var ioSvc = Cc["@mozilla.org/network/io-service;1"].
- getService(Ci.nsIIOService);
- var testsDir = ioSvc.newURI(directory)
+ var testsDir = Services.io.newURI(directory)
.QueryInterface(Ci.nsIFileURL).file;
let en = testsDir.directoryEntries;
while (en.hasMoreElements()) {
let file = en.getNext();
yield file.QueryInterface(Ci.nsIFile);
}
}
@@ -52,17 +49,17 @@ function getParent(path) {
}
function copyDirToTempProfile(path, subdirname) {
if (subdirname === undefined) {
subdirname = "mochikit-tmp";
}
- let tmpdir = gDirSvc.get("ProfD", Ci.nsIFile);
+ let tmpdir = Services.dirsvc.get("ProfD", Ci.nsIFile);
tmpdir.append(subdirname);
tmpdir.createUnique(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0o777);
let rootDir = getParent(path);
if (rootDir == "") {
return tmpdir;
}
@@ -71,18 +68,17 @@ function copyDirToTempProfile(path, subd
for (let f in files) {
files[f].copyTo(tmpdir, "");
}
return tmpdir;
}
function convertChromeURI(chromeURI) {
- let uri = Cc["@mozilla.org/network/io-service;1"].
- getService(Ci.nsIIOService).newURI(chromeURI);
+ let uri = Services.io.newURI(chromeURI);
return gChromeReg.convertChromeURL(uri);
}
function chromeURIToFile(chromeURI) {
var jar = getJar(chromeURI);
if (jar) {
var tmpDir = extractJarToTmp(jar);
let parts = chromeURI.split("/");
@@ -94,17 +90,17 @@ function chromeURIToFile(chromeURI) {
return convertChromeURI(chromeURI).
QueryInterface(Ci.nsIFileURL).file;
}
// Register a chrome manifest temporarily and return a function which un-does
// the registrarion when no longer needed.
function createManifestTemporarily(tempDir, manifestText) {
- gPrefs.setBoolPref(XUL_CACHE_PREF, true);
+ Services.prefs.setBoolPref(XUL_CACHE_PREF, true);
tempDir.append("temp.manifest");
let foStream = Cc["@mozilla.org/network/file-output-stream;1"]
.createInstance(Ci.nsIFileOutputStream);
foStream.init(tempDir,
0x02 | 0x08 | 0x20, 0o664, 0); // write, create, truncate
foStream.write(manifestText, manifestText.length);
@@ -115,38 +111,38 @@ function createManifestTemporarily(tempD
autoRegister(tempfile);
gChromeReg.refreshSkins();
return function() {
tempfile.fileSize = 0; // truncate the manifest
gChromeReg.checkForNewChrome();
gChromeReg.refreshSkins();
- gPrefs.clearUserPref(XUL_CACHE_PREF);
+ Services.prefs.clearUserPref(XUL_CACHE_PREF);
};
}
// Register a chrome manifest temporarily and return a function which un-does
// the registrarion when no longer needed.
function registerManifestTemporarily(manifestURI) {
- gPrefs.setBoolPref(XUL_CACHE_PREF, true);
+ Services.prefs.setBoolPref(XUL_CACHE_PREF, true);
let file = chromeURIToFile(manifestURI);
let tempfile = copyToTemporaryFile(file);
Components.manager.QueryInterface(Ci.nsIComponentRegistrar).
autoRegister(tempfile);
gChromeReg.refreshSkins();
return function() {
tempfile.fileSize = 0; // truncate the manifest
gChromeReg.checkForNewChrome();
gChromeReg.refreshSkins();
- gPrefs.clearUserPref(XUL_CACHE_PREF);
+ Services.prefs.clearUserPref(XUL_CACHE_PREF);
};
}
function registerManifestPermanently(manifestURI) {
var chromepath = chromeURIToFile(manifestURI);
Components.manager.QueryInterface(Ci.nsIComponentRegistrar).
autoRegister(chromepath);
--- a/toolkit/content/tests/unit/test_contentAreaUtils.js
+++ b/toolkit/content/tests/unit/test_contentAreaUtils.js
@@ -1,22 +1,23 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cr = Components.results;
+var Cu = Components.utils;
+
+Cu.import("resource://gre/modules/Services.jsm");
function loadUtilsScript() {
- var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
- getService(Ci.mozIJSSubScriptLoader);
/* import-globals-from ../../contentAreaUtils.js */
- loader.loadSubScript("chrome://global/content/contentAreaUtils.js");
+ Services.scriptloader.loadSubScript("chrome://global/content/contentAreaUtils.js");
}
function test_urlSecurityCheck() {
var nullPrincipal = Cc["@mozilla.org/nullprincipal;1"].
createInstance(Ci.nsIPrincipal);
const HTTP_URI = "http://www.mozilla.org/";
const CHROME_URI = "chrome://browser/content/browser.xul";
--- a/toolkit/content/viewZoomOverlay.js
+++ b/toolkit/content/viewZoomOverlay.js
@@ -5,39 +5,37 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Document Zoom Management Code
*
* To use this, you'll need to have a getBrowser() function or use the methods
* that accept a browser to be modified.
**/
+var Cu = Components.utils;
+
+Cu.import("resource://gre/modules/Services.jsm");
+
var ZoomManager = {
- get _prefBranch() {
- delete this._prefBranch;
- return this._prefBranch = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefBranch);
- },
-
get MIN() {
delete this.MIN;
- return this.MIN = this._prefBranch.getIntPref("zoom.minPercent") / 100;
+ return this.MIN = Services.prefs.getIntPref("zoom.minPercent") / 100;
},
get MAX() {
delete this.MAX;
- return this.MAX = this._prefBranch.getIntPref("zoom.maxPercent") / 100;
+ return this.MAX = Services.prefs.getIntPref("zoom.maxPercent") / 100;
},
get useFullZoom() {
- return this._prefBranch.getBoolPref("browser.zoom.full");
+ return Services.prefs.getBoolPref("browser.zoom.full");
},
set useFullZoom(aVal) {
- this._prefBranch.setBoolPref("browser.zoom.full", aVal);
+ Services.prefs.setBoolPref("browser.zoom.full", aVal);
return aVal;
},
get zoom() {
return this.getZoomForBrowser(getBrowser());
},
getZoomForBrowser: function ZoomManager_getZoomForBrowser(aBrowser) {
@@ -61,18 +59,18 @@ var ZoomManager = {
aBrowser.fullZoom = aVal;
} else {
aBrowser.textZoom = aVal;
aBrowser.fullZoom = 1;
}
},
get zoomValues() {
- var zoomValues = this._prefBranch.getCharPref("toolkit.zoomManager.zoomValues")
- .split(",").map(parseFloat);
+ var zoomValues = Services.prefs.getCharPref("toolkit.zoomManager.zoomValues")
+ .split(",").map(parseFloat);
zoomValues.sort((a, b) => a - b);
while (zoomValues[0] < this.MIN)
zoomValues.shift();
while (zoomValues[zoomValues.length - 1] > this.MAX)
zoomValues.pop();
--- a/toolkit/crashreporter/CrashSubmit.jsm
+++ b/toolkit/crashreporter/CrashSubmit.jsm
@@ -39,19 +39,17 @@ function parseINIStrings(path) {
obj[key] = parser.getString("Strings", key);
}
return obj;
}
// Since we're basically re-implementing (with async) part of the crashreporter
// client here, we'll just steal the strings we need from crashreporter.ini
async function getL10nStrings() {
- let dirSvc = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties);
- let path = OS.Path.join(dirSvc.get("GreD", Ci.nsIFile).path,
+ let path = OS.Path.join(Services.dirsvc.get("GreD", Ci.nsIFile).path,
"crashreporter.ini");
let pathExists = await OS.File.exists(path);
if (!pathExists) {
// we if we're on a mac
let parentDir = OS.Path.dirname(path);
path = OS.Path.join(parentDir, "MacOS", "crashreporter.app", "Contents",
"Resources", "crashreporter.ini");
@@ -70,17 +68,17 @@ async function getL10nStrings() {
}
let crstrings = parseINIStrings(path);
let strings = {
"crashid": crstrings.CrashID,
"reporturl": crstrings.CrashDetailsURL
};
- path = OS.Path.join(dirSvc.get("XCurProcD", Ci.nsIFile).path,
+ path = OS.Path.join(Services.dirsvc.get("XCurProcD", Ci.nsIFile).path,
"crashreporter-override.ini");
pathExists = await OS.File.exists(path);
if (pathExists) {
crstrings = parseINIStrings(path);
if ("CrashID" in crstrings) {
strings.crashid = crstrings.CrashID;
@@ -90,19 +88,17 @@ async function getL10nStrings() {
strings.reporturl = crstrings.CrashDetailsURL;
}
}
return strings;
}
function getDir(name) {
- let dirSvc = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties);
- let uAppDataPath = dirSvc.get("UAppData", Ci.nsIFile).path;
+ let uAppDataPath = Services.dirsvc.get("UAppData", Ci.nsIFile).path;
return OS.Path.join(uAppDataPath, "Crash Reports", name);
}
async function isDirAsync(path) {
try {
let dirInfo = await OS.File.stat(path);
if (!dirInfo.isDir) {
--- a/toolkit/crashreporter/content/crashes.js
+++ b/toolkit/crashreporter/content/crashes.js
@@ -44,22 +44,18 @@ function submitPendingReport(event) {
event.initEvent("CrashSubmitFailed", true, false);
document.dispatchEvent(event);
});
event.preventDefault();
return false;
}
function populateReportList() {
-
- var prefService = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
-
try {
- reportURL = prefService.getCharPref("breakpad.reportURL");
+ reportURL = Services.prefs.getCharPref("breakpad.reportURL");
// Ignore any non http/https urls
if (!/^https?:/i.test(reportURL))
reportURL = null;
} catch (e) { }
if (!reportURL) {
document.getElementById("clear-reports").style.display = "none";
document.getElementById("reportList").style.display = "none";
document.getElementById("noConfig").style.display = "block";
@@ -88,21 +84,19 @@ function populateReportList() {
}
};
timeFormatter = {
format(date) {
return date.toLocaleTimeString();
}
};
}
- var ios = Cc["@mozilla.org/network/io-service;1"].
- getService(Ci.nsIIOService);
- var reportURI = ios.newURI(reportURL);
+ var reportURI = Services.io.newURI(reportURL);
// resolving this URI relative to /report/index
- var aboutThrottling = ios.newURI("../../about/throttling", null, reportURI);
+ var aboutThrottling = Services.io.newURI("../../about/throttling", null, reportURI);
for (var i = 0; i < reports.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
row.appendChild(cell);
var link = document.createElement("a");
if (reports[i].pending) {
link.setAttribute("href", aboutThrottling.spec);
--- a/toolkit/crashreporter/test/browser/browser_aboutCrashes.js
+++ b/toolkit/crashreporter/test/browser/browser_aboutCrashes.js
@@ -1,17 +1,15 @@
add_task(async function test() {
let appD = make_fake_appdir();
let crD = appD.clone();
crD.append("Crash Reports");
let crashes = add_fake_crashes(crD, 5);
// sanity check
- let dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties);
- let appDtest = dirSvc.get("UAppData", Components.interfaces.nsIFile);
+ let appDtest = Services.dirsvc.get("UAppData", Components.interfaces.nsIFile);
ok(appD.equals(appDtest), "directory service provider registered ok");
await BrowserTestUtils.withNewTab({ gBrowser, url: "about:crashes" }, function(browser) {
info("about:crashes loaded");
return ContentTask.spawn(browser, crashes, function(crashes) {
let doc = content.document;
let crashlinks = doc.getElementById("submitted").querySelectorAll(".crashReport");
Assert.equal(crashlinks.length, crashes.length,
--- a/toolkit/crashreporter/test/browser/head.js
+++ b/toolkit/crashreporter/test/browser/head.js
@@ -1,8 +1,10 @@
+Cu.import("resource://gre/modules/Services.jsm");
+
function create_subdir(dir, subdirname) {
let subdir = dir.clone();
subdir.append(subdirname);
if (subdir.exists()) {
subdir.remove(true);
}
subdir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755);
return subdir;
@@ -10,19 +12,17 @@ function create_subdir(dir, subdirname)
// need to hold on to this to unregister for cleanup
var _provider = null;
function make_fake_appdir() {
// Create a directory inside the profile and register it as UAppData, so
// we can stick fake crash reports inside there. We put it inside the profile
// just because we know that will get cleaned up after the mochitest run.
- let dirSvc = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties);
- let profD = dirSvc.get("ProfD", Ci.nsIFile);
+ let profD = Services.dirsvc.get("ProfD", Ci.nsIFile);
// create a subdir just to keep our files out of the way
let appD = create_subdir(profD, "UAppData");
let crashesDir = create_subdir(appD, "Crash Reports");
create_subdir(crashesDir, "pending");
create_subdir(crashesDir, "submitted");
_provider = {
@@ -43,33 +43,31 @@ function make_fake_appdir() {
if (iid.equals(Ci.nsIDirectoryServiceProvider) ||
iid.equals(Ci.nsISupports)) {
return this;
}
throw Components.results.NS_ERROR_NO_INTERFACE;
}
};
// register our new provider
- dirSvc.QueryInterface(Ci.nsIDirectoryService)
- .registerProvider(_provider);
+ Services.dirsvc.QueryInterface(Ci.nsIDirectoryService)
+ .registerProvider(_provider);
// and undefine the old value
try {
- dirSvc.undefine("UAppData");
+ Services.dirsvc.undefine("UAppData");
} catch (ex) {} // it's ok if this fails, the value might not be cached yet
return appD.clone();
}
function cleanup_fake_appdir() {
- let dirSvc = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties);
- dirSvc.QueryInterface(Ci.nsIDirectoryService)
- .unregisterProvider(_provider);
+ Services.dirsvc.QueryInterface(Ci.nsIDirectoryService)
+ .unregisterProvider(_provider);
// undefine our value so future calls get the real value
try {
- dirSvc.undefine("UAppData");
+ Services.dirsvc.undefine("UAppData");
} catch (ex) {
dump("cleanup_fake_appdir: dirSvc.undefine failed: " + ex.message + "\n");
}
}
function add_fake_crashes(crD, count) {
let results = [];
let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"]
--- a/toolkit/crashreporter/test/unit/crasher_subprocess_head.js
+++ b/toolkit/crashreporter/test/unit/crasher_subprocess_head.js
@@ -1,33 +1,30 @@
+Components.utils.import("resource://gre/modules/Services.jsm");
+
// enable crash reporting first
-var cwd = Components.classes["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties)
- .get("CurWorkD", Components.interfaces.nsIFile);
+var cwd = Services.dirsvc.get("CurWorkD", Components.interfaces.nsIFile);
// get the temp dir
var env = Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment);
var _tmpd = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsIFile);
_tmpd.initWithPath(env.get("XPCSHELL_TEST_TEMP_DIR"));
var crashReporter =
Components.classes["@mozilla.org/toolkit/crash-reporter;1"]
.getService(Components.interfaces.nsICrashReporter);
// We need to call this or crash events go in an undefined location.
crashReporter.UpdateCrashEventsDir();
// Setting the minidump path is not allowed in content processes
-var processType = Components.classes["@mozilla.org/xre/runtime;1"].
- getService(Components.interfaces.nsIXULRuntime).processType;
+var processType = Services.appinfo.processType;
if (processType == Components.interfaces.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
crashReporter.minidumpPath = _tmpd;
}
-var ios = Components.classes["@mozilla.org/network/io-service;1"]
- .getService(Components.interfaces.nsIIOService);
-var protocolHandler = ios.getProtocolHandler("resource")
- .QueryInterface(Components.interfaces.nsIResProtocolHandler);
-var curDirURI = ios.newFileURI(cwd);
+var protocolHandler = Services.io.getProtocolHandler("resource")
+ .QueryInterface(Components.interfaces.nsIResProtocolHandler);
+var curDirURI = Services.io.newFileURI(cwd);
protocolHandler.setSubstitution("test", curDirURI);
Components.utils.import("resource://test/CrashTestUtils.jsm");
var crashType = CrashTestUtils.CRASH_INVALID_POINTER_DEREF;
var shouldDelay = false;
--- a/toolkit/crashreporter/test/unit/crasher_subprocess_tail.js
+++ b/toolkit/crashreporter/test/unit/crasher_subprocess_tail.js
@@ -1,15 +1,13 @@
/* import-globals-from crasher_subprocess_head.js */
// Let the event loop process a bit before crashing.
if (shouldDelay) {
let shouldCrashNow = false;
- let tm = Components.classes["@mozilla.org/thread-manager;1"]
- .getService(Components.interfaces.nsIThreadManager);
- tm.dispatchToMainThread({ run: () => { shouldCrashNow = true; } });
+ Services.tm.dispatchToMainThread({ run: () => { shouldCrashNow = true; } });
- tm.spinEventLoopUntil(() => shouldCrashNow);
+ Services.tm.spinEventLoopUntil(() => shouldCrashNow);
}
// now actually crash
CrashTestUtils.crash(crashType);
--- a/toolkit/crashreporter/test/unit/head_crashreporter.js
+++ b/toolkit/crashreporter/test/unit/head_crashreporter.js
@@ -34,25 +34,23 @@ function getEventDir() {
* @param canReturnZero
* If true, the subprocess may return with a zero exit code.
* Certain types of crashes may not cause the process to
* exit with an error.
*
*/
function do_crash(setup, callback, canReturnZero) {
// get current process filename (xpcshell)
- let ds = Components.classes["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties);
- let bin = ds.get("XREExeF", Components.interfaces.nsIFile);
+ let bin = Services.dirsvc.get("XREExeF", Components.interfaces.nsIFile);
if (!bin.exists()) {
// weird, can't find xpcshell binary?
do_throw("Can't find xpcshell binary!");
}
// get Gre dir (GreD)
- let greD = ds.get("GreD", Components.interfaces.nsIFile);
+ let greD = Services.dirsvc.get("GreD", Components.interfaces.nsIFile);
let headfile = do_get_file("crasher_subprocess_head.js");
let tailfile = do_get_file("crasher_subprocess_tail.js");
// run xpcshell -g GreD -f head -e "some setup code" -f tail
let process = Components.classes["@mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess);
process.init(bin);
let args = ["-g", greD.path,
"-f", headfile.path];
@@ -104,19 +102,17 @@ function getMinidump() {
}
function runMinidumpAnalyzer(dumpFile, additionalArgs) {
if (AppConstants.platform !== "win") {
return;
}
// find minidump-analyzer executable.
- let ds = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties);
- let bin = ds.get("XREExeF", Ci.nsIFile);
+ let bin = Services.dirsvc.get("XREExeF", Ci.nsIFile);
ok(bin && bin.exists());
bin = bin.parent;
ok(bin && bin.exists());
bin.append("minidump-analyzer.exe");
ok(bin.exists());
let process = Cc["@mozilla.org/process/util;1"]
.createInstance(Ci.nsIProcess);
--- a/toolkit/crashreporter/test/unit/test_crash_after_js_large_allocation_failure_reporting.js
+++ b/toolkit/crashreporter/test/unit/test_crash_after_js_large_allocation_failure_reporting.js
@@ -8,19 +8,17 @@ function run_test() {
function() {
crashType = CrashTestUtils.CRASH_MOZ_CRASH;
crashReporter.annotateCrashReport("TestingOOMCrash", "Yes");
function crashWhileReporting() {
CrashTestUtils.crash(crashType);
}
- var observerService = Components.classes["@mozilla.org/observer-service;1"]
- .getService(Components.interfaces.nsIObserverService);
- observerService.addObserver(crashWhileReporting, "memory-pressure");
+ Services.obs.addObserver(crashWhileReporting, "memory-pressure");
Components.utils.getJSTestingFunctions().reportLargeAllocationFailure();
},
function(mdump, extra) {
do_check_eq(extra.TestingOOMCrash, "Yes");
do_check_eq(extra.JSLargeAllocationFailure, "Reporting");
},
true);
}
--- a/toolkit/crashreporter/test/unit/test_crash_with_memory_report.js
+++ b/toolkit/crashreporter/test/unit/test_crash_with_memory_report.js
@@ -18,18 +18,16 @@ function run_test() {
let env = Cc["@mozilla.org/process/environment;1"]
.getService(Ci.nsIEnvironment);
let profd = env.get("XPCSHELL_TEST_PROFILE_DIR");
let file = Cc["@mozilla.org/file/local;1"]
.createInstance(Ci.nsIFile);
file.initWithPath(profd);
- let dirSvc = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties);
let provider = {
getFile(prop, persistent) {
persistent.value = true;
if (prop == "ProfD" || prop == "ProfLD" || prop == "ProfDS" ||
prop == "ProfLDS" || prop == "TmpD") {
return file.clone();
}
throw Components.results.NS_ERROR_FAILURE;
@@ -37,18 +35,18 @@ function run_test() {
QueryInterface(iid) {
if (iid.equals(Ci.nsIDirectoryServiceProvider) ||
iid.equals(Ci.nsISupports)) {
return this;
}
throw Components.results.NS_ERROR_NO_INTERFACE;
}
};
- dirSvc.QueryInterface(Ci.nsIDirectoryService)
- .registerProvider(provider);
+ Services.dirsvc.QueryInterface(Ci.nsIDirectoryService)
+ .registerProvider(provider);
crashReporter.saveMemoryReport();
},
function(mdump, extra) {
do_check_eq(extra.ContainsMemoryReport, "1");
},
true);
}
--- a/toolkit/crashreporter/test/unit/test_crashreporter.js
+++ b/toolkit/crashreporter/test/unit/test_crashreporter.js
@@ -9,30 +9,28 @@ function run_test() {
try {
cr.serverURL;
do_throw("Getting serverURL when not set should have thrown!");
} catch (ex) {
do_check_eq(ex.result, Components.results.NS_ERROR_FAILURE);
}
// check setting/getting serverURL
- var ios = Components.classes["@mozilla.org/network/io-service;1"]
- .getService(Components.interfaces.nsIIOService);
// try it with two different URLs, just for kicks
var testspecs = ["http://example.com/submit",
"https://example.org/anothersubmit"];
for (var i = 0; i < testspecs.length; ++i) {
- cr.serverURL = ios.newURI(testspecs[i]);
+ cr.serverURL = Services.io.newURI(testspecs[i]);
do_check_eq(cr.serverURL.spec, testspecs[i]);
}
// should not allow setting non-http/https URLs
try {
- cr.serverURL = ios.newURI("ftp://example.com/submit");
+ cr.serverURL = Services.io.newURI("ftp://example.com/submit");
do_throw("Setting serverURL to a non-http(s) URL should have thrown!");
} catch (ex) {
do_check_eq(ex.result, Components.results.NS_ERROR_INVALID_ARG);
}
// check getting/setting minidumpPath
// it should be $TEMP by default, but I'm not sure if we can exactly test that
// this will at least test that it doesn't throw
--- a/toolkit/crashreporter/test/unit/test_crashreporter_crash.js
+++ b/toolkit/crashreporter/test/unit/test_crashreporter_crash.js
@@ -56,22 +56,20 @@ function run_test() {
"The TelemetryClientId field is omitted by default");
Assert.ok(!("TelemetryServerURL" in extra),
"The TelemetryServerURL field is omitted by default");
});
do_crash(function() {
// Enable the FHR, official policy bypass (since we're in a test) and
// specify a telemetry server & client ID.
- let prefs = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefBranch);
- prefs.setBoolPref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
- prefs.setBoolPref("datareporting.healthreport.uploadEnabled", true);
- prefs.setCharPref("toolkit.telemetry.server", "http://a.telemetry.server");
- prefs.setCharPref("toolkit.telemetry.cachedClientID",
+ Services.prefs.setBoolPref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
+ Services.prefs.setBoolPref("datareporting.healthreport.uploadEnabled", true);
+ Services.prefs.setCharPref("toolkit.telemetry.server", "http://a.telemetry.server");
+ Services.prefs.setCharPref("toolkit.telemetry.cachedClientID",
"f3582dee-22b9-4d73-96d1-79ef5bf2fc24");
// TelemetrySession setup will trigger the session annotation
let scope = {};
Components.utils.import("resource://gre/modules/TelemetryController.jsm", scope);
Components.utils.import("resource://gre/modules/TelemetrySend.jsm", scope);
scope.TelemetrySend.setTestModeEnabled(true);
scope.TelemetryController.testSetup();
@@ -84,20 +82,18 @@ function run_test() {
Assert.ok("TelemetryServerURL" in extra,
"The TelemetryServerURL field is present when the FHR is on");
Assert.equal(extra.TelemetryServerURL, "http://a.telemetry.server",
"The TelemetryServerURL matches the expected value");
});
do_crash(function() {
// Disable the FHR upload, no telemetry annotations should be present.
- let prefs = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefBranch);
- prefs.setBoolPref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
- prefs.setBoolPref("datareporting.healthreport.uploadEnabled", false);
+ Services.prefs.setBoolPref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
+ Services.prefs.setBoolPref("datareporting.healthreport.uploadEnabled", false);
// TelemetrySession setup will trigger the session annotation
let scope = {};
Components.utils.import("resource://gre/modules/TelemetryController.jsm", scope);
Components.utils.import("resource://gre/modules/TelemetrySend.jsm", scope);
scope.TelemetrySend.setTestModeEnabled(true);
scope.TelemetryController.testSetup();
}, function(mdump, extra) {
@@ -105,20 +101,18 @@ function run_test() {
"The TelemetryClientId field is omitted when FHR upload is disabled");
Assert.ok(!("TelemetryServerURL" in extra),
"The TelemetryServerURL field is omitted when FHR upload is disabled");
});
do_crash(function() {
// No telemetry annotations should be present if the user has not been
// notified yet
- let prefs = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefBranch);
- prefs.setBoolPref("datareporting.policy.dataSubmissionPolicyBypassNotification", false);
- prefs.setBoolPref("datareporting.healthreport.uploadEnabled", true);
+ Services.prefs.setBoolPref("datareporting.policy.dataSubmissionPolicyBypassNotification", false);
+ Services.prefs.setBoolPref("datareporting.healthreport.uploadEnabled", true);
// TelemetrySession setup will trigger the session annotation
let scope = {};
Components.utils.import("resource://gre/modules/TelemetryController.jsm", scope);
Components.utils.import("resource://gre/modules/TelemetrySend.jsm", scope);
scope.TelemetrySend.setTestModeEnabled(true);
scope.TelemetryController.testSetup();
}, function(mdump, extra) {
--- a/toolkit/forgetaboutsite/ForgetAboutSite.jsm
+++ b/toolkit/forgetaboutsite/ForgetAboutSite.jsm
@@ -44,43 +44,39 @@ const Cu = Components.utils;
this.ForgetAboutSite = {
async removeDataFromDomain(aDomain) {
PlacesUtils.history.removePagesFromHost(aDomain, true);
let promises = [];
// Cache
promises.push((async function() {
- let cs = Cc["@mozilla.org/netwerk/cache-storage-service;1"].
- getService(Ci.nsICacheStorageService);
// NOTE: there is no way to clear just that domain, so we clear out
// everything)
- cs.clear();
+ Services.cache2.clear();
})().catch(ex => {
throw new Error("Exception thrown while clearing the cache: " + ex);
}));
// Image Cache
promises.push((async function() {
let imageCache = Cc["@mozilla.org/image/tools;1"].
getService(Ci.imgITools).getImgCacheForDocument(null);
imageCache.clearCache(false); // true=chrome, false=content
})().catch(ex => {
throw new Error("Exception thrown while clearing the image cache: " + ex);
}));
// Cookies
// Need to maximize the number of cookies cleaned here
promises.push((async function() {
- let cm = Cc["@mozilla.org/cookiemanager;1"].
- getService(Ci.nsICookieManager);
- let enumerator = cm.getCookiesWithOriginAttributes(JSON.stringify({}), aDomain);
+ let enumerator = Services.cookies.getCookiesWithOriginAttributes(JSON.stringify({}), aDomain);
while (enumerator.hasMoreElements()) {
let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie);
- cm.remove(cookie.host, cookie.name, cookie.path, false, cookie.originAttributes);
+ Services.cookies.remove(cookie.host, cookie.name, cookie.path, false, cookie.originAttributes);
}
})().catch(ex => {
throw new Error("Exception thrown while clearning cookies: " + ex);
}));
// EME
promises.push((async function() {
let mps = Cc["@mozilla.org/gecko-media-plugin-service;1"].
@@ -114,67 +110,61 @@ this.ForgetAboutSite = {
list.removeFinished(download => hasRootDomain(
NetUtil.newURI(download.source.url).host, aDomain));
})().catch(ex => {
throw new Error("Exception in clearing Downloads: " + ex);
}));
// Passwords
promises.push((async function() {
- let lm = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
// Clear all passwords for domain
- let logins = lm.getAllLogins();
+ let logins = Services.logins.getAllLogins();
for (let i = 0; i < logins.length; i++)
if (hasRootDomain(logins[i].hostname, aDomain))
- lm.removeLogin(logins[i]);
+ Services.logins.removeLogin(logins[i]);
})().catch(ex => {
// XXXehsan: is there a better way to do this rather than this
// hacky comparison?
if (ex.message.indexOf("User canceled Master Password entry") == -1) {
throw new Error("Exception occured in clearing passwords :" + ex);
}
}));
// Permissions
- let pm = Cc["@mozilla.org/permissionmanager;1"].
- getService(Ci.nsIPermissionManager);
// Enumerate all of the permissions, and if one matches, remove it
- let enumerator = pm.enumerator;
+ let enumerator = Services.perms.enumerator;
while (enumerator.hasMoreElements()) {
let perm = enumerator.getNext().QueryInterface(Ci.nsIPermission);
promises.push(new Promise((resolve, reject) => {
try {
if (hasRootDomain(perm.principal.URI.host, aDomain)) {
- pm.removePermission(perm);
+ Services.perms.removePermission(perm);
}
} catch (ex) {
// Ignore entry
} finally {
resolve();
}
}));
}
// Offline Storages
promises.push((async function() {
- let qms = Cc["@mozilla.org/dom/quota-manager-service;1"].
- getService(Ci.nsIQuotaManagerService);
// delete data from both HTTP and HTTPS sites
let httpURI = NetUtil.newURI("http://" + aDomain);
let httpsURI = NetUtil.newURI("https://" + aDomain);
// Following code section has been reverted to the state before Bug 1238183,
// but added a new argument to clearStoragesForPrincipal() for indicating
// clear all storages under a given origin.
let httpPrincipal = Services.scriptSecurityManager
.createCodebasePrincipal(httpURI, {});
let httpsPrincipal = Services.scriptSecurityManager
.createCodebasePrincipal(httpsURI, {});
- qms.clearStoragesForPrincipal(httpPrincipal, null, true);
- qms.clearStoragesForPrincipal(httpsPrincipal, null, true);
+ Services.qms.clearStoragesForPrincipal(httpPrincipal, null, true);
+ Services.qms.clearStoragesForPrincipal(httpsPrincipal, null, true);
})().catch(ex => {
throw new Error("Exception occured while clearing offline storages: " + ex);
}));
// Content Preferences
promises.push((async function() {
let cps2 = Cc["@mozilla.org/content-pref/service;1"].
getService(Ci.nsIContentPrefService2);
--- a/toolkit/forgetaboutsite/test/unit/head_forgetaboutsite.js
+++ b/toolkit/forgetaboutsite/test/unit/head_forgetaboutsite.js
@@ -3,30 +3,31 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* import-globals-from ../../../../dom/push/test/xpcshell/head.js */
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
-var dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
+Cu.import("resource://gre/modules/Services.jsm");
+
var profileDir = do_get_profile();
/**
* Removes any files that could make our tests fail.
*/
function cleanUp() {
let files = [
"places.sqlite",
"cookies.sqlite",
"signons.sqlite",
"permissions.sqlite"
];
for (let i = 0; i < files.length; i++) {
- let file = dirSvc.get("ProfD", Ci.nsIFile);
+ let file = Services.dirsvc.get("ProfD", Ci.nsIFile);
file.append(files[i]);
if (file.exists())
file.remove(false);
}
}
cleanUp();
--- a/toolkit/forgetaboutsite/test/unit/test_removeDataFromDomain.js
+++ b/toolkit/forgetaboutsite/test/unit/test_removeDataFromDomain.js
@@ -31,29 +31,16 @@ const LOGIN_PASSWORD_FIELD = "password_f
const PERMISSION_TYPE = "test-perm";
const PERMISSION_VALUE = Ci.nsIPermissionManager.ALLOW_ACTION;
const PREFERENCE_NAME = "test-pref";
// Utility Functions
/**
- * Creates an nsIURI object for the given string representation of a URI.
- *
- * @param aURIString
- * The spec of the URI to create.
- * @returns an nsIURI representing aURIString.
- */
-function uri(aURIString) {
- return Cc["@mozilla.org/network/io-service;1"].
- getService(Ci.nsIIOService).
- newURI(aURIString);
-}
-
-/**
* Asynchronously check a url is visited.
*
* @param aURI
* The URI.
*
* @return {Promise}
* @resolves When the check has been added successfully.
* @rejects JavaScript exception.
@@ -69,138 +56,120 @@ function promiseIsURIVisited(aURI) {
/**
* Add a cookie to the cookie service.
*
* @param aDomain
*/
function add_cookie(aDomain) {
check_cookie_exists(aDomain, false);
- let cm = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);
- cm.add(aDomain, COOKIE_PATH, COOKIE_NAME, "", false, false, false,
- COOKIE_EXPIRY, {});
+ Services.cookies.add(aDomain, COOKIE_PATH, COOKIE_NAME, "", false, false, false,
+ COOKIE_EXPIRY, {});
check_cookie_exists(aDomain, true);
}
/**
* Checks to ensure that a cookie exists or not for a domain.
*
* @param aDomain
* The domain to check for the cookie.
* @param aExists
* True if the cookie should exist, false otherwise.
*/
function check_cookie_exists(aDomain, aExists) {
- let cm = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);
let cookie = {
host: aDomain,
name: COOKIE_NAME,
path: COOKIE_PATH
};
let checker = aExists ? do_check_true : do_check_false;
- checker(cm.cookieExists(cookie));
+ checker(Services.cookies.cookieExists(cookie));
}
/**
* Adds a disabled host to the login manager.
*
* @param aHost
* The host to add to the list of disabled hosts.
*/
function add_disabled_host(aHost) {
check_disabled_host(aHost, false);
- let lm = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
- lm.setLoginSavingEnabled(aHost, false);
+ Services.logins.setLoginSavingEnabled(aHost, false);
check_disabled_host(aHost, true);
}
/**
* Checks to see if a host is disabled for storing logins or not.
*
* @param aHost
* The host to check if it is disabled.
* @param aIsDisabled
* True if the host should be disabled, false otherwise.
*/
function check_disabled_host(aHost, aIsDisabled) {
- let lm = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
let checker = aIsDisabled ? do_check_false : do_check_true;
- checker(lm.getLoginSavingEnabled(aHost));
+ checker(Services.logins.getLoginSavingEnabled(aHost));
}
/**
* Adds a login for the specified host to the login manager.
*
* @param aHost
* The host to add the login for.
*/
function add_login(aHost) {
check_login_exists(aHost, false);
let login = Cc["@mozilla.org/login-manager/loginInfo;1"].
createInstance(Ci.nsILoginInfo);
login.init(aHost, "", null, LOGIN_USERNAME, LOGIN_PASSWORD,
LOGIN_USERNAME_FIELD, LOGIN_PASSWORD_FIELD);
- let lm = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
- lm.addLogin(login);
+ Services.logins.addLogin(login);
check_login_exists(aHost, true);
}
/**
* Checks to see if a login exists for a host.
*
* @param aHost
* The host to check for the test login.
* @param aExists
* True if the login should exist, false otherwise.
*/
function check_login_exists(aHost, aExists) {
- let lm = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
let count = { value: 0 };
- lm.findLogins(count, aHost, "", null);
+ Services.logins.findLogins(count, aHost, "", null);
do_check_eq(count.value, aExists ? 1 : 0);
}
/**
* Adds a permission for the specified URI to the permission manager.
*
* @param aURI
* The URI to add the test permission for.
*/
function add_permission(aURI) {
check_permission_exists(aURI, false);
- let pm = Cc["@mozilla.org/permissionmanager;1"].
- getService(Ci.nsIPermissionManager);
- let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"]
- .getService(Ci.nsIScriptSecurityManager);
- let principal = ssm.createCodebasePrincipal(aURI, {});
+ let principal = Services.scriptSecurityManager.createCodebasePrincipal(aURI, {});
- pm.addFromPrincipal(principal, PERMISSION_TYPE, PERMISSION_VALUE);
+ Services.perms.addFromPrincipal(principal, PERMISSION_TYPE, PERMISSION_VALUE);
check_permission_exists(aURI, true);
}
/**
* Checks to see if a permission exists for the given URI.
*
* @param aURI
* The URI to check if a permission exists.
* @param aExists
* True if the permission should exist, false otherwise.
*/
function check_permission_exists(aURI, aExists) {
- let pm = Cc["@mozilla.org/permissionmanager;1"].
- getService(Ci.nsIPermissionManager);
- let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"]
- .getService(Ci.nsIScriptSecurityManager);
- let principal = ssm.createCodebasePrincipal(aURI, {});
+ let principal = Services.scriptSecurityManager.createCodebasePrincipal(aURI, {});
- let perm = pm.testExactPermissionFromPrincipal(principal, PERMISSION_TYPE);
+ let perm = Services.perms.testExactPermissionFromPrincipal(principal, PERMISSION_TYPE);
let checker = aExists ? do_check_eq : do_check_neq;
checker(perm, PERMISSION_VALUE);
}
/**
* Adds a content preference for the specified URI.
*
* @param aURI
@@ -233,35 +202,35 @@ function preference_exists(aURI) {
});
});
}
// Test Functions
// History
async function test_history_cleared_with_direct_match() {
- const TEST_URI = uri("http://mozilla.org/foo");
+ const TEST_URI = Services.io.newURI("http://mozilla.org/foo");
do_check_false(await promiseIsURIVisited(TEST_URI));
await PlacesTestUtils.addVisits(TEST_URI);
do_check_true(await promiseIsURIVisited(TEST_URI));
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
do_check_false(await promiseIsURIVisited(TEST_URI));
}
async function test_history_cleared_with_subdomain() {
- const TEST_URI = uri("http://www.mozilla.org/foo");
+ const TEST_URI = Services.io.newURI("http://www.mozilla.org/foo");
do_check_false(await promiseIsURIVisited(TEST_URI));
await PlacesTestUtils.addVisits(TEST_URI);
do_check_true(await promiseIsURIVisited(TEST_URI));
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
do_check_false(await promiseIsURIVisited(TEST_URI));
}
async function test_history_not_cleared_with_uri_contains_domain() {
- const TEST_URI = uri("http://ilovemozilla.org/foo");
+ const TEST_URI = Services.io.newURI("http://ilovemozilla.org/foo");
do_check_false(await promiseIsURIVisited(TEST_URI));
await PlacesTestUtils.addVisits(TEST_URI);
do_check_true(await promiseIsURIVisited(TEST_URI));
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
do_check_true(await promiseIsURIVisited(TEST_URI));
// Clear history since we left something there from this test.
await PlacesTestUtils.clearHistory();
@@ -306,19 +275,17 @@ async function test_login_manager_disabl
async function test_login_manager_disabled_hosts_not_cleared_with_uri_contains_domain() {
const TEST_HOST = "http://ilovemozilla.org";
add_disabled_host(TEST_HOST);
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
check_disabled_host(TEST_HOST, true);
// Reset state
- let lm = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
- lm.setLoginSavingEnabled(TEST_HOST, true);
+ Services.logins.setLoginSavingEnabled(TEST_HOST, true);
check_disabled_host(TEST_HOST, false);
}
async function test_login_manager_logins_cleared_with_direct_match() {
const TEST_HOST = "http://mozilla.org";
add_login(TEST_HOST);
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
check_login_exists(TEST_HOST, false);
@@ -332,47 +299,43 @@ async function test_login_manager_logins
}
async function test_login_manager_logins_not_cleared_with_uri_contains_domain() {
const TEST_HOST = "http://ilovemozilla.org";
add_login(TEST_HOST);
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
check_login_exists(TEST_HOST, true);
- let lm = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
- lm.removeAllLogins();
+ Services.logins.removeAllLogins();
check_login_exists(TEST_HOST, false);
}
// Permission Manager
async function test_permission_manager_cleared_with_direct_match() {
- const TEST_URI = uri("http://mozilla.org");
+ const TEST_URI = Services.io.newURI("http://mozilla.org");
add_permission(TEST_URI);
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
check_permission_exists(TEST_URI, false);
}
async function test_permission_manager_cleared_with_subdomain() {
- const TEST_URI = uri("http://www.mozilla.org");
+ const TEST_URI = Services.io.newURI("http://www.mozilla.org");
add_permission(TEST_URI);
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
check_permission_exists(TEST_URI, false);
}
async function test_permission_manager_not_cleared_with_uri_contains_domain() {
- const TEST_URI = uri("http://ilovemozilla.org");
+ const TEST_URI = Services.io.newURI("http://ilovemozilla.org");
add_permission(TEST_URI);
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
check_permission_exists(TEST_URI, true);
// Reset state
- let pm = Cc["@mozilla.org/permissionmanager;1"].
- getService(Ci.nsIPermissionManager);
- pm.removeAll();
+ Services.perms.removeAll();
check_permission_exists(TEST_URI, false);
}
function waitForPurgeNotification() {
return new Promise(resolve => {
let observer = {
observe(aSubject, aTopic, aData) {
@@ -387,55 +350,53 @@ function waitForPurgeNotification() {
};
Services.obs.addObserver(observer, "browser:purge-domain-data");
});
}
// Content Preferences
async function test_content_preferences_cleared_with_direct_match() {
- const TEST_URI = uri("http://mozilla.org");
+ const TEST_URI = Services.io.newURI("http://mozilla.org");
do_check_false(await preference_exists(TEST_URI));
await add_preference(TEST_URI);
do_check_true(await preference_exists(TEST_URI));
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
await waitForPurgeNotification();
do_check_false(await preference_exists(TEST_URI));
}
async function test_content_preferences_cleared_with_subdomain() {
- const TEST_URI = uri("http://www.mozilla.org");
+ const TEST_URI = Services.io.newURI("http://www.mozilla.org");
do_check_false(await preference_exists(TEST_URI));
await add_preference(TEST_URI);
do_check_true(await preference_exists(TEST_URI));
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
await waitForPurgeNotification();
do_check_false(await preference_exists(TEST_URI));
}
async function test_content_preferences_not_cleared_with_uri_contains_domain() {
- const TEST_URI = uri("http://ilovemozilla.org");
+ const TEST_URI = Services.io.newURI("http://ilovemozilla.org");
do_check_false(await preference_exists(TEST_URI));
await add_preference(TEST_URI);
do_check_true(await preference_exists(TEST_URI));
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
await waitForPurgeNotification();
do_check_true(await preference_exists(TEST_URI));
// Reset state
await ForgetAboutSite.removeDataFromDomain("ilovemozilla.org");
await waitForPurgeNotification();
do_check_false(await preference_exists(TEST_URI));
}
function push_registration_exists(aURL, ps) {
return new Promise(resolve => {
- let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"]
- .getService(Ci.nsIScriptSecurityManager);
- let principal = ssm.createCodebasePrincipalFromOrigin(aURL);
+ let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(aURL);
return ps.getSubscription(aURL, principal, (status, record) => {
if (!Components.isSuccessCode(status)) {
resolve(false);
} else {
resolve(!!record);
}
});
});
@@ -504,46 +465,40 @@ async function test_cache_cleared() {
// Because this test is asynchronous, it should be the last test
do_check_true(tests[tests.length - 1] == test_cache_cleared);
// NOTE: We could be more extensive with this test and actually add an entry
// to the cache, and then make sure it is gone. However, we trust that
// the API is well tested, and that when we get the observer
// notification, we have actually cleared the cache.
// This seems to happen asynchronously...
- let os = Cc["@mozilla.org/observer-service;1"].
- getService(Ci.nsIObserverService);
let observer = {
observe(aSubject, aTopic, aData) {
- os.removeObserver(observer, "cacheservice:empty-cache");
+ Services.obs.removeObserver(observer, "cacheservice:empty-cache");
// Shutdown the download manager.
Services.obs.notifyObservers(null, "quit-application");
do_test_finished();
}
};
- os.addObserver(observer, "cacheservice:empty-cache");
+ Services.obs.addObserver(observer, "cacheservice:empty-cache");
await ForgetAboutSite.removeDataFromDomain("mozilla.org");
do_test_pending();
}
async function test_storage_cleared() {
function getStorageForURI(aURI) {
- let ssm = Cc["@mozilla.org/scriptsecuritymanager;1"]
- .getService(Ci.nsIScriptSecurityManager);
- let principal = ssm.createCodebasePrincipal(aURI, {});
+ let principal = Services.scriptSecurityManager.createCodebasePrincipal(aURI, {});
- let dsm = Cc["@mozilla.org/dom/localStorage-manager;1"].
- getService(Ci.nsIDOMStorageManager);
- return dsm.createStorage(null, principal, "");
+ return Services.domStorageManager.createStorage(null, principal, "");
}
let s = [
- getStorageForURI(uri("http://mozilla.org")),
- getStorageForURI(uri("http://my.mozilla.org")),
- getStorageForURI(uri("http://ilovemozilla.org")),
+ getStorageForURI(Services.io.newURI("http://mozilla.org")),
+ getStorageForURI(Services.io.newURI("http://my.mozilla.org")),
+ getStorageForURI(Services.io.newURI("http://ilovemozilla.org")),
];
for (let i = 0; i < s.length; ++i) {
let storage = s[i];
storage.setItem("test", "value" + i);
do_check_eq(storage.length, 1);
do_check_eq(storage.key(0), "test");
do_check_eq(storage.getItem("test"), "value" + i);
--- a/toolkit/modules/BrowserUtils.jsm
+++ b/toolkit/modules/BrowserUtils.jsm
@@ -69,30 +69,28 @@ this.BrowserUtils = {
dump("\n");
},
/**
* restartApplication: Restarts the application, keeping it in
* safe mode if it is already in safe mode.
*/
restartApplication() {
- let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]
- .getService(Ci.nsIAppStartup);
let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"]
.createInstance(Ci.nsISupportsPRBool);
Services.obs.notifyObservers(cancelQuit, "quit-application-requested", "restart");
if (cancelQuit.data) { // The quit request has been canceled.
return false;
}
// if already in safe mode restart in safe mode
if (Services.appinfo.inSafeMode) {
- appStartup.restartInSafeMode(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart);
+ Services.startup.restartInSafeMode(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart);
return undefined;
}
- appStartup.quit(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart);
+ Services.startup.quit(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart);
return undefined;
},
/**
* urlSecurityCheck: JavaScript wrapper for checkLoadURIWithPrincipal
* and checkLoadURIStrWithPrincipal.
* If |aPrincipal| is not allowed to link to |aURL|, this function throws with
* an error message.
@@ -545,20 +543,18 @@ this.BrowserUtils = {
offset < container.textContent.length)
delimitedAtEnd = /\W/.test(container.textContent[offset]);
else
delimitedAtEnd = true;
}
}
if (delimitedAtStart && delimitedAtEnd) {
- let uriFixup = Cc["@mozilla.org/docshell/urifixup;1"]
- .getService(Ci.nsIURIFixup);
try {
- url = uriFixup.createFixupURI(linkText, uriFixup.FIXUP_FLAG_NONE);
+ url = Services.uriFixup.createFixupURI(linkText, Services.uriFixup.FIXUP_FLAG_NONE);
} catch (ex) {}
}
}
}
if (selectionStr) {
// Pass up to 16K through unmolested. If an add-on needs more, they will
// have to use a content script.
--- a/toolkit/modules/Finder.jsm
+++ b/toolkit/modules/Finder.jsm
@@ -307,25 +307,24 @@ Finder.prototype = {
!l.shouldFocusContent())
return;
} catch (ex) {
Cu.reportError(ex);
}
}
let fastFind = this._fastFind;
- const fm = Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager);
try {
// Try to find the best possible match that should receive focus and
// block scrolling on focus since find already scrolls. Further
// scrolling is due to user action, so don't override this.
if (fastFind.foundLink) {
- fm.setFocus(fastFind.foundLink, fm.FLAG_NOSCROLL);
+ Services.focus.setFocus(fastFind.foundLink, Services.focus.FLAG_NOSCROLL);
} else if (fastFind.foundEditable) {
- fm.setFocus(fastFind.foundEditable, fm.FLAG_NOSCROLL);
+ Services.focus.setFocus(fastFind.foundEditable, Services.focus.FLAG_NOSCROLL);
fastFind.collapseSelection();
} else {
this._getWindow().focus();
}
} catch (e) {}
},
onFindbarClose() {
--- a/toolkit/modules/InlineSpellChecker.jsm
+++ b/toolkit/modules/InlineSpellChecker.jsm
@@ -7,16 +7,18 @@ this.EXPORTED_SYMBOLS = [ "InlineSpellCh
var gLanguageBundle;
var gRegionBundle;
const MAX_UNDO_STACK_DEPTH = 1;
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
+Cu.import("resource://gre/modules/Services.jsm");
+
this.InlineSpellChecker = function InlineSpellChecker(aEditor) {
this.init(aEditor);
this.mAddedWordStack = []; // We init this here to preserve it between init/uninit calls
};
InlineSpellChecker.prototype = {
// Call this function to initialize for a given editor
init(aEditor) {
@@ -253,21 +255,19 @@ InlineSpellChecker.prototype = {
var [/* languageTag */, languageSubtag, scriptSubtag, regionSubtag, variantSubtags] = dictionaryName.match(languageTagMatch);
} catch (e) {
// If we weren't given a valid language tag, just use the raw dictionary name.
return dictionaryName;
}
if (!gLanguageBundle) {
// Create the bundles for language and region names.
- var bundleService = Components.classes["@mozilla.org/intl/stringbundle;1"]
- .getService(Components.interfaces.nsIStringBundleService);
- gLanguageBundle = bundleService.createBundle(
+ gLanguageBundle = Services.strings.createBundle(
"chrome://global/locale/languageNames.properties");
- gRegionBundle = bundleService.createBundle(
+ gRegionBundle = Services.strings.createBundle(
"chrome://global/locale/regionNames.properties");
}
var displayName = "";
// Language subtag will normally be 2 or 3 letters, but could be up to 8.
try {
displayName += gLanguageBundle.GetStringFromName(languageSubtag.toLowerCase());
--- a/toolkit/modules/Log.jsm
+++ b/toolkit/modules/Log.jsm
@@ -15,16 +15,18 @@ const ONE_MEGABYTE = 1024 * ONE_KILOBYTE
const STREAM_SEGMENT_SIZE = 4096;
const PR_UINT32_MAX = 0xffffffff;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Services",
+ "resource://gre/modules/Services.jsm");
const INTERNAL_FIELDS = new Set(["_level", "_message", "_time", "_namespace"]);
/*
* Dump a message everywhere we can if we have a failure.
*/
function dumpError(text) {
dump(text + "\n");
@@ -752,18 +754,17 @@ ConsoleAppender.prototype = {
Cu.reportError(m);
return;
}
this.doAppend(m);
}
},
doAppend: function CApp_doAppend(formatted) {
- Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService).logStringMessage(formatted);
+ Services.console.logStringMessage(formatted);
}
};
/**
* Append to an nsIStorageStream
*
* This writes logging output to an in-memory stream which can later be read
* back as an nsIInputStream. It can be used to avoid expensive I/O operations
--- a/toolkit/modules/PopupNotifications.jsm
+++ b/toolkit/modules/PopupNotifications.jsm
@@ -476,18 +476,17 @@ PopupNotifications.prototype = {
let existingNotification = this.getNotification(id, browser);
if (existingNotification)
this._remove(existingNotification);
let notifications = this._getNotificationsForBrowser(browser);
notifications.push(notification);
let isActiveBrowser = this._isActiveBrowser(browser);
- let fm = Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager);
- let isActiveWindow = fm.activeWindow == this.window;
+ let isActiveWindow = Services.focus.activeWindow == this.window;
if (isActiveBrowser) {
if (isActiveWindow) {
// Autofocus if the notification requests focus.
if (options && !options.dismissed && options.autofocus) {
this.panel.removeAttribute("noautofocus");
} else {
--- a/toolkit/modules/RemoteWebProgress.jsm
+++ b/toolkit/modules/RemoteWebProgress.jsm
@@ -5,27 +5,23 @@
this.EXPORTED_SYMBOLS = ["RemoteWebProgressManager"];
const Ci = Components.interfaces;
const Cc = Components.classes;
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-function newURI(spec) {
- return Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
- .newURI(spec);
-}
+Cu.import("resource://gre/modules/Services.jsm");
function RemoteWebProgressRequest(spec, originalSpec, requestCPOW) {
this.wrappedJSObject = this;
- this._uri = newURI(spec);
- this._originalURI = newURI(originalSpec);
+ this._uri = Services.io.newURI(spec);
+ this._originalURI = Services.io.newURI(originalSpec);
this._requestCPOW = requestCPOW;
}
RemoteWebProgressRequest.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIChannel]),
get URI() { return this._uri.clone(); },
get originalURI() { return this._originalURI.clone(); }
@@ -234,36 +230,36 @@ RemoteWebProgressManager.prototype = {
this._browser._characterSet = json.charset;
this._browser._mayEnableCharacterEncodingMenu = json.mayEnableCharacterEncodingMenu;
}
}
switch (aMessage.name) {
case "Content:StateChange":
if (isTopLevel) {
- this._browser._documentURI = newURI(json.documentURI);
+ this._browser._documentURI = Services.io.newURI(json.documentURI);
}
this._callProgressListeners(
Ci.nsIWebProgress.NOTIFY_STATE_ALL, "onStateChange", webProgress,
request, json.stateFlags, json.status
);
break;
case "Content:LocationChange":
- let location = newURI(json.location);
+ let location = Services.io.newURI(json.location);
let flags = json.flags;
let remoteWebNav = this._browser._remoteWebNavigationImpl;
// These properties can change even for a sub-frame navigation.
remoteWebNav.canGoBack = json.canGoBack;
remoteWebNav.canGoForward = json.canGoForward;
if (isTopLevel) {
remoteWebNav._currentURI = location;
- this._browser._documentURI = newURI(json.documentURI);
+ this._browser._documentURI = Services.io.newURI(json.documentURI);
this._browser._contentTitle = json.title;
this._browser._imageDocument = null;
this._browser._contentPrincipal = json.principal;
this._browser._isSyntheticDocument = json.synthetic;
this._browser._innerWindowID = json.innerWindowID;
this._browser._contentRequestContextID = json.requestContextID;
}
--- a/toolkit/modules/ResetProfile.jsm
+++ b/toolkit/modules/ResetProfile.jsm
@@ -54,12 +54,11 @@ this.ResetProfile = {
if (!params.reset)
return;
// Set the reset profile environment variable.
let env = Cc["@mozilla.org/process/environment;1"]
.getService(Ci.nsIEnvironment);
env.set("MOZ_RESET_PROFILE_RESTART", "1");
- let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].getService(Ci.nsIAppStartup);
- appStartup.quit(Ci.nsIAppStartup.eForceQuit | Ci.nsIAppStartup.eRestart);
+ Services.startup.quit(Ci.nsIAppStartup.eForceQuit | Ci.nsIAppStartup.eRestart);
},
};
--- a/toolkit/modules/Troubleshoot.jsm
+++ b/toolkit/modules/Troubleshoot.jsm
@@ -165,42 +165,36 @@ this.Troubleshoot = {
// Each data provider is a name => function mapping. When a snapshot is
// captured, each provider's function is called, and it's the function's job to
// generate the provider's data. The function is passed a "done" callback, and
// when done, it must pass its data to the callback. The resulting snapshot
// object will contain a name => data entry for each provider.
var dataProviders = {
application: function application(done) {
-
- let sysInfo = Cc["@mozilla.org/system-info;1"].
- getService(Ci.nsIPropertyBag2);
-
let data = {
name: Services.appinfo.name,
- osVersion: sysInfo.getProperty("name") + " " + sysInfo.getProperty("version"),
+ osVersion: Services.sysinfo.getProperty("name") + " " + Services.sysinfo.getProperty("version"),
version: AppConstants.MOZ_APP_VERSION_DISPLAY,
buildID: Services.appinfo.appBuildID,
userAgent: Cc["@mozilla.org/network/protocol;1?name=http"].
getService(Ci.nsIHttpProtocolHandler).
userAgent,
safeMode: Services.appinfo.inSafeMode,
};
if (AppConstants.MOZ_UPDATER)
data.updateChannel = Cu.import("resource://gre/modules/UpdateUtils.jsm", {}).UpdateUtils.UpdateChannel;
// eslint-disable-next-line mozilla/use-default-preference-values
try {
data.vendor = Services.prefs.getCharPref("app.support.vendor");
} catch (e) {}
- let urlFormatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
- getService(Ci.nsIURLFormatter);
try {
- data.supportURL = urlFormatter.formatURLPref("app.support.baseURL");
+ data.supportURL = Services.urlFormatter.formatURLPref("app.support.baseURL");
} catch (e) {}
data.numTotalWindows = 0;
data.numRemoteWindows = 0;
let winEnumer = Services.wm.getEnumerator("navigator:browser");
while (winEnumer.hasMoreElements()) {
data.numTotalWindows++;
let remote = winEnumer.getNext().
@@ -687,21 +681,19 @@ if (AppConstants.MOZ_CRASHREPORTER) {
if (AppConstants.MOZ_SANDBOX) {
dataProviders.sandbox = function sandbox(done) {
let data = {};
if (AppConstants.platform == "linux") {
const keys = ["hasSeccompBPF", "hasSeccompTSync",
"hasPrivilegedUserNamespaces", "hasUserNamespaces",
"canSandboxContent", "canSandboxMedia"];
- let sysInfo = Cc["@mozilla.org/system-info;1"].
- getService(Ci.nsIPropertyBag2);
for (let key of keys) {
- if (sysInfo.hasKey(key)) {
- data[key] = sysInfo.getPropertyAsBool(key);
+ if (Services.sysinfo.hasKey(key)) {
+ data[key] = Services.sysinfo.getPropertyAsBool(key);
}
}
let reporter = Cc["@mozilla.org/sandbox/syscall-reporter;1"].
getService(Ci.mozISandboxReporter);
const snapshot = reporter.snapshot();
let syscalls = [];
for (let index = snapshot.begin; index < snapshot.end; ++index) {
--- a/toolkit/modules/debug.js
+++ b/toolkit/modules/debug.js
@@ -5,16 +5,22 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// This file contains functions that are useful for debugging purposes from
// within JavaScript code.
this.EXPORTED_SYMBOLS = ["NS_ASSERT"];
+var Cu = Components.utils;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Services",
+ "resource://gre/modules/Services.jsm");
+
var gTraceOnAssert = false;
/**
* This function provides a simple assertion function for JavaScript.
* If the condition is true, this function will do nothing. If the
* condition is false, then the message will be printed to the console
* and an alert will appear showing a stack trace, so that the (alpha
* or nightly) user can file a bug containing it. For future enhancements,
@@ -29,19 +35,17 @@ var gTraceOnAssert = false;
* @param message a string to be displayed upon failure of the assertion
*/
this.NS_ASSERT = function NS_ASSERT(condition, message) {
if (condition)
return;
var releaseBuild = true;
- var defB = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefService)
- .getDefaultBranch(null);
+ var defB = Services.prefs.getDefaultBranch(null);
try {
switch (defB.getCharPref("app.update.channel")) {
case "nightly":
case "aurora":
case "beta":
case "default":
releaseBuild = false;
}
--- a/toolkit/modules/tests/xpcshell/test_Preferences.js
+++ b/toolkit/modules/tests/xpcshell/test_Preferences.js
@@ -109,37 +109,31 @@ add_test(function test_set_unsupported_p
do_check_true(false);
} catch (ex) {}
run_next_test();
});
// Make sure that we can get a string pref that we didn't set ourselves.
add_test(function test_get_string_pref() {
- let svc = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefService).
- getBranch("");
- svc.setCharPref("test_get_string_pref", "a normal string");
+ Services.prefs.setCharPref("test_get_string_pref", "a normal string");
do_check_eq(Preferences.get("test_get_string_pref"), "a normal string");
// Clean up.
Preferences.reset("test_get_string_pref");
run_next_test();
});
add_test(function test_get_localized_string_pref() {
- let svc = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefService).
- getBranch("");
let prefName = "test_get_localized_string_pref";
let localizedString = Cc["@mozilla.org/pref-localizedstring;1"]
.createInstance(Ci.nsIPrefLocalizedString);
localizedString.data = "a localized string";
- svc.setComplexValue(prefName, Ci.nsIPrefLocalizedString, localizedString);
+ Services.prefs.setComplexValue(prefName, Ci.nsIPrefLocalizedString, localizedString);
do_check_eq(Preferences.get(prefName, null, Ci.nsIPrefLocalizedString),
"a localized string");
// Clean up.
Preferences.reset(prefName);
run_next_test();
});
--- a/toolkit/profile/content/createProfileWizard.js
+++ b/toolkit/profile/content/createProfileWizard.js
@@ -1,16 +1,17 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const C = Components.classes;
const I = Components.interfaces;
Components.utils.import("resource://gre/modules/AppConstants.jsm");
+Components.utils.import("resource://gre/modules/Services.jsm");
const ToolkitProfileService = "@mozilla.org/toolkit/profile-service;1";
var gProfileService;
var gProfileManagerBundle;
var gDefaultProfileParent;
@@ -21,18 +22,17 @@ var gProfileRoot;
var gProfileDisplay;
// Called once when the wizard is opened.
function initWizard() {
try {
gProfileService = C[ToolkitProfileService].getService(I.nsIToolkitProfileService);
gProfileManagerBundle = document.getElementById("bundle_profileManager");
- var dirService = C["@mozilla.org/file/directory_service;1"].getService(I.nsIProperties);
- gDefaultProfileParent = dirService.get("DefProfRt", I.nsIFile);
+ gDefaultProfileParent = Services.dirsvc.get("DefProfRt", I.nsIFile);
// Initialize the profile location display.
gProfileDisplay = document.getElementById("profileDisplay").firstChild;
setDisplayToDefaultFolder();
} catch (e) {
window.close();
throw (e);
}
@@ -178,20 +178,18 @@ function onFinish() {
// Create profile named profileName in profileRoot.
try {
profile = gProfileService.createProfile(gProfileRoot, profileName);
} catch (e) {
var profileCreationFailed =
gProfileManagerBundle.getString("profileCreationFailed");
var profileCreationFailedTitle =
gProfileManagerBundle.getString("profileCreationFailedTitle");
- var promptService = C["@mozilla.org/embedcomp/prompt-service;1"].
- getService(I.nsIPromptService);
- promptService.alert(window, profileCreationFailedTitle,
- profileCreationFailed + "\n" + e);
+ Services.prompt.alert(window, profileCreationFailedTitle,
+ profileCreationFailed + "\n" + e);
return false;
}
// window.opener is false if the Create Profile Wizard was opened from the
// command line.
if (window.opener) {
// Add new profile to the list in the Profile Manager.
--- a/toolkit/xre/test/browser_checkdllblockliststate.js
+++ b/toolkit/xre/test/browser_checkdllblockliststate.js
@@ -1,16 +1,12 @@
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
// Tests that the dll blocklist initializes correctly during test runs.
add_task(async function test() {
await BrowserTestUtils.withNewTab({gBrowser, url: "about:blank" }, function(browser) {
- ok(Components.classes["@mozilla.org/xre/app-info;1"]
- .getService(Ci.nsIXULRuntime)
- .windowsDLLBlocklistStatus,
+ ok(Services.appinfo.windowsDLLBlocklistStatus,
"Windows dll blocklist status should be true, indicating it is " +
"running properly. A failure in this test is considered a " +
"release blocker.");
});
});
-
-