Bug 1729460 - Change users of defineLazyServiceGetter(s) to use Services.* where appropriate. r=mossop,webdriver-reviewers,extension-reviewers,whimboo,robwu

Differential Revision: https://phabricator.services.mozilla.com/D124838
This commit is contained in:
Mark Banner 2021-09-10 12:09:49 +00:00
parent ba14a8c91c
commit 14aedbb785
63 changed files with 361 additions and 625 deletions

View file

@ -13,10 +13,6 @@ ChromeUtils.defineModuleGetter(
"resource://gre/modules/PromiseUtils.jsm" "resource://gre/modules/PromiseUtils.jsm"
); );
XPCOMUtils.defineLazyServiceGetters(this, {
uuidGen: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
// Various tests in this directory may define gTestBrowser, to use as the // Various tests in this directory may define gTestBrowser, to use as the
// default browser under test in some of the functions below. // default browser under test in some of the functions below.
/* global gTestBrowser:true */ /* global gTestBrowser:true */

View file

@ -31,13 +31,6 @@ XPCOMUtils.defineLazyGetter(this, "gWidgetsBundle", function() {
return Services.strings.createBundle(kUrl); return Services.strings.createBundle(kUrl);
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"gELS",
"@mozilla.org/eventlistenerservice;1",
"nsIEventListenerService"
);
XPCOMUtils.defineLazyPreferenceGetter( XPCOMUtils.defineLazyPreferenceGetter(
this, this,
"gBookmarksToolbar2h2020", "gBookmarksToolbar2h2020",
@ -1188,8 +1181,8 @@ var CustomizableUIInternal = {
}, },
addPanelCloseListeners(aPanel) { addPanelCloseListeners(aPanel) {
gELS.addSystemEventListener(aPanel, "click", this, false); Services.els.addSystemEventListener(aPanel, "click", this, false);
gELS.addSystemEventListener(aPanel, "keypress", this, false); Services.els.addSystemEventListener(aPanel, "keypress", this, false);
let win = aPanel.ownerGlobal; let win = aPanel.ownerGlobal;
if (!gPanelsForWindow.has(win)) { if (!gPanelsForWindow.has(win)) {
gPanelsForWindow.set(win, new Set()); gPanelsForWindow.set(win, new Set());
@ -1198,8 +1191,8 @@ var CustomizableUIInternal = {
}, },
removePanelCloseListeners(aPanel) { removePanelCloseListeners(aPanel) {
gELS.removeSystemEventListener(aPanel, "click", this, false); Services.els.removeSystemEventListener(aPanel, "click", this, false);
gELS.removeSystemEventListener(aPanel, "keypress", this, false); Services.els.removeSystemEventListener(aPanel, "keypress", this, false);
let win = aPanel.ownerGlobal; let win = aPanel.ownerGlobal;
let panels = gPanelsForWindow.get(win); let panels = gPanelsForWindow.get(win);
if (panels) { if (panels) {
@ -5090,7 +5083,7 @@ OverflowableToolbar.prototype = {
let mainViewId = multiview.getAttribute("mainViewId"); let mainViewId = multiview.getAttribute("mainViewId");
let mainView = doc.getElementById(mainViewId); let mainView = doc.getElementById(mainViewId);
let contextMenu = doc.getElementById(mainView.getAttribute("context")); let contextMenu = doc.getElementById(mainView.getAttribute("context"));
gELS.addSystemEventListener(contextMenu, "command", this, true); Services.els.addSystemEventListener(contextMenu, "command", this, true);
let anchor = this._chevron.icon; let anchor = this._chevron.icon;
let popupshown = false; let popupshown = false;
@ -5170,7 +5163,12 @@ OverflowableToolbar.prototype = {
let contextMenuId = this._panel.getAttribute("context"); let contextMenuId = this._panel.getAttribute("context");
if (contextMenuId) { if (contextMenuId) {
let contextMenu = doc.getElementById(contextMenuId); let contextMenu = doc.getElementById(contextMenuId);
gELS.removeSystemEventListener(contextMenu, "command", this, true); Services.els.removeSystemEventListener(
contextMenu,
"command",
this,
true
);
} }
}, },

View file

@ -51,13 +51,6 @@ XPCOMUtils.defineLazyServiceGetter(
"nsIDNSService" "nsIDNSService"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"gUUIDGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
// The canonical domain whose subdomains we will be resolving. // The canonical domain whose subdomains we will be resolving.
XPCOMUtils.defineLazyPreferenceGetter( XPCOMUtils.defineLazyPreferenceGetter(
this, this,
@ -94,7 +87,7 @@ XPCOMUtils.defineLazyPreferenceGetter(
); );
function getRandomSubdomain() { function getRandomSubdomain() {
let uuid = gUUIDGenerator let uuid = Services.uuid
.generateUUID() .generateUUID()
.toString() .toString()
.slice(1, -1); // Discard surrounding braces .slice(1, -1); // Discard surrounding braces

View file

@ -2,13 +2,6 @@
/* vim: set sts=2 sw=2 et tw=80: */ /* vim: set sts=2 sw=2 et tw=80: */
"use strict"; "use strict";
XPCOMUtils.defineLazyServiceGetter(
this,
"loginManager",
"@mozilla.org/login-manager;1",
"nsILoginManager"
);
const REFERENCE_DATE = Date.now(); const REFERENCE_DATE = Date.now();
const LOGIN_USERNAME = "username"; const LOGIN_USERNAME = "username";
const LOGIN_PASSWORD = "password"; const LOGIN_PASSWORD = "password";
@ -17,7 +10,7 @@ const NEW_HOST = "http://mozilla.com";
const FXA_HOST = "chrome://FirefoxAccounts"; const FXA_HOST = "chrome://FirefoxAccounts";
function checkLoginExists(host, shouldExist) { function checkLoginExists(host, shouldExist) {
let logins = loginManager.findLogins(host, "", null); let logins = Services.logins.findLogins(host, "", null);
equal( equal(
logins.length, logins.length,
shouldExist ? 1 : 0, shouldExist ? 1 : 0,
@ -33,12 +26,12 @@ function addLogin(host, timestamp) {
login.init(host, "", null, LOGIN_USERNAME, LOGIN_PASSWORD); login.init(host, "", null, LOGIN_USERNAME, LOGIN_PASSWORD);
login.QueryInterface(Ci.nsILoginMetaInfo); login.QueryInterface(Ci.nsILoginMetaInfo);
login.timePasswordChanged = timestamp; login.timePasswordChanged = timestamp;
loginManager.addLogin(login); Services.logins.addLogin(login);
checkLoginExists(host, true); checkLoginExists(host, true);
} }
async function setupPasswords() { async function setupPasswords() {
loginManager.removeAllUserFacingLogins(); Services.logins.removeAllUserFacingLogins();
addLogin(FXA_HOST, REFERENCE_DATE); addLogin(FXA_HOST, REFERENCE_DATE);
addLogin(NEW_HOST, REFERENCE_DATE); addLogin(NEW_HOST, REFERENCE_DATE);
addLogin(OLD_HOST, REFERENCE_DATE - 10000); addLogin(OLD_HOST, REFERENCE_DATE - 10000);

View file

@ -15,9 +15,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
TelemetrySession: "resource://gre/modules/TelemetrySession.jsm", TelemetrySession: "resource://gre/modules/TelemetrySession.jsm",
AttributionCode: "resource:///modules/AttributionCode.jsm", AttributionCode: "resource:///modules/AttributionCode.jsm",
}); });
XPCOMUtils.defineLazyServiceGetters(this, {
gUUIDGenerator: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
XPCOMUtils.defineLazyPreferenceGetter( XPCOMUtils.defineLazyPreferenceGetter(
this, this,
"structuredIngestionEndpointBase", "structuredIngestionEndpointBase",
@ -58,8 +55,8 @@ class AboutWelcomeTelemetry {
} }
_generateStructuredIngestionEndpoint() { _generateStructuredIngestionEndpoint() {
const uuid = gUUIDGenerator.generateUUID().toString(); const uuid = Services.uuid.generateUUID().toString();
// Structured Ingestion does not support the UUID generated by gUUIDGenerator, // Structured Ingestion does not support the UUID generated by Services.uuid,
// because it contains leading and trailing braces. Need to trim them first. // because it contains leading and trailing braces. Need to trim them first.
const docID = uuid.slice(1, -1); const docID = uuid.slice(1, -1);
const extension = `${STRUCTURED_INGESTION_NAMESPACE_MS}/${PING_TYPE}/${PING_VERSION}/${docID}`; const extension = `${STRUCTURED_INGESTION_NAMESPACE_MS}/${PING_TYPE}/${PING_VERSION}/${docID}`;

View file

@ -38,9 +38,6 @@ ChromeUtils.defineModuleGetter(
"PersistentCache", "PersistentCache",
"resource://activity-stream/lib/PersistentCache.jsm" "resource://activity-stream/lib/PersistentCache.jsm"
); );
XPCOMUtils.defineLazyServiceGetters(this, {
gUUIDGenerator: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
const CACHE_KEY = "discovery_stream"; const CACHE_KEY = "discovery_stream";
const LAYOUT_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes const LAYOUT_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes
@ -93,7 +90,7 @@ this.DiscoveryStreamFeed = class DiscoveryStreamFeed {
getOrCreateImpressionId() { getOrCreateImpressionId() {
let impressionId = Services.prefs.getCharPref(PREF_IMPRESSION_ID, ""); let impressionId = Services.prefs.getCharPref(PREF_IMPRESSION_ID, "");
if (!impressionId) { if (!impressionId) {
impressionId = String(gUUIDGenerator.generateUUID()); impressionId = String(Services.uuid.generateUUID());
Services.prefs.setCharPref(PREF_IMPRESSION_ID, impressionId); Services.prefs.setCharPref(PREF_IMPRESSION_ID, impressionId);
} }
return impressionId; return impressionId;

View file

@ -69,10 +69,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
TelemetrySession: "resource://gre/modules/TelemetrySession.jsm", TelemetrySession: "resource://gre/modules/TelemetrySession.jsm",
}); });
XPCOMUtils.defineLazyServiceGetters(this, {
gUUIDGenerator: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
const ACTIVITY_STREAM_ID = "activity-stream"; const ACTIVITY_STREAM_ID = "activity-stream";
const DOMWINDOW_OPENED_TOPIC = "domwindowopened"; const DOMWINDOW_OPENED_TOPIC = "domwindowopened";
const DOMWINDOW_UNLOAD_TOPIC = "unload"; const DOMWINDOW_UNLOAD_TOPIC = "unload";
@ -126,7 +122,7 @@ const CONTEXT_ID_PREF = "browser.contextual-services.contextId";
XPCOMUtils.defineLazyGetter(this, "contextId", () => { XPCOMUtils.defineLazyGetter(this, "contextId", () => {
let _contextId = Services.prefs.getStringPref(CONTEXT_ID_PREF, null); let _contextId = Services.prefs.getStringPref(CONTEXT_ID_PREF, null);
if (!_contextId) { if (!_contextId) {
_contextId = String(gUUIDGenerator.generateUUID()); _contextId = String(Services.uuid.generateUUID());
Services.prefs.setStringPref(CONTEXT_ID_PREF, _contextId); Services.prefs.setStringPref(CONTEXT_ID_PREF, _contextId);
} }
return _contextId; return _contextId;
@ -246,7 +242,7 @@ this.TelemetryFeed = class TelemetryFeed {
getOrCreateImpressionId() { getOrCreateImpressionId() {
let impressionId = this._prefs.get(PREF_IMPRESSION_ID); let impressionId = this._prefs.get(PREF_IMPRESSION_ID);
if (!impressionId) { if (!impressionId) {
impressionId = String(gUUIDGenerator.generateUUID()); impressionId = String(Services.uuid.generateUUID());
this._prefs.set(PREF_IMPRESSION_ID, impressionId); this._prefs.set(PREF_IMPRESSION_ID, impressionId);
} }
return impressionId; return impressionId;
@ -389,7 +385,7 @@ this.TelemetryFeed = class TelemetryFeed {
} }
const session = { const session = {
session_id: String(gUUIDGenerator.generateUUID()), session_id: String(Services.uuid.generateUUID()),
// "unknown" will be overwritten when appropriate // "unknown" will be overwritten when appropriate
page: url ? url : "unknown", page: url ? url : "unknown",
perf: { perf: {
@ -807,8 +803,8 @@ this.TelemetryFeed = class TelemetryFeed {
* @param {String} version Endpoint version for this ping type. * @param {String} version Endpoint version for this ping type.
*/ */
_generateStructuredIngestionEndpoint(namespace, pingType, version) { _generateStructuredIngestionEndpoint(namespace, pingType, version) {
const uuid = gUUIDGenerator.generateUUID().toString(); const uuid = Services.uuid.generateUUID().toString();
// Structured Ingestion does not support the UUID generated by gUUIDGenerator, // Structured Ingestion does not support the UUID generated by Services.uuid,
// because it contains leading and trailing braces. Need to trim them first. // because it contains leading and trailing braces. Need to trim them first.
const docID = uuid.slice(1, -1); const docID = uuid.slice(1, -1);
const extension = `${namespace}/${pingType}/${version}/${docID}`; const extension = `${namespace}/${pingType}/${version}/${docID}`;

View file

@ -329,14 +329,14 @@ describe("TelemetryFeed", () => {
assert.equal(instance.sessions.get("foo"), session); assert.equal(instance.sessions.get("foo"), session);
}); });
it("should set the session_id", () => { it("should set the session_id", () => {
sandbox.spy(global.gUUIDGenerator, "generateUUID"); sandbox.spy(Services.uuid, "generateUUID");
const session = instance.addSession("foo"); const session = instance.addSession("foo");
assert.calledOnce(global.gUUIDGenerator.generateUUID); assert.calledOnce(Services.uuid.generateUUID);
assert.equal( assert.equal(
session.session_id, session.session_id,
global.gUUIDGenerator.generateUUID.firstCall.returnValue Services.uuid.generateUUID.firstCall.returnValue
); );
}); });
it("should set the page if a url parameter is given", () => { it("should set the page if a url parameter is given", () => {
@ -1786,7 +1786,7 @@ describe("TelemetryFeed", () => {
FakePrefs.prototype.prefs[ FakePrefs.prototype.prefs[
STRUCTURED_INGESTION_ENDPOINT_PREF STRUCTURED_INGESTION_ENDPOINT_PREF
] = fakeEndpoint; ] = fakeEndpoint;
sandbox.stub(global.gUUIDGenerator, "generateUUID").returns(fakeUUID); sandbox.stub(Services.uuid, "generateUUID").returns(fakeUUID);
const feed = new TelemetryFeed(); const feed = new TelemetryFeed();
const url = feed._generateStructuredIngestionEndpoint( const url = feed._generateStructuredIngestionEndpoint(
"testNameSpace", "testNameSpace",

View file

@ -314,6 +314,11 @@ const TEST_GLOBAL = {
scalarSet: () => {}, scalarSet: () => {},
keyedScalarAdd: () => {}, keyedScalarAdd: () => {},
}, },
uuid: {
generateUUID() {
return "{foo-123-foo}";
},
},
console: { logStringMessage: () => {} }, console: { logStringMessage: () => {} },
prefs: { prefs: {
addObserver() {}, addObserver() {},
@ -514,9 +519,6 @@ const TEST_GLOBAL = {
addExpirationFilter() {}, addExpirationFilter() {},
removeExpirationFilter() {}, removeExpirationFilter() {},
}, },
gUUIDGenerator: {
generateUUID: () => "{foo-123-foo}",
},
Logger, Logger,
}; };
TEST_GLOBAL.NimbusFeatures.pocketNewtab = TEST_GLOBAL.NimbusFeatures.newtab; TEST_GLOBAL.NimbusFeatures.pocketNewtab = TEST_GLOBAL.NimbusFeatures.newtab;

View file

@ -72,12 +72,6 @@ PlacesInsertionPoint.prototype = {
function PlacesController(aView) { function PlacesController(aView) {
this._view = aView; this._view = aView;
XPCOMUtils.defineLazyServiceGetter(
this,
"clipboard",
"@mozilla.org/widget/clipboard;1",
"nsIClipboard"
);
XPCOMUtils.defineLazyGetter(this, "profileName", function() { XPCOMUtils.defineLazyGetter(this, "profileName", function() {
return Services.dirsvc.get("ProfD", Ci.nsIFile).leafName; return Services.dirsvc.get("ProfD", Ci.nsIFile).leafName;
}); });
@ -178,7 +172,7 @@ PlacesController.prototype = {
// Of course later paste() should ignore any invalid data. // Of course later paste() should ignore any invalid data.
return ( return (
canInsert && canInsert &&
this.clipboard.hasDataMatchingFlavors( Services.clipboard.hasDataMatchingFlavors(
[ [
...PlacesUIUtils.PLACES_FLAVORS, ...PlacesUIUtils.PLACES_FLAVORS,
PlacesUtils.TYPE_X_MOZ_URL, PlacesUtils.TYPE_X_MOZ_URL,
@ -1056,7 +1050,7 @@ PlacesController.prototype = {
); );
xferable.init(null); xferable.init(null);
xferable.addDataFlavor(PlacesUtils.TYPE_X_MOZ_PLACE_ACTION); xferable.addDataFlavor(PlacesUtils.TYPE_X_MOZ_PLACE_ACTION);
this.clipboard.getData(xferable, Ci.nsIClipboard.kGlobalClipboard); Services.clipboard.getData(xferable, Ci.nsIClipboard.kGlobalClipboard);
xferable.getTransferData(PlacesUtils.TYPE_X_MOZ_PLACE_ACTION, action); xferable.getTransferData(PlacesUtils.TYPE_X_MOZ_PLACE_ACTION, action);
[action, actionOwner] = action.value [action, actionOwner] = action.value
.QueryInterface(Ci.nsISupportsString) .QueryInterface(Ci.nsISupportsString)
@ -1079,7 +1073,7 @@ PlacesController.prototype = {
_releaseClipboardOwnership: function PC__releaseClipboardOwnership() { _releaseClipboardOwnership: function PC__releaseClipboardOwnership() {
if (this.cutNodes.length) { if (this.cutNodes.length) {
// This clears the logical clipboard, doesn't remove data. // This clears the logical clipboard, doesn't remove data.
this.clipboard.emptyClipboard(Ci.nsIClipboard.kGlobalClipboard); Services.clipboard.emptyClipboard(Ci.nsIClipboard.kGlobalClipboard);
} }
}, },
@ -1092,7 +1086,11 @@ PlacesController.prototype = {
const TYPE = "text/x-moz-place-empty"; const TYPE = "text/x-moz-place-empty";
xferable.addDataFlavor(TYPE); xferable.addDataFlavor(TYPE);
xferable.setTransferData(TYPE, PlacesUtils.toISupportsString("")); xferable.setTransferData(TYPE, PlacesUtils.toISupportsString(""));
this.clipboard.setData(xferable, null, Ci.nsIClipboard.kGlobalClipboard); Services.clipboard.setData(
xferable,
null,
Ci.nsIClipboard.kGlobalClipboard
);
}, },
_populateClipboard: function PC__populateClipboard(aNodes, aAction) { _populateClipboard: function PC__populateClipboard(aNodes, aAction) {
@ -1152,7 +1150,7 @@ PlacesController.prototype = {
); );
if (hasData) { if (hasData) {
this.clipboard.setData( Services.clipboard.setData(
xferable, xferable,
aAction == "cut" ? this : null, aAction == "cut" ? this : null,
Ci.nsIClipboard.kGlobalClipboard Ci.nsIClipboard.kGlobalClipboard
@ -1238,7 +1236,7 @@ PlacesController.prototype = {
PlacesUtils.TYPE_UNICODE, PlacesUtils.TYPE_UNICODE,
].forEach(type => xferable.addDataFlavor(type)); ].forEach(type => xferable.addDataFlavor(type));
this.clipboard.getData(xferable, Ci.nsIClipboard.kGlobalClipboard); Services.clipboard.getData(xferable, Ci.nsIClipboard.kGlobalClipboard);
// Now get the clipboard contents, in the best available flavor. // Now get the clipboard contents, in the best available flavor.
let data = {}, let data = {},

View file

@ -20,9 +20,6 @@ ChromeUtils.defineModuleGetter(
"pktApi", "pktApi",
"chrome://pocket/content/pktApi.jsm" "chrome://pocket/content/pktApi.jsm"
); );
XPCOMUtils.defineLazyServiceGetters(this, {
gUUIDGenerator: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyModuleGetters(this, {
TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.jsm", TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.jsm",
}); });
@ -65,7 +62,7 @@ var pktTelemetry = {
let impressionId = Services.prefs.getStringPref(PREF_IMPRESSION_ID, ""); let impressionId = Services.prefs.getStringPref(PREF_IMPRESSION_ID, "");
if (!impressionId) { if (!impressionId) {
impressionId = String(gUUIDGenerator.generateUUID()); impressionId = String(Services.uuid.generateUUID());
Services.prefs.setStringPref(PREF_IMPRESSION_ID, impressionId); Services.prefs.setStringPref(PREF_IMPRESSION_ID, impressionId);
} }
return impressionId; return impressionId;
@ -96,7 +93,7 @@ var pktTelemetry = {
}, },
_generateUUID() { _generateUUID() {
return String(gUUIDGenerator.generateUUID()); return String(Services.uuid.generateUUID());
}, },
/** /**

View file

@ -34,13 +34,6 @@ const { AsyncShutdown } = ChromeUtils.import(
"resource://gre/modules/AsyncShutdown.jsm" "resource://gre/modules/AsyncShutdown.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"Telemetry",
"@mozilla.org/base/telemetry;1",
"nsITelemetry"
);
XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyModuleGetters(this, {
RunState: "resource:///modules/sessionstore/RunState.jsm", RunState: "resource:///modules/sessionstore/RunState.jsm",
SessionStore: "resource:///modules/sessionstore/SessionStore.jsm", SessionStore: "resource:///modules/sessionstore/SessionStore.jsm",
@ -298,12 +291,12 @@ var SessionFileInternal = {
parsed, parsed,
useOldExtension, useOldExtension,
}; };
Telemetry.getHistogramById("FX_SESSION_RESTORE_CORRUPT_FILE").add( Services.telemetry
false .getHistogramById("FX_SESSION_RESTORE_CORRUPT_FILE")
); .add(false);
Telemetry.getHistogramById("FX_SESSION_RESTORE_READ_FILE_MS").add( Services.telemetry
Date.now() - startMs .getHistogramById("FX_SESSION_RESTORE_READ_FILE_MS")
); .add(Date.now() - startMs);
break; break;
} catch (ex) { } catch (ex) {
if (ex instanceof OS.File.Error && ex.becauseNoSuchFile) { if (ex instanceof OS.File.Error && ex.becauseNoSuchFile) {
@ -325,9 +318,9 @@ var SessionFileInternal = {
} finally { } finally {
if (exists) { if (exists) {
noFilesFound = false; noFilesFound = false;
Telemetry.getHistogramById("FX_SESSION_RESTORE_CORRUPT_FILE").add( Services.telemetry
corrupted .getHistogramById("FX_SESSION_RESTORE_CORRUPT_FILE")
); .add(corrupted);
} }
} }
} }
@ -347,9 +340,9 @@ var SessionFileInternal = {
// All files are corrupted if files found but none could deliver a result. // All files are corrupted if files found but none could deliver a result.
let allCorrupt = !noFilesFound && !result; let allCorrupt = !noFilesFound && !result;
Telemetry.getHistogramById("FX_SESSION_RESTORE_ALL_FILES_CORRUPT").add( Services.telemetry
allCorrupt .getHistogramById("FX_SESSION_RESTORE_ALL_FILES_CORRUPT")
); .add(allCorrupt);
if (!result) { if (!result) {
// If everything fails, start with an empty session. // If everything fails, start with an empty session.
@ -542,7 +535,7 @@ var SessionFileInternal = {
} else { } else {
samples.push(value); samples.push(value);
} }
let histogram = Telemetry.getHistogramById(id); let histogram = Services.telemetry.getHistogramById(id);
for (let sample of samples) { for (let sample of samples) {
histogram.add(sample); histogram.add(sample);
} }

View file

@ -29,13 +29,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm", UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
// This must be kept in sync with FeatureManifest.js. UrlbarPrefs.get() will // This must be kept in sync with FeatureManifest.js. UrlbarPrefs.get() will
// throw an "unknown pref" error if a test enrolls in a mock experiment and hits // throw an "unknown pref" error if a test enrolls in a mock experiment and hits
// a code path that accesses a Nimbus feature variable not defined here. // a code path that accesses a Nimbus feature variable not defined here.
@ -965,7 +958,7 @@ class TestProvider extends UrlbarProvider {
*/ */
constructor({ constructor({
results, results,
name = "TestProvider" + uuidGenerator.generateUUID(), name = "TestProvider" + Services.uuid.generateUUID(),
type = UrlbarUtils.PROVIDER_TYPE.PROFILE, type = UrlbarUtils.PROVIDER_TYPE.PROFILE,
priority = 0, priority = 0,
addTimeout = 0, addTimeout = 0,

View file

@ -21,10 +21,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
PingCentre: "resource:///modules/PingCentre.jsm", PingCentre: "resource:///modules/PingCentre.jsm",
}); });
XPCOMUtils.defineLazyServiceGetters(this, {
gUUIDGenerator: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
// Endpoint base URL for Structured Ingestion // Endpoint base URL for Structured Ingestion
XPCOMUtils.defineLazyPreferenceGetter( XPCOMUtils.defineLazyPreferenceGetter(
this, this,
@ -44,7 +40,7 @@ const CONTEXT_ID_PREF = "browser.contextual-services.contextId";
XPCOMUtils.defineLazyGetter(this, "contextId", () => { XPCOMUtils.defineLazyGetter(this, "contextId", () => {
let _contextId = Services.prefs.getStringPref(CONTEXT_ID_PREF, null); let _contextId = Services.prefs.getStringPref(CONTEXT_ID_PREF, null);
if (!_contextId) { if (!_contextId) {
_contextId = String(gUUIDGenerator.generateUUID()); _contextId = String(Services.uuid.generateUUID());
Services.prefs.setStringPref(CONTEXT_ID_PREF, _contextId); Services.prefs.setStringPref(CONTEXT_ID_PREF, _contextId);
} }
return _contextId; return _contextId;
@ -220,7 +216,7 @@ function recordTelemetryEvent({ method, objectString, value }) {
function makeEndpointUrl(pingType, version) { function makeEndpointUrl(pingType, version) {
// Structured Ingestion does not support the UUID generated by gUUIDGenerator. // Structured Ingestion does not support the UUID generated by gUUIDGenerator.
// Stripping off the leading and trailing braces to make it happy. // Stripping off the leading and trailing braces to make it happy.
const docID = gUUIDGenerator const docID = Services.uuid
.generateUUID() .generateUUID()
.toString() .toString()
.slice(1, -1); .slice(1, -1);

View file

@ -718,8 +718,10 @@ var AeroPeek = {
return; return;
} }
this.prefs.addObserver(TOGGLE_PREF_NAME, this, true); Services.prefs.addObserver(TOGGLE_PREF_NAME, this, true);
this.enabled = this._prefenabled = this.prefs.getBoolPref(TOGGLE_PREF_NAME); this.enabled = this._prefenabled = Services.prefs.getBoolPref(
TOGGLE_PREF_NAME
);
this.initialized = true; this.initialized = true;
}, },
@ -768,8 +770,8 @@ var AeroPeek = {
enable() { enable() {
if (!this._observersAdded) { if (!this._observersAdded) {
this.prefs.addObserver(DISABLE_THRESHOLD_PREF_NAME, this, true); Services.prefs.addObserver(DISABLE_THRESHOLD_PREF_NAME, this, true);
this.prefs.addObserver(CACHE_EXPIRATION_TIME_PREF_NAME, this, true); Services.prefs.addObserver(CACHE_EXPIRATION_TIME_PREF_NAME, this, true);
this._placesListener = this.handlePlacesEvents.bind(this); this._placesListener = this.handlePlacesEvents.bind(this);
PlacesUtils.observers.addListener( PlacesUtils.observers.addListener(
["favicon-changed"], ["favicon-changed"],
@ -778,9 +780,11 @@ var AeroPeek = {
this._observersAdded = true; this._observersAdded = true;
} }
this.cacheLifespan = this.prefs.getIntPref(CACHE_EXPIRATION_TIME_PREF_NAME); this.cacheLifespan = Services.prefs.getIntPref(
CACHE_EXPIRATION_TIME_PREF_NAME
);
this.maxpreviews = this.prefs.getIntPref(DISABLE_THRESHOLD_PREF_NAME); this.maxpreviews = Services.prefs.getIntPref(DISABLE_THRESHOLD_PREF_NAME);
// If the user toggled us on/off while the browser was already up // If the user toggled us on/off while the browser was already up
// (rather than this code running on startup because the pref was // (rather than this code running on startup because the pref was
@ -861,7 +865,7 @@ var AeroPeek = {
// nsIObserver // nsIObserver
observe(aSubject, aTopic, aData) { observe(aSubject, aTopic, aData) {
if (aTopic == "nsPref:changed" && aData == TOGGLE_PREF_NAME) { if (aTopic == "nsPref:changed" && aData == TOGGLE_PREF_NAME) {
this._prefenabled = this.prefs.getBoolPref(TOGGLE_PREF_NAME); this._prefenabled = Services.prefs.getBoolPref(TOGGLE_PREF_NAME);
} }
if (!this._prefenabled) { if (!this._prefenabled) {
return; return;
@ -873,7 +877,9 @@ var AeroPeek = {
} }
if (aData == DISABLE_THRESHOLD_PREF_NAME) { if (aData == DISABLE_THRESHOLD_PREF_NAME) {
this.maxpreviews = this.prefs.getIntPref(DISABLE_THRESHOLD_PREF_NAME); this.maxpreviews = Services.prefs.getIntPref(
DISABLE_THRESHOLD_PREF_NAME
);
} }
// Might need to enable/disable ourselves // Might need to enable/disable ourselves
this.checkPreviewCount(); this.checkPreviewCount();
@ -913,11 +919,4 @@ XPCOMUtils.defineLazyGetter(AeroPeek, "cacheTimer", () =>
Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer) Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer)
); );
XPCOMUtils.defineLazyServiceGetter(
AeroPeek,
"prefs",
"@mozilla.org/preferences-service;1",
"nsIPrefBranch"
);
AeroPeek.initialize(); AeroPeek.initialize();

View file

@ -23,12 +23,6 @@ XPCOMUtils.defineLazyServiceGetter(
"@mozilla.org/push/Notifier;1", "@mozilla.org/push/Notifier;1",
"nsIPushNotifier" "nsIPushNotifier"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"eTLDService",
"@mozilla.org/network/effective-tld-service;1",
"nsIEffectiveTLDService"
);
ChromeUtils.defineModuleGetter( ChromeUtils.defineModuleGetter(
this, this,
"pushBroadcastService", "pushBroadcastService",
@ -1285,7 +1279,7 @@ var PushService = {
record => record =>
info.domain == "*" || info.domain == "*" ||
(record.uri && (record.uri &&
eTLDService.hasRootDomain(record.uri.prePath, info.domain)) Services.eTLD.hasRootDomain(record.uri.prePath, info.domain))
); );
}) })
.catch(e => { .catch(e => {

View file

@ -12,13 +12,6 @@ const { XPCOMUtils } = ChromeUtils.import(
); );
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyServiceGetter(
this,
"gScriptSecurityManager",
"@mozilla.org/scriptsecuritymanager;1",
"nsIScriptSecurityManager"
);
XPCOMUtils.defineLazyServiceGetter( XPCOMUtils.defineLazyServiceGetter(
this, this,
"gContentSecurityManager", "gContentSecurityManager",
@ -51,13 +44,19 @@ add_task(async function test_isOriginPotentiallyTrustworthy() {
["http://1234567890abcdef.onion/", false], ["http://1234567890abcdef.onion/", false],
]) { ]) {
let uri = NetUtil.newURI(uriSpec); let uri = NetUtil.newURI(uriSpec);
let principal = gScriptSecurityManager.createContentPrincipal(uri, {}); let principal = Services.scriptSecurityManager.createContentPrincipal(
uri,
{}
);
Assert.equal(principal.isOriginPotentiallyTrustworthy, expectedResult); Assert.equal(principal.isOriginPotentiallyTrustworthy, expectedResult);
} }
// And now let's test whether .onion sites are properly treated when // And now let's test whether .onion sites are properly treated when
// allowlisted, see bug 1382359. // allowlisted, see bug 1382359.
Services.prefs.setBoolPref("dom.securecontext.whitelist_onions", true); Services.prefs.setBoolPref("dom.securecontext.whitelist_onions", true);
let uri = NetUtil.newURI("http://1234567890abcdef.onion/"); let uri = NetUtil.newURI("http://1234567890abcdef.onion/");
let principal = gScriptSecurityManager.createContentPrincipal(uri, {}); let principal = Services.scriptSecurityManager.createContentPrincipal(
uri,
{}
);
Assert.equal(principal.isOriginPotentiallyTrustworthy, true); Assert.equal(principal.isOriginPotentiallyTrustworthy, true);
}); });

View file

@ -10,13 +10,6 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm" "resource://gre/modules/XPCOMUtils.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"gPrompter",
"@mozilla.org/prompter;1",
"nsIPromptService"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const EXPORTED_SYMBOLS = ["GeckoViewPromptChild"]; const EXPORTED_SYMBOLS = ["GeckoViewPromptChild"];
@ -30,7 +23,7 @@ class GeckoViewPromptChild extends GeckoViewActorChild {
case "click": // fall-through case "click": // fall-through
case "contextmenu": // fall-through case "contextmenu": // fall-through
case "DOMPopupBlocked": case "DOMPopupBlocked":
gPrompter.wrappedJSObject.handleEvent(event); Services.prompt.wrappedJSObject.handleEvent(event);
} }
} }
} }

View file

@ -16,16 +16,9 @@ const { XPCOMUtils } = ChromeUtils.import(
const { debug, warn } = GeckoViewUtils.initLogging("GeckoViewPrompter"); const { debug, warn } = GeckoViewUtils.initLogging("GeckoViewPrompter");
XPCOMUtils.defineLazyServiceGetter(
this,
"gUUIDGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
class GeckoViewPrompter { class GeckoViewPrompter {
constructor(aParent) { constructor(aParent) {
this.id = gUUIDGenerator this.id = Services.uuid
.generateUUID() .generateUUID()
.toString() .toString()
.slice(1, -1); // Discard surrounding braces .slice(1, -1); // Discard surrounding braces

View file

@ -17,15 +17,9 @@ XPCOMUtils.defineLazyModuleGetters(this, {
DeferredTask: "resource://gre/modules/DeferredTask.jsm", DeferredTask: "resource://gre/modules/DeferredTask.jsm",
FormLikeFactory: "resource://gre/modules/FormLikeFactory.jsm", FormLikeFactory: "resource://gre/modules/FormLikeFactory.jsm",
LoginManagerChild: "resource://gre/modules/LoginManagerChild.jsm", LoginManagerChild: "resource://gre/modules/LoginManagerChild.jsm",
Services: "resource://gre/modules/Services.jsm",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"UUIDGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
const { debug, warn } = GeckoViewUtils.initLogging("Autofill"); const { debug, warn } = GeckoViewUtils.initLogging("Autofill");
class GeckoViewAutofill { class GeckoViewAutofill {
@ -67,7 +61,8 @@ class GeckoViewAutofill {
info = { info = {
isInputElement, isInputElement,
uuid: UUIDGen.generateUUID() uuid: Services.uuid
.generateUUID()
.toString() .toString()
.slice(1, -1), // discard the surrounding curly braces .slice(1, -1), // discard the surrounding curly braces
parentUuid: aParent, parentUuid: aParent,

View file

@ -10,13 +10,6 @@ const { XPCOMUtils } = ChromeUtils.import(
var EXPORTED_SYMBOLS = ["EventDispatcher"]; var EXPORTED_SYMBOLS = ["EventDispatcher"];
XPCOMUtils.defineLazyServiceGetter(
this,
"UUIDGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
const IS_PARENT_PROCESS = const IS_PARENT_PROCESS =
Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_DEFAULT; Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_DEFAULT;
@ -85,7 +78,7 @@ DispatcherDelegate.prototype = {
}; };
if (aCallback) { if (aCallback) {
const uuid = UUIDGen.generateUUID().toString(); const uuid = Services.uuid.generateUUID().toString();
this._replies.set(uuid, { this._replies.set(uuid, {
callback: aCallback, callback: aCallback,
finalizer: aFinalizer, finalizer: aFinalizer,

View file

@ -16,13 +16,6 @@ const { CookieXPCShellUtils } = ChromeUtils.import(
CookieXPCShellUtils.init(this); CookieXPCShellUtils.init(this);
CookieXPCShellUtils.createServer({ hosts: ["example.org"] }); CookieXPCShellUtils.createServer({ hosts: ["example.org"] });
XPCOMUtils.defineLazyServiceGetter(
this,
"cm",
"@mozilla.org/cookiemanager;1",
"nsICookieManager"
);
add_task(async function test_basic_eviction() { add_task(async function test_basic_eviction() {
do_get_profile(); do_get_profile();
@ -121,14 +114,14 @@ add_task(async function test_basic_eviction() {
BASE_URI BASE_URI
); );
cm.removeAll(); Services.cookies.removeAll();
}); });
// Verify that the given cookie names exist, and are ordered from least to most recently accessed // Verify that the given cookie names exist, and are ordered from least to most recently accessed
function verifyCookies(names, uri) { function verifyCookies(names, uri) {
Assert.equal(cm.countCookiesFromHost(uri.host), names.length); Assert.equal(Services.cookies.countCookiesFromHost(uri.host), names.length);
let actual_cookies = []; let actual_cookies = [];
for (let cookie of cm.getCookiesFromHost(uri.host, {})) { for (let cookie of Services.cookies.getCookiesFromHost(uri.host, {})) {
actual_cookies.push(cookie); actual_cookies.push(cookie);
} }
if (names.length != actual_cookies.length) { if (names.length != actual_cookies.length) {

View file

@ -5,13 +5,6 @@ var { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm" "resource://gre/modules/XPCOMUtils.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
Services,
"cookiemgr",
"@mozilla.org/cookiemanager;1",
"nsICookieManager"
);
function inChildProcess() { function inChildProcess() {
return Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT; return Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
} }
@ -176,7 +169,7 @@ add_task(async _ => {
} }
info("Let's set a cookie without scheme"); info("Let's set a cookie without scheme");
Services.cookiemgr.add( Services.cookies.add(
"example.org", "example.org",
"/", "/",
"a", "a",

View file

@ -13,14 +13,11 @@ const { XPCOMUtils } = ChromeUtils.import(
XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyModuleGetters(this, {
AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm", AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
OS: "resource://gre/modules/osfile.jsm", OS: "resource://gre/modules/osfile.jsm",
Services: "resource://gre/modules/Services.jsm",
UnsupportedError: "chrome://remote/content/cdp/Error.jsm", UnsupportedError: "chrome://remote/content/cdp/Error.jsm",
}); });
XPCOMUtils.defineLazyServiceGetters(this, {
uuidGen: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
class StreamRegistry { class StreamRegistry {
constructor() { constructor() {
// handle => stream // handle => stream
@ -74,7 +71,7 @@ class StreamRegistry {
let handle; let handle;
if (stream instanceof OS.File) { if (stream instanceof OS.File) {
handle = uuidGen handle = Services.uuid
.generateUUID() .generateUUID()
.toString() .toString()
.slice(1, -1); .slice(1, -1);

View file

@ -6,21 +6,12 @@
var EXPORTED_SYMBOLS = ["Page"]; var EXPORTED_SYMBOLS = ["Page"];
const { XPCOMUtils } = ChromeUtils.import( const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
"resource://gre/modules/XPCOMUtils.jsm"
);
const { ContentProcessDomain } = ChromeUtils.import( const { ContentProcessDomain } = ChromeUtils.import(
"chrome://remote/content/cdp/domains/ContentProcessDomain.jsm" "chrome://remote/content/cdp/domains/ContentProcessDomain.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
const { const {
LOAD_FLAGS_BYPASS_CACHE, LOAD_FLAGS_BYPASS_CACHE,
LOAD_FLAGS_BYPASS_PROXY, LOAD_FLAGS_BYPASS_PROXY,
@ -194,7 +185,7 @@ class Page extends ContentProcessDomain {
if (worldName) { if (worldName) {
this.worldsToEvaluateOnLoad.add(worldName); this.worldsToEvaluateOnLoad.add(worldName);
} }
const identifier = uuidGen const identifier = Services.uuid
.generateUUID() .generateUUID()
.toString() .toString()
.slice(1, -1); .slice(1, -1);

View file

@ -6,16 +6,7 @@
var EXPORTED_SYMBOLS = ["ExecutionContext"]; var EXPORTED_SYMBOLS = ["ExecutionContext"];
var { XPCOMUtils } = ChromeUtils.import( const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyServiceGetter(
this,
"UUIDGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
const TYPED_ARRAY_CLASSES = [ const TYPED_ARRAY_CLASSES = [
"Uint8Array", "Uint8Array",
@ -30,7 +21,8 @@ const TYPED_ARRAY_CLASSES = [
]; ];
function uuid() { function uuid() {
return UUIDGen.generateUUID() return Services.uuid
.generateUUID()
.toString() .toString()
.slice(1, -1); .slice(1, -1);
} }

View file

@ -13,6 +13,7 @@ const { XPCOMUtils } = ChromeUtils.import(
XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyModuleGetters(this, {
ContextualIdentityService: ContextualIdentityService:
"resource://gre/modules/ContextualIdentityService.jsm", "resource://gre/modules/ContextualIdentityService.jsm",
Services: "resource://gre/modules/Services.jsm",
Domain: "chrome://remote/content/cdp/domains/Domain.jsm", Domain: "chrome://remote/content/cdp/domains/Domain.jsm",
MainProcessTarget: MainProcessTarget:
@ -22,13 +23,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
windowManager: "chrome://remote/content/shared/WindowManager.jsm", windowManager: "chrome://remote/content/shared/WindowManager.jsm",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"UUIDGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
let browserContextIds = 1; let browserContextIds = 1;
class Target extends Domain { class Target extends Domain {
@ -141,7 +135,8 @@ class Target extends Domain {
const tabSession = new TabSession( const tabSession = new TabSession(
this.session.connection, this.session.connection,
target, target,
UUIDGen.generateUUID() Services.uuid
.generateUUID()
.toString() .toString()
.slice(1, -1) .slice(1, -1)
); );

View file

@ -12,16 +12,10 @@ const { XPCOMUtils } = ChromeUtils.import(
XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyModuleGetters(this, {
CDPConnection: "chrome://remote/content/cdp/CDPConnection.jsm", CDPConnection: "chrome://remote/content/cdp/CDPConnection.jsm",
Services: "resource://gre/modules/Services.jsm",
WebSocketHandshake: "chrome://remote/content/server/WebSocketHandshake.jsm", WebSocketHandshake: "chrome://remote/content/server/WebSocketHandshake.jsm",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"UUIDGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
/** /**
* Base class for all the targets. * Base class for all the targets.
*/ */
@ -43,7 +37,8 @@ class Target {
// There can be more than one connection if multiple clients connect to the remote agent. // There can be more than one connection if multiple clients connect to the remote agent.
this.connections = new Set(); this.connections = new Set();
this.id = UUIDGen.generateUUID() this.id = Services.uuid
.generateUUID()
.toString() .toString()
.slice(1, -1); .slice(1, -1);
} }

View file

@ -19,6 +19,7 @@ const { XPCOMUtils } = ChromeUtils.import(
XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyModuleGetters(this, {
ContentDOMReference: "resource://gre/modules/ContentDOMReference.jsm", ContentDOMReference: "resource://gre/modules/ContentDOMReference.jsm",
Services: "resource://gre/modules/Services.jsm",
assert: "chrome://remote/content/shared/webdriver/Assert.jsm", assert: "chrome://remote/content/shared/webdriver/Assert.jsm",
atom: "chrome://remote/content/marionette/atom.js", atom: "chrome://remote/content/marionette/atom.js",
@ -27,13 +28,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
pprint: "chrome://remote/content/shared/Format.jsm", pprint: "chrome://remote/content/shared/Format.jsm",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
const ORDERED_NODE_ITERATOR_TYPE = 5; const ORDERED_NODE_ITERATOR_TYPE = 5;
const FIRST_ORDERED_NODE_TYPE = 9; const FIRST_ORDERED_NODE_TYPE = 9;
@ -1596,7 +1590,7 @@ class WebElement {
* UUID. * UUID.
*/ */
static generateUUID() { static generateUUID() {
let uuid = uuidGen.generateUUID().toString(); let uuid = Services.uuid.generateUUID().toString();
return uuid.substring(1, uuid.length - 1); return uuid.substring(1, uuid.length - 1);
} }
} }

View file

@ -10,21 +10,16 @@ var EXPORTED_SYMBOLS = ["WebSocketConnection"];
const { XPCOMUtils } = ChromeUtils.import( const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm" "resource://gre/modules/XPCOMUtils.jsm"
); );
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyModuleGetters(this, {
Log: "chrome://remote/content/shared/Log.jsm", Log: "chrome://remote/content/shared/Log.jsm",
Services: "resource://gre/modules/Services.jsm",
WebSocketTransport: "chrome://remote/content/server/WebSocketTransport.jsm", WebSocketTransport: "chrome://remote/content/server/WebSocketTransport.jsm",
}); });
XPCOMUtils.defineLazyGetter(this, "logger", () => Log.get()); XPCOMUtils.defineLazyGetter(this, "logger", () => Log.get());
XPCOMUtils.defineLazyServiceGetter(
this,
"UUIDGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
class WebSocketConnection { class WebSocketConnection {
/** /**
* @param {WebSocket} webSocket * @param {WebSocket} webSocket
@ -33,7 +28,7 @@ class WebSocketConnection {
* Reference to the httpd.js's connection needed for clean-up. * Reference to the httpd.js's connection needed for clean-up.
*/ */
constructor(webSocket, httpdConnection) { constructor(webSocket, httpdConnection) {
this.id = UUIDGen.generateUUID().toString(); this.id = Services.uuid.generateUUID().toString();
this.httpdConnection = httpdConnection; this.httpdConnection = httpdConnection;
this.transport = new WebSocketTransport(webSocket); this.transport = new WebSocketTransport(webSocket);

View file

@ -21,13 +21,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
waitForObserverTopic: "chrome://remote/content/marionette/sync.js", waitForObserverTopic: "chrome://remote/content/marionette/sync.js",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
/** /**
* Provides helpers to interact with Window objects. * Provides helpers to interact with Window objects.
* *
@ -165,7 +158,7 @@ class WindowManager {
const key = browserElement.permanentKey; const key = browserElement.permanentKey;
if (!this._windowHandles.has(key)) { if (!this._windowHandles.has(key)) {
const uuid = uuidGen.generateUUID().toString(); const uuid = Services.uuid.generateUUID().toString();
this._windowHandles.set(key, uuid.substring(1, uuid.length - 1)); this._windowHandles.set(key, uuid.substring(1, uuid.length - 1));
} }
return this._windowHandles.get(key); return this._windowHandles.get(key);
@ -181,7 +174,7 @@ class WindowManager {
*/ */
getIdForWindow(win) { getIdForWindow(win) {
if (!this._chromeWindowHandles.has(win)) { if (!this._chromeWindowHandles.has(win)) {
const uuid = uuidGen.generateUUID().toString(); const uuid = Services.uuid.generateUUID().toString();
this._chromeWindowHandles.set(win, uuid.substring(1, uuid.length - 1)); this._chromeWindowHandles.set(win, uuid.substring(1, uuid.length - 1));
} }
return this._chromeWindowHandles.get(win); return this._chromeWindowHandles.get(win);

View file

@ -11,6 +11,8 @@ const { XPCOMUtils } = ChromeUtils.import(
); );
XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyModuleGetters(this, {
Services: "resource://gre/modules/Services.jsm",
accessibility: "chrome://remote/content/marionette/accessibility.js", accessibility: "chrome://remote/content/marionette/accessibility.js",
allowAllCerts: "chrome://remote/content/marionette/cert.js", allowAllCerts: "chrome://remote/content/marionette/cert.js",
Capabilities: "chrome://remote/content/shared/webdriver/Capabilities.jsm", Capabilities: "chrome://remote/content/shared/webdriver/Capabilities.jsm",
@ -25,13 +27,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
WebSocketHandshake: "chrome://remote/content/server/WebSocketHandshake.jsm", WebSocketHandshake: "chrome://remote/content/server/WebSocketHandshake.jsm",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
XPCOMUtils.defineLazyGetter(this, "logger", () => Log.get()); XPCOMUtils.defineLazyGetter(this, "logger", () => Log.get());
/** /**
@ -165,7 +160,7 @@ class WebDriverSession {
// to reconnect. // to reconnect.
this._connections = new Set(); this._connections = new Set();
this.id = uuidGen this.id = Services.uuid
.generateUUID() .generateUUID()
.toString() .toString()
.slice(1, -1); .slice(1, -1);

View file

@ -42,13 +42,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
let constants = {}; let constants = {};
ChromeUtils.import("resource://services-sync/constants.js", constants); ChromeUtils.import("resource://services-sync/constants.js", constants);
XPCOMUtils.defineLazyServiceGetter(
this,
"Telemetry",
"@mozilla.org/base/telemetry;1",
"nsITelemetry"
);
XPCOMUtils.defineLazyGetter( XPCOMUtils.defineLazyGetter(
this, this,
"WeaveService", "WeaveService",
@ -116,7 +109,7 @@ const reProfileDir = new RegExp(
function tryGetMonotonicTimestamp() { function tryGetMonotonicTimestamp() {
try { try {
return Telemetry.msSinceProcessStart(); return Services.telemetry.msSinceProcessStart();
} catch (e) { } catch (e) {
log.warn("Unable to get a monotonic timestamp!"); log.warn("Unable to get a monotonic timestamp!");
return -1; return -1;
@ -567,7 +560,7 @@ class SyncTelemetryImpl {
this.maxPayloadCount = Svc.Prefs.get("telemetry.maxPayloadCount"); this.maxPayloadCount = Svc.Prefs.get("telemetry.maxPayloadCount");
this.submissionInterval = this.submissionInterval =
Svc.Prefs.get("telemetry.submissionInterval") * 1000; Svc.Prefs.get("telemetry.submissionInterval") * 1000;
this.lastSubmissionTime = Telemetry.msSinceProcessStart(); this.lastSubmissionTime = Services.telemetry.msSinceProcessStart();
this.lastUID = EMPTY_UID; this.lastUID = EMPTY_UID;
this.lastSyncNodeType = null; this.lastSyncNodeType = null;
this.currentSyncNodeType = null; this.currentSyncNodeType = null;
@ -851,7 +844,7 @@ class SyncTelemetryImpl {
"Early submission of sync telemetry due to changed IDs/NodeType" "Early submission of sync telemetry due to changed IDs/NodeType"
); );
this.finish("idchange"); // this actually submits. this.finish("idchange"); // this actually submits.
this.lastSubmissionTime = Telemetry.msSinceProcessStart(); this.lastSubmissionTime = Services.telemetry.msSinceProcessStart();
} }
// Only update the last UIDs if we actually know them. // Only update the last UIDs if we actually know them.
@ -870,11 +863,11 @@ class SyncTelemetryImpl {
// the sync and the events caused by it in different pings. // the sync and the events caused by it in different pings.
if ( if (
this.current == null && this.current == null &&
Telemetry.msSinceProcessStart() - this.lastSubmissionTime > Services.telemetry.msSinceProcessStart() - this.lastSubmissionTime >
this.submissionInterval this.submissionInterval
) { ) {
this.finish("schedule"); this.finish("schedule");
this.lastSubmissionTime = Telemetry.msSinceProcessStart(); this.lastSubmissionTime = Services.telemetry.msSinceProcessStart();
} }
} }
@ -901,7 +894,7 @@ class SyncTelemetryImpl {
} }
_addHistogram(hist) { _addHistogram(hist) {
let histogram = Telemetry.getHistogramById(hist); let histogram = Services.telemetry.getHistogramById(hist);
let s = histogram.snapshot(); let s = histogram.snapshot();
this.histograms[hist] = s; this.histograms[hist] = s;
} }

View file

@ -9,18 +9,9 @@ var EXPORTED_SYMBOLS = ["MockRegistrar"];
const Cm = Components.manager; const Cm = Components.manager;
const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm");
const { XPCOMUtils } = ChromeUtils.import( const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
"resource://gre/modules/XPCOMUtils.jsm"
);
var logger = Log.repository.getLogger("MockRegistrar"); var logger = Log.repository.getLogger("MockRegistrar");
XPCOMUtils.defineLazyServiceGetter(
this,
"UUIDGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
var MockRegistrar = Object.freeze({ var MockRegistrar = Object.freeze({
_registeredComponents: new Map(), _registeredComponents: new Map(),
_originalCIDs: new Map(), _originalCIDs: new Map(),
@ -52,7 +43,7 @@ var MockRegistrar = Object.freeze({
let originalFactory = Cm.getClassObject(originalCID, Ci.nsIFactory); let originalFactory = Cm.getClassObject(originalCID, Ci.nsIFactory);
let cid = UUIDGen.generateUUID(); let cid = Services.uuid.generateUUID();
let factory = { let factory = {
createInstance(outer, iid) { createInstance(outer, iid) {

View file

@ -10,13 +10,6 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm" "resource://gre/modules/XPCOMUtils.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"quotaManagerService",
"@mozilla.org/dom/quota-manager-service;1",
"nsIQuotaManagerService"
);
XPCOMUtils.defineLazyServiceGetter( XPCOMUtils.defineLazyServiceGetter(
this, this,
"serviceWorkerManager", "serviceWorkerManager",
@ -88,7 +81,7 @@ class PrincipalsCollector {
async _getAllPrincipalsInternal(progress = {}) { async _getAllPrincipalsInternal(progress = {}) {
progress.step = "principals-quota-manager"; progress.step = "principals-quota-manager";
let principals = await new Promise(resolve => { let principals = await new Promise(resolve => {
quotaManagerService.listOrigins().callback = request => { Services.qms.listOrigins().callback = request => {
progress.step = "principals-quota-manager-listOrigins"; progress.step = "principals-quota-manager-listOrigins";
if (request.resultCode != Cr.NS_OK) { if (request.resultCode != Cr.NS_OK) {
// We are probably shutting down. We don't want to propagate the // We are probably shutting down. We don't want to propagate the

View file

@ -99,7 +99,6 @@ XPCOMUtils.defineLazyServiceGetters(this, {
"amIAddonManagerStartup", "amIAddonManagerStartup",
], ],
spellCheck: ["@mozilla.org/spellchecker/engine;1", "mozISpellCheckingEngine"], spellCheck: ["@mozilla.org/spellchecker/engine;1", "mozISpellCheckingEngine"],
uuidGen: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
}); });
XPCOMUtils.defineLazyPreferenceGetter( XPCOMUtils.defineLazyPreferenceGetter(
@ -311,7 +310,7 @@ var UUIDMap = {
let uuid = null; let uuid = null;
if (create) { if (create) {
uuid = uuidGen.generateUUID().number; uuid = Services.uuid.generateUUID().number;
uuid = uuid.slice(1, -1); // Strip { and } off the UUID. uuid = uuid.slice(1, -1); // Strip { and } off the UUID.
map[id] = uuid; map[id] = uuid;

View file

@ -21,13 +21,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
OS: "resource://gre/modules/osfile.jsm", OS: "resource://gre/modules/osfile.jsm",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"quotaManagerService",
"@mozilla.org/dom/quota-manager-service;1",
"nsIQuotaManagerService"
);
// The userContextID reserved for the extension storage (its purpose is ensuring that the IndexedDB // The userContextID reserved for the extension storage (its purpose is ensuring that the IndexedDB
// storage used by the browser.storage.local API is not directly accessible from the extension code, // storage used by the browser.storage.local API is not directly accessible from the extension code,
// it is defined and reserved as "userContextIdInternal.webextStorageLocal" in ContextualIdentityService.jsm). // it is defined and reserved as "userContextIdInternal.webextStorageLocal" in ContextualIdentityService.jsm).
@ -749,7 +742,7 @@ this.ExtensionStorageIDB = {
persist(storagePrincipal) { persist(storagePrincipal) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const request = quotaManagerService.persist(storagePrincipal); const request = Services.qms.persist(storagePrincipal);
request.callback = () => { request.callback = () => {
if (request.resultCode === Cr.NS_OK) { if (request.resultCode === Cr.NS_OK) {
resolve(); resolve();

View file

@ -66,13 +66,6 @@ const { ExtensionUtils } = ChromeUtils.import(
"resource://gre/modules/ExtensionUtils.jsm" "resource://gre/modules/ExtensionUtils.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
const { flushJarCache } = ExtensionUtils; const { flushJarCache } = ExtensionUtils;
const { instanceOf } = ExtensionCommon; const { instanceOf } = ExtensionCommon;
@ -292,7 +285,7 @@ ExtensionTestCommon = class ExtensionTestCommon {
} }
if (data.background) { if (data.background) {
let bgScript = uuidGen.generateUUID().number + ".js"; let bgScript = Services.uuid.generateUUID().number + ".js";
provide(manifest, ["background", "scripts"], [bgScript], true); provide(manifest, ["background", "scripts"], [bgScript], true);
files[bgScript] = data.background; files[bgScript] = data.background;
@ -438,7 +431,7 @@ ExtensionTestCommon = class ExtensionTestCommon {
provide( provide(
data, data,
["manifest", "applications", "gecko", "id"], ["manifest", "applications", "gecko", "id"],
uuidGen.generateUUID().number Services.uuid.generateUUID().number
); );
} }
@ -483,7 +476,7 @@ ExtensionTestCommon = class ExtensionTestCommon {
} }
} }
if (!id) { if (!id) {
id = uuidGen.generateUUID().number; id = Services.uuid.generateUUID().number;
} }
let signedState = AddonManager.SIGNEDSTATE_SIGNED; let signedState = AddonManager.SIGNEDSTATE_SIGNED;

View file

@ -12,13 +12,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
BrowsingDataDelegate: "resource:///modules/ExtensionBrowsingData.jsm", BrowsingDataDelegate: "resource:///modules/ExtensionBrowsingData.jsm",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"quotaManagerService",
"@mozilla.org/dom/quota-manager-service;1",
"nsIQuotaManagerService"
);
/** /**
* A number of iterations after which to yield time back * A number of iterations after which to yield time back
* to the system. * to the system.
@ -145,7 +138,7 @@ async function clearQuotaManager(options, dataType) {
let promises = []; let promises = [];
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
quotaManagerService.getUsage(request => { Services.qms.getUsage(request => {
if (request.resultCode != Cr.NS_OK) { if (request.resultCode != Cr.NS_OK) {
reject({ message: `Clear ${dataType} failed` }); reject({ message: `Clear ${dataType} failed` });
return; return;
@ -175,13 +168,13 @@ async function clearQuotaManager(options, dataType) {
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
let clearRequest; let clearRequest;
if (dataType === "indexedDB") { if (dataType === "indexedDB") {
clearRequest = quotaManagerService.clearStoragesForPrincipal( clearRequest = Services.qms.clearStoragesForPrincipal(
principal, principal,
null, null,
"idb" "idb"
); );
} else { } else {
clearRequest = quotaManagerService.clearStoragesForPrincipal( clearRequest = Services.qms.clearStoragesForPrincipal(
principal, principal,
"default", "default",
"ls" "ls"

View file

@ -16,6 +16,11 @@ ChromeUtils.defineModuleGetter(
"AddonManager", "AddonManager",
"resource://gre/modules/AddonManager.jsm" "resource://gre/modules/AddonManager.jsm"
); );
// We can't use Services.prompt here at the moment, as tests need to mock
// the prompt service. We could use sinon, but that didn't seem to work
// with Android builds.
// eslint-disable-next-line mozilla/use-services
XPCOMUtils.defineLazyServiceGetter( XPCOMUtils.defineLazyServiceGetter(
this, this,
"promptService", "promptService",
@ -237,9 +242,8 @@ this.management = class extends ExtensionAPI {
} }
let title = _("uninstall.confirmation.title", extension.name); let title = _("uninstall.confirmation.title", extension.name);
let buttonFlags = let buttonFlags =
promptService.BUTTON_POS_0 * Ci.nsIPrompt.BUTTON_POS_0 * Ci.nsIPrompt.BUTTON_TITLE_IS_STRING +
promptService.BUTTON_TITLE_IS_STRING + Ci.nsIPrompt.BUTTON_POS_1 * Ci.nsIPrompt.BUTTON_TITLE_IS_STRING;
promptService.BUTTON_POS_1 * promptService.BUTTON_TITLE_IS_STRING;
let button0Title = _("uninstall.confirmation.button-0.label"); let button0Title = _("uninstall.confirmation.button-0.label");
let button1Title = _("uninstall.confirmation.button-1.label"); let button1Title = _("uninstall.confirmation.button-1.label");
let response = promptService.confirmEx( let response = promptService.confirmEx(

View file

@ -58,10 +58,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
CreditCard: "resource://gre/modules/CreditCard.jsm", CreditCard: "resource://gre/modules/CreditCard.jsm",
}); });
XPCOMUtils.defineLazyServiceGetters(this, {
gUUIDGenerator: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
this.log = null; this.log = null;
FormAutofill.defineLazyLogGetter(this, EXPORTED_SYMBOLS[0]); FormAutofill.defineLazyLogGetter(this, EXPORTED_SYMBOLS[0]);
@ -927,7 +923,7 @@ class FormAutofillCreditCardSection extends FormAutofillSection {
this.handler = handler; this.handler = handler;
// Identifier used to correlate events relating to the same form // Identifier used to correlate events relating to the same form
this.flowId = gUUIDGenerator.generateUUID().toString(); this.flowId = Services.uuid.generateUUID().toString();
log.debug("Creating new credit card section with flowId =", this.flowId); log.debug("Creating new credit card section with flowId =", this.flowId);
if (!this.isValidSection()) { if (!this.isValidSection()) {

View file

@ -130,9 +130,6 @@ this.EXPORTED_SYMBOLS = [
"AddressesBase", "AddressesBase",
]; ];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { FormAutofill } = ChromeUtils.import( const { FormAutofill } = ChromeUtils.import(
@ -165,13 +162,6 @@ ChromeUtils.defineModuleGetter(
"resource://autofill/phonenumberutils/PhoneNumber.jsm" "resource://autofill/phonenumberutils/PhoneNumber.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"gUUIDGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
const CryptoHash = Components.Constructor( const CryptoHash = Components.Constructor(
"@mozilla.org/security/hash;1", "@mozilla.org/security/hash;1",
"nsICryptoHash", "nsICryptoHash",
@ -450,7 +440,7 @@ class AutofillRecords {
_generateGUID() { _generateGUID() {
let guid; let guid;
while (!guid || this._findByGUID(guid)) { while (!guid || this._findByGUID(guid)) {
guid = gUUIDGenerator guid = Services.uuid
.generateUUID() .generateUUID()
.toString() .toString()
.replace(/[{}-]/g, "") .replace(/[{}-]/g, "")

View file

@ -6,21 +6,12 @@
var EXPORTED_SYMBOLS = ["NormandyUtils"]; var EXPORTED_SYMBOLS = ["NormandyUtils"];
const { XPCOMUtils } = ChromeUtils.import( const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
var NormandyUtils = { var NormandyUtils = {
generateUuid() { generateUuid() {
// Generate a random UUID, convert it to a string, and slice the braces off the ends. // Generate a random UUID, convert it to a string, and slice the braces off the ends.
return uuidGenerator return Services.uuid
.generateUUID() .generateUUID()
.toString() .toString()
.slice(1, -1); .slice(1, -1);

View file

@ -20,12 +20,6 @@ XPCOMUtils.defineLazyServiceGetter(
"@mozilla.org/contentsecuritymanager;1", "@mozilla.org/contentsecuritymanager;1",
"nsIContentSecurityManager" "nsIContentSecurityManager"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"gScriptSecurityManager",
"@mozilla.org/scriptsecuritymanager;1",
"nsIScriptSecurityManager"
);
ChromeUtils.defineModuleGetter( ChromeUtils.defineModuleGetter(
this, this,
"LoginHelper", "LoginHelper",
@ -95,7 +89,10 @@ this.InsecurePasswordUtils = {
let uri = Services.io.newURI( let uri = Services.io.newURI(
aForm.rootElement.action || aForm.rootElement.baseURI aForm.rootElement.action || aForm.rootElement.baseURI
); );
let principal = gScriptSecurityManager.createContentPrincipal(uri, {}); let principal = Services.scriptSecurityManager.createContentPrincipal(
uri,
{}
);
if (uri.schemeIs("http")) { if (uri.schemeIs("http")) {
isFormSubmitHTTP = true; isFormSubmitHTTP = true;

View file

@ -27,13 +27,6 @@ ChromeUtils.defineModuleGetter(
"resource://gre/modules/LoginStore.jsm" "resource://gre/modules/LoginStore.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"gUUIDGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
XPCOMUtils.defineLazyModuleGetters(this, { XPCOMUtils.defineLazyModuleGetters(this, {
FXA_PWDMGR_HOST: "resource://gre/modules/FxAccountsCommon.js", FXA_PWDMGR_HOST: "resource://gre/modules/FxAccountsCommon.js",
FXA_PWDMGR_REALM: "resource://gre/modules/FxAccountsCommon.js", FXA_PWDMGR_REALM: "resource://gre/modules/FxAccountsCommon.js",
@ -231,7 +224,7 @@ class LoginManagerStorage_json {
this._store.data.logins.splice(foundIndex, 1); this._store.data.logins.splice(foundIndex, 1);
} }
} else { } else {
loginClone.guid = gUUIDGenerator.generateUUID().toString(); loginClone.guid = Services.uuid.generateUUID().toString();
} }
// Set timestamps // Set timestamps

View file

@ -10,13 +10,6 @@
// Globals // Globals
XPCOMUtils.defineLazyServiceGetter(
this,
"gUUIDGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
const gLooksLikeUUIDRegex = /^\{\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\}$/; const gLooksLikeUUIDRegex = /^\{\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\}$/;
/** /**
@ -76,7 +69,7 @@ add_task(function test_initialize() {
gLoginInfo1 = TestData.formLogin(); gLoginInfo1 = TestData.formLogin();
gLoginInfo2 = TestData.formLogin({ gLoginInfo2 = TestData.formLogin({
origin: "http://other.example.com", origin: "http://other.example.com",
guid: gUUIDGenerator.generateUUID().toString(), guid: Services.uuid.generateUUID().toString(),
timeCreated: baseTimeMs, timeCreated: baseTimeMs,
timeLastUsed: baseTimeMs + 2, timeLastUsed: baseTimeMs + 2,
timePasswordChanged: baseTimeMs + 1, timePasswordChanged: baseTimeMs + 1,
@ -149,7 +142,7 @@ add_task(function test_addLogin_metainfo_duplicate() {
*/ */
add_task(function test_modifyLogin_nsILoginInfo_metainfo_ignored() { add_task(function test_modifyLogin_nsILoginInfo_metainfo_ignored() {
let newLoginInfo = gLoginInfo1.clone().QueryInterface(Ci.nsILoginMetaInfo); let newLoginInfo = gLoginInfo1.clone().QueryInterface(Ci.nsILoginMetaInfo);
newLoginInfo.guid = gUUIDGenerator.generateUUID().toString(); newLoginInfo.guid = Services.uuid.generateUUID().toString();
newLoginInfo.timeCreated = Date.now(); newLoginInfo.timeCreated = Date.now();
newLoginInfo.timeLastUsed = Date.now(); newLoginInfo.timeLastUsed = Date.now();
newLoginInfo.timePasswordChanged = Date.now(); newLoginInfo.timePasswordChanged = Date.now();
@ -166,7 +159,7 @@ add_task(function test_modifyLogin_nsILoginInfo_metainfo_ignored() {
add_task(function test_modifyLogin_nsIProperyBag_metainfo() { add_task(function test_modifyLogin_nsIProperyBag_metainfo() {
// Use a new reference time that is two minutes from now. // Use a new reference time that is two minutes from now.
let newTimeMs = Date.now() + 120000; let newTimeMs = Date.now() + 120000;
let newUUIDValue = gUUIDGenerator.generateUUID().toString(); let newUUIDValue = Services.uuid.generateUUID().toString();
// Check that properties are changed as requested. // Check that properties are changed as requested.
Services.logins.modifyLogin( Services.logins.modifyLogin(

View file

@ -87,20 +87,11 @@
var EXPORTED_SYMBOLS = ["FormHistory"]; var EXPORTED_SYMBOLS = ["FormHistory"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { AppConstants } = ChromeUtils.import( const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm" "resource://gre/modules/AppConstants.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidService",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
ChromeUtils.defineModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm"); ChromeUtils.defineModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm");
ChromeUtils.defineModuleGetter( ChromeUtils.defineModuleGetter(
this, this,
@ -317,7 +308,7 @@ function makeQueryPredicates(aQueryData, delimiter = " AND ") {
function generateGUID() { function generateGUID() {
// string like: "{f60d9eac-9421-4abc-8491-8e8322b063d4}" // string like: "{f60d9eac-9421-4abc-8491-8e8322b063d4}"
let uuid = uuidService.generateUUID().toString(); let uuid = Services.uuid.generateUUID().toString();
let raw = ""; // A string with the low bytes set to random values let raw = ""; // A string with the low bytes set to random values
let bytes = 0; let bytes = 0;
for (let i = 1; bytes < 12; i += 2) { for (let i = 1; bytes < 12; i += 2) {

View file

@ -26,13 +26,6 @@ const SEARCH_DATA_TRANSFERRED_SCALAR = "browser.search.data_transferred";
const SEARCH_TELEMETRY_KEY_PREFIX = "sggt"; const SEARCH_TELEMETRY_KEY_PREFIX = "sggt";
const SEARCH_TELEMETRY_PRIVATE_BROWSING_KEY_SUFFIX = "pb"; const SEARCH_TELEMETRY_PRIVATE_BROWSING_KEY_SUFFIX = "pb";
XPCOMUtils.defineLazyServiceGetter(
this,
"UUIDGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
/** /**
* Generates an UUID. * Generates an UUID.
* *
@ -40,7 +33,7 @@ XPCOMUtils.defineLazyServiceGetter(
* An UUID string, without leading or trailing braces. * An UUID string, without leading or trailing braces.
*/ */
function uuid() { function uuid() {
let uuid = UUIDGenerator.generateUUID().toString(); let uuid = Services.uuid.generateUUID().toString();
return uuid.slice(1, uuid.length - 1); return uuid.slice(1, uuid.length - 1);
} }

View file

@ -48,13 +48,6 @@ const PING_TYPE_UNINSTALL = "uninstall";
const REASON_GATHER_PAYLOAD = "gather-payload"; const REASON_GATHER_PAYLOAD = "gather-payload";
const REASON_GATHER_SUBSESSION_PAYLOAD = "gather-subsession-payload"; const REASON_GATHER_SUBSESSION_PAYLOAD = "gather-subsession-payload";
XPCOMUtils.defineLazyServiceGetter(
this,
"Telemetry",
"@mozilla.org/base/telemetry;1",
"nsITelemetry"
);
ChromeUtils.defineModuleGetter( ChromeUtils.defineModuleGetter(
this, this,
"jwcrypto", "jwcrypto",
@ -476,9 +469,9 @@ var Impl = {
// cached. // cached.
if (!this._clientID && aOptions.addClientId && !aOptions.overrideClientId) { if (!this._clientID && aOptions.addClientId && !aOptions.overrideClientId) {
this._log.trace("_submitPingLogic - Waiting on client id"); this._log.trace("_submitPingLogic - Waiting on client id");
Telemetry.getHistogramById( Services.telemetry
"TELEMETRY_PING_SUBMISSION_WAITING_CLIENTID" .getHistogramById("TELEMETRY_PING_SUBMISSION_WAITING_CLIENTID")
).add(); .add();
// We can safely call |getClientID| here and during initialization: we would still // We can safely call |getClientID| here and during initialization: we would still
// spawn and return one single loading task. // spawn and return one single loading task.
this._clientID = await ClientID.getClientID(); this._clientID = await ClientID.getClientID();
@ -607,7 +600,7 @@ var Impl = {
const typeUuid = /^[a-z0-9][a-z0-9-]+[a-z0-9]$/i; const typeUuid = /^[a-z0-9][a-z0-9-]+[a-z0-9]$/i;
if (!typeUuid.test(aType)) { if (!typeUuid.test(aType)) {
this._log.error("submitExternalPing - invalid ping type: " + aType); this._log.error("submitExternalPing - invalid ping type: " + aType);
let histogram = Telemetry.getKeyedHistogramById( let histogram = Services.telemetry.getKeyedHistogramById(
"TELEMETRY_INVALID_PING_TYPE_SUBMITTED" "TELEMETRY_INVALID_PING_TYPE_SUBMITTED"
); );
histogram.add(aType, 1); histogram.add(aType, 1);
@ -622,7 +615,7 @@ var Impl = {
this._log.error( this._log.error(
"submitExternalPing - invalid payload type: " + typeof aPayload "submitExternalPing - invalid payload type: " + typeof aPayload
); );
let histogram = Telemetry.getHistogramById( let histogram = Services.telemetry.getHistogramById(
"TELEMETRY_INVALID_PAYLOAD_SUBMITTED" "TELEMETRY_INVALID_PAYLOAD_SUBMITTED"
); );
histogram.add(1); histogram.add(1);
@ -1106,7 +1099,7 @@ var Impl = {
await ClientID.removeClientID(); await ClientID.removeClientID();
let id = await ClientID.getClientID(); let id = await ClientID.getClientID();
this._clientID = id; this._clientID = id;
Telemetry.scalarSet("telemetry.data_upload_optin", true); Services.telemetry.scalarSet("telemetry.data_upload_optin", true);
await this.saveUninstallPing().catch(e => await this.saveUninstallPing().catch(e =>
this._log.warn("_onUploadPrefChange - saveUninstallPing failed", e) this._log.warn("_onUploadPrefChange - saveUninstallPing failed", e)
@ -1142,7 +1135,7 @@ var Impl = {
// 5. Collect any additional identifiers we want to send in the // 5. Collect any additional identifiers we want to send in the
// deletion request. // deletion request.
const scalars = Telemetry.getSnapshotForScalars( const scalars = Services.telemetry.getSnapshotForScalars(
"deletion-request", "deletion-request",
/* clear */ true /* clear */ true
); );
@ -1213,7 +1206,7 @@ var Impl = {
this._log.trace("getCurrentPingData - subsession: " + aSubsession); this._log.trace("getCurrentPingData - subsession: " + aSubsession);
// Telemetry is disabled, don't gather any data. // Telemetry is disabled, don't gather any data.
if (!Telemetry.canRecordBase) { if (!Services.telemetry.canRecordBase) {
return null; return null;
} }
@ -1284,7 +1277,7 @@ var Impl = {
"sendNewProfilePing - shutting down: " + this._shuttingDown "sendNewProfilePing - shutting down: " + this._shuttingDown
); );
const scalars = Telemetry.getSnapshotForScalars( const scalars = Services.telemetry.getSnapshotForScalars(
"new-profile", "new-profile",
/* clear */ true /* clear */ true
); );
@ -1375,13 +1368,13 @@ var Impl = {
let newValue; let newValue;
switch (value) { switch (value) {
case "nsITelemetry::SCALAR_TYPE_COUNT": case "nsITelemetry::SCALAR_TYPE_COUNT":
newValue = Telemetry.SCALAR_TYPE_COUNT; newValue = Services.telemetry.SCALAR_TYPE_COUNT;
break; break;
case "nsITelemetry::SCALAR_TYPE_BOOLEAN": case "nsITelemetry::SCALAR_TYPE_BOOLEAN":
newValue = Telemetry.SCALAR_TYPE_BOOLEAN; newValue = Services.telemetry.SCALAR_TYPE_BOOLEAN;
break; break;
case "nsITelemetry::SCALAR_TYPE_STRING": case "nsITelemetry::SCALAR_TYPE_STRING":
newValue = Telemetry.SCALAR_TYPE_STRING; newValue = Services.telemetry.SCALAR_TYPE_STRING;
break; break;
} }
return newValue; return newValue;
@ -1412,7 +1405,10 @@ var Impl = {
def.expired = true; def.expired = true;
} }
} }
Telemetry.registerBuiltinScalars(category, scalarJSProbes[category]); Services.telemetry.registerBuiltinScalars(
category,
scalarJSProbes[category]
);
} }
}, },
@ -1452,7 +1448,10 @@ var Impl = {
def.expired = true; def.expired = true;
} }
} }
Telemetry.registerBuiltinEvents(category, eventJSProbes[category]); Services.telemetry.registerBuiltinEvents(
category,
eventJSProbes[category]
);
} }
}, },
}; };

View file

@ -23,9 +23,6 @@ var EXPORTED_SYMBOLS = [
const { AppConstants } = ChromeUtils.import( const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm" "resource://gre/modules/AppConstants.jsm"
); );
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { ClientID } = ChromeUtils.import("resource://gre/modules/ClientID.jsm"); const { ClientID } = ChromeUtils.import("resource://gre/modules/ClientID.jsm");
const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm");
const { PromiseUtils } = ChromeUtils.import( const { PromiseUtils } = ChromeUtils.import(
@ -53,12 +50,6 @@ ChromeUtils.defineModuleGetter(
"resource://gre/modules/TelemetryReportingPolicy.jsm" "resource://gre/modules/TelemetryReportingPolicy.jsm"
); );
ChromeUtils.defineModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm"); ChromeUtils.defineModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm");
XPCOMUtils.defineLazyServiceGetter(
this,
"Telemetry",
"@mozilla.org/base/telemetry;1",
"nsITelemetry"
);
ChromeUtils.defineModuleGetter( ChromeUtils.defineModuleGetter(
this, this,
"TelemetryHealthPing", "TelemetryHealthPing",
@ -853,7 +844,9 @@ var TelemetrySendImpl = {
const ageInDays = Utils.millisecondsToDays( const ageInDays = Utils.millisecondsToDays(
Math.abs(now.getTime() - pingInfo.lastModificationDate) Math.abs(now.getTime() - pingInfo.lastModificationDate)
); );
Telemetry.getHistogramById("TELEMETRY_PENDING_PINGS_AGE").add(ageInDays); Services.telemetry
.getHistogramById("TELEMETRY_PENDING_PINGS_AGE")
.add(ageInDays);
} }
}, },
@ -920,11 +913,13 @@ var TelemetrySendImpl = {
"TELEMETRY_SEND_FAILURE_TYPE", "TELEMETRY_SEND_FAILURE_TYPE",
]; ];
histograms.forEach(h => Telemetry.getHistogramById(h).clear()); histograms.forEach(h => Services.telemetry.getHistogramById(h).clear());
const keyedHistograms = ["TELEMETRY_SEND_FAILURE_TYPE_PER_PING"]; const keyedHistograms = ["TELEMETRY_SEND_FAILURE_TYPE_PER_PING"];
keyedHistograms.forEach(h => Telemetry.getKeyedHistogramById(h).clear()); keyedHistograms.forEach(h =>
Services.telemetry.getKeyedHistogramById(h).clear()
);
return SendScheduler.reset(); return SendScheduler.reset();
}, },
@ -1208,8 +1203,8 @@ var TelemetrySendImpl = {
); );
let sendId = success ? "TELEMETRY_SEND_SUCCESS" : "TELEMETRY_SEND_FAILURE"; let sendId = success ? "TELEMETRY_SEND_SUCCESS" : "TELEMETRY_SEND_FAILURE";
let hsend = Telemetry.getHistogramById(sendId); let hsend = Services.telemetry.getHistogramById(sendId);
let hsuccess = Telemetry.getHistogramById("TELEMETRY_SUCCESS"); let hsuccess = Services.telemetry.getHistogramById("TELEMETRY_SUCCESS");
hsend.add(Utils.monotonicNow() - startTime); hsend.add(Utils.monotonicNow() - startTime);
hsuccess.add(success); hsuccess.add(success);
@ -1286,10 +1281,12 @@ var TelemetrySendImpl = {
if (this._tooLateToSend) { if (this._tooLateToSend) {
// Too late to send now. Reject so we pend the ping to send it next time. // Too late to send now. Reject so we pend the ping to send it next time.
this._log.trace("_doPing - Too late to send ping " + ping.id); this._log.trace("_doPing - Too late to send ping " + ping.id);
Telemetry.getHistogramById("TELEMETRY_SEND_FAILURE_TYPE").add("eTooLate"); Services.telemetry
Telemetry.getKeyedHistogramById( .getHistogramById("TELEMETRY_SEND_FAILURE_TYPE")
"TELEMETRY_SEND_FAILURE_TYPE_PER_PING" .add("eTooLate");
).add(ping.type, "eTooLate"); Services.telemetry
.getKeyedHistogramById("TELEMETRY_SEND_FAILURE_TYPE_PER_PING")
.add(ping.type, "eTooLate");
return Promise.reject(); return Promise.reject();
} }
@ -1370,10 +1367,12 @@ var TelemetrySendImpl = {
} }
} }
Telemetry.getHistogramById("TELEMETRY_SEND_FAILURE_TYPE").add(failure); Services.telemetry
Telemetry.getKeyedHistogramById( .getHistogramById("TELEMETRY_SEND_FAILURE_TYPE")
"TELEMETRY_SEND_FAILURE_TYPE_PER_PING" .add(failure);
).add(ping.type, failure); Services.telemetry
.getKeyedHistogramById("TELEMETRY_SEND_FAILURE_TYPE_PER_PING")
.add(ping.type, failure);
this._log.error( this._log.error(
"_doPing - error making request to " + url + ": " + failure "_doPing - error making request to " + url + ": " + failure
@ -1402,9 +1401,9 @@ var TelemetrySendImpl = {
status + status +
" - ping request broken?" " - ping request broken?"
); );
Telemetry.getHistogramById( Services.telemetry
"TELEMETRY_PING_EVICTED_FOR_SERVER_ERRORS" .getHistogramById("TELEMETRY_PING_EVICTED_FOR_SERVER_ERRORS")
).add(); .add();
// TODO: we should handle this better, but for now we should avoid resubmitting // TODO: we should handle this better, but for now we should avoid resubmitting
// broken requests by pretending success. // broken requests by pretending success.
success = true; success = true;
@ -1444,9 +1443,9 @@ var TelemetrySendImpl = {
JSON.stringify(networkPayload) JSON.stringify(networkPayload)
); );
utf8Payload += converter.Finish(); utf8Payload += converter.Finish();
Telemetry.getHistogramById("TELEMETRY_STRINGIFY").add( Services.telemetry
Utils.monotonicNow() - startTime .getHistogramById("TELEMETRY_STRINGIFY")
); .add(Utils.monotonicNow() - startTime);
let payloadStream = Cc[ let payloadStream = Cc[
"@mozilla.org/io/string-input-stream;1" "@mozilla.org/io/string-input-stream;1"
@ -1461,10 +1460,12 @@ var TelemetrySendImpl = {
"_doPing - submitted ping exceeds the size limit, size: " + "_doPing - submitted ping exceeds the size limit, size: " +
compressedPingSizeBytes compressedPingSizeBytes
); );
Telemetry.getHistogramById("TELEMETRY_PING_SIZE_EXCEEDED_SEND").add(); Services.telemetry
Telemetry.getHistogramById("TELEMETRY_DISCARDED_SEND_PINGS_SIZE_MB").add( .getHistogramById("TELEMETRY_PING_SIZE_EXCEEDED_SEND")
Math.floor(compressedPingSizeBytes / 1024 / 1024) .add();
); Services.telemetry
.getHistogramById("TELEMETRY_DISCARDED_SEND_PINGS_SIZE_MB")
.add(Math.floor(compressedPingSizeBytes / 1024 / 1024));
// We don't need to call |request.abort()| as it was not sent yet. // We don't need to call |request.abort()| as it was not sent yet.
this._pendingPingRequests.delete(id); this._pendingPingRequests.delete(id);
@ -1472,9 +1473,9 @@ var TelemetrySendImpl = {
return TelemetryStorage.removePendingPing(id); return TelemetryStorage.removePendingPing(id);
} }
Telemetry.getHistogramById("TELEMETRY_COMPRESS").add( Services.telemetry
Utils.monotonicNow() - startTime .getHistogramById("TELEMETRY_COMPRESS")
); .add(Utils.monotonicNow() - startTime);
request.sendInputStream(payloadStream); request.sendInputStream(payloadStream);
this.payloadStream = payloadStream; this.payloadStream = payloadStream;
@ -1508,7 +1509,7 @@ var TelemetrySendImpl = {
sendingEnabled(ping = null) { sendingEnabled(ping = null) {
// We only send pings from official builds, but allow overriding this for tests. // We only send pings from official builds, but allow overriding this for tests.
if ( if (
!Telemetry.isOfficialTelemetry && !Services.telemetry.isOfficialTelemetry &&
!this._testMode && !this._testMode &&
!this._overrideOfficialCheck !this._overrideOfficialCheck
) { ) {

View file

@ -21,10 +21,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
Log: "resource://gre/modules/Log.jsm", Log: "resource://gre/modules/Log.jsm",
}); });
XPCOMUtils.defineLazyServiceGetters(this, {
Telemetry: ["@mozilla.org/base/telemetry;1", "nsITelemetry"],
});
ChromeUtils.defineModuleGetter( ChromeUtils.defineModuleGetter(
this, this,
"setTimeout", "setTimeout",
@ -85,7 +81,7 @@ var TelemetryEventPing = {
_processStartTimestamp: 0, _processStartTimestamp: 0,
get dataset() { get dataset() {
return Telemetry.canRecordPrereleaseData return Services.telemetry.canRecordPrereleaseData
? Ci.nsITelemetry.DATASET_PRERELEASE_CHANNELS ? Ci.nsITelemetry.DATASET_PRERELEASE_CHANNELS
: Ci.nsITelemetry.DATASET_ALL_CHANNELS; : Ci.nsITelemetry.DATASET_ALL_CHANNELS;
}, },
@ -180,7 +176,7 @@ var TelemetryEventPing = {
this._startTimer(); this._startTimer();
} }
let snapshot = Telemetry.snapshotEvents( let snapshot = Services.telemetry.snapshotEvents(
this.dataset, this.dataset,
true /* clear */, true /* clear */,
DEFAULT_EVENT_LIMIT DEFAULT_EVENT_LIMIT
@ -220,7 +216,10 @@ var TelemetryEventPing = {
// Any leftovers must be discarded, the count submitted in the ping. // Any leftovers must be discarded, the count submitted in the ping.
// This can happen on shutdown or if our max was reached before faster // This can happen on shutdown or if our max was reached before faster
// than our maxFrequency. // than our maxFrequency.
let leftovers = Telemetry.snapshotEvents(this.dataset, true /* clear */); let leftovers = Services.telemetry.snapshotEvents(
this.dataset,
true /* clear */
);
let leftoverCount = Object.values(leftovers).reduce( let leftoverCount = Object.values(leftovers).reduce(
(acc, val) => acc + val.length, (acc, val) => acc + val.length,
0 0
@ -235,7 +234,9 @@ var TelemetryEventPing = {
}; };
this._lastSendTime = Utils.monotonicNow(); this._lastSendTime = Utils.monotonicNow();
Telemetry.getHistogramById("TELEMETRY_EVENT_PING_SENT").add(reason); Services.telemetry
.getHistogramById("TELEMETRY_EVENT_PING_SENT")
.add(reason);
Policy.sendPing(this.EVENT_PING_TYPE, payload, options); Policy.sendPing(this.EVENT_PING_TYPE, payload, options);
}, },

View file

@ -24,6 +24,11 @@ ChromeUtils.defineModuleGetter(
"AppConstants", "AppConstants",
"resource://gre/modules/AppConstants.jsm" "resource://gre/modules/AppConstants.jsm"
); );
ChromeUtils.defineModuleGetter(
this,
"Services",
"resource://gre/modules/Services.jsm"
);
XPCOMUtils.defineLazyServiceGetter( XPCOMUtils.defineLazyServiceGetter(
this, this,
@ -31,12 +36,6 @@ XPCOMUtils.defineLazyServiceGetter(
"@mozilla.org/updates/timer-manager;1", "@mozilla.org/updates/timer-manager;1",
"nsIUpdateTimerManager" "nsIUpdateTimerManager"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"Telemetry",
"@mozilla.org/base/telemetry;1",
"nsITelemetry"
);
var EXPORTED_SYMBOLS = ["TelemetryModules"]; var EXPORTED_SYMBOLS = ["TelemetryModules"];
@ -80,7 +79,7 @@ var TelemetryModules = Object.freeze({
*/ */
notify() { notify() {
try { try {
Telemetry.getLoadedModules().then( Services.telemetry.getLoadedModules().then(
modules => { modules => {
modules = modules.filter(module => !!module.name.length); modules = modules.filter(module => !!module.name.length);

View file

@ -20,10 +20,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
Log: "resource://gre/modules/Log.jsm", Log: "resource://gre/modules/Log.jsm",
}); });
XPCOMUtils.defineLazyServiceGetters(this, {
Telemetry: ["@mozilla.org/base/telemetry;1", "nsITelemetry"],
});
const { TelemetryUtils } = ChromeUtils.import( const { TelemetryUtils } = ChromeUtils.import(
"resource://gre/modules/TelemetryUtils.jsm" "resource://gre/modules/TelemetryUtils.jsm"
); );
@ -43,7 +39,7 @@ var Policy = {
sendPing: (type, payload, options) => sendPing: (type, payload, options) =>
TelemetryController.submitExternalPing(type, payload, options), TelemetryController.submitExternalPing(type, payload, options),
getEncodedOriginSnapshot: async aClear => getEncodedOriginSnapshot: async aClear =>
Telemetry.getEncodedOriginSnapshot(aClear), Services.telemetry.getEncodedOriginSnapshot(aClear),
}; };
var TelemetryPrioPing = { var TelemetryPrioPing = {
@ -60,7 +56,7 @@ var TelemetryPrioPing = {
_timeoutId: null, _timeoutId: null,
startup() { startup() {
if (!this._testing && !Telemetry.canRecordPrereleaseData) { if (!this._testing && !Services.telemetry.canRecordPrereleaseData) {
this._log.trace("Extended collection disabled. Prio ping disabled."); this._log.trace("Extended collection disabled. Prio ping disabled.");
return; return;
} }

View file

@ -63,10 +63,6 @@ const IS_UNIFIED_TELEMETRY = Services.prefs.getBoolPref(
var gWasDebuggerAttached = false; var gWasDebuggerAttached = false;
XPCOMUtils.defineLazyServiceGetters(this, {
Telemetry: ["@mozilla.org/base/telemetry;1", "nsITelemetry"],
});
function generateUUID() { function generateUUID() {
let str = Services.uuid.generateUUID().toString(); let str = Services.uuid.generateUUID().toString();
// strip {} // strip {}
@ -411,7 +407,7 @@ var Impl = {
} catch (ex) {} } catch (ex) {}
// Only submit this if the extended set is enabled. // Only submit this if the extended set is enabled.
if (!Utils.isContentProcess && Telemetry.canRecordExtended) { if (!Utils.isContentProcess && Services.telemetry.canRecordExtended) {
try { try {
ret.addonManager = AddonManagerPrivate.getSimpleMeasures(); ret.addonManager = AddonManagerPrivate.getSimpleMeasures();
} catch (ex) {} } catch (ex) {}
@ -448,12 +444,12 @@ var Impl = {
gWasDebuggerAttached = gWasDebuggerAttached || isDebuggerAttached; gWasDebuggerAttached = gWasDebuggerAttached || isDebuggerAttached;
ret.debuggerAttached = Number(gWasDebuggerAttached); ret.debuggerAttached = Number(gWasDebuggerAttached);
let shutdownDuration = Telemetry.lastShutdownDuration; let shutdownDuration = Services.telemetry.lastShutdownDuration;
if (shutdownDuration) { if (shutdownDuration) {
ret.shutdownDuration = shutdownDuration; ret.shutdownDuration = shutdownDuration;
} }
let failedProfileLockCount = Telemetry.failedProfileLockCount; let failedProfileLockCount = Services.telemetry.failedProfileLockCount;
if (failedProfileLockCount) { if (failedProfileLockCount) {
ret.failedProfileLockCount = failedProfileLockCount; ret.failedProfileLockCount = failedProfileLockCount;
} }
@ -477,7 +473,7 @@ var Impl = {
}, },
getHistograms: function getHistograms(clearSubsession) { getHistograms: function getHistograms(clearSubsession) {
return Telemetry.getSnapshotForHistograms( return Services.telemetry.getSnapshotForHistograms(
"main", "main",
clearSubsession, clearSubsession,
!this._testing !this._testing
@ -485,7 +481,7 @@ var Impl = {
}, },
getKeyedHistograms(clearSubsession) { getKeyedHistograms(clearSubsession) {
return Telemetry.getSnapshotForKeyedHistograms( return Services.telemetry.getSnapshotForKeyedHistograms(
"main", "main",
clearSubsession, clearSubsession,
!this._testing !this._testing
@ -509,12 +505,12 @@ var Impl = {
} }
let scalarsSnapshot = keyed let scalarsSnapshot = keyed
? Telemetry.getSnapshotForKeyedScalars( ? Services.telemetry.getSnapshotForKeyedScalars(
"main", "main",
clearSubsession, clearSubsession,
!this._testing !this._testing
) )
: Telemetry.getSnapshotForScalars( : Services.telemetry.getSnapshotForScalars(
"main", "main",
clearSubsession, clearSubsession,
!this._testing !this._testing
@ -619,7 +615,7 @@ var Impl = {
}; };
// Add extended set measurements common to chrome & content processes // Add extended set measurements common to chrome & content processes
if (Telemetry.canRecordExtended) { if (Services.telemetry.canRecordExtended) {
payloadObj.log = []; payloadObj.log = [];
} }
@ -695,10 +691,12 @@ var Impl = {
payloadObj.info = info; payloadObj.info = info;
// Add extended set measurements for chrome process. // Add extended set measurements for chrome process.
if (Telemetry.canRecordExtended) { if (Services.telemetry.canRecordExtended) {
payloadObj.slowSQL = protect(() => Telemetry.slowSQL); payloadObj.slowSQL = protect(() => Services.telemetry.slowSQL);
payloadObj.fileIOReports = protect(() => Telemetry.fileIOReports); payloadObj.fileIOReports = protect(
payloadObj.lateWrites = protect(() => Telemetry.lateWrites); () => Services.telemetry.fileIOReports
);
payloadObj.lateWrites = protect(() => Services.telemetry.lateWrites);
payloadObj.addonDetails = protect(() => payloadObj.addonDetails = protect(() =>
AddonManagerPrivate.getTelemetryDetails() AddonManagerPrivate.getTelemetryDetails()
@ -749,13 +747,13 @@ var Impl = {
// been suspended since boot, we want the previous property to hold, // been suspended since boot, we want the previous property to hold,
// regardless of the delay during or between the two // regardless of the delay during or between the two
// `msSinceProcessStart*` calls. // `msSinceProcessStart*` calls.
Telemetry.scalarSet( Services.telemetry.scalarSet(
"browser.engagement.session_time_excluding_suspend", "browser.engagement.session_time_excluding_suspend",
Telemetry.msSinceProcessStartExcludingSuspend() Services.telemetry.msSinceProcessStartExcludingSuspend()
); );
Telemetry.scalarSet( Services.telemetry.scalarSet(
"browser.engagement.session_time_including_suspend", "browser.engagement.session_time_including_suspend",
Telemetry.msSinceProcessStartIncludingSuspend() Services.telemetry.msSinceProcessStartIncludingSuspend()
); );
if (isMobile) { if (isMobile) {
@ -775,7 +773,9 @@ var Impl = {
clearSubsession clearSubsession
); );
} catch (ex) { } catch (ex) {
Telemetry.getHistogramById("TELEMETRY_ASSEMBLE_PAYLOAD_EXCEPTION").add(1); Services.telemetry
.getHistogramById("TELEMETRY_ASSEMBLE_PAYLOAD_EXCEPTION")
.add(1);
throw ex; throw ex;
} finally { } finally {
if (!Utils.isContentProcess && clearSubsession) { if (!Utils.isContentProcess && clearSubsession) {
@ -847,7 +847,7 @@ var Impl = {
return; return;
} }
if (!Telemetry.canRecordBase && !testing) { if (!Services.telemetry.canRecordBase && !testing) {
this._log.config( this._log.config(
"earlyInit - Telemetry recording is disabled, skipping Chrome process setup." "earlyInit - Telemetry recording is disabled, skipping Chrome process setup."
); );
@ -903,7 +903,7 @@ var Impl = {
this.addObserver("idle-daily"); this.addObserver("idle-daily");
await Services.telemetry.gatherMemory(); await Services.telemetry.gatherMemory();
Telemetry.asyncFetchTelemetryData(function() {}); Services.telemetry.asyncFetchTelemetryData(function() {});
if (IS_UNIFIED_TELEMETRY) { if (IS_UNIFIED_TELEMETRY) {
// Check for a previously written aborted session ping. // Check for a previously written aborted session ping.
@ -1020,7 +1020,10 @@ var Impl = {
} }
} }
if (AppConstants.platform == "android" && Telemetry.canRecordExtended) { if (
AppConstants.platform == "android" &&
Services.telemetry.canRecordExtended
) {
let payload = this.getSessionPayload(REASON_SAVED_SESSION, false); let payload = this.getSessionPayload(REASON_SAVED_SESSION, false);
let options = { let options = {
@ -1080,7 +1083,7 @@ var Impl = {
// This function returns the current Telemetry payload to the caller. // This function returns the current Telemetry payload to the caller.
// We only gather startup info once. // We only gather startup info once.
if (!Object.keys(this._slowSQLStartup).length) { if (!Object.keys(this._slowSQLStartup).length) {
this._slowSQLStartup = Telemetry.slowSQL; this._slowSQLStartup = Services.telemetry.slowSQL;
} }
Services.telemetry.gatherMemory(); Services.telemetry.gatherMemory();
return this.getSessionPayload(reason, clearSubsession); return this.getSessionPayload(reason, clearSubsession);
@ -1095,7 +1098,7 @@ var Impl = {
this._startupIO.startupSessionRestoreWriteBytes, this._startupIO.startupSessionRestoreWriteBytes,
] = counters; ] = counters;
} }
this._slowSQLStartup = Telemetry.slowSQL; this._slowSQLStartup = Services.telemetry.slowSQL;
}, },
setAddOns: function setAddOns(aAddOns) { setAddOns: function setAddOns(aAddOns) {
@ -1117,7 +1120,7 @@ var Impl = {
// inactivity, because it is just the start of this active tick. // inactivity, because it is just the start of this active tick.
if (needsUpdate) { if (needsUpdate) {
this._sessionActiveTicks++; this._sessionActiveTicks++;
Telemetry.scalarAdd("browser.engagement.active_ticks", 1); Services.telemetry.scalarAdd("browser.engagement.active_ticks", 1);
} }
}, },
@ -1302,9 +1305,9 @@ var Impl = {
!("sessionId" in data) !("sessionId" in data)
) { ) {
this._log.error("_loadSessionData - session data is invalid"); this._log.error("_loadSessionData - session data is invalid");
Telemetry.getHistogramById("TELEMETRY_SESSIONDATA_FAILED_VALIDATION").add( Services.telemetry
1 .getHistogramById("TELEMETRY_SESSIONDATA_FAILED_VALIDATION")
); .add(1);
return null; return null;
} }

View file

@ -25,7 +25,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
}); });
XPCOMUtils.defineLazyServiceGetters(this, { XPCOMUtils.defineLazyServiceGetters(this, {
Telemetry: ["@mozilla.org/base/telemetry;1", "nsITelemetry"],
UpdateTimerManager: [ UpdateTimerManager: [
"@mozilla.org/updates/timer-manager;1", "@mozilla.org/updates/timer-manager;1",
"nsIUpdateTimerManager", "nsIUpdateTimerManager",
@ -55,7 +54,7 @@ var TelemetryUntrustedModulesPing = Object.freeze({
notify() { notify() {
try { try {
Telemetry.getUntrustedModuleLoadEvents().then(payload => { Services.telemetry.getUntrustedModuleLoadEvents().then(payload => {
try { try {
if (payload) { if (payload) {
TelemetryController.submitExternalPing( TelemetryController.submitExternalPing(

View file

@ -14,13 +14,6 @@ Services.scriptloader.loadSubScript(
); );
var { PageThumbsStorageMigrator } = tmp; var { PageThumbsStorageMigrator } = tmp;
XPCOMUtils.defineLazyServiceGetter(
this,
"gDirSvc",
"@mozilla.org/file/directory_service;1",
"nsIProperties"
);
/** /**
* This test makes sure we correctly migrate to thumbnail storage version 3. * This test makes sure we correctly migrate to thumbnail storage version 3.
* This means copying existing thumbnails from the roaming to the local profile * This means copying existing thumbnails from the roaming to the local profile
@ -76,13 +69,13 @@ function* runTests() {
} }
function changeLocation(aLocation, aNewDir) { function changeLocation(aLocation, aNewDir) {
let oldDir = gDirSvc.get(aLocation, Ci.nsIFile); let oldDir = Services.dirsvc.get(aLocation, Ci.nsIFile);
gDirSvc.undefine(aLocation); Services.dirsvc.undefine(aLocation);
gDirSvc.set(aLocation, aNewDir); Services.dirsvc.set(aLocation, aNewDir);
registerCleanupFunction(function() { registerCleanupFunction(function() {
gDirSvc.undefine(aLocation); Services.dirsvc.undefine(aLocation);
gDirSvc.set(aLocation, oldDir); Services.dirsvc.set(aLocation, oldDir);
}); });
} }

View file

@ -12,6 +12,11 @@ const Cm = Components.manager;
const { XPCOMUtils } = ChromeUtils.import( const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm" "resource://gre/modules/XPCOMUtils.jsm"
); );
ChromeUtils.defineModuleGetter(
this,
"Services",
"resource://gre/modules/Services.jsm"
);
const CATEGORY_UPDATE_TIMER = "update-timer"; const CATEGORY_UPDATE_TIMER = "update-timer";
@ -137,20 +142,6 @@ const TESTS = [
var gUTM; var gUTM;
var gNextFunc; var gNextFunc;
XPCOMUtils.defineLazyServiceGetter(
this,
"gPref",
"@mozilla.org/preferences-service;1",
"nsIPrefBranch"
);
XPCOMUtils.defineLazyServiceGetter(
this,
"gCatMan",
"@mozilla.org/categorymanager;1",
"nsICategoryManager"
);
XPCOMUtils.defineLazyGetter(this, "gCompReg", function() { XPCOMUtils.defineLazyGetter(this, "gCompReg", function() {
return Cm.QueryInterface(Ci.nsIComponentRegistrar); return Cm.QueryInterface(Ci.nsIComponentRegistrar);
}); });
@ -224,7 +215,11 @@ const gTest3Factory = {
const gTest4TimerCallback = { const gTest4TimerCallback = {
notify: function T4CB_notify(aTimer) { notify: function T4CB_notify(aTimer) {
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[4].desc, true); Services.catMan.deleteCategoryEntry(
CATEGORY_UPDATE_TIMER,
TESTS[4].desc,
true
);
TESTS[4].notified = true; TESTS[4].notified = true;
finished_test0thru7(); finished_test0thru7();
}, },
@ -242,7 +237,11 @@ const gTest4Factory = {
const gTest5TimerCallback = { const gTest5TimerCallback = {
notify: function T5CB_notify(aTimer) { notify: function T5CB_notify(aTimer) {
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[5].desc, true); Services.catMan.deleteCategoryEntry(
CATEGORY_UPDATE_TIMER,
TESTS[5].desc,
true
);
TESTS[5].notified = true; TESTS[5].notified = true;
finished_test0thru7(); finished_test0thru7();
}, },
@ -260,7 +259,11 @@ const gTest5Factory = {
const gTest6TimerCallback = { const gTest6TimerCallback = {
notify: function T6CB_notify(aTimer) { notify: function T6CB_notify(aTimer) {
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[6].desc, true); Services.catMan.deleteCategoryEntry(
CATEGORY_UPDATE_TIMER,
TESTS[6].desc,
true
);
TESTS[6].notified = true; TESTS[6].notified = true;
finished_test0thru7(); finished_test0thru7();
}, },
@ -278,7 +281,11 @@ const gTest6Factory = {
const gTest7TimerCallback = { const gTest7TimerCallback = {
notify: function T7CB_notify(aTimer) { notify: function T7CB_notify(aTimer) {
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[7].desc, true); Services.catMan.deleteCategoryEntry(
CATEGORY_UPDATE_TIMER,
TESTS[7].desc,
true
);
TESTS[7].notified = true; TESTS[7].notified = true;
finished_test0thru7(); finished_test0thru7();
}, },
@ -347,18 +354,21 @@ function run_test() {
do_test_pending(); do_test_pending();
// Set the timer to fire every second // Set the timer to fire every second
gPref.setIntPref( Services.prefs.setIntPref(
PREF_APP_UPDATE_TIMERMINIMUMDELAY, PREF_APP_UPDATE_TIMERMINIMUMDELAY,
MAIN_TIMER_INTERVAL / 1000 MAIN_TIMER_INTERVAL / 1000
); );
gPref.setIntPref(PREF_APP_UPDATE_TIMERFIRSTINTERVAL, MAIN_TIMER_INTERVAL); Services.prefs.setIntPref(
gPref.setBoolPref(PREF_APP_UPDATE_LOG_ALL, true); PREF_APP_UPDATE_TIMERFIRSTINTERVAL,
MAIN_TIMER_INTERVAL
);
Services.prefs.setBoolPref(PREF_APP_UPDATE_LOG_ALL, true);
// Remove existing update timers to prevent them from being notified // Remove existing update timers to prevent them from being notified
for (let { data: entry } of gCatMan.enumerateCategory( for (let { data: entry } of Services.catMan.enumerateCategory(
CATEGORY_UPDATE_TIMER CATEGORY_UPDATE_TIMER
)) { )) {
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, entry, false); Services.catMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, entry, false);
} }
gUTM = Cc["@mozilla.org/updates/timer-manager;1"] gUTM = Cc["@mozilla.org/updates/timer-manager;1"]
@ -383,7 +393,7 @@ function run_test0thru7() {
TESTS[0].contractID, TESTS[0].contractID,
gTest0Factory gTest0Factory
); );
gCatMan.addCategoryEntry( Services.catMan.addCategoryEntry(
CATEGORY_UPDATE_TIMER, CATEGORY_UPDATE_TIMER,
TESTS[0].desc, TESTS[0].desc,
[ [
@ -404,7 +414,7 @@ function run_test0thru7() {
TESTS[1].contractID, TESTS[1].contractID,
gTest1Factory gTest1Factory
); );
gCatMan.addCategoryEntry( Services.catMan.addCategoryEntry(
CATEGORY_UPDATE_TIMER, CATEGORY_UPDATE_TIMER,
TESTS[1].desc, TESTS[1].desc,
[ [
@ -420,7 +430,7 @@ function run_test0thru7() {
// has a last update time of now - 43200 which is half of its interval // has a last update time of now - 43200 which is half of its interval
let lastUpdateTime = Math.round(Date.now() / 1000) - 43200; let lastUpdateTime = Math.round(Date.now() / 1000) - 43200;
gPref.setIntPref( Services.prefs.setIntPref(
PREF_BRANCH_LAST_UPDATE_TIME + TESTS[2].timerID, PREF_BRANCH_LAST_UPDATE_TIME + TESTS[2].timerID,
lastUpdateTime lastUpdateTime
); );
@ -430,7 +440,7 @@ function run_test0thru7() {
TESTS[2].contractID, TESTS[2].contractID,
gTest2Factory gTest2Factory
); );
gCatMan.addCategoryEntry( Services.catMan.addCategoryEntry(
CATEGORY_UPDATE_TIMER, CATEGORY_UPDATE_TIMER,
TESTS[2].desc, TESTS[2].desc,
[ [
@ -451,7 +461,7 @@ function run_test0thru7() {
TESTS[3].contractID, TESTS[3].contractID,
gTest3Factory gTest3Factory
); );
gCatMan.addCategoryEntry( Services.catMan.addCategoryEntry(
CATEGORY_UPDATE_TIMER, CATEGORY_UPDATE_TIMER,
TESTS[3].desc, TESTS[3].desc,
[ [
@ -466,14 +476,14 @@ function run_test0thru7() {
); );
// already has a last update time // already has a last update time
gPref.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[4].timerID, 1); Services.prefs.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[4].timerID, 1);
gCompReg.registerFactory( gCompReg.registerFactory(
TESTS[4].classID, TESTS[4].classID,
TESTS[4].desc, TESTS[4].desc,
TESTS[4].contractID, TESTS[4].contractID,
gTest4Factory gTest4Factory
); );
gCatMan.addCategoryEntry( Services.catMan.addCategoryEntry(
CATEGORY_UPDATE_TIMER, CATEGORY_UPDATE_TIMER,
TESTS[4].desc, TESTS[4].desc,
[ [
@ -488,14 +498,14 @@ function run_test0thru7() {
); );
// has an interval preference that overrides the default // has an interval preference that overrides the default
gPref.setIntPref(TESTS[5].prefInterval, CONSUMER_TIMER_INTERVAL); Services.prefs.setIntPref(TESTS[5].prefInterval, CONSUMER_TIMER_INTERVAL);
gCompReg.registerFactory( gCompReg.registerFactory(
TESTS[5].classID, TESTS[5].classID,
TESTS[5].desc, TESTS[5].desc,
TESTS[5].contractID, TESTS[5].contractID,
gTest5Factory gTest5Factory
); );
gCatMan.addCategoryEntry( Services.catMan.addCategoryEntry(
CATEGORY_UPDATE_TIMER, CATEGORY_UPDATE_TIMER,
TESTS[5].desc, TESTS[5].desc,
[ [
@ -511,7 +521,7 @@ function run_test0thru7() {
// has a next update time 24 hours from now // has a next update time 24 hours from now
let nextUpdateTime = Math.round(Date.now() / 1000) + 86400; let nextUpdateTime = Math.round(Date.now() / 1000) + 86400;
gPref.setIntPref( Services.prefs.setIntPref(
PREF_BRANCH_LAST_UPDATE_TIME + TESTS[6].timerID, PREF_BRANCH_LAST_UPDATE_TIME + TESTS[6].timerID,
nextUpdateTime nextUpdateTime
); );
@ -521,7 +531,7 @@ function run_test0thru7() {
TESTS[6].contractID, TESTS[6].contractID,
gTest6Factory gTest6Factory
); );
gCatMan.addCategoryEntry( Services.catMan.addCategoryEntry(
CATEGORY_UPDATE_TIMER, CATEGORY_UPDATE_TIMER,
TESTS[6].desc, TESTS[6].desc,
[ [
@ -536,14 +546,14 @@ function run_test0thru7() {
); );
// has a maximum interval set by the value of MAIN_TIMER_INTERVAL // has a maximum interval set by the value of MAIN_TIMER_INTERVAL
gPref.setIntPref(TESTS[7].prefInterval, 86400); Services.prefs.setIntPref(TESTS[7].prefInterval, 86400);
gCompReg.registerFactory( gCompReg.registerFactory(
TESTS[7].classID, TESTS[7].classID,
TESTS[7].desc, TESTS[7].desc,
TESTS[7].contractID, TESTS[7].contractID,
gTest7Factory gTest7Factory
); );
gCatMan.addCategoryEntry( Services.catMan.addCategoryEntry(
CATEGORY_UPDATE_TIMER, CATEGORY_UPDATE_TIMER,
TESTS[7].desc, TESTS[7].desc,
[ [
@ -610,28 +620,48 @@ function check_test0thru7() {
); );
Assert.ok( Assert.ok(
gPref.prefHasUserValue(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[4].timerID), Services.prefs.prefHasUserValue(
PREF_BRANCH_LAST_UPDATE_TIME + TESTS[4].timerID
),
"first of two category registered timers last update time has " + "first of two category registered timers last update time has " +
"a user value" "a user value"
); );
Assert.ok( Assert.ok(
gPref.prefHasUserValue(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[5].timerID), Services.prefs.prefHasUserValue(
PREF_BRANCH_LAST_UPDATE_TIME + TESTS[5].timerID
),
"second of two category registered timers last update time has " + "second of two category registered timers last update time has " +
"a user value" "a user value"
); );
// Remove the category timers that should have failed // Remove the category timers that should have failed
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[0].desc, true); Services.catMan.deleteCategoryEntry(
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[1].desc, true); CATEGORY_UPDATE_TIMER,
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[2].desc, true); TESTS[0].desc,
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[3].desc, true); true
for (let { data: entry } of gCatMan.enumerateCategory( );
Services.catMan.deleteCategoryEntry(
CATEGORY_UPDATE_TIMER,
TESTS[1].desc,
true
);
Services.catMan.deleteCategoryEntry(
CATEGORY_UPDATE_TIMER,
TESTS[2].desc,
true
);
Services.catMan.deleteCategoryEntry(
CATEGORY_UPDATE_TIMER,
TESTS[3].desc,
true
);
for (let { data: entry } of Services.catMan.enumerateCategory(
CATEGORY_UPDATE_TIMER CATEGORY_UPDATE_TIMER
)) { )) {
gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, entry, false); Services.catMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, entry, false);
} }
let entries = gCatMan.enumerateCategory(CATEGORY_UPDATE_TIMER); let entries = Services.catMan.enumerateCategory(CATEGORY_UPDATE_TIMER);
Assert.ok( Assert.ok(
!entries.hasMoreElements(), !entries.hasMoreElements(),
"no " + "no " +
@ -644,7 +674,7 @@ function check_test0thru7() {
} }
function run_test8thru10() { function run_test8thru10() {
gPref.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[8].timerID, 1); Services.prefs.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[8].timerID, 1);
gCompReg.registerFactory( gCompReg.registerFactory(
TESTS[8].classID, TESTS[8].classID,
TESTS[8].desc, TESTS[8].desc,
@ -656,7 +686,7 @@ function run_test8thru10() {
gTest8TimerCallback, gTest8TimerCallback,
TESTS[8].defaultInterval TESTS[8].defaultInterval
); );
gPref.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[9].timerID, 1); Services.prefs.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[9].timerID, 1);
gCompReg.registerFactory( gCompReg.registerFactory(
TESTS[9].classID, TESTS[9].classID,
TESTS[9].desc, TESTS[9].desc,
@ -702,7 +732,9 @@ function check_test8thru10(aTestTimerCallback) {
"time should have occured" "time should have occured"
); );
let time = gPref.getIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[8].timerID); let time = Services.prefs.getIntPref(
PREF_BRANCH_LAST_UPDATE_TIME + TESTS[8].timerID
);
Assert.notEqual( Assert.notEqual(
time, time,
1, 1,
@ -710,7 +742,9 @@ function check_test8thru10(aTestTimerCallback) {
"should have been updated" "should have been updated"
); );
time = gPref.getIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[9].timerID); time = Services.prefs.getIntPref(
PREF_BRANCH_LAST_UPDATE_TIME + TESTS[9].timerID
);
Assert.notEqual( Assert.notEqual(
time, time,
1, 1,

View file

@ -5,10 +5,6 @@
var EXPORTED_SYMBOLS = ["FileUtils"]; var EXPORTED_SYMBOLS = ["FileUtils"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
ChromeUtils.defineModuleGetter( ChromeUtils.defineModuleGetter(
this, this,
"Services", "Services",
@ -21,13 +17,6 @@ ChromeUtils.defineModuleGetter(
"resource://gre/modules/Deprecated.jsm" "resource://gre/modules/Deprecated.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"gDirService",
"@mozilla.org/file/directory_service;1",
"nsIProperties"
);
var FileUtils = { var FileUtils = {
MODE_RDONLY: 0x01, MODE_RDONLY: 0x01,
MODE_WRONLY: 0x02, MODE_WRONLY: 0x02,
@ -71,7 +60,7 @@ var FileUtils = {
* @return nsIFile object for the location specified. * @return nsIFile object for the location specified.
*/ */
getDir: function FileUtils_getDir(key, pathArray, shouldCreate) { getDir: function FileUtils_getDir(key, pathArray, shouldCreate) {
var dir = gDirService.get(key, Ci.nsIFile); var dir = Services.dirsvc.get(key, Ci.nsIFile);
for (var i = 0; i < pathArray.length; ++i) { for (var i = 0; i < pathArray.length; ++i) {
dir.append(pathArray[i]); dir.append(pathArray[i]);
} }

View file

@ -21,12 +21,6 @@ ChromeUtils.defineModuleGetter(
"resource://gre/modules/FinderIterator.jsm" "resource://gre/modules/FinderIterator.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"Clipboard",
"@mozilla.org/widget/clipboard;1",
"nsIClipboard"
);
XPCOMUtils.defineLazyServiceGetter( XPCOMUtils.defineLazyServiceGetter(
this, this,
"ClipboardHelper", "ClipboardHelper",
@ -807,7 +801,7 @@ Finder.prototype = {
function GetClipboardSearchString(aLoadContext) { function GetClipboardSearchString(aLoadContext) {
let searchString = ""; let searchString = "";
if (!Clipboard.supportsFindClipboard()) { if (!Services.clipboard.supportsFindClipboard()) {
return searchString; return searchString;
} }
@ -818,7 +812,7 @@ function GetClipboardSearchString(aLoadContext) {
trans.init(aLoadContext); trans.init(aLoadContext);
trans.addDataFlavor("text/unicode"); trans.addDataFlavor("text/unicode");
Clipboard.getData(trans, Ci.nsIClipboard.kFindClipboard); Services.clipboard.getData(trans, Ci.nsIClipboard.kFindClipboard);
let data = {}; let data = {};
trans.getTransferData("text/unicode", data); trans.getTransferData("text/unicode", data);
@ -832,7 +826,7 @@ function GetClipboardSearchString(aLoadContext) {
} }
function SetClipboardSearchString(aSearchString) { function SetClipboardSearchString(aSearchString) {
if (!aSearchString || !Clipboard.supportsFindClipboard()) { if (!aSearchString || !Services.clipboard.supportsFindClipboard()) {
return; return;
} }

View file

@ -7,21 +7,12 @@
var EXPORTED_SYMBOLS = ["SessionHistory"]; var EXPORTED_SYMBOLS = ["SessionHistory"];
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
ChromeUtils.defineModuleGetter( ChromeUtils.defineModuleGetter(
this, this,
"E10SUtils", "E10SUtils",
"resource://gre/modules/E10SUtils.jsm" "resource://gre/modules/E10SUtils.jsm"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
function debug(msg) { function debug(msg) {
Services.console.logStringMessage("SessionHistory: " + msg); Services.console.logStringMessage("SessionHistory: " + msg);
@ -482,7 +473,7 @@ var SessionHistoryInternal = {
// is correctly stored as a string. // is correctly stored as a string.
this._docshellUUIDMap.set( this._docshellUUIDMap.set(
entry.docshellID, entry.docshellID,
uuidGenerator.generateUUID().toString() Services.uuid.generateUUID().toString()
); );
} }
entry.docshellUUID = this._docshellUUIDMap.get(entry.docshellID); entry.docshellUUID = this._docshellUUIDMap.get(entry.docshellID);

View file

@ -46,7 +46,6 @@ XPCOMUtils.defineLazyServiceGetters(this, {
"@mozilla.org/addons/addon-manager-startup;1", "@mozilla.org/addons/addon-manager-startup;1",
"amIAddonManagerStartup", "amIAddonManagerStartup",
], ],
uuidGen: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
}); });
XPCOMUtils.defineLazyGetter(this, "AppInfo", () => { XPCOMUtils.defineLazyGetter(this, "AppInfo", () => {
@ -613,7 +612,7 @@ var AddonTestUtils = {
} catch (e) { } catch (e) {
// IDs for WebExtensions are extracted from the certificate when // IDs for WebExtensions are extracted from the certificate when
// not present in the manifest, so just generate a random one. // not present in the manifest, so just generate a random one.
return uuidGen.generateUUID().number; return Services.uuid.generateUUID().number;
} }
}, },
@ -810,7 +809,7 @@ var AddonTestUtils = {
} }
for (let item of newData) { for (let item of newData) {
if (!item.id) { if (!item.id) {
item.id = uuidGen.generateUUID().number.slice(1, -1); item.id = Services.uuid.generateUUID().number.slice(1, -1);
} }
if (!item.last_modified) { if (!item.last_modified) {
item.last_modified = Date.now(); item.last_modified = Date.now();
@ -1147,7 +1146,7 @@ var AddonTestUtils = {
allocTempXPIFile() { allocTempXPIFile() {
let file = this.tempDir.clone(); let file = this.tempDir.clone();
let uuid = uuidGen.generateUUID().number.slice(1, -1); let uuid = Services.uuid.generateUUID().number.slice(1, -1);
file.append(`${uuid}.xpi`); file.append(`${uuid}.xpi`);
this.tempXPIs.push(file); this.tempXPIs.push(file);

View file

@ -54,13 +54,6 @@ XPCOMUtils.defineLazyModuleGetters(this, {
XPIInternal: "resource://gre/modules/addons/XPIProvider.jsm", XPIInternal: "resource://gre/modules/addons/XPIProvider.jsm",
}); });
XPCOMUtils.defineLazyServiceGetter(
this,
"uuidGen",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
XPCOMUtils.defineLazyGetter(this, "IconDetails", () => { XPCOMUtils.defineLazyGetter(this, "IconDetails", () => {
return ChromeUtils.import("resource://gre/modules/ExtensionParent.jsm", {}) return ChromeUtils.import("resource://gre/modules/ExtensionParent.jsm", {})
.ExtensionParent.IconDetails; .ExtensionParent.IconDetails;
@ -626,7 +619,7 @@ function defineSyncGUID(aAddon) {
// Define .syncGUID as a lazy property which is also settable // Define .syncGUID as a lazy property which is also settable
Object.defineProperty(aAddon, "syncGUID", { Object.defineProperty(aAddon, "syncGUID", {
get: () => { get: () => {
aAddon.syncGUID = uuidGen.generateUUID().toString(); aAddon.syncGUID = Services.uuid.generateUUID().toString();
return aAddon.syncGUID; return aAddon.syncGUID;
}, },
set: val => { set: val => {
@ -3565,7 +3558,7 @@ class SystemAddonInstaller extends DirectoryInstaller {
newDir.append("blank"); newDir.append("blank");
while (true) { while (true) {
newDir.leafName = uuidGen.generateUUID().toString(); newDir.leafName = Services.uuid.generateUUID().toString();
try { try {
await OS.File.makeDir(newDir.path, { ignoreExisting: false }); await OS.File.makeDir(newDir.path, { ignoreExisting: false });
break; break;

View file

@ -9,12 +9,6 @@ XPCOMUtils.defineLazyServiceGetter(
"@mozilla.org/mime;1", "@mozilla.org/mime;1",
"nsIMIMEService" "nsIMIMEService"
); );
XPCOMUtils.defineLazyServiceGetter(
this,
"gBundleService",
"@mozilla.org/intl/stringbundle;1",
"nsIStringBundleService"
);
// PDF files should always have a generic description instead // PDF files should always have a generic description instead
// of relying on what is registered with the Operating System. // of relying on what is registered with the Operating System.
@ -25,7 +19,7 @@ add_task(async function test_check_unknown_mime_type() {
let extension = mimeService.getPrimaryExtension("application/pdf", ""); let extension = mimeService.getPrimaryExtension("application/pdf", "");
Assert.equal(extension, "pdf", "Expect pdf extension when given mime"); Assert.equal(extension, "pdf", "Expect pdf extension when given mime");
let mimeInfo = gMIMEService.getFromTypeAndExtension("", "pdf"); let mimeInfo = gMIMEService.getFromTypeAndExtension("", "pdf");
let stringBundle = gBundleService.createBundle( let stringBundle = Services.strings.createBundle(
"chrome://mozapps/locale/downloads/unknownContentType.properties" "chrome://mozapps/locale/downloads/unknownContentType.properties"
); );
Assert.equal( Assert.equal(