Bug 1874684 - Part 33: Defer allocation of options object for CalendarDateFromFields...
[gecko.git] / remote / shared / Sync.sys.mjs
blob7b14f8b2c82c214a9ffb4d86d74abe5a5f90185c
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/. */
5 const lazy = {};
7 ChromeUtils.defineESModuleGetters(lazy, {
8   error: "chrome://remote/content/shared/webdriver/Errors.sys.mjs",
9   Log: "chrome://remote/content/shared/Log.sys.mjs",
10 });
12 const { TYPE_ONE_SHOT, TYPE_REPEATING_SLACK } = Ci.nsITimer;
14 ChromeUtils.defineLazyGetter(lazy, "logger", () =>
15   lazy.Log.get(lazy.Log.TYPES.REMOTE_AGENT)
18 /**
19  * Throttle until the `window` has performed an animation frame.
20  *
21  * @param {ChromeWindow} win
22  *     Window to request the animation frame from.
23  *
24  * @returns {Promise}
25  */
26 export function AnimationFramePromise(win) {
27   const animationFramePromise = new Promise(resolve => {
28     win.requestAnimationFrame(resolve);
29   });
31   // Abort if the underlying window gets closed
32   const windowClosedPromise = new PollPromise(resolve => {
33     if (win.closed) {
34       resolve();
35     }
36   });
38   return Promise.race([animationFramePromise, windowClosedPromise]);
41 /**
42  * Create a helper object to defer a promise.
43  *
44  * @returns {object}
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
52  */
53 export function Deferred() {
54   const 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;
64       resolve(...args);
65     };
67     deferred.reject = (...args) => {
68       deferred.pending = false;
69       deferred.rejected = true;
70       reject(...args);
71     };
72   });
74   return deferred;
77 /**
78  * Wait for an event to be fired on a specified element.
79  *
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:
84  *
85  *     const promise = new EventPromise(element, "myEvent");
86  *     // same event tick here
87  *     await promise;
88  *     // next event tick here
89  *
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
111  *     false.
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}
122  */
123 export function EventPromise(subject, eventName, options = {}) {
124   const {
125     capture = false,
126     checkFn = null,
127     timeout = null,
128     mozSystemGroup = false,
129     wantUntrusted = false,
130   } = options;
131   if (
132     !subject ||
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"
140   ) {
141     throw new TypeError();
142   }
143   if (timeout < 0) {
144     throw new RangeError();
145   }
147   return new Promise((resolve, reject) => {
148     let timer;
150     function cleanUp() {
151       subject.removeEventListener(eventName, listener, capture);
152       timer?.cancel();
153     }
155     function listener(event) {
156       lazy.logger.trace(`Received DOM event ${event.type} for ${event.target}`);
157       try {
158         if (checkFn && !checkFn(event)) {
159           return;
160         }
161       } catch (e) {
162         // Treat an exception in the callback as a falsy value
163         lazy.logger.warn(`Event check failed: ${e.message}`);
164       }
166       cleanUp();
167       executeSoon(() => resolve(event));
168     }
170     subject.addEventListener(eventName, listener, {
171       capture,
172       mozSystemGroup,
173       wantUntrusted,
174     });
176     if (timeout !== null) {
177       timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
178       timer.init(
179         () => {
180           cleanUp();
181           reject(
182             new lazy.error.TimeoutError(
183               `EventPromise timed out after ${timeout} ms`
184             )
185           );
186         },
187         timeout,
188         TYPE_ONE_SHOT
189       );
190     }
191   });
195  * Wait for the next tick in the event loop to execute a callback.
197  * @param {Function} fn
198  *     Function to be executed.
199  */
200 export function executeSoon(fn) {
201   if (typeof fn != "function") {
202     throw new TypeError();
203   }
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.
227  * Usage::
229  *     let els = new PollPromise((resolve, reject) => {
230  *       let res = document.querySelectorAll("p");
231  *       if (res.length > 0) {
232  *         resolve(Array.from(res));
233  *       } else {
234  *         reject([]);
235  *       }
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.
256  * @throws {*}
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.
262  */
263 export function PollPromise(func, options = {}) {
264   const {
265     errorMessage = "PollPromise timed out",
266     interval = 10,
267     timeout = null,
268   } = options;
269   const timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
270   let didTimeOut = false;
272   if (typeof func != "function") {
273     throw new TypeError();
274   }
275   if (timeout != null && typeof timeout != "number") {
276     throw new TypeError();
277   }
278   if (typeof interval != "number") {
279     throw new TypeError();
280   }
281   if (
282     (timeout && (!Number.isInteger(timeout) || timeout < 0)) ||
283     !Number.isInteger(interval) ||
284     interval < 0
285   ) {
286     throw new RangeError();
287   }
289   return new Promise((resolve, reject) => {
290     let start, end;
292     if (Number.isInteger(timeout)) {
293       start = new Date().getTime();
294       end = start + timeout;
295     }
297     let evalFn = () => {
298       new Promise(func)
299         .then(resolve, rejected => {
300           if (typeof rejected != "undefined") {
301             throw rejected;
302           }
304           // return if there is a timeout and set to 0,
305           // allowing |func| to be evaluated at least once
306           if (
307             typeof end != "undefined" &&
308             (start == end || new Date().getTime() >= end)
309           ) {
310             didTimeOut = true;
311             resolve(rejected);
312           }
313         })
314         .catch(reject);
315     };
317     // the repeating slack timer waits |interval|
318     // before invoking |evalFn|
319     evalFn();
321     timer.init(evalFn, interval, TYPE_REPEATING_SLACK);
322   }).then(
323     res => {
324       if (didTimeOut) {
325         lazy.logger.warn(`${errorMessage} after ${timeout} ms`);
326       }
327       timer.cancel();
328       return res;
329     },
330     err => {
331       timer.cancel();
332       throw err;
333     }
334   );