summaryrefslogtreecommitdiffstats
path: root/accessible/tests/browser/shared-head.js
blob: fe87a777650f853e1abf4b36f4c9f882e4523744 (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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
/* 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/. */

"use strict";

/* import-globals-from ../mochitest/common.js */
/* import-globals-from ../mochitest/layout.js */
/* import-globals-from ../mochitest/promisified-events.js */

/* exported Logger, MOCHITESTS_DIR, invokeSetAttribute, invokeFocus,
            invokeSetStyle, getAccessibleDOMNodeID, getAccessibleTagName,
            addAccessibleTask, findAccessibleChildByID, isDefunct,
            CURRENT_CONTENT_DIR, loadScripts, loadContentScripts, snippetToURL,
            Cc, Cu, arrayFromChildren, forceGC, contentSpawnMutation,
            DEFAULT_IFRAME_ID, DEFAULT_IFRAME_DOC_BODY_ID, invokeContentTask,
            matchContentDoc, currentContentDoc, getContentDPR,
            waitForImageMap, getContentBoundsForDOMElm, untilCacheIs,
            untilCacheOk, testBoundsWithContent, waitForContentPaint,
            runPython */

const CURRENT_FILE_DIR = "/browser/accessible/tests/browser/";

/**
 * Current browser test directory path used to load subscripts.
 */
const CURRENT_DIR = `chrome://mochitests/content${CURRENT_FILE_DIR}`;
/**
 * A11y mochitest directory where we find common files used in both browser and
 * plain tests.
 */
const MOCHITESTS_DIR =
  "chrome://mochitests/content/a11y/accessible/tests/mochitest/";
/**
 * A base URL for test files used in content.
 */
// eslint-disable-next-line @microsoft/sdl/no-insecure-url
const CURRENT_CONTENT_DIR = `http://example.com${CURRENT_FILE_DIR}`;

const LOADED_CONTENT_SCRIPTS = new Map();

const DEFAULT_CONTENT_DOC_BODY_ID = "body";
const DEFAULT_IFRAME_ID = "default-iframe-id";
const DEFAULT_IFRAME_DOC_BODY_ID = "default-iframe-body-id";

const HTML_MIME_TYPE = "text/html";
const XHTML_MIME_TYPE = "application/xhtml+xml";

function loadHTMLFromFile(path) {
  // Load the HTML to return in the response from file.
  // Since it's relative to the cwd of the test runner, we start there and
  // append to get to the actual path of the file.
  const testHTMLFile = Services.dirsvc.get("CurWorkD", Ci.nsIFile);
  const dirs = path.split("/");
  for (let i = 0; i < dirs.length; i++) {
    testHTMLFile.append(dirs[i]);
  }

  const testHTMLFileStream = Cc[
    "@mozilla.org/network/file-input-stream;1"
  ].createInstance(Ci.nsIFileInputStream);
  testHTMLFileStream.init(testHTMLFile, -1, 0, 0);
  const testHTML = NetUtil.readInputStreamToString(
    testHTMLFileStream,
    testHTMLFileStream.available()
  );

  return testHTML;
}

let gIsIframe = false;
let gIsRemoteIframe = false;

function currentContentDoc() {
  return gIsIframe ? DEFAULT_IFRAME_DOC_BODY_ID : DEFAULT_CONTENT_DOC_BODY_ID;
}

/**
 * Accessible event match criteria based on the id of the current document
 * accessible in test.
 *
 * @param   {nsIAccessibleEvent}  event
 *        Accessible event to be tested for a match.
 *
 * @return  {Boolean}
 *          True if accessible event's accessible object ID matches current
 *          document accessible ID.
 */
function matchContentDoc(event) {
  return getAccessibleDOMNodeID(event.accessible) === currentContentDoc();
}

/**
 * Used to dump debug information.
 */
let Logger = {
  /**
   * Set up this variable to dump log messages into console.
   */
  dumpToConsole: false,

  /**
   * Set up this variable to dump log messages into error console.
   */
  dumpToAppConsole: false,

  /**
   * Return true if dump is enabled.
   */
  get enabled() {
    return this.dumpToConsole || this.dumpToAppConsole;
  },

  /**
   * Dump information into console if applicable.
   */
  log(msg) {
    if (this.enabled) {
      this.logToConsole(msg);
      this.logToAppConsole(msg);
    }
  },

  /**
   * Log message to console.
   */
  logToConsole(msg) {
    if (this.dumpToConsole) {
      dump(`\n${msg}\n`);
    }
  },

  /**
   * Log message to error console.
   */
  logToAppConsole(msg) {
    if (this.dumpToAppConsole) {
      Services.console.logStringMessage(`${msg}`);
    }
  },
};

/**
 * Asynchronously set or remove content element's attribute (in content process
 * if e10s is enabled).
 * @param  {Object}  browser  current "tabbrowser" element
 * @param  {String}  id       content element id
 * @param  {String}  attr     attribute name
 * @param  {String?} value    optional attribute value, if not present, remove
 *                            attribute
 * @return {Promise}          promise indicating that attribute is set/removed
 */
function invokeSetAttribute(browser, id, attr, value) {
  if (value) {
    Logger.log(`Setting ${attr} attribute to ${value} for node with id: ${id}`);
  } else {
    Logger.log(`Removing ${attr} attribute from node with id: ${id}`);
  }

  return invokeContentTask(
    browser,
    [id, attr, value],
    (contentId, contentAttr, contentValue) => {
      let elm = content.document.getElementById(contentId);
      if (contentValue) {
        elm.setAttribute(contentAttr, contentValue);
      } else {
        elm.removeAttribute(contentAttr);
      }
    }
  );
}

/**
 * Asynchronously set or remove content element's style (in content process if
 * e10s is enabled, or in fission process if fission is enabled and a fission
 * frame is present).
 * @param  {Object}  browser  current "tabbrowser" element
 * @param  {String}  id       content element id
 * @param  {String}  aStyle   style property name
 * @param  {String?} aValue   optional style property value, if not present,
 *                            remove style
 * @return {Promise}          promise indicating that style is set/removed
 */
function invokeSetStyle(browser, id, style, value) {
  if (value) {
    Logger.log(`Setting ${style} style to ${value} for node with id: ${id}`);
  } else {
    Logger.log(`Removing ${style} style from node with id: ${id}`);
  }

  return invokeContentTask(
    browser,
    [id, style, value],
    (contentId, contentStyle, contentValue) => {
      const elm = content.document.getElementById(contentId);
      if (contentValue) {
        elm.style[contentStyle] = contentValue;
      } else {
        delete elm.style[contentStyle];
      }
    }
  );
}

/**
 * Asynchronously set focus on a content element (in content process if e10s is
 * enabled, or in fission process if fission is enabled and a fission frame is
 * present).
 * @param  {Object}  browser  current "tabbrowser" element
 * @param  {String}  id       content element id
 * @return {Promise} promise  indicating that focus is set
 */
function invokeFocus(browser, id) {
  Logger.log(`Setting focus on a node with id: ${id}`);

  return invokeContentTask(browser, [id], contentId => {
    const elm = content.document.getElementById(contentId);
    if (elm.editor) {
      elm.selectionStart = elm.selectionEnd = elm.value.length;
    }

    elm.focus();
  });
}

/**
 * Get DPR for a specific content window.
 * @param  browser
 *         Browser for which we want its content window's DPR reported.
 *
 * @return {Promise}
 *         Promise with the value that resolves to the devicePixelRatio of the
 *         content window of a given browser.
 *
 */
function getContentDPR(browser) {
  return invokeContentTask(browser, [], () => content.window.devicePixelRatio);
}

/**
 * Asynchronously perform a task in content (in content process if e10s is
 * enabled, or in fission process if fission is enabled and a fission frame is
 * present).
 * @param  {Object}    browser  current "tabbrowser" element
 * @param  {Array}     args     arguments for the content task
 * @param  {Function}  task     content task function
 *
 * @return {Promise} promise  indicating that content task is complete
 */
function invokeContentTask(browser, args, task) {
  return SpecialPowers.spawn(
    browser,
    [DEFAULT_IFRAME_ID, task.toString(), ...args],
    (iframeId, contentTask, ...contentArgs) => {
      // eslint-disable-next-line no-eval
      const runnableTask = eval(`
      (() => {
        return (${contentTask});
      })();`);
      const frame = content.document.getElementById(iframeId);

      return frame
        ? SpecialPowers.spawn(frame, contentArgs, runnableTask)
        : runnableTask.call(this, ...contentArgs);
    }
  );
}

/**
 * Compare process ID's between the top level content process and possible
 * remote/local iframe proccess.
 * @param {Object}  browser
 *        Top level browser object for a tab.
 * @param {Boolean} isRemote
 *        Indicates if we expect the iframe content process to be remote or not.
 */
async function comparePIDs(browser, isRemote) {
  function getProcessID() {
    return Services.appinfo.processID;
  }

  const contentPID = await SpecialPowers.spawn(browser, [], getProcessID);
  const iframePID = await invokeContentTask(browser, [], getProcessID);
  is(
    isRemote,
    contentPID !== iframePID,
    isRemote
      ? "Remote IFRAME is in a different process."
      : "IFRAME is in the same process."
  );
}

/**
 * Load a list of scripts into the test
 * @param {Array} scripts  a list of scripts to load
 */
function loadScripts(...scripts) {
  for (let script of scripts) {
    let path =
      typeof script === "string"
        ? `${CURRENT_DIR}${script}`
        : `${script.dir}${script.name}`;
    Services.scriptloader.loadSubScript(path, this);
  }
}

/**
 * Load a list of scripts into target's content.
 * @param {Object} target
 *        target for loading scripts into
 * @param {Array}  scripts
 *        a list of scripts to load into content
 */
async function loadContentScripts(target, ...scripts) {
  for (let { script, symbol } of scripts) {
    let contentScript = `${CURRENT_DIR}${script}`;
    let loadedScriptSet = LOADED_CONTENT_SCRIPTS.get(contentScript);
    if (!loadedScriptSet) {
      loadedScriptSet = new WeakSet();
      LOADED_CONTENT_SCRIPTS.set(contentScript, loadedScriptSet);
    } else if (loadedScriptSet.has(target)) {
      continue;
    }

    await SpecialPowers.spawn(
      target,
      [contentScript, symbol],
      async (_contentScript, importSymbol) => {
        let module = ChromeUtils.importESModule(_contentScript);
        content.window[importSymbol] = module[importSymbol];
      }
    );
    loadedScriptSet.add(target);
  }
}

function attrsToString(attrs) {
  return Object.entries(attrs)
    .map(([attr, value]) => `${attr}=${JSON.stringify(value)}`)
    .join(" ");
}

function wrapWithIFrame(doc, options = {}) {
  let src;
  let { iframeAttrs = {}, iframeDocBodyAttrs = {} } = options;
  iframeDocBodyAttrs = {
    id: DEFAULT_IFRAME_DOC_BODY_ID,
    ...iframeDocBodyAttrs,
  };
  if (options.remoteIframe) {
    // eslint-disable-next-line @microsoft/sdl/no-insecure-url
    const srcURL = new URL(`http://example.net/document-builder.sjs`);
    if (doc.endsWith("html")) {
      srcURL.searchParams.append("file", `${CURRENT_FILE_DIR}${doc}`);
    } else {
      srcURL.searchParams.append(
        "html",
        `<!doctype html>
        <html>
          <head>
            <meta charset="utf-8"/>
            <title>Accessibility Fission Test</title>
          </head>
          <body ${attrsToString(iframeDocBodyAttrs)}>${doc}</body>
        </html>`
      );
    }
    src = srcURL.href;
  } else {
    const mimeType = doc.endsWith("xhtml") ? XHTML_MIME_TYPE : HTML_MIME_TYPE;
    if (doc.endsWith("html")) {
      doc = loadHTMLFromFile(`${CURRENT_FILE_DIR}${doc}`);
      doc = doc.replace(
        /<body[.\s\S]*?>/,
        `<body ${attrsToString(iframeDocBodyAttrs)}>`
      );
    } else {
      doc = `<!doctype html>
      <body ${attrsToString(iframeDocBodyAttrs)}>${doc}</body>`;
    }

    src = `data:${mimeType};charset=utf-8,${encodeURIComponent(doc)}`;
  }

  iframeAttrs = {
    id: DEFAULT_IFRAME_ID,
    src,
    ...iframeAttrs,
  };

  return `<iframe ${attrsToString(iframeAttrs)}/>`;
}

/**
 * Takes an HTML snippet or HTML doc url and returns an encoded URI for a full
 * document with the snippet or the URL as a source for the IFRAME.
 * @param {String} doc
 *        a markup snippet or url.
 * @param {Object} options (see options in addAccessibleTask).
 *
 * @return {String}
 *        a base64 encoded data url of the document container the snippet.
 **/
function snippetToURL(doc, options = {}) {
  const { contentDocBodyAttrs = {} } = options;
  const attrs = {
    id: DEFAULT_CONTENT_DOC_BODY_ID,
    ...contentDocBodyAttrs,
  };

  if (gIsIframe) {
    doc = wrapWithIFrame(doc, options);
  }

  const encodedDoc = encodeURIComponent(
    `<!doctype html>
    <html>
      <head>
        <meta charset="utf-8"/>
        <title>Accessibility Test</title>
      </head>
      <body ${attrsToString(attrs)}>${doc}</body>
    </html>`
  );

  return `data:text/html;charset=utf-8,${encodedDoc}`;
}

function accessibleTask(doc, task, options = {}) {
  return async function () {
    gIsRemoteIframe = options.remoteIframe;
    gIsIframe = options.iframe || gIsRemoteIframe;
    let url;
    if (options.chrome && doc.endsWith("html")) {
      // Load with a chrome:// URL so this loads as a chrome document in the
      // parent process.
      url = `${CURRENT_DIR}${doc}`;
    } else if (doc.endsWith("html") && !gIsIframe) {
      url = `${CURRENT_CONTENT_DIR}${doc}`;
    } else {
      url = snippetToURL(doc, options);
    }

    registerCleanupFunction(() => {
      for (let observer of Services.obs.enumerateObservers(
        "accessible-event"
      )) {
        Services.obs.removeObserver(observer, "accessible-event");
      }
      if (gPythonSocket) {
        // Remove any globals set by Python code run in this test.
        runPython(`__reset__`);
      }
    });

    let onContentDocLoad;
    if (!options.chrome) {
      onContentDocLoad = waitForEvent(
        EVENT_DOCUMENT_LOAD_COMPLETE,
        DEFAULT_CONTENT_DOC_BODY_ID
      );
    }

    let onIframeDocLoad;
    if (options.remoteIframe && !options.skipFissionDocLoad) {
      onIframeDocLoad = waitForEvent(
        EVENT_DOCUMENT_LOAD_COMPLETE,
        DEFAULT_IFRAME_DOC_BODY_ID
      );
    }

    await BrowserTestUtils.withNewTab(
      {
        gBrowser,
        // For chrome, we need a non-remote browser.
        opening: !options.chrome
          ? url
          : () => {
              // Passing forceNotRemote: true still sets maychangeremoteness,
              // which will cause data: URIs to load remotely. There's no way to
              // avoid this with gBrowser or BrowserTestUtils. Therefore, we
              // load a blank document initially and replace it below.
              gBrowser.selectedTab = BrowserTestUtils.addTab(
                gBrowser,
                "about:blank",
                {
                  forceNotRemote: true,
                }
              );
            },
      },
      async function (browser) {
        registerCleanupFunction(() => {
          if (browser) {
            let tab = gBrowser.getTabForBrowser(browser);
            if (tab && !tab.closing && tab.linkedBrowser) {
              gBrowser.removeTab(tab);
            }
          }
        });

        if (options.chrome) {
          await SpecialPowers.pushPrefEnv({
            set: [["security.allow_unsafe_parent_loads", true]],
          });
          // Ensure this never becomes a remote browser.
          browser.removeAttribute("maychangeremoteness");
          // Now we can load our page without it becoming remote.
          browser.setAttribute("src", url);
        }

        await SimpleTest.promiseFocus(browser);

        if (options.chrome) {
          ok(!browser.isRemoteBrowser, "Not remote browser");
        } else if (Services.appinfo.browserTabsRemoteAutostart) {
          ok(browser.isRemoteBrowser, "Actually remote browser");
        }

        let docAccessible;
        if (options.chrome) {
          // Chrome documents don't fire DOCUMENT_LOAD_COMPLETE. Instead, wait
          // until we can get the DocAccessible and it doesn't have the busy
          // state.
          await BrowserTestUtils.waitForCondition(() => {
            docAccessible = getAccessible(browser.contentWindow.document);
            if (!docAccessible) {
              return false;
            }
            const state = {};
            docAccessible.getState(state, {});
            return !(state.value & STATE_BUSY);
          });
        } else {
          ({ accessible: docAccessible } = await onContentDocLoad);
        }
        let iframeDocAccessible;
        if (gIsIframe) {
          if (!options.skipFissionDocLoad) {
            await comparePIDs(browser, options.remoteIframe);
            iframeDocAccessible = onIframeDocLoad
              ? (await onIframeDocLoad).accessible
              : findAccessibleChildByID(docAccessible, DEFAULT_IFRAME_ID)
                  .firstChild;
          }
        }

        await loadContentScripts(browser, {
          script: "Common.sys.mjs",
          symbol: "CommonUtils",
        });

        await task(
          browser,
          iframeDocAccessible || docAccessible,
          iframeDocAccessible && docAccessible
        );
      }
    );
  };
}

/**
 * A wrapper around browser test add_task that triggers an accessible test task
 * as a new browser test task with given document, data URL or markup snippet.
 * @param  {String} doc
 *         URL (relative to current directory) or data URL or markup snippet
 *         that is used to test content with
 * @param  {Function|AsyncFunction} task
 *         a generator or a function with tests to run
 * @param  {null|Object} options
 *         Options for running accessibility test tasks:
 *         - {Boolean} topLevel
 *           Flag to run the test with content in the top level content process.
 *           Default is true.
 *         - {Boolean} chrome
 *           Flag to run the test with content as a chrome document in the
 *           parent process. Default is false. Although url can be a markup
 *           snippet, a snippet cannot be used for XUL content. To load XUL,
 *           specify a relative URL to a XUL document. In that case, toplevel
 *           should usually be set to false, since XUL documents don't work in
 *           content processes.
 *         - {Boolean} iframe
 *           Flag to run the test with content wrapped in an iframe. Default is
 *           false.
 *         - {Boolean} remoteIframe
 *           Flag to run the test with content wrapped in a remote iframe.
 *           Default is false.
 *         - {Object} iframeAttrs
 *           A map of attribute/value pairs to be applied to IFRAME element.
 *         - {Boolean} skipFissionDocLoad
 *           If true, the test will not wait for iframe document document
 *           loaded event (useful for when IFRAME is initially hidden).
 *         - {Object} contentDocBodyAttrs
 *           a set of attributes to be applied to a top level content document
 *           body
 *         - {Object} iframeDocBodyAttrs
 *           a set of attributes to be applied to a iframe content document body
 */
function addAccessibleTask(doc, task, options = {}) {
  const {
    topLevel = true,
    chrome = false,
    iframe = false,
    remoteIframe = false,
  } = options;
  if (topLevel) {
    add_task(
      accessibleTask(doc, task, {
        ...options,
        chrome: false,
        iframe: false,
        remoteIframe: false,
      })
    );
  }

  if (chrome) {
    add_task(
      accessibleTask(doc, task, {
        ...options,
        topLevel: false,
        iframe: false,
        remoteIframe: false,
      })
    );
  }

  if (iframe) {
    add_task(
      accessibleTask(doc, task, {
        ...options,
        topLevel: false,
        chrome: false,
        remoteIframe: false,
      })
    );
  }

  if (gFissionBrowser && remoteIframe) {
    add_task(
      accessibleTask(doc, task, {
        ...options,
        topLevel: false,
        chrome: false,
        iframe: false,
      })
    );
  }
}

/**
 * Check if an accessible object has a defunct test.
 * @param  {nsIAccessible}  accessible object to test defunct state for
 * @return {Boolean}        flag indicating defunct state
 */
function isDefunct(accessible) {
  let defunct = false;
  try {
    let extState = {};
    accessible.getState({}, extState);
    defunct = extState.value & Ci.nsIAccessibleStates.EXT_STATE_DEFUNCT;
  } catch (x) {
    defunct = true;
  } finally {
    if (defunct) {
      Logger.log(`Defunct accessible: ${prettyName(accessible)}`);
    }
  }
  return defunct;
}

/**
 * Get the DOM tag name for a given accessible.
 * @param  {nsIAccessible}  accessible accessible
 * @return {String?}                   tag name of associated DOM node, or null.
 */
function getAccessibleTagName(acc) {
  try {
    return acc.attributes.getStringProperty("tag");
  } catch (e) {
    return null;
  }
}

/**
 * Traverses the accessible tree starting from a given accessible as a root and
 * looks for an accessible that matches based on its DOMNode id.
 * @param  {nsIAccessible}  accessible root accessible
 * @param  {String}         id         id to look up accessible for
 * @param  {Array?}         interfaces the interface or an array interfaces
 *                                     to query it/them from obtained accessible
 * @return {nsIAccessible?}            found accessible if any
 */
function findAccessibleChildByID(accessible, id, interfaces) {
  if (getAccessibleDOMNodeID(accessible) === id) {
    return queryInterfaces(accessible, interfaces);
  }
  for (let i = 0; i < accessible.children.length; ++i) {
    let found = findAccessibleChildByID(accessible.getChildAt(i), id);
    if (found) {
      return queryInterfaces(found, interfaces);
    }
  }
  return null;
}

function queryInterfaces(accessible, interfaces) {
  if (!interfaces) {
    return accessible;
  }

  for (let iface of interfaces.filter(i => !(accessible instanceof i))) {
    try {
      accessible.QueryInterface(iface);
    } catch (e) {
      ok(false, "Can't query " + iface);
    }
  }

  return accessible;
}

function arrayFromChildren(accessible) {
  return Array.from({ length: accessible.childCount }, (c, i) =>
    accessible.getChildAt(i)
  );
}

/**
 * Force garbage collection.
 */
function forceGC() {
  SpecialPowers.gc();
  SpecialPowers.forceShrinkingGC();
  SpecialPowers.forceCC();
  SpecialPowers.gc();
  SpecialPowers.forceShrinkingGC();
  SpecialPowers.forceCC();
}

/*
 * This function spawns a content task and awaits expected mutation events from
 * various content changes. It's good at catching events we did *not* expect. We
 * do this advancing the layout refresh to flush the relocations/insertions
 * queue.
 */
async function contentSpawnMutation(browser, waitFor, func, args = []) {
  let onReorders = waitForEvents({ expected: waitFor.expected || [] });
  let unexpectedListener = new UnexpectedEvents(waitFor.unexpected || []);

  function tick() {
    // 100ms is an arbitrary positive number to advance the clock.
    // We don't need to advance the clock for a11y mutations, but other
    // tick listeners may depend on an advancing clock with each refresh.
    content.windowUtils.advanceTimeAndRefresh(100);
  }

  // This stops the refreh driver from doing its regular ticks, and leaves
  // us in control.
  await invokeContentTask(browser, [], tick);

  // Perform the tree mutation.
  await invokeContentTask(browser, args, func);

  // Do one tick to flush our queue (insertions, relocations, etc.)
  await invokeContentTask(browser, [], tick);

  let events = await onReorders;

  unexpectedListener.stop();

  // Go back to normal refresh driver ticks.
  await invokeContentTask(browser, [], function () {
    content.windowUtils.restoreNormalRefresh();
  });

  return events;
}

async function waitForImageMap(browser, accDoc, id = "imgmap") {
  let acc = findAccessibleChildByID(accDoc, id);

  if (!acc) {
    const onShow = waitForEvent(EVENT_SHOW, id);
    acc = (await onShow).accessible;
  }

  if (acc.firstChild) {
    return;
  }

  const onReorder = waitForEvent(EVENT_REORDER, id);
  // Wave over image map
  await invokeContentTask(browser, [id], contentId => {
    const { ContentTaskUtils } = ChromeUtils.importESModule(
      "resource://testing-common/ContentTaskUtils.sys.mjs"
    );
    const EventUtils = ContentTaskUtils.getEventUtils(content);
    EventUtils.synthesizeMouse(
      content.document.getElementById(contentId),
      10,
      10,
      { type: "mousemove" },
      content
    );
  });
  await onReorder;
}

async function getContentBoundsForDOMElm(browser, id) {
  return invokeContentTask(browser, [id], contentId => {
    const { Layout: LayoutUtils } = ChromeUtils.importESModule(
      "chrome://mochitests/content/browser/accessible/tests/browser/Layout.sys.mjs"
    );

    return LayoutUtils.getBoundsForDOMElm(contentId, content.document);
  });
}

const CACHE_WAIT_TIMEOUT_MS = 5000;

/**
 * Wait for a predicate to be true after cache ticks.
 * This function takes two callbacks, the condition is evaluated
 * by calling the first callback with the arguments returned by the second.
 * This allows us to asynchronously return the arguments as a result if the condition
 * of the first callback is met, or if it times out. The returned arguments can then
 * be used to record a pass or fail in the test.
 */
function untilCacheCondition(conditionFunc, argsFunc) {
  return new Promise((resolve, reject) => {
    let args = argsFunc();
    if (conditionFunc(...args)) {
      resolve(args);
      return;
    }

    let cacheObserver = {
      observe(subject) {
        args = argsFunc();
        if (conditionFunc(...args)) {
          clearTimeout(this.timer);
          Services.obs.removeObserver(this, "accessible-cache");
          resolve(args);
        }
      },

      timeout() {
        ok(false, "Timeout while waiting for cache update");
        Services.obs.removeObserver(this, "accessible-cache");
        args = argsFunc();
        resolve(args);
      },
    };

    cacheObserver.timer = setTimeout(
      cacheObserver.timeout.bind(cacheObserver),
      CACHE_WAIT_TIMEOUT_MS
    );
    Services.obs.addObserver(cacheObserver, "accessible-cache");
  });
}

function untilCacheOk(conditionFunc, message) {
  return untilCacheCondition(
    (v, _unusedMessage) => v,
    () => [conditionFunc(), message]
  ).then(([v, msg]) => ok(v, msg));
}

function untilCacheIs(retrievalFunc, expected, message) {
  return untilCacheCondition(
    (a, b, _unusedMessage) => Object.is(a, b),
    () => [retrievalFunc(), expected, message]
  ).then(([got, exp, msg]) => is(got, exp, msg));
}

async function waitForContentPaint(browser) {
  await SpecialPowers.spawn(browser, [], () => {
    return new Promise(function (r) {
      content.requestAnimationFrame(() => content.setTimeout(r));
    });
  });
}

// Returns true if both number arrays match within `FUZZ`.
function areBoundsFuzzyEqual(actual, expected) {
  const FUZZ = 1;
  return actual
    .map((val, i) => Math.abs(val - expected[i]) <= FUZZ)
    .reduce((a, b) => a && b, true);
}

function assertBoundsFuzzyEqual(actual, expected) {
  ok(
    areBoundsFuzzyEqual(actual, expected),
    `${actual} fuzzily matches expected ${expected}`
  );
}

async function testBoundsWithContent(iframeDocAcc, id, browser) {
  // Retrieve layout bounds from content
  let expectedBounds = await invokeContentTask(browser, [id], _id => {
    const { Layout: LayoutUtils } = ChromeUtils.importESModule(
      "chrome://mochitests/content/browser/accessible/tests/browser/Layout.sys.mjs"
    );
    return LayoutUtils.getBoundsForDOMElm(_id, content.document);
  });

  function isWithinExpected(bounds) {
    return areBoundsFuzzyEqual(bounds, expectedBounds);
  }

  const acc = findAccessibleChildByID(iframeDocAcc, id);
  let [accBounds] = await untilCacheCondition(isWithinExpected, () => [
    getBounds(acc),
  ]);

  assertBoundsFuzzyEqual(accBounds, expectedBounds);

  return accBounds;
}

let gPythonSocket = null;

/**
 * Run some Python code. This is useful for testing OS APIs.
 * This function returns a Promise which is resolved or rejected when the Python
 * code completes. The Python code can return a result with the return
 * statement, as long as the result can be serialized to JSON. For convenience,
 * if the code is a single line which does not begin with return, it will be
 * treated as an expression and its result will be returned. The JS Promise will
 * be resolved with the deserialized result. If the Python code raises an
 * exception, the JS Promise will be rejected with the Python traceback.
 * An info() function is provided in Python to log an info message.
 * See windows/a11y_setup.py for other things available in the Python
 * environment.
 */
function runPython(code) {
  if (!gPythonSocket) {
    // Keep the socket open across calls to avoid repeated setup overhead.
    gPythonSocket = new WebSocket(
      "ws://mochi.test:8888/browser/accessible/tests/browser/python_runner"
    );
    if (gPythonSocket.readyState != WebSocket.OPEN) {
      gPythonSocket.onopen = evt => {
        gPythonSocket.send(code);
        gPythonSocket.onopen = null;
      };
    }
  }
  return new Promise((resolve, reject) => {
    gPythonSocket.onmessage = evt => {
      const message = JSON.parse(evt.data);
      if (message[0] == "return") {
        gPythonSocket.onmessage = null;
        resolve(message[1]);
      } else if (message[0] == "exception") {
        gPythonSocket.onmessage = null;
        reject(new Error(message[1]));
      } else if (message[0] == "info") {
        info(message[1]);
      }
    };
    // If gPythonSocket isn't open yet, we'll send the message when .onopen is
    // called. If it's open, we can send it immediately.
    if (gPythonSocket.readyState == WebSocket.OPEN) {
      gPythonSocket.send(code);
    }
  });
}