--- a/toolkit/components/apppicker/content/appPicker.js
+++ b/toolkit/components/apppicker/content/appPicker.js
@@ -1,13 +1,14 @@
/* 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/. */
Components.utils.import("resource://gre/modules/AppConstants.jsm");
+Components.utils.import("resource://gre/modules/Services.jsm");
function AppPicker() {}
AppPicker.prototype =
{
// Class members
_incomingParams: null,
@@ -91,24 +92,20 @@ AppPicker.prototype =
document.getElementById("app-picker-notfound").removeAttribute("hidden");
}
},
/**
* Retrieve the moz-icon for the app
*/
getFileIconURL: function getFileIconURL(file) {
- var ios = Components.classes["@mozilla.org/network/io-service;1"].
- getService(Components.interfaces.nsIIOService);
-
- if (!ios) return "";
const nsIFileProtocolHandler =
Components.interfaces.nsIFileProtocolHandler;
- var fph = ios.getProtocolHandler("file")
+ var fph = Services.io.getProtocolHandler("file")
.QueryInterface(nsIFileProtocolHandler);
if (!fph) return "";
var urlSpec = fph.getURLSpecFromFile(file);
return "moz-icon://" + urlSpec + "?size=32";
},
/**
@@ -175,28 +172,26 @@ AppPicker.prototype =
appPickerBrowse: function appPickerBrowse() {
var nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes["@mozilla.org/filepicker;1"].
createInstance(nsIFilePicker);
fp.init(window, this._incomingParams.title, nsIFilePicker.modeOpen);
fp.appendFilters(nsIFilePicker.filterApps);
- var fileLoc = Components.classes["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties);
var startLocation;
if (AppConstants.platform == "win") {
startLocation = "ProgF"; // Program Files
} else if (AppConstants.platform == "macosx") {
startLocation = "LocApp"; // Local Applications
} else {
startLocation = "Home";
}
fp.displayDirectory =
- fileLoc.get(startLocation, Components.interfaces.nsIFile);
+ Services.dirsvc.get(startLocation, Components.interfaces.nsIFile);
fp.open(rv => {
if (rv == nsIFilePicker.returnOK && fp.file) {
var localHandlerApp =
Components.classes["@mozilla.org/uriloader/local-handler-app;1"].
createInstance(Components.interfaces.nsILocalHandlerApp);
localHandlerApp.executable = fp.file;
--- a/toolkit/components/asyncshutdown/AsyncShutdown.jsm
+++ b/toolkit/components/asyncshutdown/AsyncShutdown.jsm
@@ -60,19 +60,20 @@ Object.defineProperty(this, "gCrashRepor
} catch (ex) {
return this.gCrashReporter = null;
}
},
configurable: true
});
// `true` if this is a content process, `false` otherwise.
-// It would be nicer to go through `Services.appInfo`, but some tests need to be
+// It would be nicer to go through `Services.appinfo`, but some tests need to be
// able to replace that field with a custom implementation before it is first
// called.
+// eslint-disable-next-line mozilla/use-services
const isContent = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT;
// Display timeout warnings after 10 seconds
const DELAY_WARNING_MS = 10 * 1000;
// Crash the process if shutdown is really too long
// (allowing for sleep).
--- a/toolkit/components/captivedetect/test/unit/head_setprefs.js
+++ b/toolkit/components/captivedetect/test/unit/head_setprefs.js
@@ -20,23 +20,20 @@ const kPrefsCanonicalURL = "captivedetec
const kPrefsCanonicalContent = "captivedetect.canonicalContent";
const kPrefsMaxWaitingTime = "captivedetect.maxWaitingTime";
const kPrefsPollingTime = "captivedetect.pollingTime";
var gServer;
var gServerURL;
function setupPrefs() {
- let prefs = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefService)
- .QueryInterface(Components.interfaces.nsIPrefBranch);
- prefs.setCharPref(kPrefsCanonicalURL, gServerURL + kCanonicalSitePath);
- prefs.setCharPref(kPrefsCanonicalContent, kCanonicalSiteContent);
- prefs.setIntPref(kPrefsMaxWaitingTime, 0);
- prefs.setIntPref(kPrefsPollingTime, 1);
+ Services.prefs.setCharPref(kPrefsCanonicalURL, gServerURL + kCanonicalSitePath);
+ Services.prefs.setCharPref(kPrefsCanonicalContent, kCanonicalSiteContent);
+ Services.prefs.setIntPref(kPrefsMaxWaitingTime, 0);
+ Services.prefs.setIntPref(kPrefsPollingTime, 1);
}
function run_captivedetect_test(xhr_handler, fakeUIResponse, testfun) {
gServer = new HttpServer();
gServer.registerPathHandler(kCanonicalSitePath, xhr_handler);
gServer.start(-1);
gServerURL = "http://localhost:" + gServer.identity.primaryPort;
--- a/toolkit/components/contentprefs/ContentPrefService2.js
+++ b/toolkit/components/contentprefs/ContentPrefService2.js
@@ -25,20 +25,20 @@ function ContentPrefService2() {
}
// If this throws an exception, it causes the getService call to fail,
// but the next time a consumer tries to retrieve the service, we'll try
// to initialize the database again, which might work if the failure
// was due to a temporary condition (like being out of disk space).
this._dbInit();
- this._observerSvc.addObserver(this, "last-pb-context-exited");
+ Services.obs.addObserver(this, "last-pb-context-exited");
// Observe shutdown so we can shut down the database connection.
- this._observerSvc.addObserver(this, "xpcom-shutdown");
+ Services.obs.addObserver(this, "xpcom-shutdown");
}
const cache = new ContentPrefStore();
cache.set = function CPS_cache_set(group, name, val) {
Object.getPrototypeOf(this).set.apply(this, arguments);
let groupCount = this._groups.size;
if (groupCount >= CACHE_MAX_GROUP_ENTRIES) {
// Clean half of the entries
@@ -53,58 +53,35 @@ cache.set = function CPS_cache_set(group
const privModeStorage = new ContentPrefStore();
ContentPrefService2.prototype = {
// XPCOM Plumbing
classID: Components.ID("{e3f772f3-023f-4b32-b074-36cf0fd5d414}"),
- // Convenience Getters
-
- // Observer Service
- __observerSvc: null,
- get _observerSvc() {
- if (!this.__observerSvc)
- this.__observerSvc = Cc["@mozilla.org/observer-service;1"].
- getService(Ci.nsIObserverService);
- return this.__observerSvc;
- },
-
- // Preferences Service
- __prefSvc: null,
- get _prefSvc() {
- if (!this.__prefSvc)
- this.__prefSvc = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
- return this.__prefSvc;
- },
-
-
// Destruction
_destroy: function ContentPrefService__destroy() {
- this._observerSvc.removeObserver(this, "xpcom-shutdown");
- this._observerSvc.removeObserver(this, "last-pb-context-exited");
+ Services.obs.removeObserver(this, "xpcom-shutdown");
+ Services.obs.removeObserver(this, "last-pb-context-exited");
this.destroy();
this._dbConnection.asyncClose(() => {
Services.obs.notifyObservers(null, "content-prefs-db-closed");
});
// Delete references to XPCOM components to make sure we don't leak them
// (although we haven't observed leakage in tests). Also delete references
// in _observers and _genericObservers to avoid cycles with those that
// refer to us and don't remove themselves from those observer pools.
delete this._observers;
delete this._genericObservers;
delete this.__grouper;
- delete this.__observerSvc;
- delete this.__prefSvc;
},
// in-memory cache and private-browsing stores
_cache: cache,
_pbStore: privModeStorage,
@@ -1029,75 +1006,69 @@ ContentPrefService2.prototype = {
_dbConnection: null,
// _dbInit and the methods it calls (_dbCreate, _dbMigrate, and version-
// specific migration methods) must be careful not to call any method
// of the service that assumes the database connection has already been
// initialized, since it won't be initialized until at the end of _dbInit.
_dbInit: function ContentPrefService__dbInit() {
- var dirService = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties);
- var dbFile = dirService.get("ProfD", Ci.nsIFile);
+ var dbFile = Services.dirsvc.get("ProfD", Ci.nsIFile);
dbFile.append("content-prefs.sqlite");
- var dbService = Cc["@mozilla.org/storage/service;1"].
- getService(Ci.mozIStorageService);
-
var dbConnection;
if (!dbFile.exists())
- dbConnection = this._dbCreate(dbService, dbFile);
+ dbConnection = this._dbCreate(dbFile);
else {
try {
- dbConnection = dbService.openDatabase(dbFile);
+ dbConnection = Services.storage.openDatabase(dbFile);
} catch (e) {
// If the connection isn't ready after we open the database, that means
// the database has been corrupted, so we back it up and then recreate it.
if (e.result != Cr.NS_ERROR_FILE_CORRUPTED)
throw e;
- dbConnection = this._dbBackUpAndRecreate(dbService, dbFile,
- dbConnection);
+ dbConnection = this._dbBackUpAndRecreate(dbFile, dbConnection);
}
// Get the version of the schema in the file.
var version = dbConnection.schemaVersion;
// Try to migrate the schema in the database to the current schema used by
// the service. If migration fails, back up the database and recreate it.
if (version != this._dbVersion) {
try {
this._dbMigrate(dbConnection, version, this._dbVersion);
} catch (ex) {
Cu.reportError("error migrating DB: " + ex + "; backing up and recreating");
- dbConnection = this._dbBackUpAndRecreate(dbService, dbFile, dbConnection);
+ dbConnection = this._dbBackUpAndRecreate(dbFile, dbConnection);
}
}
}
// Turn off disk synchronization checking to reduce disk churn and speed up
// operations when prefs are changed rapidly (such as when a user repeatedly
// changes the value of the browser zoom setting for a site).
//
// Note: this could cause database corruption if the OS crashes or machine
// loses power before the data gets written to disk, but this is considered
// a reasonable risk for the not-so-critical data stored in this database.
//
// If you really don't want to take this risk, however, just set the
// toolkit.storage.synchronous pref to 1 (NORMAL synchronization) or 2
// (FULL synchronization), in which case mozStorageConnection::Initialize
// will use that value, and we won't override it here.
- if (!this._prefSvc.prefHasUserValue("toolkit.storage.synchronous"))
+ if (!Services.prefs.prefHasUserValue("toolkit.storage.synchronous"))
dbConnection.executeSimpleSQL("PRAGMA synchronous = OFF");
this._dbConnection = dbConnection;
},
- _dbCreate: function ContentPrefService__dbCreate(aDBService, aDBFile) {
- var dbConnection = aDBService.openDatabase(aDBFile);
+ _dbCreate: function ContentPrefService__dbCreate(aDBFile) {
+ var dbConnection = Services.storage.openDatabase(aDBFile);
try {
this._dbCreateSchema(dbConnection);
dbConnection.schemaVersion = this._dbVersion;
} catch (ex) {
// If we failed to create the database (perhaps because the disk ran out
// of space), then remove the database file so we don't leave it in some
// half-created state from which we won't know how to recover.
@@ -1125,29 +1096,28 @@ ContentPrefService2.prototype = {
let statement = `
CREATE INDEX IF NOT EXISTS ${name} ON ${index.table}
(${index.columns.join(", ")})
`;
aDBConnection.executeSimpleSQL(statement);
}
},
- _dbBackUpAndRecreate: function ContentPrefService__dbBackUpAndRecreate(aDBService,
- aDBFile,
+ _dbBackUpAndRecreate: function ContentPrefService__dbBackUpAndRecreate(aDBFile,
aDBConnection) {
- aDBService.backupDatabaseFile(aDBFile, "content-prefs.sqlite.corrupt");
+ Services.storage.backupDatabaseFile(aDBFile, "content-prefs.sqlite.corrupt");
// Close the database, ignoring the "already closed" exception, if any.
// It'll be open if we're here because of a migration failure but closed
// if we're here because of database corruption.
try { aDBConnection.close(); } catch (ex) {}
aDBFile.remove(false);
- let dbConnection = this._dbCreate(aDBService, aDBFile);
+ let dbConnection = this._dbCreate(aDBFile);
return dbConnection;
},
_dbMigrate: function ContentPrefService__dbMigrate(aDBConnection, aOldVersion, aNewVersion) {
/**
* Migrations should follow the template rules in bug 1074817 comment 3 which are:
* 1. Migration should be incremental and non-breaking.
--- a/toolkit/components/contentprefs/ContentPrefServiceChild.jsm
+++ b/toolkit/components/contentprefs/ContentPrefServiceChild.jsm
@@ -7,16 +7,17 @@
this.EXPORTED_SYMBOLS = [ "ContentPrefServiceChild" ];
const Ci = Components.interfaces;
const Cc = Components.classes;
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/ContentPrefUtils.jsm");
Cu.import("resource://gre/modules/ContentPrefStore.jsm");
// We only need one bit of information out of the context.
function contextArg(context) {
return (context && context.usePrivateBrowsing) ?
{ usePrivateBrowsing: true } :
null;
@@ -48,31 +49,28 @@ CallbackCaller.prototype = {
};
var ContentPrefServiceChild = {
QueryInterface: XPCOMUtils.generateQI([ Ci.nsIContentPrefService2 ]),
// Map from pref name -> set of observers
_observers: new Map(),
- _mm: Cc["@mozilla.org/childprocessmessagemanager;1"]
- .getService(Ci.nsIMessageSender),
-
_getRandomId() {
return Cc["@mozilla.org/uuid-generator;1"]
.getService(Ci.nsIUUIDGenerator).generateUUID().toString();
},
// Map from random ID string -> CallbackCaller, per request
_requests: new Map(),
init() {
- this._mm.addMessageListener("ContentPrefs:HandleResult", this);
- this._mm.addMessageListener("ContentPrefs:HandleError", this);
- this._mm.addMessageListener("ContentPrefs:HandleCompletion", this);
+ Services.cpmm.addMessageListener("ContentPrefs:HandleResult", this);
+ Services.cpmm.addMessageListener("ContentPrefs:HandleError", this);
+ Services.cpmm.addMessageListener("ContentPrefs:HandleCompletion", this);
},
receiveMessage(msg) {
let data = msg.data;
let callback;
switch (msg.name) {
case "ContentPrefs:HandleResult":
callback = this._requests.get(data.requestId);
@@ -103,58 +101,58 @@ var ContentPrefServiceChild = {
}
}
},
_callFunction(call, args, callback) {
let requestId = this._getRandomId();
let data = { call, args, requestId };
- this._mm.sendAsyncMessage("ContentPrefs:FunctionCall", data);
+ Services.cpmm.sendAsyncMessage("ContentPrefs:FunctionCall", data);
this._requests.set(requestId, new CallbackCaller(callback));
},
getCachedByDomainAndName: NYI,
getCachedBySubdomainAndName: NYI,
getCachedGlobal: NYI,
addObserverForName(name, observer) {
let set = this._observers.get(name);
if (!set) {
set = new Set();
if (this._observers.size === 0) {
// This is the first observer of any kind. Start listening for changes.
- this._mm.addMessageListener("ContentPrefs:NotifyObservers", this);
+ Services.cpmm.addMessageListener("ContentPrefs:NotifyObservers", this);
}
// This is the first observer for this name. Start listening for changes
// to it.
- this._mm.sendAsyncMessage("ContentPrefs:AddObserverForName", { name });
+ Services.cpmm.sendAsyncMessage("ContentPrefs:AddObserverForName", { name });
this._observers.set(name, set);
}
set.add(observer);
},
removeObserverForName(name, observer) {
let set = this._observers.get(name);
if (!set)
return;
set.delete(observer);
if (set.size === 0) {
// This was the last observer for this name. Stop listening for changes.
- this._mm.sendAsyncMessage("ContentPrefs:RemoveObserverForName", { name });
+ Services.cpmm.sendAsyncMessage("ContentPrefs:RemoveObserverForName", { name });
this._observers.delete(name);
if (this._observers.size === 0) {
// This was the last observer for this process. Stop listing for all
// changes.
- this._mm.removeMessageListener("ContentPrefs:NotifyObservers", this);
+ Services.cpmm.removeMessageListener("ContentPrefs:NotifyObservers", this);
}
}
},
extractDomain: NYI
};
function forwardMethodToParent(method, signature, ...args) {
--- a/toolkit/components/contentprefs/tests/unit_cps2/AsyncRunner.jsm
+++ b/toolkit/components/contentprefs/tests/unit_cps2/AsyncRunner.jsm
@@ -1,26 +1,26 @@
/* 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 EXPORTED_SYMBOLS = [
"AsyncRunner",
];
-const { interfaces: Ci, classes: Cc } = Components;
+const { interfaces: Ci, classes: Cc, utils: Cu } = Components;
+
+Cu.import("resource://gre/modules/Services.jsm");
function AsyncRunner(callbacks) {
this._callbacks = callbacks;
this._iteratorQueue = [];
// This catches errors reported to the console, e.g., via Cu.reportError.
- Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService).
- registerListener(this);
+ Services.console.registerListener(this);
}
AsyncRunner.prototype = {
appendIterator: function AR_appendIterator(iter) {
this._iteratorQueue.push(iter);
},
@@ -47,19 +47,17 @@ AsyncRunner.prototype = {
if (value) {
if (typeof(value) != "boolean")
this._iteratorQueue.unshift(value);
this.next();
}
},
destroy: function AR_destroy() {
- Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService).
- unregisterListener(this);
+ Services.console.unregisterListener(this);
this.destroy = function AR_alreadyDestroyed() {};
},
observe: function AR_consoleServiceListener(msg) {
if (msg instanceof Ci.nsIScriptError &&
!(msg.flags & Ci.nsIScriptError.warningFlag)) {
this._callbacks.consoleError(msg);
}
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_migrationToSchema4.js
+++ b/toolkit/components/contentprefs/tests/unit_cps2/test_migrationToSchema4.js
@@ -21,27 +21,22 @@ BEGIN TRANSACTION;
INSERT INTO "prefs" VALUES(4,NULL,1,0.1);
CREATE INDEX groups_idx ON groups(name);
CREATE INDEX settings_idx ON settings(name);
CREATE INDEX prefs_idx ON prefs(groupID, settingID);
COMMIT;`;
function prepareVersion3Schema(callback) {
- var dirService = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties);
-
- var dbFile = dirService.get("ProfD", Ci.nsIFile);
+ var dbFile = Services.dirsvc.get("ProfD", Ci.nsIFile);
dbFile.append("content-prefs.sqlite");
- var dbService = Cc["@mozilla.org/storage/service;1"].
- getService(Ci.mozIStorageService);
ok(!dbFile.exists(), "Db should not exist yet.");
- var dbConnection = dbService.openDatabase(dbFile);
+ var dbConnection = Services.storage.openDatabase(dbFile);
equal(dbConnection.schemaVersion, 0);
dbConnection.executeSimpleSQL(schema_version3);
dbConnection.schemaVersion = 3;
dbConnection.close();
}
--- a/toolkit/components/ctypes/tests/unit/head.js
+++ b/toolkit/components/ctypes/tests/unit/head.js
@@ -1,10 +1,12 @@
/* global ThreadSafeChromeUtils */
+Components.utils.import("resource://gre/modules/Services.jsm");
+
try {
// We might be running without privileges, in which case it's up to the
// harness to give us the 'ctypes' object.
Components.utils.import("resource://gre/modules/ctypes.jsm");
} catch (e) {
}
function open_ctypes_test_lib() {
@@ -123,10 +125,10 @@ function must_throw(f, expected) {
do_check_eq(x.toString(), expected);
}
has_thrown = true;
}
do_check_true(has_thrown);
}
function get_os() {
- return Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).OS;
+ return Services.appinfo.OS;
}
--- a/toolkit/components/extensions/ExtensionCommon.jsm
+++ b/toolkit/components/extensions/ExtensionCommon.jsm
@@ -1647,19 +1647,17 @@ function ignoreEvent(context, name) {
let id = context.extension.id;
let frame = Components.stack.caller;
let msg = `In add-on ${id}, attempting to use listener "${name}", which is unimplemented.`;
let scriptError = Cc["@mozilla.org/scripterror;1"]
.createInstance(Ci.nsIScriptError);
scriptError.init(msg, frame.filename, null, frame.lineNumber,
frame.columnNumber, Ci.nsIScriptError.warningFlag,
"content javascript");
- let consoleService = Cc["@mozilla.org/consoleservice;1"]
- .getService(Ci.nsIConsoleService);
- consoleService.logMessage(scriptError);
+ Services.console.logMessage(scriptError);
},
removeListener: function(callback) {},
hasListener: function(callback) {},
};
}
const stylesheetMap = new DefaultMap(url => {
--- a/toolkit/components/extensions/ExtensionUtils.jsm
+++ b/toolkit/components/extensions/ExtensionUtils.jsm
@@ -20,16 +20,20 @@ function getConsole() {
return new ConsoleAPI({
maxLogLevelPref: "extensions.webextensions.log.level",
prefix: "WebExtensions",
});
}
XPCOMUtils.defineLazyGetter(this, "console", getConsole);
+// It would be nicer to go through `Services.appinfo`, but some tests need to be
+// able to replace that field with a custom implementation before it is first
+// called.
+// eslint-disable-next-line mozilla/use-services
const appinfo = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
let nextId = 0;
const uniqueProcessID = appinfo.uniqueProcessID;
// Store the process ID in a 16 bit field left shifted to end of a
// double's mantissa.
// Note: We can't use bitwise ops here, since they truncate to a 32 bit
// integer and we need all 53 mantissa bits.
--- a/toolkit/components/extensions/ext-management.js
+++ b/toolkit/components/extensions/ext-management.js
@@ -1,18 +1,17 @@
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
"use strict";
// The ext-* files are imported into the same scopes.
/* import-globals-from ext-toolkit.js */
XPCOMUtils.defineLazyGetter(this, "strBundle", function() {
- const stringSvc = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
- return stringSvc.createBundle("chrome://global/locale/extensions.properties");
+ return Services.strings.createBundle("chrome://global/locale/extensions.properties");
});
XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
"resource://gre/modules/AddonManager.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "promptService",
"@mozilla.org/embedcomp/prompt-service;1",
"nsIPromptService");
XPCOMUtils.defineLazyGetter(this, "GlobalManager", () => {
--- a/toolkit/components/extensions/extension-process-script.js
+++ b/toolkit/components/extensions/extension-process-script.js
@@ -28,16 +28,17 @@ XPCOMUtils.defineLazyGetter(this, "conso
const {
DefaultWeakMap,
getInnerWindowID,
} = ExtensionUtils;
// We need to avoid touching Services.appinfo here in order to prevent
// the wrong version from being cached during xpcshell test startup.
+// eslint-disable-next-line mozilla/use-services
const appinfo = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
const isContentProcess = appinfo.processType == appinfo.PROCESS_TYPE_CONTENT;
function parseScriptOptions(options) {
return {
allFrames: options.all_frames,
matchAboutBlank: options.match_about_blank,
frameID: options.frame_id,
--- a/toolkit/components/extensions/test/mochitest/test_ext_webrequest_filter.html
+++ b/toolkit/components/extensions/test/mochitest/test_ext_webrequest_filter.html
@@ -15,19 +15,17 @@
if (AppConstants.platform === "android") {
SimpleTest.requestLongerTimeout(6);
}
let windowData, testWindow;
add_task(async function setup() {
let chromeScript = SpecialPowers.loadChromeScript(function() {
- let cache = Components.classes["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Components.interfaces.nsICacheStorageService);
- cache.clear();
+ Services.cache2.clear();
});
chromeScript.destroy();
testWindow = window.open("about:blank", "_blank", "width=100,height=100");
await waitForLoad(testWindow);
// Fetch the windowId and tabId we need to filter with WebRequest.
let extension = ExtensionTestUtils.loadExtension({
--- a/toolkit/components/extensions/test/xpcshell/head.js
+++ b/toolkit/components/extensions/test/xpcshell/head.js
@@ -63,19 +63,17 @@ function createHttpServer(port = -1) {
if (AppConstants.platform === "android") {
Services.io.offline = true;
}
/**
* Clears the HTTP and content image caches.
*/
function clearCache() {
- let cache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Ci.nsICacheStorageService);
- cache.clear();
+ Services.cache2.clear();
let imageCache = Cc["@mozilla.org/image/tools;1"]
.getService(Ci.imgITools)
.getImgCacheForDocument(null);
imageCache.clearCache(false);
}
var promiseConsoleOutput = async function(task) {
--- a/toolkit/components/feeds/FeedProcessor.js
+++ b/toolkit/components/feeds/FeedProcessor.js
@@ -4,18 +4,20 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function LOG(str) {
dump("*** " + str + "\n");
}
const Ci = Components.interfaces;
const Cc = Components.classes;
+const Cu = Components.utils;
const Cr = Components.results;
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
const FP_CONTRACTID = "@mozilla.org/feed-processor;1";
const FP_CLASSID = Components.ID("{26acb1f0-28fc-43bc-867a-a46aabc85dd4}");
const FP_CLASSNAME = "Feed Processor";
const FR_CONTRACTID = "@mozilla.org/feed-result;1";
const FR_CLASSID = Components.ID("{072a5c3d-30c6-4f07-b87f-9f63d51403f2}");
const FR_CLASSNAME = "Feed Result";
const FEED_CONTRACTID = "@mozilla.org/feed;1";
@@ -38,28 +40,25 @@ const PERSON_CLASSNAME = "Feed Person";
const IO_CONTRACTID = "@mozilla.org/network/io-service;1";
const BAG_CONTRACTID = "@mozilla.org/hash-property-bag;1";
const ARRAY_CONTRACTID = "@mozilla.org/array;1";
const SAX_CONTRACTID = "@mozilla.org/saxparser/xmlreader;1";
const PARSERUTILS_CONTRACTID = "@mozilla.org/parserutils;1";
const gMimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
-var gIoService = null;
const XMLNS = "http://www.w3.org/XML/1998/namespace";
const RSS090NS = "http://my.netscape.com/rdf/simple/0.9/";
/** *** Some general utils *****/
function strToURI(link, base) {
base = base || null;
- if (!gIoService)
- gIoService = Cc[IO_CONTRACTID].getService(Ci.nsIIOService);
try {
- return gIoService.newURI(link, null, base);
+ return Services.io.newURI(link, null, base);
} catch (e) {
return null;
}
}
function isArray(a) {
return isObject(a) && a.constructor == Array;
}
--- a/toolkit/components/filepicker/content/filepicker.js
+++ b/toolkit/components/filepicker/content/filepicker.js
@@ -8,17 +8,20 @@ const nsIFilePicker = Components.i
const nsIProperties = Components.interfaces.nsIProperties;
const NS_DIRECTORYSERVICE_CONTRACTID = "@mozilla.org/file/directory_service;1";
const NS_IOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
const nsIFileView = Components.interfaces.nsIFileView;
const NS_FILEVIEW_CONTRACTID = "@mozilla.org/filepicker/fileview;1";
const nsITreeView = Components.interfaces.nsITreeView;
const nsIFile = Components.interfaces.nsIFile;
const NS_LOCAL_FILE_CONTRACTID = "@mozilla.org/file/local;1";
-const NS_PROMPTSERVICE_CONTRACTID = "@mozilla.org/embedcomp/prompt-service;1";
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+Cu.import("resource://gre/modules/Services.jsm");
var sfile = Components.classes[NS_LOCAL_FILE_CONTRACTID].createInstance(nsIFile);
var retvals;
var filePickerMode;
var homeDir;
var treeView;
var allowURLs;
@@ -169,44 +172,40 @@ function changeFilter(filterTypes) {
window.setCursor("auto");
}
function showErrorDialog(titleStrName, messageStrName, file) {
var errorTitle =
gFilePickerBundle.getFormattedString(titleStrName, [file.path]);
var errorMessage =
gFilePickerBundle.getFormattedString(messageStrName, [file.path]);
- var promptService =
- Components.classes[NS_PROMPTSERVICE_CONTRACTID].getService(Components.interfaces.nsIPromptService);
-
- promptService.alert(window, errorTitle, errorMessage);
+ Services.prompt.alert(window, errorTitle, errorMessage);
}
function openOnOK() {
var dir = treeView.selectedFiles.queryElementAt(0, nsIFile);
if (dir)
gotoDirectory(dir);
return false;
}
function selectOnOK() {
- var errorTitle, errorMessage, promptService;
+ var errorTitle, errorMessage;
var ret = nsIFilePicker.returnOK;
var isDir = false;
var isFile = false;
retvals.filterIndex = document.getElementById("filterMenuList").selectedIndex;
retvals.fileURL = null;
if (allowURLs) {
try {
- var ios = Components.classes[NS_IOSERVICE_CONTRACTID].getService(Components.interfaces.nsIIOService);
- retvals.fileURL = ios.newURI(textInput.value);
+ retvals.fileURL = Services.io.newURI(textInput.value);
let fileList = [];
if (retvals.fileURL instanceof Components.interfaces.nsIFileURL)
fileList.push(retvals.fileURL.file);
gFilesEnumerator.mFiles = fileList;
retvals.files = gFilesEnumerator;
retvals.buttonStatus = ret;
return true;
@@ -229,17 +228,17 @@ function selectOnOK() {
var file = fileList[curFileIndex].QueryInterface(nsIFile);
// try to normalize - if this fails we will ignore the error
// because we will notice the
// error later and show a fitting error alert.
try {
file.normalize();
} catch (e) {
- // promptService.alert(window, "Problem", "normalize failed, continuing");
+ // Services.prompt.alert(window, "Problem", "normalize failed, continuing");
}
var fileExists = file.exists();
if (!fileExists && (filePickerMode == nsIFilePicker.modeOpen ||
filePickerMode == nsIFilePicker.modeOpenMultiple)) {
showErrorDialog("errorOpenFileDoesntExistTitle",
"errorOpenFileDoesntExistMessage",
@@ -289,18 +288,17 @@ function selectOnOK() {
ret = nsIFilePicker.returnCancel;
} else {
// we need to pop up a dialog asking if you want to save
var confirmTitle = gFilePickerBundle.getString("confirmTitle");
var message =
gFilePickerBundle.getFormattedString("confirmFileReplacing",
[file.path]);
- promptService = Components.classes[NS_PROMPTSERVICE_CONTRACTID].getService(Components.interfaces.nsIPromptService);
- var rv = promptService.confirm(window, confirmTitle, message);
+ var rv = Services.prompt.confirm(window, confirmTitle, message);
if (rv) {
ret = nsIFilePicker.returnReplace;
retvals.directory = file.parent.path;
} else {
ret = nsIFilePicker.returnCancel;
}
}
} else if (isDir) {
@@ -331,18 +329,17 @@ function selectOnOK() {
errorMessage =
gFilePickerBundle.getFormattedString("saveParentDoesntExistMessage",
[oldParent.path, file.path]);
}
if (!parent.isWritable()) {
errorMessage =
gFilePickerBundle.getFormattedString("saveWithoutPermissionMessage_dir", [parent.path]);
}
- promptService = Components.classes[NS_PROMPTSERVICE_CONTRACTID].getService(Components.interfaces.nsIPromptService);
- promptService.alert(window, errorTitle, errorMessage);
+ Services.prompt.alert(window, errorTitle, errorMessage);
ret = nsIFilePicker.returnCancel;
}
}
break;
case nsIFilePicker.modeGetFolder:
if (isDir) {
retvals.directory = file.parent.path;
} else { // if nothing selected, the current directory will be fine
@@ -619,23 +616,21 @@ function goUp() {
}
function goHome() {
gotoDirectory(homeDir);
}
function newDir() {
var file;
- var promptService =
- Components.classes[NS_PROMPTSERVICE_CONTRACTID].getService(Components.interfaces.nsIPromptService);
var dialogTitle =
gFilePickerBundle.getString("promptNewDirTitle");
var dialogMsg =
gFilePickerBundle.getString("promptNewDirMessage");
- var ret = promptService.prompt(window, dialogTitle, dialogMsg, gNewDirName, null, {value: 0});
+ var ret = Services.prompt.prompt(window, dialogTitle, dialogMsg, gNewDirName, null, {value: 0});
if (ret) {
file = processPath(gNewDirName.value);
if (!file) {
showErrorDialog("errorCreateNewDirTitle",
"errorCreateNewDirMessage",
file);
return false;
--- a/toolkit/components/filepicker/nsFilePicker.js
+++ b/toolkit/components/filepicker/nsFilePicker.js
@@ -13,16 +13,17 @@
* In JS, you can actually cheat, because a thrown exception will cause the
* CreateInstance call to fail in turn, but not all languages are so lucky.
* (Though ANSI C++ provides exceptions, they are verboten in Mozilla code
* for portability reasons -- and even when you're building completely
* platform-specific code, you can't throw across an XPCOM method boundary.)
*/
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+Components.utils.import("resource://gre/modules/Services.jsm");
const DEBUG = false; /* set to true to enable debug messages */
var debug;
const LOCAL_FILE_CONTRACTID = "@mozilla.org/file/local;1";
const APPSHELL_SERV_CONTRACTID = "@mozilla.org/appshell/appShellService;1";
const STRBUNDLE_SERV_CONTRACTID = "@mozilla.org/intl/stringbundle;1";
@@ -119,20 +120,17 @@ nsFilePicker.prototype = {
/* readonly attribute nsIURI fileURL; */
get fileURL() {
if (this.mFileURL)
return this.mFileURL;
if (!this.mFilesEnumerator)
return null;
- var ioService = Components.classes["@mozilla.org/network/io-service;1"]
- .getService(Components.interfaces.nsIIOService);
-
- return this.mFileURL = ioService.newFileURI(this.file);
+ return this.mFileURL = Services.io.newFileURI(this.file);
},
/* attribute wstring defaultString; */
set defaultString(a) { this.mDefaultString = a; },
get defaultString() { return this.mDefaultString; },
/* attribute wstring defaultExtension */
set defaultExtension(ext) { },
@@ -203,19 +201,17 @@ nsFilePicker.prototype = {
},
appendFilter(title, extensions) {
this.mFilterTitles.push(title);
this.mFilters.push(extensions);
},
open(aFilePickerShownCallback) {
- var tm = Components.classes["@mozilla.org/thread-manager;1"]
- .getService(Components.interfaces.nsIThreadManager);
- tm.dispatchToMainThread(() => {
+ Services.tm.dispatchToMainThread(() => {
let result = Components.interfaces.nsIFilePicker.returnCancel;
try {
result = this.show();
} catch (ex) {
}
let promises = [];
--- a/toolkit/components/mozintl/mozIntl.js
+++ b/toolkit/components/mozintl/mozIntl.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/. */
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+Components.utils.import("resource://gre/modules/Services.jsm");
const Cc = Components.classes;
const Ci = Components.interfaces;
const mozIntlHelper =
Cc["@mozilla.org/mozintlhelper;1"].getService(Ci.mozIMozIntlHelper);
-const localeSvc =
- Cc["@mozilla.org/intl/localeservice;1"].getService(Ci.mozILocaleService);
const osPrefs =
Cc["@mozilla.org/intl/ospreferences;1"].getService(Ci.mozIOSPreferences);
/**
* This helper function retrives currently used app locales, allowing
* all mozIntl APIs to use the current regional prefs locales unless
* called with explicitly listed locales.
*/
function getLocales(locales) {
if (!locales) {
- return localeSvc.getRegionalPrefsLocales();
+ return Services.locale.getRegionalPrefsLocales();
}
return locales;
}
function getDateTimePatternStyle(option) {
switch (option) {
case "full":
return osPrefs.dateTimeFormatStyleFull;
--- a/toolkit/components/mozintl/test/test_mozintl.js
+++ b/toolkit/components/mozintl/test/test_mozintl.js
@@ -1,27 +1,26 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
+Components.utils.import("resource://gre/modules/Services.jsm");
+
function run_test() {
- const mozIntl = Components.classes["@mozilla.org/mozintl;1"]
- .getService(Components.interfaces.mozIMozIntl);
-
- test_methods_presence(mozIntl);
- test_methods_calling(mozIntl);
+ test_methods_presence();
+ test_methods_calling();
ok(true);
}
-function test_methods_presence(mozIntl) {
- equal(mozIntl.getCalendarInfo instanceof Function, true);
- equal(mozIntl.getDisplayNames instanceof Function, true);
- equal(mozIntl.getLocaleInfo instanceof Function, true);
- equal(mozIntl.createDateTimeFormat instanceof Function, true);
+function test_methods_presence() {
+ equal(Services.intl.getCalendarInfo instanceof Function, true);
+ equal(Services.intl.getDisplayNames instanceof Function, true);
+ equal(Services.intl.getLocaleInfo instanceof Function, true);
+ equal(Services.intl.createDateTimeFormat instanceof Function, true);
}
-function test_methods_calling(mozIntl) {
- mozIntl.getCalendarInfo("pl");
- mozIntl.getDisplayNames("ar");
- mozIntl.getLocaleInfo("de");
- mozIntl.createDateTimeFormat("fr");
+function test_methods_calling() {
+ Services.intl.getCalendarInfo("pl");
+ Services.intl.getDisplayNames("ar");
+ Services.intl.getLocaleInfo("de");
+ Services.intl.createDateTimeFormat("fr");
ok(true);
}
--- a/toolkit/components/nsDefaultCLH.js
+++ b/toolkit/components/nsDefaultCLH.js
@@ -1,13 +1,14 @@
/* 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/. */
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+Components.utils.import("resource://gre/modules/Services.jsm");
const nsISupports = Components.interfaces.nsISupports;
const nsICommandLine = Components.interfaces.nsICommandLine;
const nsICommandLineHandler = Components.interfaces.nsICommandLineHandler;
const nsIPrefBranch = Components.interfaces.nsIPrefBranch;
const nsISupportsString = Components.interfaces.nsISupportsString;
const nsIWindowWatcher = Components.interfaces.nsIWindowWatcher;
@@ -80,21 +81,18 @@ nsDefaultCLH.prototype = {
return;
var prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(nsIPrefBranch);
try {
var singletonWindowType =
prefs.getCharPref("toolkit.singletonWindowType");
- var windowMediator =
- Components.classes["@mozilla.org/appshell/window-mediator;1"]
- .getService(Components.interfaces.nsIWindowMediator);
- var win = windowMediator.getMostRecentWindow(singletonWindowType);
+ var win = Services.wm.getMostRecentWindow(singletonWindowType);
if (win) {
win.focus();
cmdLine.preventDefault = true;
return;
}
} catch (e) { }
// if the pref is missing, ignore the exception
--- a/toolkit/components/osfile/modules/osfile_async_front.jsm
+++ b/toolkit/components/osfile/modules/osfile_async_front.jsm
@@ -1419,19 +1419,20 @@ this.OS.Path = Path;
// Returns a resolved promise when all the queued operation have been completed.
Object.defineProperty(OS.File, "queue", {
get() {
return Scheduler.queue;
}
});
// `true` if this is a content process, `false` otherwise.
-// It would be nicer to go through `Services.appInfo`, but some tests need to be
+// It would be nicer to go through `Services.appinfo`, but some tests need to be
// able to replace that field with a custom implementation before it is first
// called.
+// eslint-disable-next-line mozilla/use-services
const isContent = Components.classes["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT;
/**
* Shutdown barriers, to let clients register to be informed during shutdown.
*/
var Barriers = {
shutdown: new AsyncShutdown.Barrier("OS.File: Waiting for clients before full shutdown"),
/**
--- a/toolkit/components/reputationservice/test/unit/head_download_manager.js
+++ b/toolkit/components/reputationservice/test/unit/head_download_manager.js
@@ -11,13 +11,11 @@ var Cr = Components.results;
do_get_profile();
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://testing-common/httpd.js");
function createURI(aObj) {
- var ios = Cc["@mozilla.org/network/io-service;1"].
- getService(Ci.nsIIOService);
- return (aObj instanceof Ci.nsIFile) ? ios.newFileURI(aObj) :
- ios.newURI(aObj);
+ return (aObj instanceof Ci.nsIFile) ? Services.io.newFileURI(aObj) :
+ Services.io.newURI(aObj);
}
--- a/toolkit/modules/Services.jsm
+++ b/toolkit/modules/Services.jsm
@@ -1,12 +1,14 @@
/* 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/. */
+/* eslint mozilla/use-services:off */
+
this.EXPORTED_SYMBOLS = ["Services"];
const Ci = Components.interfaces;
const Cc = Components.classes;
const Cr = Components.results;
Components.utils.import("resource://gre/modules/AppConstants.jsm");
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");