Bug 1772096 - Part 8: Use plain object for lazy getter in remote/shared/. r=webdriver-reviewers,jdescottes

Differential Revision: https://phabricator.services.mozilla.com/D148005
This commit is contained in:
Tooru Fujisawa 2022-06-06 07:10:45 +00:00
Родитель 2d20b01ca6
Коммит cda5ad9e91
9 изменённых файлов: 99 добавлений и 79 удалений

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

@ -11,11 +11,13 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
Log: "chrome://remote/content/shared/Log.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () => Log.get());
XPCOMUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get());
const ELEMENT_NODE = 1;
const MAX_STRING_LENGTH = 250;
@ -101,7 +103,7 @@ function pprint(ss, ...values) {
try {
s = pretty(values[i]);
} catch (e) {
logger.warn("Problem pretty printing:", e);
lazy.logger.warn("Problem pretty printing:", e);
s = typeof values[i];
}
res.push(s);

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

@ -18,9 +18,11 @@ const PREF_REMOTE_LOG_LEVEL = "remote.log.level";
// This can be removed when geckodriver 0.30 (bug 1686110) has been released.
const PREF_MARIONETTE_LOG_LEVEL = "marionette.log.level";
const lazy = {};
// Lazy getter which will return the preference (remote or marionette) which has
// the most verbose log level.
XPCOMUtils.defineLazyGetter(this, "prefLogLevel", () => {
XPCOMUtils.defineLazyGetter(lazy, "prefLogLevel", () => {
function getLogLevelNumber(pref) {
const level = Services.prefs.getCharPref(pref, "Fatal");
return (
@ -60,7 +62,7 @@ class Log {
const logger = StdLog.repository.getLogger(type);
if (logger.ownAppenders.length == 0) {
logger.addAppender(new StdLog.DumpAppender());
logger.manageLevelFromPref(prefLogLevel);
logger.manageLevelFromPref(lazy.prefLogLevel);
}
return logger;
}
@ -71,7 +73,7 @@ class Log {
* unnecessarily.
*/
static get isTraceLevel() {
return [StdLog.Level.All, StdLog.Level.Trace].includes(prefLogLevel);
return [StdLog.Level.All, StdLog.Level.Trace].includes(lazy.prefLogLevel);
}
static get verbose() {

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

@ -13,7 +13,9 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
clearTimeout: "resource://gre/modules/Timer.jsm",
setTimeout: "resource://gre/modules/Timer.jsm",
@ -22,8 +24,8 @@ XPCOMUtils.defineLazyModuleGetters(this, {
truncate: "chrome://remote/content/shared/Format.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () =>
Log.get(Log.TYPES.REMOTE_AGENT)
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
lazy.Log.get(lazy.Log.TYPES.REMOTE_AGENT)
);
// Used to keep weak references of webProgressListeners alive.
@ -68,8 +70,8 @@ async function waitForInitialNavigationCompleted(webProgress, options = {}) {
// If the current document is not the initial "about:blank" and is also
// no longer loading, assume the navigation is done and return.
if (!isInitial && !listener.isLoadingDocument) {
logger.trace(
truncate`[${browsingContext.id}] Document already finished loading: ${browsingContext.currentURI?.spec}`
lazy.logger.trace(
lazy.truncate`[${browsingContext.id}] Document already finished loading: ${browsingContext.currentURI?.spec}`
);
// Will resolve the navigated promise.
@ -172,12 +174,12 @@ class ProgressListener {
this.#targetURI = this.#getTargetURI(request);
logger.trace(
truncate`${messagePrefix} state=start: ${this.targetURI?.spec}`
lazy.logger.trace(
lazy.truncate`${messagePrefix} state=start: ${this.targetURI?.spec}`
);
if (this.#unloadTimerId !== null) {
clearTimeout(this.#unloadTimerId);
lazy.clearTimeout(this.#unloadTimerId);
this.#unloadTimerId = null;
}
@ -206,8 +208,8 @@ class ProgressListener {
// The navigation request caused an error.
const errorName = ChromeUtils.getXPCOMErrorName(status);
logger.trace(
truncate`${messagePrefix} state=stop: error=0x${status.toString(
lazy.logger.trace(
lazy.truncate`${messagePrefix} state=stop: error=0x${status.toString(
16
)} (${errorName})`
);
@ -215,8 +217,8 @@ class ProgressListener {
return;
}
logger.trace(
truncate`${messagePrefix} state=stop: ${this.currentURI.spec}`
lazy.logger.trace(
lazy.truncate`${messagePrefix} state=stop: ${this.currentURI.spec}`
);
// If a non initial page finished loading the navigation is done.
@ -226,7 +228,7 @@ class ProgressListener {
}
// Otherwise wait for a potential additional page load.
logger.trace(
lazy.logger.trace(
`${messagePrefix} Initial document loaded. Wait for a potential further navigation.`
);
this.#seenStartFlag = false;
@ -244,9 +246,9 @@ class ProgressListener {
#setUnloadTimer() {
if (!this.#expectNavigation) {
this.#unloadTimerId = setTimeout(() => {
logger.trace(
truncate`[${this.browsingContext.id}] No navigation detected: ${this.currentURI?.spec}`
this.#unloadTimerId = lazy.setTimeout(() => {
lazy.logger.trace(
lazy.truncate`[${this.browsingContext.id}] No navigation detected: ${this.currentURI?.spec}`
);
// Assume the target is the currently loaded URI.
this.#targetURI = this.currentURI;
@ -268,8 +270,8 @@ class ProgressListener {
// If an error page has been loaded abort the navigation.
if (flag & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE) {
logger.trace(
truncate`${messagePrefix} location=errorPage: ${location.spec}`
lazy.logger.trace(
lazy.truncate`${messagePrefix} location=errorPage: ${location.spec}`
);
this.stop({ error: new Error("Address restricted") });
return;
@ -278,8 +280,8 @@ class ProgressListener {
// If location has changed in the same document the navigation is done.
if (flag & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT) {
this.#targetURI = location;
logger.trace(
truncate`${messagePrefix} location=sameDocument: ${this.targetURI?.spec}`
lazy.logger.trace(
lazy.truncate`${messagePrefix} location=sameDocument: ${this.targetURI?.spec}`
);
this.stop();
}
@ -306,7 +308,7 @@ class ProgressListener {
}
}
this.#deferredNavigation = new Deferred();
this.#deferredNavigation = new lazy.Deferred();
// Enable all location change and state notifications to get informed about an upcoming load
// as early as possible.
@ -344,7 +346,7 @@ class ProgressListener {
throw new Error(`Progress listener not yet started`);
}
clearTimeout(this.#unloadTimerId);
lazy.clearTimeout(this.#unloadTimerId);
this.#unloadTimerId = null;
this.#webProgress.removeProgressListener(

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

@ -10,7 +10,9 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
assert: "chrome://remote/content/shared/webdriver/Assert.jsm",
clearInterval: "resource://gre/modules/Timer.jsm",
setInterval: "resource://gre/modules/Timer.jsm",
@ -18,7 +20,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
Log: "chrome://remote/content/shared/Log.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () => Log.get());
XPCOMUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get());
const print = {
maxScaleValue: 2.0,
@ -134,14 +136,14 @@ function parseRanges(ranges) {
let limits;
if (typeof range !== "string") {
// We got a single integer so the limits are just that page
assert.positiveInteger(range);
lazy.assert.positiveInteger(range);
limits = [range, range];
} else {
// We got a string presumably of the form <int> | <int>? "-" <int>?
const msg = `Expected a range of the form <int> or <int>-<int>, got ${range}`;
limits = range.split("-").map(x => x.trim());
assert.that(o => [1, 2].includes(o.length), msg)(limits);
lazy.assert.that(o => [1, 2].includes(o.length), msg)(limits);
// Single numbers map to a range with that page at the start and the end
if (limits.length == 1) {
@ -150,7 +152,7 @@ function parseRanges(ranges) {
// Need to check that both limits are strings conisting only of
// decimal digits (or empty strings)
const assertNumeric = assert.that(o => /^\d*$/.test(o), msg);
const assertNumeric = lazy.assert.that(o => /^\d*$/.test(o), msg);
limits.every(x => assertNumeric(x));
// Convert from strings representing numbers to actual numbers
@ -163,7 +165,7 @@ function parseRanges(ranges) {
return parseInt(limitStr);
});
}
assert.that(
lazy.assert.that(
x => x[0] <= x[1],
"Lower limit ${parts[0]} is higher than upper limit ${parts[1]}"
)(limits);
@ -189,7 +191,7 @@ function parseRanges(ranges) {
}
let rv = parsedRanges.flat();
logger.debug(`Got page ranges [${rv.join(", ")}]`);
lazy.logger.debug(`Got page ranges [${rv.join(", ")}]`);
return rv;
}
@ -211,16 +213,16 @@ print.printToFile = async function(browser, settings) {
const DELAY_CHECK_FILE_COMPLETELY_WRITTEN = 100;
let lastSize = 0;
const timerId = setInterval(async () => {
const timerId = lazy.setInterval(async () => {
const fileInfo = await IOUtils.stat(filePath);
if (lastSize > 0 && fileInfo.size == lastSize) {
clearInterval(timerId);
lazy.clearInterval(timerId);
resolve();
}
lastSize = fileInfo.size;
}, DELAY_CHECK_FILE_COMPLETELY_WRITTEN);
});
logger.debug(`PDF output written to ${filePath}`);
lazy.logger.debug(`PDF output written to ${filePath}`);
return filePath;
};

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

@ -11,20 +11,22 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
Preferences: "resource://gre/modules/Preferences.jsm",
Log: "chrome://remote/content/shared/Log.jsm",
});
XPCOMUtils.defineLazyPreferenceGetter(
this,
lazy,
"useRecommendedPrefs",
"remote.prefs.recommended",
false
);
XPCOMUtils.defineLazyGetter(this, "logger", () => Log.get());
XPCOMUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get());
// Ensure we are in the parent process.
if (Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
@ -283,7 +285,7 @@ const RecommendedPreferences = {
* Map of preference key to preference value.
*/
applyPreferences(preferences) {
if (!useRecommendedPrefs) {
if (!lazy.useRecommendedPrefs) {
// If remote.prefs.recommended is set to false, do not set any preference
// here. Needed for our Firefox CI.
return;
@ -299,9 +301,9 @@ const RecommendedPreferences = {
}
for (const [k, v] of preferences) {
if (!Preferences.isSet(k)) {
logger.debug(`Setting recommended pref ${k} to ${v}`);
Preferences.set(k, v);
if (!lazy.Preferences.isSet(k)) {
lazy.logger.debug(`Setting recommended pref ${k} to ${v}`);
lazy.Preferences.set(k, v);
// Keep track all the altered preferences to restore them on
// quit-application.
@ -333,8 +335,8 @@ const RecommendedPreferences = {
*/
restorePreferences(preferences) {
for (const k of preferences.keys()) {
logger.debug(`Resetting recommended pref ${k}`);
Preferences.reset(k);
lazy.logger.debug(`Resetting recommended pref ${k}`);
lazy.Preferences.reset(k);
this.alteredPrefs.delete(k);
}
},

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

@ -17,14 +17,16 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
Log: "chrome://remote/content/shared/Log.jsm",
});
const { TYPE_REPEATING_SLACK } = Ci.nsITimer;
XPCOMUtils.defineLazyGetter(this, "logger", () =>
Log.get(Log.TYPES.REMOTE_AGENT)
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
lazy.Log.get(lazy.Log.TYPES.REMOTE_AGENT)
);
/**
@ -144,14 +146,14 @@ function EventPromise(subject, eventName, options = {}) {
return new Promise((resolve, reject) => {
function listener(event) {
logger.trace(`Received DOM event ${event.type} for ${event.target}`);
lazy.logger.trace(`Received DOM event ${event.type} for ${event.target}`);
try {
if (checkFn && !checkFn(event)) {
return;
}
} catch (e) {
// Treat an exception in the callback as a falsy value
logger.warn(`Event check failed: ${e.message}`);
lazy.logger.warn(`Event check failed: ${e.message}`);
}
subject.removeEventListener(eventName, listener, capture);

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

@ -11,7 +11,9 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AppInfo: "chrome://remote/content/marionette/appinfo.js",
EventPromise: "chrome://remote/content/shared/Sync.jsm",
MobileTabBrowser: "chrome://remote/content/shared/MobileTabBrowser.jsm",
@ -110,7 +112,7 @@ var TabManager = {
// GeckoView
// TODO: Migrate to AppInfo.isAndroid after AppInfo moves to shared/
if (Services.appinfo.OS === "Android") {
return new MobileTabBrowser(win);
return new lazy.MobileTabBrowser(win);
// Firefox
} else if ("gBrowser" in win) {
return win.gBrowser;
@ -292,7 +294,7 @@ var TabManager = {
return Promise.resolve();
}
const selected = new EventPromise(ownerWindow, "TabSelect");
const selected = new lazy.EventPromise(ownerWindow, "TabSelect");
tabBrowser.selectedTab = tab;
return selected;
},
@ -300,7 +302,7 @@ var TabManager = {
supportsTabs() {
// TODO: Only Firefox supports adding tabs at the moment.
// Geckoview support should be added via Bug 1506782.
return AppInfo.name === "Firefox";
return lazy.AppInfo.name === "Firefox";
},
_getWindowForTab(tab) {

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

@ -12,12 +12,14 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
Log: "chrome://remote/content/shared/Log.jsm",
WebSocketTransport: "chrome://remote/content/server/WebSocketTransport.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () => Log.get());
XPCOMUtils.defineLazyGetter(lazy, "logger", () => lazy.Log.get());
class WebSocketConnection {
/**
@ -34,11 +36,11 @@ class WebSocketConnection {
this.httpdConnection = httpdConnection;
this.transport = new WebSocketTransport(webSocket);
this.transport = new lazy.WebSocketTransport(webSocket);
this.transport.hooks = this;
this.transport.ready();
logger.debug(`${this.constructor.name} ${this.id} accepted`);
lazy.logger.debug(`${this.constructor.name} ${this.id} accepted`);
}
/**
@ -112,7 +114,7 @@ class WebSocketConnection {
* Called by the `transport` when the connection is closed.
*/
onClosed(status) {
logger.debug(`${this.constructor.name} ${this.id} closed`);
lazy.logger.debug(`${this.constructor.name} ${this.id} closed`);
}
/**

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

@ -11,7 +11,9 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AppInfo: "chrome://remote/content/marionette/appinfo.js",
error: "chrome://remote/content/shared/webdriver/Errors.jsm",
TabManager: "chrome://remote/content/shared/TabManager.jsm",
@ -65,11 +67,13 @@ class WindowManager {
// Otherwise check if the chrome window has a tab browser, and that it
// contains a tab with the wanted window handle.
const tabBrowser = TabManager.getTabBrowser(win);
const tabBrowser = lazy.TabManager.getTabBrowser(win);
if (tabBrowser && tabBrowser.tabs) {
for (let i = 0; i < tabBrowser.tabs.length; ++i) {
let contentBrowser = TabManager.getBrowserForTab(tabBrowser.tabs[i]);
let contentWindowId = TabManager.getIdForBrowser(contentBrowser);
let contentBrowser = lazy.TabManager.getBrowserForTab(
tabBrowser.tabs[i]
);
let contentWindowId = lazy.TabManager.getIdForBrowser(contentBrowser);
if (contentWindowId == handle) {
return this.getWindowProperties(win, { tabIndex: i });
@ -114,7 +118,7 @@ class WindowManager {
return {
win,
id: this.getIdForWindow(win),
hasTabBrowser: !!TabManager.getTabBrowser(win),
hasTabBrowser: !!lazy.TabManager.getTabBrowser(win),
tabIndex: options.tabIndex,
};
}
@ -144,7 +148,7 @@ class WindowManager {
* A promise which is resolved when the current window has been closed.
*/
async closeWindow(win) {
const destroyed = waitForObserverTopic("xul-window-destroyed", {
const destroyed = lazy.waitForObserverTopic("xul-window-destroyed", {
checkFn: () => win && win.closed,
});
@ -163,8 +167,8 @@ class WindowManager {
*/
async focusWindow(win) {
if (Services.focus.activeWindow != win) {
let activated = new EventPromise(win, "activate");
let focused = new EventPromise(win, "focus", { capture: true });
let activated = new lazy.EventPromise(win, "activate");
let focused = new lazy.EventPromise(win, "focus", { capture: true });
win.focus();
@ -189,7 +193,7 @@ class WindowManager {
async openBrowserWindow(options = {}) {
let { focus = false, isPrivate = false, openerWindow = null } = options;
switch (AppInfo.name) {
switch (lazy.AppInfo.name) {
case "Firefox":
if (openerWindow === null) {
// If no opener was provided, fallback to the topmost window.
@ -197,7 +201,7 @@ class WindowManager {
}
if (!openerWindow) {
throw new error.UnsupportedOperationError(
throw new lazy.error.UnsupportedOperationError(
`openWindow() could not find a valid opener window`
);
}
@ -207,9 +211,9 @@ class WindowManager {
// race condition when promptly focusing to the original window again.
const win = openerWindow.OpenBrowserWindow({ private: isPrivate });
const activated = new EventPromise(win, "activate");
const focused = new EventPromise(win, "focus", { capture: true });
const startup = waitForObserverTopic(
const activated = new lazy.EventPromise(win, "activate");
const focused = new lazy.EventPromise(win, "focus", { capture: true });
const startup = lazy.waitForObserverTopic(
"browser-delayed-startup-finished",
{
checkFn: subject => subject == win,
@ -232,8 +236,8 @@ class WindowManager {
return win;
default:
throw new error.UnsupportedOperationError(
`openWindow() not supported in ${AppInfo.name}`
throw new lazy.error.UnsupportedOperationError(
`openWindow() not supported in ${lazy.AppInfo.name}`
);
}
}
@ -245,16 +249,16 @@ class WindowManager {
* A promise that resolved to the application window.
*/
waitForInitialApplicationWindowLoaded() {
return new TimedPromise(
return new lazy.TimedPromise(
async resolve => {
const windowReadyTopic = AppInfo.isThunderbird
const windowReadyTopic = lazy.AppInfo.isThunderbird
? "mail-delayed-startup-finished"
: "browser-delayed-startup-finished";
// This call includes a fallback to "mail3:pane" as well.
const win = Services.wm.getMostRecentBrowserWindow();
const windowLoaded = waitForObserverTopic(windowReadyTopic, {
const windowLoaded = lazy.waitForObserverTopic(windowReadyTopic, {
checkFn: subject => (win !== null ? subject == win : true),
});