summaryrefslogtreecommitdiffstats
path: root/layout/tools/reftest/reftest.sys.mjs
blob: 0f103c5816a5844b6815d2ec7fef73b4f78cb86a (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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
/* 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/. */

import { FileUtils } from "resource://gre/modules/FileUtils.sys.mjs";

import { globals } from "resource://reftest/globals.sys.mjs";

const {
  XHTML_NS,
  XUL_NS,

  DEBUG_CONTRACTID,

  TYPE_REFTEST_EQUAL,
  TYPE_REFTEST_NOTEQUAL,
  TYPE_LOAD,
  TYPE_SCRIPT,
  TYPE_PRINT,

  URL_TARGET_TYPE_TEST,
  URL_TARGET_TYPE_REFERENCE,

  EXPECTED_PASS,
  EXPECTED_FAIL,
  EXPECTED_RANDOM,
  EXPECTED_FUZZY,

  PREF_BOOLEAN,
  PREF_STRING,
  PREF_INTEGER,

  FOCUS_FILTER_NON_NEEDS_FOCUS_TESTS,

  g,
} = globals;

import { HttpServer } from "resource://reftest/httpd.sys.mjs";

import {
  ReadTopManifest,
  CreateUrls,
} from "resource://reftest/manifest.sys.mjs";
import { StructuredLogger } from "resource://reftest/StructuredLog.sys.mjs";
import { PerTestCoverageUtils } from "resource://reftest/PerTestCoverageUtils.sys.mjs";
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
import { E10SUtils } from "resource://gre/modules/E10SUtils.sys.mjs";

const lazy = {};

XPCOMUtils.defineLazyServiceGetters(lazy, {
  proxyService: [
    "@mozilla.org/network/protocol-proxy-service;1",
    "nsIProtocolProxyService",
  ],
});

function HasUnexpectedResult() {
  return (
    g.testResults.Exception > 0 ||
    g.testResults.FailedLoad > 0 ||
    g.testResults.UnexpectedFail > 0 ||
    g.testResults.UnexpectedPass > 0 ||
    g.testResults.AssertionUnexpected > 0 ||
    g.testResults.AssertionUnexpectedFixed > 0
  );
}

// By default we just log to stdout
var gDumpFn = function (line) {
  dump(line);
  if (g.logFile) {
    g.logFile.writeString(line);
  }
};
var gDumpRawLog = function (record) {
  // Dump JSON representation of data on a single line
  var line = "\n" + JSON.stringify(record) + "\n";
  dump(line);

  if (g.logFile) {
    g.logFile.writeString(line);
  }
};
g.logger = new StructuredLogger("reftest", gDumpRawLog);
var logger = g.logger;

function TestBuffer(str) {
  logger.debug(str);
  g.testLog.push(str);
}

function isAndroidDevice() {
  // This is the best we can do for now; maybe in the future we'll have
  // more correct detection of this case.
  return Services.appinfo.OS == "Android" && g.browserIsRemote;
}

function FlushTestBuffer() {
  // In debug mode, we've dumped all these messages already.
  if (g.logLevel !== "debug") {
    for (var i = 0; i < g.testLog.length; ++i) {
      logger.info("Saved log: " + g.testLog[i]);
    }
  }
  g.testLog = [];
}

function LogWidgetLayersFailure() {
  logger.error(
    "Screen resolution is too low - USE_WIDGET_LAYERS was disabled. " +
      (g.browserIsRemote
        ? "Since E10s is enabled, there is no fallback rendering path!"
        : "The fallback rendering path is not reliably consistent with on-screen rendering.")
  );

  logger.error(
    "If you cannot increase your screen resolution you can try reducing " +
      "gecko's pixel scaling by adding something like '--setpref " +
      "layout.css.devPixelsPerPx=1.0' to your './mach reftest' command " +
      "(possibly as an alias in ~/.mozbuild/machrc). Note that this is " +
      "inconsistent with CI testing, and may interfere with HighDPI/" +
      "reftest-zoom tests."
  );
}

function AllocateCanvas() {
  if (g.recycledCanvases.length) {
    return g.recycledCanvases.shift();
  }

  var canvas = g.containingWindow.document.createElementNS(XHTML_NS, "canvas");
  var r = g.browser.getBoundingClientRect();
  canvas.setAttribute("width", Math.ceil(r.width));
  canvas.setAttribute("height", Math.ceil(r.height));

  return canvas;
}

function ReleaseCanvas(canvas) {
  // store a maximum of 2 canvases, if we're not caching
  if (!g.noCanvasCache || g.recycledCanvases.length < 2) {
    g.recycledCanvases.push(canvas);
  }
}

export function OnRefTestLoad(win) {
  g.crashDumpDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
  g.crashDumpDir.append("minidumps");

  g.pendingCrashDumpDir = Services.dirsvc.get("UAppData", Ci.nsIFile);
  g.pendingCrashDumpDir.append("Crash Reports");
  g.pendingCrashDumpDir.append("pending");

  g.browserIsRemote = Services.appinfo.browserTabsRemoteAutostart;
  g.browserIsFission = Services.appinfo.fissionAutostart;

  g.browserIsIframe = Services.prefs.getBoolPref(
    "reftest.browser.iframe.enabled",
    false
  );
  g.useDrawSnapshot = Services.prefs.getBoolPref(
    "reftest.use-draw-snapshot",
    false
  );

  g.logLevel = Services.prefs.getStringPref("reftest.logLevel", "info");

  if (g.containingWindow == null && win != null) {
    g.containingWindow = win;
  }

  if (g.browserIsIframe) {
    g.browser = g.containingWindow.document.createElementNS(XHTML_NS, "iframe");
    g.browser.setAttribute("mozbrowser", "");
  } else {
    g.browser = g.containingWindow.document.createElementNS(
      XUL_NS,
      "xul:browser"
    );
  }
  g.browser.setAttribute("id", "browser");
  g.browser.setAttribute("type", "content");
  g.browser.setAttribute("primary", "true");
  // FIXME: This ideally shouldn't be needed, but on android and windows
  // sometimes the window is occluded / hidden, which causes some crashtests
  // to time out. Bug 1864255 might be able to help here.
  g.browser.setAttribute("manualactiveness", "true");
  g.browser.setAttribute("remote", g.browserIsRemote ? "true" : "false");
  // Make sure the browser element is exactly 800x1000, no matter
  // what size our window is
  g.browser.setAttribute(
    "style",
    "padding: 0px; margin: 0px; border:none; min-width: 800px; min-height: 1000px; max-width: 800px; max-height: 1000px; color-scheme: env(-moz-content-preferred-color-scheme)"
  );

  if (Services.appinfo.OS == "Android") {
    let doc = g.containingWindow.document.getElementById("main-window");
    while (doc.hasChildNodes()) {
      doc.firstChild.remove();
    }
    doc.appendChild(g.browser);
    // TODO Bug 1156817: reftests don't have most of GeckoView infra so we
    // can't register this actor
    ChromeUtils.unregisterWindowActor("LoadURIDelegate");
  } else {
    win.document.getElementById("reftest-window").appendChild(g.browser);
  }

  g.browserMessageManager = g.browser.frameLoader.messageManager;
  // See the comment above about manualactiveness.
  g.browser.docShellIsActive = true;
  // The content script waits for the initial onload, then notifies
  // us.
  RegisterMessageListenersAndLoadContentScript(false);
}

function InitAndStartRefTests() {
  try {
    Services.prefs.setBoolPref("android.widget_paints_background", false);
  } catch (e) {}

  // If fission is enabled, then also put data: URIs in the default web process,
  // since most reftests run in the file process, and this will make data:
  // <iframe>s OOP.
  if (g.browserIsFission) {
    Services.prefs.setBoolPref(
      "browser.tabs.remote.dataUriInDefaultWebProcess",
      true
    );
  }

  /* set the g.loadTimeout */
  g.loadTimeout = Services.prefs.getIntPref("reftest.timeout", 5 * 60 * 1000);

  /* Get the logfile for android tests */
  try {
    var logFile = Services.prefs.getStringPref("reftest.logFile");
    if (logFile) {
      var f = FileUtils.File(logFile);
      var out = FileUtils.openFileOutputStream(
        f,
        FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE
      );
      g.logFile = Cc[
        "@mozilla.org/intl/converter-output-stream;1"
      ].createInstance(Ci.nsIConverterOutputStream);
      g.logFile.init(out, null);
    }
  } catch (e) {}

  g.remote = Services.prefs.getBoolPref("reftest.remote", false);

  g.ignoreWindowSize = Services.prefs.getBoolPref(
    "reftest.ignoreWindowSize",
    false
  );

  /* Support for running a chunk (subset) of tests.  In separate try as this is optional */
  try {
    g.totalChunks = Services.prefs.getIntPref("reftest.totalChunks");
    g.thisChunk = Services.prefs.getIntPref("reftest.thisChunk");
  } catch (e) {
    g.totalChunks = 0;
    g.thisChunk = 0;
  }

  g.focusFilterMode = Services.prefs.getStringPref(
    "reftest.focusFilterMode",
    ""
  );

  g.isCoverageBuild = Services.prefs.getBoolPref(
    "reftest.isCoverageBuild",
    false
  );

  g.compareRetainedDisplayLists = Services.prefs.getBoolPref(
    "reftest.compareRetainedDisplayLists",
    false
  );

  try {
    // We have to set print.always_print_silent or a print dialog would
    // appear for each print operation, which would interrupt the test run.
    Services.prefs.setBoolPref("print.always_print_silent", true);
  } catch (e) {
    /* uh oh, print reftests may not work... */
    logger.warning("Failed to set silent printing pref, EXCEPTION: " + e);
  }

  g.windowUtils = g.containingWindow.windowUtils;
  if (!g.windowUtils || !g.windowUtils.compareCanvases) {
    throw new Error("nsIDOMWindowUtils inteface missing");
  }

  g.ioService = Services.io;
  g.debug = Cc[DEBUG_CONTRACTID].getService(Ci.nsIDebug2);

  RegisterProcessCrashObservers();

  if (g.remote) {
    g.server = null;
  } else {
    g.server = new HttpServer();
  }
  try {
    if (g.server) {
      StartHTTPServer();
    }
  } catch (ex) {
    //g.browser.loadURI('data:text/plain,' + ex);
    ++g.testResults.Exception;
    logger.error("EXCEPTION: " + ex);
    DoneTests();
  }

  // Focus the content browser.
  if (g.focusFilterMode != FOCUS_FILTER_NON_NEEDS_FOCUS_TESTS) {
    if (Services.focus.activeWindow != g.containingWindow) {
      Focus();
    }
    g.browser.addEventListener("focus", ReadTests, true);
    g.browser.focus();
  } else {
    ReadTests();
  }
}

function StartHTTPServer() {
  g.server.registerContentType("sjs", "sjs");
  g.server.start(-1);

  g.server.identity.add("http", "example.org", "80");
  g.server.identity.add("https", "example.org", "443");

  const proxyFilter = {
    proxyInfo: lazy.proxyService.newProxyInfo(
      "http", // type of proxy
      "localhost", //proxy host
      g.server.identity.primaryPort, // proxy host port
      "", // auth header
      "", // isolation key
      0, // flags
      4096, // timeout
      null // failover proxy
    ),

    applyFilter(channel, defaultProxyInfo, callback) {
      if (channel.URI.host == "example.org") {
        callback.onProxyFilterResult(this.proxyInfo);
      } else {
        callback.onProxyFilterResult(defaultProxyInfo);
      }
    },
  };

  lazy.proxyService.registerChannelFilter(proxyFilter, 0);

  g.httpServerPort = g.server.identity.primaryPort;
}

// Perform a Fisher-Yates shuffle of the array.
function Shuffle(array) {
  for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

function ReadTests() {
  try {
    if (g.focusFilterMode != FOCUS_FILTER_NON_NEEDS_FOCUS_TESTS) {
      g.browser.removeEventListener("focus", ReadTests, true);
    }

    g.urls = [];

    /* There are three modes implemented here:
     * 1) reftest.manifests
     * 2) reftest.manifests and reftest.manifests.dumpTests
     * 3) reftest.tests
     *
     * The first will parse the specified manifests, then immediately
     * run the tests. The second will parse the manifests, save the test
     * objects to a file and exit. The third will load a file of test
     * objects and run them.
     *
     * The latter two modes are used to pass test data back and forth
     * with python harness.
     */
    let manifests = Services.prefs.getStringPref("reftest.manifests", null);
    let dumpTests = Services.prefs.getStringPref(
      "reftest.manifests.dumpTests",
      null
    );
    let testList = Services.prefs.getStringPref("reftest.tests", null);

    if ((testList && manifests) || !(testList || manifests)) {
      logger.error(
        "Exactly one of reftest.manifests or reftest.tests must be specified."
      );
      logger.debug("reftest.manifests is: " + manifests);
      logger.error("reftest.tests is: " + testList);
      DoneTests();
    }

    if (testList) {
      logger.debug("Reading test objects from: " + testList);
      IOUtils.readJSON(testList)
        .then(function onSuccess(json) {
          g.urls = json.map(CreateUrls);
          StartTests();
        })
        .catch(function onFailure(e) {
          logger.error("Failed to load test objects: " + e);
          DoneTests();
        });
    } else if (manifests) {
      // Parse reftest manifests
      logger.debug("Reading " + manifests.length + " manifests");
      manifests = JSON.parse(manifests);
      g.urlsFilterRegex = manifests.null;

      var globalFilter = null;
      if (manifests.hasOwnProperty("")) {
        let filterAndId = manifests[""];
        if (!Array.isArray(filterAndId)) {
          logger.error(`manifest[""] should be an array`);
          DoneTests();
        }
        if (filterAndId.length === 0) {
          logger.error(
            `manifest[""] should contain a filter pattern in the 1st item`
          );
          DoneTests();
        }
        let filter = filterAndId[0];
        if (typeof filter !== "string") {
          logger.error(`The first item of manifest[""] should be a string`);
          DoneTests();
        }
        globalFilter = new RegExp(filter);
        delete manifests[""];
      }

      var manifestURLs = Object.keys(manifests);

      // Ensure we read manifests from higher up the directory tree first so that we
      // process includes before reading the included manifest again
      manifestURLs.sort(function (a, b) {
        return a.length - b.length;
      });
      manifestURLs.forEach(function (manifestURL) {
        logger.info("Reading manifest " + manifestURL);
        var manifestInfo = manifests[manifestURL];
        var filter = manifestInfo[0] ? new RegExp(manifestInfo[0]) : null;
        var manifestID = manifestInfo[1];
        ReadTopManifest(manifestURL, [globalFilter, filter, false], manifestID);
      });

      if (dumpTests) {
        logger.debug("Dumping test objects to file: " + dumpTests);
        IOUtils.writeJSON(dumpTests, g.urls, { flush: true }).then(
          function onSuccess() {
            DoneTests();
          },
          function onFailure(reason) {
            logger.error("failed to write test data: " + reason);
            DoneTests();
          }
        );
      } else {
        logger.debug("Running " + g.urls.length + " test objects");
        g.manageSuite = true;
        g.urls = g.urls.map(CreateUrls);
        StartTests();
      }
    }
  } catch (e) {
    ++g.testResults.Exception;
    logger.error("EXCEPTION: " + e);
    DoneTests();
  }
}

function StartTests() {
  g.noCanvasCache = Services.prefs.getIntPref("reftest.nocache", false);

  g.shuffle = Services.prefs.getBoolPref("reftest.shuffle", false);

  g.runUntilFailure = Services.prefs.getBoolPref(
    "reftest.runUntilFailure",
    false
  );

  g.verify = Services.prefs.getBoolPref("reftest.verify", false);

  g.cleanupPendingCrashes = Services.prefs.getBoolPref(
    "reftest.cleanupPendingCrashes",
    false
  );

  // Check if there are any crash dump files from the startup procedure, before
  // we start running the first test. Otherwise the first test might get
  // blamed for producing a crash dump file when that was not the case.
  CleanUpCrashDumpFiles();

  // When we repeat this function is called again, so really only want to set
  // g.repeat once.
  if (g.repeat == null) {
    g.repeat = Services.prefs.getIntPref("reftest.repeat", 0);
  }

  g.runSlowTests = Services.prefs.getIntPref("reftest.skipslowtests", false);

  if (g.shuffle) {
    g.noCanvasCache = true;
  }

  try {
    BuildUseCounts();

    // Filter tests which will be skipped to get a more even distribution when chunking
    // tURLs is a temporary array containing all active tests
    var tURLs = [];
    for (var i = 0; i < g.urls.length; ++i) {
      if (g.urls[i].skip) {
        continue;
      }

      if (g.urls[i].needsFocus && !Focus()) {
        continue;
      }

      if (g.urls[i].slow && !g.runSlowTests) {
        continue;
      }

      tURLs.push(g.urls[i]);
    }

    var numActiveTests = tURLs.length;

    if (g.totalChunks > 0 && g.thisChunk > 0) {
      // Calculate start and end indices of this chunk if tURLs array were
      // divided evenly
      var testsPerChunk = tURLs.length / g.totalChunks;
      var start = Math.round((g.thisChunk - 1) * testsPerChunk);
      var end = Math.round(g.thisChunk * testsPerChunk);
      numActiveTests = end - start;

      // Map these indices onto the g.urls array. This avoids modifying the
      // g.urls array which prevents skipped tests from showing up in the log
      start = g.thisChunk == 1 ? 0 : g.urls.indexOf(tURLs[start]);
      end =
        g.thisChunk == g.totalChunks
          ? g.urls.length
          : g.urls.indexOf(tURLs[end + 1]) - 1;

      logger.info(
        "Running chunk " +
          g.thisChunk +
          " out of " +
          g.totalChunks +
          " chunks.  " +
          "tests " +
          (start + 1) +
          "-" +
          end +
          "/" +
          g.urls.length
      );

      g.urls = g.urls.slice(start, end);
    }

    if (g.manageSuite && !g.suiteStarted) {
      var ids = {};
      g.urls.forEach(function (test) {
        if (!(test.manifestID in ids)) {
          ids[test.manifestID] = [];
        }
        ids[test.manifestID].push(test.identifier);
      });
      var suite = Services.prefs.getStringPref("reftest.suite", "reftest");
      logger.suiteStart(ids, suite, {
        skipped: g.urls.length - numActiveTests,
      });
      g.suiteStarted = true;
    }

    if (g.shuffle) {
      Shuffle(g.urls);
    }

    g.totalTests = g.urls.length;
    if (!g.totalTests && !g.verify && !g.repeat) {
      throw new Error("No tests to run");
    }

    g.uriCanvases = {};

    PerTestCoverageUtils.beforeTest()
      .then(StartCurrentTest)
      .catch(e => {
        logger.error("EXCEPTION: " + e);
        DoneTests();
      });
  } catch (ex) {
    //g.browser.loadURI('data:text/plain,' + ex);
    ++g.testResults.Exception;
    logger.error("EXCEPTION: " + ex);
    DoneTests();
  }
}

export function OnRefTestUnload() {}

function AddURIUseCount(uri) {
  if (uri == null) {
    return;
  }

  var spec = uri.spec;
  if (spec in g.uriUseCounts) {
    g.uriUseCounts[spec]++;
  } else {
    g.uriUseCounts[spec] = 1;
  }
}

function BuildUseCounts() {
  if (g.noCanvasCache) {
    return;
  }

  g.uriUseCounts = {};
  for (var i = 0; i < g.urls.length; ++i) {
    var url = g.urls[i];
    if (
      !url.skip &&
      (url.type == TYPE_REFTEST_EQUAL || url.type == TYPE_REFTEST_NOTEQUAL)
    ) {
      if (!url.prefSettings1.length) {
        AddURIUseCount(g.urls[i].url1);
      }
      if (!url.prefSettings2.length) {
        AddURIUseCount(g.urls[i].url2);
      }
    }
  }
}

// Return true iff this window is focused when this function returns.
function Focus() {
  Services.focus.focusedWindow = g.containingWindow;

  try {
    var dock = Cc["@mozilla.org/widget/macdocksupport;1"].getService(
      Ci.nsIMacDockSupport
    );
    dock.activateApplication(true);
  } catch (ex) {}

  return true;
}

function Blur() {
  // On non-remote reftests, this will transfer focus to the dummy window
  // we created to hold focus for non-needs-focus tests.  Buggy tests
  // (ones which require focus but don't request needs-focus) will then
  // fail.
  g.containingWindow.blur();
}

async function StartCurrentTest() {
  g.testLog = [];

  // make sure we don't run tests that are expected to kill the browser
  while (g.urls.length) {
    var test = g.urls[0];
    logger.testStart(test.identifier);
    if (test.skip) {
      ++g.testResults.Skip;
      logger.testEnd(test.identifier, "SKIP");
      g.urls.shift();
    } else if (test.needsFocus && !Focus()) {
      // FIXME: Marking this as a known fail is dangerous!  What
      // if it starts failing all the time?
      ++g.testResults.Skip;
      logger.testEnd(test.identifier, "SKIP", null, "(COULDN'T GET FOCUS)");
      g.urls.shift();
    } else if (test.slow && !g.runSlowTests) {
      ++g.testResults.Slow;
      logger.testEnd(test.identifier, "SKIP", null, "(SLOW)");
      g.urls.shift();
    } else {
      break;
    }
  }

  if (
    (!g.urls.length && g.repeat == 0) ||
    (g.runUntilFailure && HasUnexpectedResult())
  ) {
    await RestoreChangedPreferences();
    DoneTests();
  } else if (!g.urls.length && g.repeat > 0) {
    // Repeat
    g.repeat--;
    ReadTests();
  } else {
    if (g.urls[0].chaosMode) {
      g.windowUtils.enterChaosMode();
    }
    if (!g.urls[0].needsFocus) {
      Blur();
    }
    var currentTest = g.totalTests - g.urls.length;
    g.containingWindow.document.title =
      "reftest: " +
      currentTest +
      " / " +
      g.totalTests +
      " (" +
      Math.floor(100 * (currentTest / g.totalTests)) +
      "%)";
    StartCurrentURI(URL_TARGET_TYPE_TEST);
  }
}

// A simplified version of the function with the same name in tabbrowser.js.
function updateBrowserRemotenessByURL(aBrowser, aURL) {
  var oa = E10SUtils.predictOriginAttributes({ browser: aBrowser });
  let remoteType = E10SUtils.getRemoteTypeForURI(
    aURL,
    aBrowser.ownerGlobal.docShell.nsILoadContext.useRemoteTabs,
    aBrowser.ownerGlobal.docShell.nsILoadContext.useRemoteSubframes,
    aBrowser.remoteType,
    aBrowser.currentURI,
    oa
  );
  // Things get confused if we switch to not-remote
  // for chrome:// URIs, so lets not for now.
  if (remoteType == E10SUtils.NOT_REMOTE && g.browserIsRemote) {
    remoteType = aBrowser.remoteType;
  }
  if (aBrowser.remoteType != remoteType) {
    if (remoteType == E10SUtils.NOT_REMOTE) {
      aBrowser.removeAttribute("remote");
      aBrowser.removeAttribute("remoteType");
    } else {
      aBrowser.setAttribute("remote", "true");
      aBrowser.setAttribute("remoteType", remoteType);
    }
    aBrowser.changeRemoteness({ remoteType });
    aBrowser.construct();

    g.browserMessageManager = aBrowser.frameLoader.messageManager;
    RegisterMessageListenersAndLoadContentScript(true);
    return new Promise(resolve => {
      g.resolveContentReady = resolve;
    });
  }

  return Promise.resolve();
}

// This logic should match SpecialPowersParent._applyPrefs.
function PrefRequiresRefresh(name) {
  return (
    name == "layout.css.prefers-color-scheme.content-override" ||
    name.startsWith("ui.") ||
    name.startsWith("browser.display.") ||
    name.startsWith("font.")
  );
}

async function StartCurrentURI(aURLTargetType) {
  const isStartingRef = aURLTargetType == URL_TARGET_TYPE_REFERENCE;

  g.currentURL = g.urls[0][isStartingRef ? "url2" : "url1"].spec;
  g.currentURLTargetType = aURLTargetType;

  await RestoreChangedPreferences();

  const prefSettings =
    g.urls[0][isStartingRef ? "prefSettings2" : "prefSettings1"];

  var prefsRequireRefresh = false;

  if (prefSettings.length) {
    var badPref = undefined;
    try {
      prefSettings.forEach(function (ps) {
        let prefExists = false;
        try {
          let prefType = Services.prefs.getPrefType(ps.name);
          prefExists = prefType != Services.prefs.PREF_INVALID;
        } catch (e) {}
        if (!prefExists) {
          logger.info("Pref " + ps.name + " not found, will be added");
        }

        let oldVal = undefined;
        if (prefExists) {
          if (ps.type == PREF_BOOLEAN) {
            // eslint-disable-next-line mozilla/use-default-preference-values
            try {
              oldVal = Services.prefs.getBoolPref(ps.name);
            } catch (e) {
              badPref = "boolean preference '" + ps.name + "'";
              throw new Error("bad pref");
            }
          } else if (ps.type == PREF_STRING) {
            try {
              oldVal = Services.prefs.getStringPref(ps.name);
            } catch (e) {
              badPref = "string preference '" + ps.name + "'";
              throw new Error("bad pref");
            }
          } else if (ps.type == PREF_INTEGER) {
            // eslint-disable-next-line mozilla/use-default-preference-values
            try {
              oldVal = Services.prefs.getIntPref(ps.name);
            } catch (e) {
              badPref = "integer preference '" + ps.name + "'";
              throw new Error("bad pref");
            }
          } else {
            throw new Error("internal error - unknown preference type");
          }
        }
        if (!prefExists || oldVal != ps.value) {
          var requiresRefresh = PrefRequiresRefresh(ps.name);
          prefsRequireRefresh = prefsRequireRefresh || requiresRefresh;
          g.prefsToRestore.push({
            name: ps.name,
            type: ps.type,
            value: oldVal,
            requiresRefresh,
            prefExisted: prefExists,
          });
          var value = ps.value;
          if (ps.type == PREF_BOOLEAN) {
            Services.prefs.setBoolPref(ps.name, value);
          } else if (ps.type == PREF_STRING) {
            Services.prefs.setStringPref(ps.name, value);
            value = '"' + value + '"';
          } else if (ps.type == PREF_INTEGER) {
            Services.prefs.setIntPref(ps.name, value);
          }
          logger.info("SET PREFERENCE pref(" + ps.name + "," + value + ")");
        }
      });
    } catch (e) {
      if (e.message == "bad pref") {
        var test = g.urls[0];
        if (test.expected == EXPECTED_FAIL) {
          logger.testEnd(
            test.identifier,
            "FAIL",
            "FAIL",
            "(SKIPPED; " + badPref + " not known or wrong type)"
          );
          ++g.testResults.Skip;
        } else {
          logger.testEnd(
            test.identifier,
            "FAIL",
            "PASS",
            badPref + " not known or wrong type"
          );
          ++g.testResults.UnexpectedFail;
        }

        // skip the test that had a bad preference
        g.urls.shift();
        await StartCurrentTest();
        return;
      }
      throw e;
    }
  }

  if (
    !prefSettings.length &&
    g.uriCanvases[g.currentURL] &&
    (g.urls[0].type == TYPE_REFTEST_EQUAL ||
      g.urls[0].type == TYPE_REFTEST_NOTEQUAL) &&
    g.urls[0].maxAsserts == 0
  ) {
    // Pretend the document loaded --- RecordResult will notice
    // there's already a canvas for this URL
    g.containingWindow.setTimeout(RecordResult, 0);
  } else {
    var currentTest = g.totalTests - g.urls.length;
    // Log this to preserve the same overall log format,
    // should be removed if the format is updated
    gDumpFn(
      "REFTEST TEST-LOAD | " +
        g.currentURL +
        " | " +
        currentTest +
        " / " +
        g.totalTests +
        " (" +
        Math.floor(100 * (currentTest / g.totalTests)) +
        "%)\n"
    );
    TestBuffer("START " + g.currentURL);
    await updateBrowserRemotenessByURL(g.browser, g.currentURL);

    if (prefsRequireRefresh) {
      await new Promise(resolve =>
        g.containingWindow.requestAnimationFrame(resolve)
      );
    }

    var type = g.urls[0].type;
    if (TYPE_SCRIPT == type) {
      SendLoadScriptTest(g.currentURL, g.loadTimeout);
    } else if (TYPE_PRINT == type) {
      SendLoadPrintTest(g.currentURL, g.loadTimeout);
    } else {
      SendLoadTest(type, g.currentURL, g.currentURLTargetType, g.loadTimeout);
    }
  }
}

function DoneTests() {
  PerTestCoverageUtils.afterTest()
    .catch(e => logger.error("EXCEPTION: " + e))
    .then(() => {
      if (g.manageSuite) {
        g.suiteStarted = false;
        logger.suiteEnd({ results: g.testResults });
      } else {
        logger.logData("results", { results: g.testResults });
      }
      logger.info(
        "Slowest test took " +
          g.slowestTestTime +
          "ms (" +
          g.slowestTestURL +
          ")"
      );
      logger.info("Total canvas count = " + g.recycledCanvases.length);
      if (g.failedUseWidgetLayers) {
        LogWidgetLayersFailure();
      }

      function onStopped() {
        if (g.logFile) {
          g.logFile.close();
          g.logFile = null;
        }
        Services.startup.quit(Ci.nsIAppStartup.eForceQuit);
      }
      if (g.server) {
        g.server.stop(onStopped);
      } else {
        onStopped();
      }
    });
}

function UpdateCanvasCache(url, canvas) {
  var spec = url.spec;

  --g.uriUseCounts[spec];

  if (g.uriUseCounts[spec] == 0) {
    ReleaseCanvas(canvas);
    delete g.uriCanvases[spec];
  } else if (g.uriUseCounts[spec] > 0) {
    g.uriCanvases[spec] = canvas;
  } else {
    throw new Error("Use counts were computed incorrectly");
  }
}

// Recompute drawWindow flags for every drawWindow operation.
// We have to do this every time since our window can be
// asynchronously resized (e.g. by the window manager, to make
// it fit on screen) at unpredictable times.
// Fortunately this is pretty cheap.
async function DoDrawWindow(ctx, x, y, w, h) {
  if (g.useDrawSnapshot) {
    try {
      let image = await g.browser.drawSnapshot(x, y, w, h, 1.0, "#fff");
      ctx.drawImage(image, x, y);
    } catch (ex) {
      logger.error(g.currentURL + " | drawSnapshot failed: " + ex);
      ++g.testResults.Exception;
    }
    return;
  }

  var flags = ctx.DRAWWINDOW_DRAW_CARET | ctx.DRAWWINDOW_DRAW_VIEW;
  var testRect = g.browser.getBoundingClientRect();
  if (
    g.ignoreWindowSize ||
    (0 <= testRect.left &&
      0 <= testRect.top &&
      g.containingWindow.innerWidth >= testRect.right &&
      g.containingWindow.innerHeight >= testRect.bottom)
  ) {
    // We can use the window's retained layer manager
    // because the window is big enough to display the entire
    // browser element
    flags |= ctx.DRAWWINDOW_USE_WIDGET_LAYERS;
  } else if (g.browserIsRemote) {
    logger.error(g.currentURL + " | can't drawWindow remote content");
    ++g.testResults.Exception;
  }

  if (g.drawWindowFlags != flags) {
    // Every time the flags change, dump the new state.
    g.drawWindowFlags = flags;
    var flagsStr = "DRAWWINDOW_DRAW_CARET | DRAWWINDOW_DRAW_VIEW";
    if (flags & ctx.DRAWWINDOW_USE_WIDGET_LAYERS) {
      flagsStr += " | DRAWWINDOW_USE_WIDGET_LAYERS";
    } else {
      // Output a special warning because we need to be able to detect
      // this whenever it happens.
      LogWidgetLayersFailure();
      g.failedUseWidgetLayers = true;
    }
    logger.info(
      "drawWindow flags = " +
        flagsStr +
        "; window size = " +
        g.containingWindow.innerWidth +
        "," +
        g.containingWindow.innerHeight +
        "; test browser size = " +
        testRect.width +
        "," +
        testRect.height
    );
  }

  TestBuffer("DoDrawWindow " + x + "," + y + "," + w + "," + h);
  ctx.save();
  ctx.translate(x, y);
  ctx.drawWindow(
    g.containingWindow,
    x,
    y,
    w,
    h,
    "rgb(255,255,255)",
    g.drawWindowFlags
  );
  ctx.restore();
}

async function InitCurrentCanvasWithSnapshot() {
  TestBuffer("Initializing canvas snapshot");

  if (
    g.urls[0].type == TYPE_LOAD ||
    g.urls[0].type == TYPE_SCRIPT ||
    g.urls[0].type == TYPE_PRINT
  ) {
    // We don't want to snapshot this kind of test
    return false;
  }

  if (!g.currentCanvas) {
    g.currentCanvas = AllocateCanvas();
  }

  var ctx = g.currentCanvas.getContext("2d");
  await DoDrawWindow(ctx, 0, 0, g.currentCanvas.width, g.currentCanvas.height);
  return true;
}

async function UpdateCurrentCanvasForInvalidation(rects) {
  TestBuffer("Updating canvas for invalidation");

  if (!g.currentCanvas) {
    return;
  }

  var ctx = g.currentCanvas.getContext("2d");
  for (var i = 0; i < rects.length; ++i) {
    var r = rects[i];
    // Set left/top/right/bottom to pixel boundaries
    var left = Math.floor(r.left);
    var top = Math.floor(r.top);
    var right = Math.ceil(r.right);
    var bottom = Math.ceil(r.bottom);

    // Clamp the values to the canvas size
    left = Math.max(0, Math.min(left, g.currentCanvas.width));
    top = Math.max(0, Math.min(top, g.currentCanvas.height));
    right = Math.max(0, Math.min(right, g.currentCanvas.width));
    bottom = Math.max(0, Math.min(bottom, g.currentCanvas.height));

    await DoDrawWindow(ctx, left, top, right - left, bottom - top);
  }
}

async function UpdateWholeCurrentCanvasForInvalidation() {
  TestBuffer("Updating entire canvas for invalidation");

  if (!g.currentCanvas) {
    return;
  }

  var ctx = g.currentCanvas.getContext("2d");
  await DoDrawWindow(ctx, 0, 0, g.currentCanvas.width, g.currentCanvas.height);
}

// eslint-disable-next-line complexity
function RecordResult(testRunTime, errorMsg, typeSpecificResults) {
  TestBuffer("RecordResult fired");

  // Keep track of which test was slowest, and how long it took.
  if (testRunTime > g.slowestTestTime) {
    g.slowestTestTime = testRunTime;
    g.slowestTestURL = g.currentURL;
  }

  // Not 'const ...' because of 'EXPECTED_*' value dependency.
  var outputs = {};
  outputs[EXPECTED_PASS] = {
    true: { s: ["PASS", "PASS"], n: "Pass" },
    false: { s: ["FAIL", "PASS"], n: "UnexpectedFail" },
  };
  outputs[EXPECTED_FAIL] = {
    true: { s: ["PASS", "FAIL"], n: "UnexpectedPass" },
    false: { s: ["FAIL", "FAIL"], n: "KnownFail" },
  };
  outputs[EXPECTED_RANDOM] = {
    true: { s: ["PASS", "PASS"], n: "Random" },
    false: { s: ["FAIL", "FAIL"], n: "Random" },
  };
  // for EXPECTED_FUZZY we need special handling because we can have
  // Pass, UnexpectedPass, or UnexpectedFail

  if (
    (g.currentURLTargetType == URL_TARGET_TYPE_TEST &&
      g.urls[0].wrCapture.test) ||
    (g.currentURLTargetType == URL_TARGET_TYPE_REFERENCE &&
      g.urls[0].wrCapture.ref)
  ) {
    logger.info("Running webrender capture");
    g.windowUtils.wrCapture();
  }

  var output;
  var extra;

  if (g.urls[0].type == TYPE_LOAD) {
    ++g.testResults.LoadOnly;
    logger.testStatus(g.urls[0].identifier, "(LOAD ONLY)", "PASS", "PASS");
    g.currentCanvas = null;
    FinishTestItem();
    return;
  }
  if (g.urls[0].type == TYPE_PRINT) {
    switch (g.currentURLTargetType) {
      case URL_TARGET_TYPE_TEST:
        // First document has been loaded.
        g.testPrintOutput = typeSpecificResults;
        // Proceed to load the second document.
        CleanUpCrashDumpFiles();
        StartCurrentURI(URL_TARGET_TYPE_REFERENCE);
        break;
      case URL_TARGET_TYPE_REFERENCE:
        let pathToTestPdf = g.testPrintOutput;
        let pathToRefPdf = typeSpecificResults;
        comparePdfs(pathToTestPdf, pathToRefPdf, function (error, results) {
          let expected = g.urls[0].expected;
          // TODO: We should complain here if results is empty!
          // (If it's empty, we'll spuriously succeed, regardless of
          // our expectations)
          if (error) {
            output = outputs[expected].false;
            extra = { status_msg: output.n };
            ++g.testResults[output.n];
            logger.testEnd(
              g.urls[0].identifier,
              output.s[0],
              output.s[1],
              error.message,
              null,
              extra
            );
          } else {
            let outputPair = outputs[expected];
            if (expected === EXPECTED_FAIL) {
              let failureResults = results.filter(function (result) {
                return !result.passed;
              });
              if (failureResults.length) {
                // We got an expected failure. Let's get rid of the
                // passes from the results so we don't trigger
                // TEST_UNEXPECTED_PASS logging for those.
                results = failureResults;
              }
              // (else, we expected a failure but got none!
              // Leave results untouched so we can log them.)
            }
            results.forEach(function (result) {
              output = outputPair[result.passed];
              let extra = { status_msg: output.n };
              ++g.testResults[output.n];
              logger.testEnd(
                g.urls[0].identifier,
                output.s[0],
                output.s[1],
                result.description,
                null,
                extra
              );
            });
          }
          FinishTestItem();
        });
        break;
      default:
        throw new Error("Unexpected state.");
    }
    return;
  }
  if (g.urls[0].type == TYPE_SCRIPT) {
    let expected = g.urls[0].expected;

    if (errorMsg) {
      // Force an unexpected failure to alert the test author to fix the test.
      expected = EXPECTED_PASS;
    } else if (!typeSpecificResults.length) {
      // This failure may be due to a JavaScript Engine bug causing
      // early termination of the test. If we do not allow silent
      // failure, report an error.
      if (!g.urls[0].allowSilentFail) {
        errorMsg = "No test results reported. (SCRIPT)\n";
      } else {
        logger.info("An expected silent failure occurred");
      }
    }

    if (errorMsg) {
      output = outputs[expected].false;
      extra = { status_msg: output.n };
      ++g.testResults[output.n];
      logger.testStatus(
        g.urls[0].identifier,
        errorMsg,
        output.s[0],
        output.s[1],
        null,
        null,
        extra
      );
      FinishTestItem();
      return;
    }

    var anyFailed = typeSpecificResults.some(function (result) {
      return !result.passed;
    });
    var outputPair;
    if (anyFailed && expected == EXPECTED_FAIL) {
      // If we're marked as expected to fail, and some (but not all) tests
      // passed, treat those tests as though they were marked random
      // (since we can't tell whether they were really intended to be
      // marked failing or not).
      outputPair = {
        true: outputs[EXPECTED_RANDOM].true,
        false: outputs[expected].false,
      };
    } else {
      outputPair = outputs[expected];
    }
    var index = 0;
    typeSpecificResults.forEach(function (result) {
      var output = outputPair[result.passed];
      var extra = { status_msg: output.n };

      ++g.testResults[output.n];
      logger.testStatus(
        g.urls[0].identifier,
        result.description + " item " + ++index,
        output.s[0],
        output.s[1],
        null,
        null,
        extra
      );
    });

    if (anyFailed && expected == EXPECTED_PASS) {
      FlushTestBuffer();
    }

    FinishTestItem();
    return;
  }

  const isRecordingRef = g.currentURLTargetType == URL_TARGET_TYPE_REFERENCE;
  const prefSettings =
    g.urls[0][isRecordingRef ? "prefSettings2" : "prefSettings1"];

  if (!prefSettings.length && g.uriCanvases[g.currentURL]) {
    g.currentCanvas = g.uriCanvases[g.currentURL];
  }
  if (g.currentCanvas == null) {
    logger.error(g.currentURL, "program error managing snapshots");
    ++g.testResults.Exception;
  }
  g[isRecordingRef ? "canvas2" : "canvas1"] = g.currentCanvas;
  g.currentCanvas = null;

  ResetRenderingState();

  switch (g.currentURLTargetType) {
    case URL_TARGET_TYPE_TEST:
      // First document has been loaded.
      // Proceed to load the second document.

      CleanUpCrashDumpFiles();
      StartCurrentURI(URL_TARGET_TYPE_REFERENCE);
      break;
    case URL_TARGET_TYPE_REFERENCE:
      // Both documents have been loaded. Compare the renderings and see
      // if the comparison result matches the expected result specified
      // in the manifest.

      // number of different pixels
      var differences;
      // whether the two renderings match:
      var equal;
      var maxDifference = {};
      // whether the allowed fuzziness from the annotations is exceeded
      // by the actual comparison results
      var fuzz_exceeded = false;

      // what is expected on this platform (PASS, FAIL, RANDOM, or FUZZY)
      let expected = g.urls[0].expected;

      differences = g.windowUtils.compareCanvases(
        g.canvas1,
        g.canvas2,
        maxDifference
      );

      if (g.urls[0].noAutoFuzz) {
        // Autofuzzing is disabled
      } else if (
        isAndroidDevice() &&
        maxDifference.value <= 2 &&
        differences > 0
      ) {
        // Autofuzz for WR on Android physical devices: Reduce any
        // maxDifference of 2 to 0, because we get a lot of off-by-ones
        // and off-by-twos that are very random and hard to annotate.
        // In cases where the difference on any pixel component is more
        // than 2 we require manual annotation. Note that this applies
        // to both == tests and != tests, so != tests don't
        // inadvertently pass due to a random off-by-one pixel
        // difference.
        logger.info(
          `REFTEST wr-on-android dropping fuzz of (${maxDifference.value}, ${differences}) to (0, 0)`
        );
        maxDifference.value = 0;
        differences = 0;
      }

      equal = differences == 0;

      if (maxDifference.value > 0 && equal) {
        throw new Error("Inconsistent result from compareCanvases.");
      }

      if (expected == EXPECTED_FUZZY) {
        logger.info(
          `REFTEST fuzzy test ` +
            `(${g.urls[0].fuzzyMinDelta}, ${g.urls[0].fuzzyMinPixels}) <= ` +
            `(${maxDifference.value}, ${differences}) <= ` +
            `(${g.urls[0].fuzzyMaxDelta}, ${g.urls[0].fuzzyMaxPixels})`
        );
        fuzz_exceeded =
          maxDifference.value > g.urls[0].fuzzyMaxDelta ||
          differences > g.urls[0].fuzzyMaxPixels;
        equal =
          !fuzz_exceeded &&
          maxDifference.value >= g.urls[0].fuzzyMinDelta &&
          differences >= g.urls[0].fuzzyMinPixels;
      }

      var failedExtraCheck =
        g.failedNoPaint ||
        g.failedNoDisplayList ||
        g.failedDisplayList ||
        g.failedOpaqueLayer ||
        g.failedAssignedLayer;

      // whether the comparison result matches what is in the manifest
      var test_passed =
        equal == (g.urls[0].type == TYPE_REFTEST_EQUAL) && !failedExtraCheck;

      if (expected != EXPECTED_FUZZY) {
        output = outputs[expected][test_passed];
      } else if (test_passed) {
        output = { s: ["PASS", "PASS"], n: "Pass" };
      } else if (
        g.urls[0].type == TYPE_REFTEST_EQUAL &&
        !failedExtraCheck &&
        !fuzz_exceeded
      ) {
        // If we get here, that means we had an '==' type test where
        // at least one of the actual difference values was below the
        // allowed range, but nothing else was wrong. So let's produce
        // UNEXPECTED-PASS in this scenario. Also, if we enter this
        // branch, 'equal' must be false so let's assert that to guard
        // against logic errors.
        if (equal) {
          throw new Error(
            "Logic error in reftest.sys.mjs fuzzy test handling!"
          );
        }
        output = { s: ["PASS", "FAIL"], n: "UnexpectedPass" };
      } else {
        // In all other cases we fail the test
        output = { s: ["FAIL", "PASS"], n: "UnexpectedFail" };
      }
      extra = { status_msg: output.n };

      ++g.testResults[output.n];

      // It's possible that we failed both an "extra check" and the normal comparison, but we don't
      // have a way to annotate these separately, so just print an error for the extra check failures.
      if (failedExtraCheck) {
        var failures = [];
        if (g.failedNoPaint) {
          failures.push("failed reftest-no-paint");
        }
        if (g.failedNoDisplayList) {
          failures.push("failed reftest-no-display-list");
        }
        if (g.failedDisplayList) {
          failures.push("failed reftest-display-list");
        }
        // The g.failed*Messages arrays will contain messages from both the test and the reference.
        if (g.failedOpaqueLayer) {
          failures.push(
            "failed reftest-opaque-layer: " +
              g.failedOpaqueLayerMessages.join(", ")
          );
        }
        if (g.failedAssignedLayer) {
          failures.push(
            "failed reftest-assigned-layer: " +
              g.failedAssignedLayerMessages.join(", ")
          );
        }
        var failureString = failures.join(", ");
        logger.testStatus(
          g.urls[0].identifier,
          failureString,
          output.s[0],
          output.s[1],
          null,
          null,
          extra
        );
      } else {
        var message =
          "image comparison, max difference: " +
          maxDifference.value +
          ", number of differing pixels: " +
          differences;
        if (
          (!test_passed && expected == EXPECTED_PASS) ||
          (!test_passed && expected == EXPECTED_FUZZY) ||
          (test_passed && expected == EXPECTED_FAIL)
        ) {
          if (!equal) {
            extra.max_difference = maxDifference.value;
            extra.differences = differences;
            let image1 = g.canvas1.toDataURL();
            let image2 = g.canvas2.toDataURL();
            extra.reftest_screenshots = [
              {
                url: g.urls[0].identifier[0],
                screenshot: image1.slice(image1.indexOf(",") + 1),
              },
              g.urls[0].identifier[1],
              {
                url: g.urls[0].identifier[2],
                screenshot: image2.slice(image2.indexOf(",") + 1),
              },
            ];
            extra.image1 = image1;
            extra.image2 = image2;
          } else {
            let image1 = g.canvas1.toDataURL();
            extra.reftest_screenshots = [
              {
                url: g.urls[0].identifier[0],
                screenshot: image1.slice(image1.indexOf(",") + 1),
              },
            ];
            extra.image1 = image1;
          }
        }
        logger.testStatus(
          g.urls[0].identifier,
          message,
          output.s[0],
          output.s[1],
          null,
          null,
          extra
        );

        if (g.noCanvasCache) {
          ReleaseCanvas(g.canvas1);
          ReleaseCanvas(g.canvas2);
        } else {
          if (!g.urls[0].prefSettings1.length) {
            UpdateCanvasCache(g.urls[0].url1, g.canvas1);
          }
          if (!g.urls[0].prefSettings2.length) {
            UpdateCanvasCache(g.urls[0].url2, g.canvas2);
          }
        }
      }

      if (
        (!test_passed && expected == EXPECTED_PASS) ||
        (test_passed && expected == EXPECTED_FAIL)
      ) {
        FlushTestBuffer();
      }

      CleanUpCrashDumpFiles();
      FinishTestItem();
      break;
    default:
      throw new Error("Unexpected state.");
  }
}

function LoadFailed(why) {
  ++g.testResults.FailedLoad;
  if (!why) {
    // reftest-content.js sets an initial reason before it sets the
    // timeout that will call us with the currently set reason, so we
    // should never get here.  If we do then there's a logic error
    // somewhere.  Perhaps tests are somehow running overlapped and the
    // timeout for one test is not being cleared before the timeout for
    // another is set?  Maybe there's some sort of race?
    logger.error(
      "load failed with unknown reason (we should always have a reason!)"
    );
  }
  logger.testStatus(
    g.urls[0].identifier,
    "load failed: " + why,
    "FAIL",
    "PASS"
  );
  FlushTestBuffer();
  FinishTestItem();
}

function RemoveExpectedCrashDumpFiles() {
  if (g.expectingProcessCrash) {
    for (let crashFilename of g.expectedCrashDumpFiles) {
      let file = g.crashDumpDir.clone();
      file.append(crashFilename);
      if (file.exists()) {
        file.remove(false);
      }
    }
  }
  g.expectedCrashDumpFiles.length = 0;
}

function FindUnexpectedCrashDumpFiles() {
  if (!g.crashDumpDir.exists()) {
    return;
  }

  let entries = g.crashDumpDir.directoryEntries;
  if (!entries) {
    return;
  }

  let foundCrashDumpFile = false;
  while (entries.hasMoreElements()) {
    let file = entries.nextFile;
    let path = String(file.path);
    if (path.match(/\.(dmp|extra)$/) && !g.unexpectedCrashDumpFiles[path]) {
      if (!foundCrashDumpFile) {
        ++g.testResults.UnexpectedFail;
        foundCrashDumpFile = true;
        if (g.currentURL) {
          logger.testStatus(
            g.urls[0].identifier,
            "crash-check",
            "FAIL",
            "PASS",
            "This test left crash dumps behind, but we weren't expecting it to!"
          );
        } else {
          logger.error(
            "Harness startup left crash dumps behind, but we weren't expecting it to!"
          );
        }
      }
      logger.info("Found unexpected crash dump file " + path);
      g.unexpectedCrashDumpFiles[path] = true;
    }
  }
}

function RemovePendingCrashDumpFiles() {
  if (!g.pendingCrashDumpDir.exists()) {
    return;
  }

  let entries = g.pendingCrashDumpDir.directoryEntries;
  while (entries.hasMoreElements()) {
    let file = entries.nextFile;
    if (file.isFile()) {
      file.remove(false);
      logger.info("This test left pending crash dumps; deleted " + file.path);
    }
  }
}

function CleanUpCrashDumpFiles() {
  RemoveExpectedCrashDumpFiles();
  FindUnexpectedCrashDumpFiles();
  if (g.cleanupPendingCrashes) {
    RemovePendingCrashDumpFiles();
  }
  g.expectingProcessCrash = false;
}

function FinishTestItem() {
  logger.testEnd(g.urls[0].identifier, "OK");

  // Replace document with BLANK_URL_FOR_CLEARING in case there are
  // assertions when unloading.
  logger.debug("Loading a blank page");
  // After clearing, content will notify us of the assertion count
  // and tests will continue.
  SendClear();
  g.failedNoPaint = false;
  g.failedNoDisplayList = false;
  g.failedDisplayList = false;
  g.failedOpaqueLayer = false;
  g.failedOpaqueLayerMessages = [];
  g.failedAssignedLayer = false;
  g.failedAssignedLayerMessages = [];
}

async function DoAssertionCheck(numAsserts) {
  if (g.debug.isDebugBuild) {
    if (g.browserIsRemote) {
      // Count chrome-process asserts too when content is out of
      // process.
      var newAssertionCount = g.debug.assertionCount;
      var numLocalAsserts = newAssertionCount - g.assertionCount;
      g.assertionCount = newAssertionCount;

      numAsserts += numLocalAsserts;
    }

    var minAsserts = g.urls[0].minAsserts;
    var maxAsserts = g.urls[0].maxAsserts;

    if (numAsserts < minAsserts) {
      ++g.testResults.AssertionUnexpectedFixed;
    } else if (numAsserts > maxAsserts) {
      ++g.testResults.AssertionUnexpected;
    } else if (numAsserts != 0) {
      ++g.testResults.AssertionKnown;
    }
    logger.assertionCount(
      g.urls[0].identifier,
      numAsserts,
      minAsserts,
      maxAsserts
    );
  }

  if (g.urls[0].chaosMode) {
    g.windowUtils.leaveChaosMode();
  }

  // And start the next test.
  g.urls.shift();
  await StartCurrentTest();
}

function ResetRenderingState() {
  SendResetRenderingState();
  // We would want to clear any viewconfig here, if we add support for it
}

async function RestoreChangedPreferences() {
  if (!g.prefsToRestore.length) {
    return;
  }
  var requiresRefresh = false;
  g.prefsToRestore.reverse();
  g.prefsToRestore.forEach(function (ps) {
    requiresRefresh = requiresRefresh || ps.requiresRefresh;
    if (ps.prefExisted) {
      var value = ps.value;
      if (ps.type == PREF_BOOLEAN) {
        Services.prefs.setBoolPref(ps.name, value);
      } else if (ps.type == PREF_STRING) {
        Services.prefs.setStringPref(ps.name, value);
        value = '"' + value + '"';
      } else if (ps.type == PREF_INTEGER) {
        Services.prefs.setIntPref(ps.name, value);
      }
      logger.info("RESTORE PREFERENCE pref(" + ps.name + "," + value + ")");
    } else {
      Services.prefs.clearUserPref(ps.name);
      logger.info(
        "RESTORE PREFERENCE pref(" +
          ps.name +
          ", <no value set>) (clearing user pref)"
      );
    }
  });

  g.prefsToRestore = [];

  if (requiresRefresh) {
    await new Promise(resolve =>
      g.containingWindow.requestAnimationFrame(resolve)
    );
  }
}

function RegisterMessageListenersAndLoadContentScript(aReload) {
  g.browserMessageManager.addMessageListener(
    "reftest:AssertionCount",
    function (m) {
      RecvAssertionCount(m.json.count);
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:ContentReady",
    function (m) {
      return RecvContentReady(m.data);
    }
  );
  g.browserMessageManager.addMessageListener("reftest:Exception", function (m) {
    RecvException(m.json.what);
  });
  g.browserMessageManager.addMessageListener(
    "reftest:FailedLoad",
    function (m) {
      RecvFailedLoad(m.json.why);
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:FailedNoPaint",
    function () {
      RecvFailedNoPaint();
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:FailedNoDisplayList",
    function () {
      RecvFailedNoDisplayList();
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:FailedDisplayList",
    function () {
      RecvFailedDisplayList();
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:FailedOpaqueLayer",
    function (m) {
      RecvFailedOpaqueLayer(m.json.why);
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:FailedAssignedLayer",
    function (m) {
      RecvFailedAssignedLayer(m.json.why);
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:InitCanvasWithSnapshot",
    function () {
      RecvInitCanvasWithSnapshot();
    }
  );
  g.browserMessageManager.addMessageListener("reftest:Log", function (m) {
    RecvLog(m.json.type, m.json.msg);
  });
  g.browserMessageManager.addMessageListener(
    "reftest:ScriptResults",
    function (m) {
      RecvScriptResults(m.json.runtimeMs, m.json.error, m.json.results);
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:StartPrint",
    function (m) {
      RecvStartPrint(m.json.isPrintSelection, m.json.printRange);
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:PrintResult",
    function (m) {
      RecvPrintResult(m.json.runtimeMs, m.json.status, m.json.fileName);
    }
  );
  g.browserMessageManager.addMessageListener("reftest:TestDone", function (m) {
    RecvTestDone(m.json.runtimeMs);
  });
  g.browserMessageManager.addMessageListener(
    "reftest:UpdateCanvasForInvalidation",
    function (m) {
      RecvUpdateCanvasForInvalidation(m.json.rects);
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:UpdateWholeCanvasForInvalidation",
    function () {
      RecvUpdateWholeCanvasForInvalidation();
    }
  );
  g.browserMessageManager.addMessageListener(
    "reftest:ExpectProcessCrash",
    function () {
      RecvExpectProcessCrash();
    }
  );

  g.browserMessageManager.loadFrameScript(
    "resource://reftest/reftest-content.js",
    true,
    true
  );

  if (aReload) {
    return;
  }

  ChromeUtils.registerWindowActor("ReftestFission", {
    parent: {
      esModuleURI: "resource://reftest/ReftestFissionParent.sys.mjs",
    },
    child: {
      esModuleURI: "resource://reftest/ReftestFissionChild.sys.mjs",
      events: {
        MozAfterPaint: {},
      },
    },
    allFrames: true,
    includeChrome: true,
  });
}

async function RecvAssertionCount(count) {
  await DoAssertionCheck(count);
}

function RecvContentReady(info) {
  if (g.resolveContentReady) {
    g.resolveContentReady();
    g.resolveContentReady = null;
  } else {
    g.contentGfxInfo = info.gfx;
    InitAndStartRefTests();
  }
  return { remote: g.browserIsRemote };
}

function RecvException(what) {
  logger.error(g.currentURL + " | " + what);
  ++g.testResults.Exception;
}

function RecvFailedLoad(why) {
  LoadFailed(why);
}

function RecvFailedNoPaint() {
  g.failedNoPaint = true;
}

function RecvFailedNoDisplayList() {
  g.failedNoDisplayList = true;
}

function RecvFailedDisplayList() {
  g.failedDisplayList = true;
}

function RecvFailedOpaqueLayer(why) {
  g.failedOpaqueLayer = true;
  g.failedOpaqueLayerMessages.push(why);
}

function RecvFailedAssignedLayer(why) {
  g.failedAssignedLayer = true;
  g.failedAssignedLayerMessages.push(why);
}

async function RecvInitCanvasWithSnapshot() {
  var painted = await InitCurrentCanvasWithSnapshot();
  SendUpdateCurrentCanvasWithSnapshotDone(painted);
}

function RecvLog(type, msg) {
  msg = "[CONTENT] " + msg;
  if (type == "info") {
    TestBuffer(msg);
  } else if (type == "warning") {
    logger.warning(msg);
  } else if (type == "error") {
    logger.error(
      "REFTEST TEST-UNEXPECTED-FAIL | " + g.currentURL + " | " + msg + "\n"
    );
    ++g.testResults.Exception;
  } else {
    logger.error(
      "REFTEST TEST-UNEXPECTED-FAIL | " +
        g.currentURL +
        " | unknown log type " +
        type +
        "\n"
    );
    ++g.testResults.Exception;
  }
}

function RecvScriptResults(runtimeMs, error, results) {
  RecordResult(runtimeMs, error, results);
}

function RecvStartPrint(isPrintSelection, printRange) {
  let fileName = `reftest-print-${Date.now()}-`;
  crypto
    .getRandomValues(new Uint8Array(4))
    .forEach(x => (fileName += x.toString(16)));
  fileName += ".pdf";
  let file = Services.dirsvc.get("TmpD", Ci.nsIFile);
  file.append(fileName);

  let PSSVC = Cc["@mozilla.org/gfx/printsettings-service;1"].getService(
    Ci.nsIPrintSettingsService
  );
  let ps = PSSVC.createNewPrintSettings();
  ps.printSilent = true;
  ps.printBGImages = true;
  ps.printBGColors = true;
  ps.unwriteableMarginTop = 0;
  ps.unwriteableMarginRight = 0;
  ps.unwriteableMarginLeft = 0;
  ps.unwriteableMarginBottom = 0;
  ps.outputDestination = Ci.nsIPrintSettings.kOutputDestinationFile;
  ps.toFileName = file.path;
  ps.outputFormat = Ci.nsIPrintSettings.kOutputFormatPDF;
  ps.printSelectionOnly = isPrintSelection;
  if (printRange) {
    ps.pageRanges = printRange
      .split(",")
      .map(function (r) {
        let range = r.split("-");
        return [+range[0] || 1, +range[1] || 1];
      })
      .flat();
  }

  ps.printInColor = Services.prefs.getBoolPref("print.print_in_color", true);

  g.browser.browsingContext
    .print(ps)
    .then(() => SendPrintDone(Cr.NS_OK, file.path))
    .catch(exception => SendPrintDone(exception.code, file.path));
}

function RecvPrintResult(runtimeMs, status, fileName) {
  if (!Components.isSuccessCode(status)) {
    logger.error(
      "REFTEST TEST-UNEXPECTED-FAIL | " +
        g.currentURL +
        " | error during printing\n"
    );
    ++g.testResults.Exception;
  }
  RecordResult(runtimeMs, "", fileName);
}

function RecvTestDone(runtimeMs) {
  RecordResult(runtimeMs, "", []);
}

async function RecvUpdateCanvasForInvalidation(rects) {
  await UpdateCurrentCanvasForInvalidation(rects);
  SendUpdateCurrentCanvasWithSnapshotDone(true);
}

async function RecvUpdateWholeCanvasForInvalidation() {
  await UpdateWholeCurrentCanvasForInvalidation();
  SendUpdateCurrentCanvasWithSnapshotDone(true);
}

function OnProcessCrashed(subject, topic) {
  let id;
  let additionalDumps;
  let propbag = subject.QueryInterface(Ci.nsIPropertyBag2);

  if (topic == "ipc:content-shutdown") {
    id = propbag.get("dumpID");
  }

  if (id) {
    g.expectedCrashDumpFiles.push(id + ".dmp");
    g.expectedCrashDumpFiles.push(id + ".extra");
  }

  if (additionalDumps && additionalDumps.length) {
    for (const name of additionalDumps.split(",")) {
      g.expectedCrashDumpFiles.push(id + "-" + name + ".dmp");
    }
  }
}

function RegisterProcessCrashObservers() {
  Services.obs.addObserver(OnProcessCrashed, "ipc:content-shutdown");
}

function RecvExpectProcessCrash() {
  g.expectingProcessCrash = true;
}

function SendClear() {
  g.browserMessageManager.sendAsyncMessage("reftest:Clear");
}

function SendLoadScriptTest(uri, timeout) {
  g.browserMessageManager.sendAsyncMessage("reftest:LoadScriptTest", {
    uri,
    timeout,
  });
}

function SendLoadPrintTest(uri, timeout) {
  g.browserMessageManager.sendAsyncMessage("reftest:LoadPrintTest", {
    uri,
    timeout,
  });
}

function SendLoadTest(type, uri, uriTargetType, timeout) {
  g.browserMessageManager.sendAsyncMessage("reftest:LoadTest", {
    type,
    uri,
    uriTargetType,
    timeout,
  });
}

function SendResetRenderingState() {
  g.browserMessageManager.sendAsyncMessage("reftest:ResetRenderingState");
}

function SendPrintDone(status, fileName) {
  g.browserMessageManager.sendAsyncMessage("reftest:PrintDone", {
    status,
    fileName,
  });
}

function SendUpdateCurrentCanvasWithSnapshotDone(painted) {
  g.browserMessageManager.sendAsyncMessage(
    "reftest:UpdateCanvasWithSnapshotDone",
    { painted }
  );
}

var pdfjsHasLoaded;

function pdfjsHasLoadedPromise() {
  if (pdfjsHasLoaded === undefined) {
    pdfjsHasLoaded = new Promise((resolve, reject) => {
      let doc = g.containingWindow.document;
      const script = doc.createElement("script");
      script.type = "module";
      script.src = "resource://pdf.js/build/pdf.mjs";
      script.onload = resolve;
      script.onerror = () => reject(new Error("PDF.js script load failed."));
      doc.documentElement.appendChild(script);
    });
  }

  return pdfjsHasLoaded;
}

function readPdf(path, callback) {
  const win = g.containingWindow;

  IOUtils.read(path).then(
    function (data) {
      win.pdfjsLib.GlobalWorkerOptions.workerSrc =
        "resource://pdf.js/build/pdf.worker.mjs";
      win.pdfjsLib
        .getDocument({
          data,
        })
        .promise.then(
          function (pdf) {
            callback(null, pdf);
          },
          function (e) {
            callback(new Error(`Couldn't parse ${path}, exception: ${e}`));
          }
        );
    },
    function (e) {
      callback(new Error(`Couldn't read PDF ${path}, exception: ${e}`));
    }
  );
}

function comparePdfs(pathToTestPdf, pathToRefPdf, callback) {
  pdfjsHasLoadedPromise()
    .then(() =>
      Promise.all(
        [pathToTestPdf, pathToRefPdf].map(function (path) {
          return new Promise(function (resolve, reject) {
            readPdf(path, function (error, pdf) {
              // Resolve or reject outer promise. reject and resolve are
              // passed to the callback function given as first arguments
              // to the Promise constructor.
              if (error) {
                reject(error);
              } else {
                resolve(pdf);
              }
            });
          });
        })
      )
    )
    .then(
      function (pdfs) {
        let numberOfPages = pdfs[1].numPages;
        let sameNumberOfPages = numberOfPages === pdfs[0].numPages;

        let resultPromises = [
          Promise.resolve({
            passed: sameNumberOfPages,
            description:
              "Expected number of pages: " +
              numberOfPages +
              ", got " +
              pdfs[0].numPages,
          }),
        ];

        if (sameNumberOfPages) {
          for (let i = 0; i < numberOfPages; i++) {
            let pageNum = i + 1;
            let testPagePromise = pdfs[0].getPage(pageNum);
            let refPagePromise = pdfs[1].getPage(pageNum);
            resultPromises.push(
              new Promise(function (resolve, reject) {
                Promise.all([testPagePromise, refPagePromise]).then(function (
                  pages
                ) {
                  let testTextPromise = pages[0].getTextContent();
                  let refTextPromise = pages[1].getTextContent();
                  Promise.all([testTextPromise, refTextPromise]).then(function (
                    texts
                  ) {
                    let testTextItems = texts[0].items;
                    let refTextItems = texts[1].items;
                    let testText;
                    let refText;
                    let passed = refTextItems.every(function (o, i) {
                      refText = o.str;
                      if (!testTextItems[i]) {
                        return false;
                      }
                      testText = testTextItems[i].str;
                      return testText === refText;
                    });
                    let description;
                    if (passed) {
                      if (testTextItems.length > refTextItems.length) {
                        passed = false;
                        description =
                          "Page " +
                          pages[0].pageNumber +
                          " contains unexpected text like '" +
                          testTextItems[refTextItems.length].str +
                          "'";
                      } else {
                        description =
                          "Page " + pages[0].pageNumber + " contains same text";
                      }
                    } else {
                      description =
                        "Expected page " +
                        pages[0].pageNumber +
                        " to contain text '" +
                        refText;
                      if (testText) {
                        description += "' but found '" + testText + "' instead";
                      }
                    }
                    resolve({
                      passed,
                      description,
                    });
                  },
                  reject);
                },
                reject);
              })
            );
          }
        }

        Promise.all(resultPromises).then(function (results) {
          callback(null, results);
        });
      },
      function (error) {
        callback(error);
      }
    );
}