summaryrefslogtreecommitdiffstats
path: root/testing/mochitest/BrowserTestUtils/BrowserTestUtilsChild.sys.mjs
blob: b7769ea8b34d877e2f9485c9254aa240c675cc25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/* vim: set ts=2 sw=2 sts=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  E10SUtils: "resource://gre/modules/E10SUtils.sys.mjs",
});

class BrowserTestUtilsChildObserver {
  constructor() {
    this.currentObserverStatus = "";
    this.observerItems = [];
  }

  startObservingTopics(aTopics) {
    for (let topic of aTopics) {
      Services.obs.addObserver(this, topic);
      this.observerItems.push({ topic });
    }
  }

  stopObservingTopics(aTopics) {
    if (aTopics) {
      for (let topic of aTopics) {
        let index = this.observerItems.findIndex(item => item.topic == topic);
        if (index >= 0) {
          Services.obs.removeObserver(this, topic);
          this.observerItems.splice(index, 1);
        }
      }
    } else {
      for (let topic of this.observerItems) {
        Services.obs.removeObserver(this, topic);
      }
      this.observerItems = [];
    }

    if (this.currentObserverStatus) {
      let error = new Error(this.currentObserverStatus);
      this.currentObserverStatus = "";
      throw error;
    }
  }

  observeTopic(topic, count, filterFn, callbackResolver) {
    // If the topic is in the list already, assume that it came from a
    // startObservingTopics call. If it isn't in the list already, assume
    // that it isn't within a start/stop set and the observer has to be
    // removed afterwards.
    let removeObserver = false;
    let index = this.observerItems.findIndex(item => item.topic == topic);
    if (index == -1) {
      removeObserver = true;
      this.startObservingTopics([topic]);
    }

    for (let item of this.observerItems) {
      if (item.topic == topic) {
        item.count = count || 1;
        item.filterFn = filterFn;
        item.promiseResolver = () => {
          if (removeObserver) {
            this.stopObservingTopics([topic]);
          }
          callbackResolver();
        };
        break;
      }
    }
  }

  observe(aSubject, aTopic, aData) {
    for (let item of this.observerItems) {
      if (item.topic != aTopic) {
        continue;
      }
      if (item.filterFn && !item.filterFn(aSubject, aTopic, aData)) {
        break;
      }

      if (--item.count >= 0) {
        if (item.count == 0 && item.promiseResolver) {
          item.promiseResolver();
        }
        return;
      }
    }

    // Otherwise, if the observer doesn't match, fail.
    console.log(
      "Failed: Observer topic " + aTopic + " not expected in content process"
    );
    this.currentObserverStatus +=
      "Topic " + aTopic + " not expected in content process\n";
  }
}

BrowserTestUtilsChildObserver.prototype.QueryInterface = ChromeUtils.generateQI(
  ["nsIObserver", "nsISupportsWeakReference"]
);

export class BrowserTestUtilsChild extends JSWindowActorChild {
  actorCreated() {
    this._EventUtils = null;
  }

  get EventUtils() {
    if (!this._EventUtils) {
      // Set up a dummy environment so that EventUtils works. We need to be careful to
      // pass a window object into each EventUtils method we call rather than having
      // it rely on the |window| global.
      let win = this.contentWindow;
      let EventUtils = {
        get KeyboardEvent() {
          return win.KeyboardEvent;
        },
        // EventUtils' `sendChar` function relies on the navigator to synthetize events.
        get navigator() {
          return win.navigator;
        },
      };

      EventUtils.window = {};
      EventUtils.parent = EventUtils.window;
      EventUtils._EU_Ci = Ci;
      EventUtils._EU_Cc = Cc;

      Services.scriptloader.loadSubScript(
        "chrome://mochikit/content/tests/SimpleTest/EventUtils.js",
        EventUtils
      );

      this._EventUtils = EventUtils;
    }

    return this._EventUtils;
  }

  receiveMessage(aMessage) {
    switch (aMessage.name) {
      case "Test:SynthesizeMouse": {
        return this.synthesizeMouse(aMessage.data, this.contentWindow);
      }

      case "Test:SynthesizeTouch": {
        return this.synthesizeTouch(aMessage.data, this.contentWindow);
      }

      case "Test:SendChar": {
        return this.EventUtils.sendChar(aMessage.data.char, this.contentWindow);
      }

      case "Test:SynthesizeKey":
        this.EventUtils.synthesizeKey(
          aMessage.data.key,
          aMessage.data.event || {},
          this.contentWindow
        );
        break;

      case "Test:SynthesizeComposition": {
        return this.EventUtils.synthesizeComposition(
          aMessage.data.event,
          this.contentWindow
        );
      }

      case "Test:SynthesizeCompositionChange":
        this.EventUtils.synthesizeCompositionChange(
          aMessage.data.event,
          this.contentWindow
        );
        break;

      case "BrowserTestUtils:StartObservingTopics": {
        this.observer = new BrowserTestUtilsChildObserver();
        this.observer.startObservingTopics(aMessage.data.topics);
        break;
      }

      case "BrowserTestUtils:StopObservingTopics": {
        if (this.observer) {
          this.observer.stopObservingTopics(aMessage.data.topics);
          this.observer = null;
        }
        break;
      }

      case "BrowserTestUtils:ObserveTopic": {
        return new Promise(resolve => {
          let filterFn;
          if (aMessage.data.filterFunctionSource) {
            /* eslint-disable-next-line no-eval */
            filterFn = eval(
              `(() => (${aMessage.data.filterFunctionSource}))()`
            );
          }

          let observer = this.observer || new BrowserTestUtilsChildObserver();
          observer.observeTopic(
            aMessage.data.topic,
            aMessage.data.count,
            filterFn,
            resolve
          );
        });
      }

      case "BrowserTestUtils:CrashFrame": {
        // This is to intentionally crash the frame.
        // We crash by using js-ctypes. The crash
        // should happen immediately
        // upon loading this frame script.

        const { ctypes } = ChromeUtils.importESModule(
          "resource://gre/modules/ctypes.sys.mjs"
        );

        let dies = function () {
          dump("\nEt tu, Brute?\n");
          ChromeUtils.privateNoteIntentionalCrash();

          switch (aMessage.data.crashType) {
            case "CRASH_OOM": {
              let debug = Cc["@mozilla.org/xpcom/debug;1"].getService(
                Ci.nsIDebug2
              );
              debug.crashWithOOM();
              break;
            }
            case "CRASH_SYSCALL": {
              if (Services.appinfo.OS == "Linux") {
                let libc = ctypes.open("libc.so.6");
                let chroot = libc.declare(
                  "chroot",
                  ctypes.default_abi,
                  ctypes.int,
                  ctypes.char.ptr
                );
                chroot("/");
              }
              break;
            }
            case "CRASH_INVALID_POINTER_DEREF": // Fallthrough
            default: {
              // Dereference a bad pointer.
              let zero = new ctypes.intptr_t(8);
              let badptr = ctypes.cast(
                zero,
                ctypes.PointerType(ctypes.int32_t)
              );
              badptr.contents;
            }
          }
        };

        if (aMessage.data.asyncCrash) {
          let { setTimeout } = ChromeUtils.importESModule(
            "resource://gre/modules/Timer.sys.mjs"
          );
          // Get out of the stack.
          setTimeout(dies, 0);
        } else {
          dies();
        }
      }
    }

    return undefined;
  }

  handleEvent(aEvent) {
    switch (aEvent.type) {
      case "DOMContentLoaded":
      case "load": {
        this.sendAsyncMessage(aEvent.type, {
          internalURL: aEvent.target.documentURI,
          visibleURL: aEvent.target.location
            ? aEvent.target.location.href
            : null,
        });
        break;
      }
    }
  }

  synthesizeMouse(data, window) {
    let target = data.target;
    if (typeof target == "string") {
      target = this.document.querySelector(target);
    } else if (typeof data.targetFn == "string") {
      let runnablestr = `
        (() => {
          return (${data.targetFn});
        })();`;
      /* eslint-disable no-eval */
      target = eval(runnablestr)();
      /* eslint-enable no-eval */
    }

    let left = data.x;
    let top = data.y;
    if (target) {
      if (target.ownerDocument !== this.document) {
        // Account for nodes found in iframes.
        let cur = target;
        do {
          // eslint-disable-next-line mozilla/use-ownerGlobal
          let frame = cur.ownerDocument.defaultView.frameElement;
          let rect = frame.getBoundingClientRect();

          left += rect.left;
          top += rect.top;

          cur = frame;
        } while (cur && cur.ownerDocument !== this.document);

        // node must be in this document tree.
        if (!cur) {
          throw new Error("target must be in the main document tree");
        }
      }

      let rect = target.getBoundingClientRect();
      left += rect.left;
      top += rect.top;

      if (data.event.centered) {
        left += rect.width / 2;
        top += rect.height / 2;
      }
    }

    let result;

    lazy.E10SUtils.wrapHandlingUserInput(window, data.handlingUserInput, () => {
      if (data.event && data.event.wheel) {
        this.EventUtils.synthesizeWheelAtPoint(left, top, data.event, window);
      } else {
        result = this.EventUtils.synthesizeMouseAtPoint(
          left,
          top,
          data.event,
          window
        );
      }
    });

    return result;
  }

  synthesizeTouch(data, window) {
    let target = data.target;
    if (typeof target == "string") {
      target = this.document.querySelector(target);
    } else if (typeof data.targetFn == "string") {
      let runnablestr = `
        (() => {
          return (${data.targetFn});
        })();`;
      /* eslint-disable no-eval */
      target = eval(runnablestr)();
      /* eslint-enable no-eval */
    }

    if (target) {
      if (target.ownerDocument !== this.document) {
        // Account for nodes found in iframes.
        let cur = target;
        do {
          cur = cur.ownerGlobal.frameElement;
        } while (cur && cur.ownerDocument !== this.document);

        // node must be in this document tree.
        if (!cur) {
          throw new Error("target must be in the main document tree");
        }
      }
    }

    return this.EventUtils.synthesizeTouch(
      target,
      data.x,
      data.y,
      data.event,
      window
    );
  }
}