1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 ChromeUtils.defineESModuleGetters(lazy, {
8 error: "chrome://remote/content/shared/webdriver/Errors.sys.mjs",
9 Log: "chrome://remote/content/shared/Log.sys.mjs",
12 const { TYPE_ONE_SHOT, TYPE_REPEATING_SLACK } = Ci.nsITimer;
14 ChromeUtils.defineLazyGetter(lazy, "logger", () =>
15 lazy.Log.get(lazy.Log.TYPES.REMOTE_AGENT)
19 * Throttle until the `window` has performed an animation frame.
21 * @param {ChromeWindow} win
22 * Window to request the animation frame from.
26 export function AnimationFramePromise(win) {
27 const animationFramePromise = new Promise(resolve => {
28 win.requestAnimationFrame(resolve);
31 // Abort if the underlying window gets closed
32 const windowClosedPromise = new PollPromise(resolve => {
38 return Promise.race([animationFramePromise, windowClosedPromise]);
42 * Create a helper object to defer a promise.
45 * An object that returns the following properties:
46 * - fulfilled Flag that indicates that the promise got resolved
47 * - pending Flag that indicates a not yet fulfilled/rejected promise
48 * - promise The actual promise
49 * - reject Callback to reject the promise
50 * - rejected Flag that indicates that the promise got rejected
51 * - resolve Callback to resolve the promise
53 export function Deferred() {
56 deferred.promise = new Promise((resolve, reject) => {
57 deferred.fulfilled = false;
58 deferred.pending = true;
59 deferred.rejected = false;
61 deferred.resolve = (...args) => {
62 deferred.fulfilled = true;
63 deferred.pending = false;
67 deferred.reject = (...args) => {
68 deferred.pending = false;
69 deferred.rejected = true;
78 * Wait for an event to be fired on a specified element.
80 * The returned promise is guaranteed to not resolve before the
81 * next event tick after the event listener is called, so that all
82 * other event listeners for the element are executed before the
83 * handler is executed. For example:
85 * const promise = new EventPromise(element, "myEvent");
86 * // same event tick here
88 * // next event tick here
90 * @param {Element} subject
91 * The element that should receive the event.
92 * @param {string} eventName
93 * Case-sensitive string representing the event name to listen for.
94 * @param {object=} options
95 * @param {boolean=} options.capture
96 * Indicates the event will be despatched to this subject,
97 * before it bubbles down to any EventTarget beneath it in the
98 * DOM tree. Defaults to false.
99 * @param {Function=} options.checkFn
100 * Called with the Event object as argument, should return true if the
101 * event is the expected one, or false if it should be ignored and
102 * listening should continue. If not specified, the first event with
103 * the specified name resolves the returned promise. Defaults to null.
104 * @param {number=} options.timeout
105 * Timeout duration in milliseconds, if provided.
106 * If specified, then the returned promise will be rejected with
107 * TimeoutError, if not already resolved, after this duration has elapsed.
108 * If not specified, then no timeout is used. Defaults to null.
109 * @param {boolean=} options.mozSystemGroup
110 * Determines whether to add listener to the system group. Defaults to
112 * @param {boolean=} options.wantUntrusted
113 * Receive synthetic events despatched by web content. Defaults to false.
115 * @returns {Promise<Event>}
116 * Either fulfilled with the first described event, satisfying
117 * options.checkFn if specified, or rejected with TimeoutError after
118 * options.timeout milliseconds if specified.
120 * @throws {TypeError}
121 * @throws {RangeError}
123 export function EventPromise(subject, eventName, options = {}) {
128 mozSystemGroup = false,
129 wantUntrusted = false,
133 !("addEventListener" in subject) ||
134 typeof eventName != "string" ||
135 typeof capture != "boolean" ||
136 (checkFn && typeof checkFn != "function") ||
137 (timeout !== null && typeof timeout != "number") ||
138 typeof mozSystemGroup != "boolean" ||
139 typeof wantUntrusted != "boolean"
141 throw new TypeError();
144 throw new RangeError();
147 return new Promise((resolve, reject) => {
151 subject.removeEventListener(eventName, listener, capture);
155 function listener(event) {
156 lazy.logger.trace(`Received DOM event ${event.type} for ${event.target}`);
158 if (checkFn && !checkFn(event)) {
162 // Treat an exception in the callback as a falsy value
163 lazy.logger.warn(`Event check failed: ${e.message}`);
167 executeSoon(() => resolve(event));
170 subject.addEventListener(eventName, listener, {
176 if (timeout !== null) {
177 timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
182 new lazy.error.TimeoutError(
183 `EventPromise timed out after ${timeout} ms`
195 * Wait for the next tick in the event loop to execute a callback.
197 * @param {Function} fn
198 * Function to be executed.
200 export function executeSoon(fn) {
201 if (typeof fn != "function") {
202 throw new TypeError();
205 Services.tm.dispatchToMainThread(fn);
209 * Runs a Promise-like function off the main thread until it is resolved
210 * through ``resolve`` or ``rejected`` callbacks. The function is
211 * guaranteed to be run at least once, irregardless of the timeout.
213 * The ``func`` is evaluated every ``interval`` for as long as its
214 * runtime duration does not exceed ``interval``. Evaluations occur
215 * sequentially, meaning that evaluations of ``func`` are queued if
216 * the runtime evaluation duration of ``func`` is greater than ``interval``.
218 * ``func`` is given two arguments, ``resolve`` and ``reject``,
219 * of which one must be called for the evaluation to complete.
220 * Calling ``resolve`` with an argument indicates that the expected
221 * wait condition was met and will return the passed value to the
222 * caller. Conversely, calling ``reject`` will evaluate ``func``
223 * again until the ``timeout`` duration has elapsed or ``func`` throws.
224 * The passed value to ``reject`` will also be returned to the caller
225 * once the wait has expired.
229 * let els = new PollPromise((resolve, reject) => {
230 * let res = document.querySelectorAll("p");
231 * if (res.length > 0) {
232 * resolve(Array.from(res));
236 * }, {timeout: 1000});
238 * @param {Condition} func
239 * Function to run off the main thread.
240 * @param {object=} options
241 * @param {string=} options.errorMessage
242 * Message to use to send a warning if ``timeout`` is over.
243 * Defaults to `PollPromise timed out`.
244 * @param {number=} options.timeout
245 * Desired timeout if wanted. If 0 or less than the runtime evaluation
246 * time of ``func``, ``func`` is guaranteed to run at least once.
247 * Defaults to using no timeout.
248 * @param {number=} options.interval
249 * Duration between each poll of ``func`` in milliseconds.
250 * Defaults to 10 milliseconds.
252 * @returns {Promise.<*>}
253 * Yields the value passed to ``func``'s
254 * ``resolve`` or ``reject`` callbacks.
257 * If ``func`` throws, its error is propagated.
258 * @throws {TypeError}
259 * If `timeout` or `interval`` are not numbers.
260 * @throws {RangeError}
261 * If `timeout` or `interval` are not unsigned integers.
263 export function PollPromise(func, options = {}) {
265 errorMessage = "PollPromise timed out",
269 const timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
270 let didTimeOut = false;
272 if (typeof func != "function") {
273 throw new TypeError();
275 if (timeout != null && typeof timeout != "number") {
276 throw new TypeError();
278 if (typeof interval != "number") {
279 throw new TypeError();
282 (timeout && (!Number.isInteger(timeout) || timeout < 0)) ||
283 !Number.isInteger(interval) ||
286 throw new RangeError();
289 return new Promise((resolve, reject) => {
292 if (Number.isInteger(timeout)) {
293 start = new Date().getTime();
294 end = start + timeout;
299 .then(resolve, rejected => {
300 if (typeof rejected != "undefined") {
304 // return if there is a timeout and set to 0,
305 // allowing |func| to be evaluated at least once
307 typeof end != "undefined" &&
308 (start == end || new Date().getTime() >= end)
317 // the repeating slack timer waits |interval|
318 // before invoking |evalFn|
321 timer.init(evalFn, interval, TYPE_REPEATING_SLACK);
325 lazy.logger.warn(`${errorMessage} after ${timeout} ms`);