summaryrefslogtreecommitdiffstats
path: root/dom/canvas/ClientWebGLContext.h
blob: 27767a7823a743b3530e76326f1af19e3b7c21a1 (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
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */

#ifndef CLIENTWEBGLCONTEXT_H_
#define CLIENTWEBGLCONTEXT_H_

#include "GLConsts.h"
#include "mozilla/dom/ImageData.h"
#include "mozilla/Range.h"
#include "mozilla/RefCounted.h"
#include "nsICanvasRenderingContextInternal.h"
#include "nsWrapperCache.h"
#include "mozilla/dom/WebGLRenderingContextBinding.h"
#include "mozilla/dom/WebGL2RenderingContextBinding.h"
#include "mozilla/layers/LayersSurfaces.h"
#include "mozilla/StaticPrefs_webgl.h"
#include "WebGLFormats.h"
#include "WebGLStrongTypes.h"
#include "WebGLTypes.h"

#include "mozilla/Logging.h"
#include "WebGLCommandQueue.h"

#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>

namespace mozilla {

class ClientWebGLExtensionBase;
class HostWebGLContext;

namespace dom {
class OwningHTMLCanvasElementOrOffscreenCanvas;
class WebGLChild;
}  // namespace dom

namespace gfx {
class DrawTargetWebgl;
}

namespace webgl {
class AvailabilityRunnable;
class TexUnpackBlob;
class TexUnpackBytes;
}  // namespace webgl

////////////////////////////////////

class WebGLActiveInfoJS final : public RefCounted<WebGLActiveInfoJS> {
 public:
  MOZ_DECLARE_REFCOUNTED_TYPENAME(WebGLActiveInfoJS)

  const webgl::ActiveInfo mInfo;

  explicit WebGLActiveInfoJS(const webgl::ActiveInfo& info) : mInfo(info) {}

  virtual ~WebGLActiveInfoJS() = default;

  // -
  // WebIDL attributes

  GLint Size() const { return static_cast<GLint>(mInfo.elemCount); }
  GLenum Type() const { return mInfo.elemType; }

  void GetName(nsString& retval) const { CopyUTF8toUTF16(mInfo.name, retval); }

  bool WrapObject(JSContext*, JS::Handle<JSObject*>,
                  JS::MutableHandle<JSObject*>);
};

class WebGLShaderPrecisionFormatJS final
    : public RefCounted<WebGLShaderPrecisionFormatJS> {
 public:
  MOZ_DECLARE_REFCOUNTED_TYPENAME(WebGLShaderPrecisionFormatJS)

  const webgl::ShaderPrecisionFormat mInfo;

  explicit WebGLShaderPrecisionFormatJS(
      const webgl::ShaderPrecisionFormat& info)
      : mInfo(info) {}

  virtual ~WebGLShaderPrecisionFormatJS() = default;

  GLint RangeMin() const { return mInfo.rangeMin; }
  GLint RangeMax() const { return mInfo.rangeMax; }
  GLint Precision() const { return mInfo.precision; }

  bool WrapObject(JSContext*, JS::Handle<JSObject*>,
                  JS::MutableHandle<JSObject*>);
};

// -----------------------

class ClientWebGLContext;
class WebGLBufferJS;
class WebGLFramebufferJS;
class WebGLProgramJS;
class WebGLQueryJS;
class WebGLRenderbufferJS;
class WebGLSamplerJS;
class WebGLShaderJS;
class WebGLTextureJS;
class WebGLTransformFeedbackJS;
class WebGLVertexArrayJS;

namespace webgl {

struct LinkResult;

class ProgramKeepAlive final {
  friend class mozilla::WebGLProgramJS;

  WebGLProgramJS* mParent;

 public:
  explicit ProgramKeepAlive(WebGLProgramJS& parent) : mParent(&parent) {}
  ~ProgramKeepAlive();
};

class ShaderKeepAlive final {
  friend class mozilla::WebGLShaderJS;

  const WebGLShaderJS* mParent;

 public:
  explicit ShaderKeepAlive(const WebGLShaderJS& parent) : mParent(&parent) {}
  ~ShaderKeepAlive();
};

class ContextGenerationInfo final {
 private:
  ObjectId mLastId = 0;

 public:
  webgl::ExtensionBits mEnabledExtensions;
  RefPtr<WebGLProgramJS> mCurrentProgram;
  std::shared_ptr<webgl::ProgramKeepAlive> mProgramKeepAlive;
  mutable std::shared_ptr<webgl::LinkResult> mActiveLinkResult;

  RefPtr<WebGLTransformFeedbackJS> mDefaultTfo;
  RefPtr<WebGLVertexArrayJS> mDefaultVao;

  std::unordered_map<GLenum, RefPtr<WebGLBufferJS>> mBoundBufferByTarget;
  std::vector<RefPtr<WebGLBufferJS>> mBoundUbos;
  RefPtr<WebGLFramebufferJS> mBoundDrawFb;
  RefPtr<WebGLFramebufferJS> mBoundReadFb;
  RefPtr<WebGLRenderbufferJS> mBoundRb;
  RefPtr<WebGLTransformFeedbackJS> mBoundTfo;
  RefPtr<WebGLVertexArrayJS> mBoundVao;
  std::unordered_map<GLenum, RefPtr<WebGLQueryJS>> mCurrentQueryByTarget;

  struct TexUnit final {
    RefPtr<WebGLSamplerJS> sampler;
    std::unordered_map<GLenum, RefPtr<WebGLTextureJS>> texByTarget;
  };
  uint32_t mActiveTexUnit = 0;
  std::vector<TexUnit> mTexUnits;

  bool mTfActiveAndNotPaused = false;

  std::vector<TypedQuad> mGenericVertexAttribs;

  std::array<int32_t, 4> mScissor = {};
  std::array<int32_t, 4> mViewport = {};
  std::array<float, 4> mClearColor = {{0, 0, 0, 0}};
  std::array<float, 4> mBlendColor = {{0, 0, 0, 0}};
  std::array<float, 2> mDepthRange = {{0, 1}};
  webgl::PixelPackingState mPixelPackState;
  webgl::PixelUnpackStateWebgl mPixelUnpackState;

  std::vector<GLenum> mCompressedTextureFormats;

  Maybe<uvec2> mDrawingBufferSize;

  webgl::ProvokingVertex mProvokingVertex = webgl::ProvokingVertex::LastVertex;

  ObjectId NextId() { return mLastId += 1; }
};

// -

// In the cross process case, the WebGL actor's ownership relationship looks
// like this:
// ---------------------------------------------------------------------
// | ClientWebGLContext -> WebGLChild -> WebGLParent -> HostWebGLContext
// ---------------------------------------------------------------------
//
// where 'A -> B' means "A owns B"

struct NotLostData final {
  ClientWebGLContext& context;
  webgl::InitContextResult info;

  RefPtr<mozilla::dom::WebGLChild> outOfProcess;
  UniquePtr<HostWebGLContext> inProcess;

  webgl::ContextGenerationInfo state;
  std::array<RefPtr<ClientWebGLExtensionBase>,
             UnderlyingValue(WebGLExtensionID::Max)>
      extensions;

  RefPtr<layers::CanvasRenderer> mCanvasRenderer;

  explicit NotLostData(ClientWebGLContext& context);
  ~NotLostData();
};

// -

class ObjectJS {
  friend ClientWebGLContext;

 public:
  const std::weak_ptr<NotLostData> mGeneration;
  const ObjectId mId;

 protected:
  bool mDeleteRequested = false;

  explicit ObjectJS(const ClientWebGLContext&);
  virtual ~ObjectJS() = default;

 public:
  ClientWebGLContext* Context() const {
    const auto locked = mGeneration.lock();
    if (!locked) return nullptr;
    return &(locked->context);
  }

  ClientWebGLContext* GetParentObject() const { return Context(); }

  // A la carte:
  bool IsForContext(const ClientWebGLContext&) const;
  virtual bool IsDeleted() const { return mDeleteRequested; }

  bool IsUsable(const ClientWebGLContext& context) const {
    return IsForContext(context) && !IsDeleted();
  }

  // The workhorse:
  bool ValidateUsable(const ClientWebGLContext& context,
                      const char* const argName) const {
    if (MOZ_LIKELY(IsUsable(context))) return true;
    WarnInvalidUse(context, argName);
    return false;
  }

  // Use by DeleteFoo:
  bool ValidateForContext(const ClientWebGLContext& context,
                          const char* const argName) const;

 private:
  void WarnInvalidUse(const ClientWebGLContext&, const char* argName) const;

  // The enum is INVALID_VALUE for Program/Shader :(
  virtual GLenum ErrorOnDeleted() const { return LOCAL_GL_INVALID_OPERATION; }
};

}  // namespace webgl

// -------------------------

class WebGLBufferJS final : public nsWrapperCache, public webgl::ObjectJS {
  friend class ClientWebGLContext;

  webgl::BufferKind mKind =
      webgl::BufferKind::Undefined;  // !IsBuffer until Bind

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLBufferJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLBufferJS)

  explicit WebGLBufferJS(const ClientWebGLContext& webgl)
      : webgl::ObjectJS(webgl) {}

 private:
  ~WebGLBufferJS();

 public:
  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLFramebufferJS final : public nsWrapperCache, public webgl::ObjectJS {
  friend class ClientWebGLContext;

 public:
  struct Attachment final {
    RefPtr<WebGLRenderbufferJS> rb;
    RefPtr<WebGLTextureJS> tex;
  };

 private:
  bool mHasBeenBound = false;  // !IsFramebuffer until Bind
  std::unordered_map<GLenum, Attachment> mAttachments;
  // Holds Some Id if async present is used
  Maybe<layers::RemoteTextureId> mLastRemoteTextureId;
  Maybe<layers::RemoteTextureOwnerId> mRemoteTextureOwnerId;
  // Needs sync IPC to ensure that the remote texture exists in the
  // RemoteTextureMap.
  bool mNeedsRemoteTextureSync = true;

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLFramebufferJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLFramebufferJS)

  explicit WebGLFramebufferJS(const ClientWebGLContext&, bool opaque = false);

  const bool mOpaque;
  bool mInOpaqueRAF = false;

 private:
  ~WebGLFramebufferJS();

  void EnsureColorAttachments();

 public:
  Attachment* GetAttachment(const GLenum slotEnum) {
    auto ret = MaybeFind(mAttachments, slotEnum);
    if (!ret) {
      EnsureColorAttachments();
      ret = MaybeFind(mAttachments, slotEnum);
    }
    return ret;
  }

  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLProgramJS final : public nsWrapperCache, public webgl::ObjectJS {
  friend class ClientWebGLContext;

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLProgramJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLProgramJS)
  // Must come first!
  // If the REFCOUNTING macro isn't declared first, the AddRef at
  // mInnerRef->js will panic when REFCOUNTING's "owning thread" var is still
  // uninitialized.

  struct Attachment final {
    RefPtr<WebGLShaderJS> shader;
    std::shared_ptr<webgl::ShaderKeepAlive> keepAlive;
  };

 private:
  std::shared_ptr<webgl::ProgramKeepAlive> mKeepAlive;
  const std::weak_ptr<webgl::ProgramKeepAlive> mKeepAliveWeak;

  std::unordered_map<GLenum, Attachment> mNextLink_Shaders;
  bool mLastValidate = false;
  mutable std::shared_ptr<webgl::LinkResult>
      mResult;  // Never null, often defaulted.

  struct UniformLocInfo final {
    const uint32_t location;
    const GLenum elemType;
  };

  mutable Maybe<std::unordered_map<std::string, UniformLocInfo>>
      mUniformLocByName;
  mutable std::vector<uint32_t> mUniformBlockBindings;

  std::unordered_set<const WebGLTransformFeedbackJS*> mActiveTfos;

  explicit WebGLProgramJS(const ClientWebGLContext&);

  ~WebGLProgramJS() {
    mKeepAlive = nullptr;  // Try to delete.

    const auto& maybe = mKeepAliveWeak.lock();
    if (maybe) {
      maybe->mParent = nullptr;
    }
  }

 public:
  bool IsDeleted() const override { return !mKeepAliveWeak.lock(); }
  GLenum ErrorOnDeleted() const override { return LOCAL_GL_INVALID_VALUE; }

  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLQueryJS final : public nsWrapperCache,
                           public webgl::ObjectJS,
                           public SupportsWeakPtr {
  friend class ClientWebGLContext;
  friend class webgl::AvailabilityRunnable;

  GLenum mTarget = 0;  // !IsQuery until Bind
  bool mCanBeAvailable = false;

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLQueryJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLQueryJS)

  explicit WebGLQueryJS(const ClientWebGLContext& webgl)
      : webgl::ObjectJS(webgl) {}

 private:
  ~WebGLQueryJS();

 public:
  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLRenderbufferJS final : public nsWrapperCache,
                                  public webgl::ObjectJS {
  friend class ClientWebGLContext;

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLRenderbufferJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLRenderbufferJS)

 private:
  bool mHasBeenBound = false;  // !IsRenderbuffer until Bind

  explicit WebGLRenderbufferJS(const ClientWebGLContext& webgl)
      : webgl::ObjectJS(webgl) {}
  ~WebGLRenderbufferJS();

 public:
  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLSamplerJS final : public nsWrapperCache, public webgl::ObjectJS {
  // IsSampler without Bind
 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLSamplerJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLSamplerJS)

  explicit WebGLSamplerJS(const ClientWebGLContext& webgl)
      : webgl::ObjectJS(webgl) {}

 private:
  ~WebGLSamplerJS();

 public:
  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLShaderJS final : public nsWrapperCache, public webgl::ObjectJS {
  friend class ClientWebGLContext;

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLShaderJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLShaderJS)

 private:
  const GLenum mType;
  std::string mSource;
  std::shared_ptr<webgl::ShaderKeepAlive> mKeepAlive;
  const std::weak_ptr<webgl::ShaderKeepAlive> mKeepAliveWeak;

  mutable webgl::CompileResult mResult;

  WebGLShaderJS(const ClientWebGLContext&, GLenum type);

  ~WebGLShaderJS() {
    mKeepAlive = nullptr;  // Try to delete.

    const auto& maybe = mKeepAliveWeak.lock();
    if (maybe) {
      maybe->mParent = nullptr;
    }
  }

 public:
  bool IsDeleted() const override { return !mKeepAliveWeak.lock(); }
  GLenum ErrorOnDeleted() const override { return LOCAL_GL_INVALID_VALUE; }

  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLSyncJS final : public nsWrapperCache,
                          public webgl::ObjectJS,
                          public SupportsWeakPtr {
  friend class ClientWebGLContext;
  friend class webgl::AvailabilityRunnable;

  bool mCanBeAvailable = false;
  uint8_t mNumQueriesBeforeFirstFrameBoundary = 0;
  bool mSignaled = false;

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLSyncJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLSyncJS)

  explicit WebGLSyncJS(const ClientWebGLContext& webgl)
      : webgl::ObjectJS(webgl) {}

 private:
  ~WebGLSyncJS();

 public:
  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLTextureJS final : public nsWrapperCache, public webgl::ObjectJS {
  friend class ClientWebGLContext;

  GLenum mTarget = 0;  // !IsTexture until Bind

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLTextureJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLTextureJS)

  explicit WebGLTextureJS(const ClientWebGLContext& webgl)
      : webgl::ObjectJS(webgl) {}

 private:
  ~WebGLTextureJS();

 public:
  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLTransformFeedbackJS final : public nsWrapperCache,
                                       public webgl::ObjectJS {
  friend class ClientWebGLContext;

  bool mHasBeenBound = false;  // !IsTransformFeedback until Bind
  bool mActiveOrPaused = false;
  std::vector<RefPtr<WebGLBufferJS>> mAttribBuffers;
  RefPtr<WebGLProgramJS> mActiveProgram;
  std::shared_ptr<webgl::ProgramKeepAlive> mActiveProgramKeepAlive;

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLTransformFeedbackJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLTransformFeedbackJS)

  explicit WebGLTransformFeedbackJS(const ClientWebGLContext&);

 private:
  ~WebGLTransformFeedbackJS();

 public:
  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

std::array<uint16_t, 3> ValidUploadElemTypes(GLenum);

class WebGLUniformLocationJS final : public nsWrapperCache,
                                     public webgl::ObjectJS {
  friend class ClientWebGLContext;

  const std::weak_ptr<webgl::LinkResult> mParent;
  const uint32_t mLocation;
  const std::array<uint16_t, 3> mValidUploadElemTypes;

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLUniformLocationJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLUniformLocationJS)

  WebGLUniformLocationJS(const ClientWebGLContext& webgl,
                         std::weak_ptr<webgl::LinkResult> parent, uint32_t loc,
                         GLenum elemType)
      : webgl::ObjectJS(webgl),
        mParent(parent),
        mLocation(loc),
        mValidUploadElemTypes(ValidUploadElemTypes(elemType)) {}

 private:
  ~WebGLUniformLocationJS() = default;

 public:
  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

// -

class WebGLVertexArrayJS final : public nsWrapperCache, public webgl::ObjectJS {
  friend class ClientWebGLContext;

  bool mHasBeenBound = false;  // !IsVertexArray until Bind
  RefPtr<WebGLBufferJS> mIndexBuffer;
  std::vector<RefPtr<WebGLBufferJS>> mAttribBuffers;

 public:
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WebGLVertexArrayJS)
  NS_DECL_CYCLE_COLLECTION_NATIVE_WRAPPERCACHE_CLASS(WebGLVertexArrayJS)

  explicit WebGLVertexArrayJS(const ClientWebGLContext&);

 private:
  ~WebGLVertexArrayJS();

 public:
  JSObject* WrapObject(JSContext*, JS::Handle<JSObject*>) override;
};

////////////////////////////////////

using Float32ListU = dom::MaybeSharedFloat32ArrayOrUnrestrictedFloatSequence;
using Int32ListU = dom::MaybeSharedInt32ArrayOrLongSequence;
using Uint32ListU = dom::MaybeSharedUint32ArrayOrUnsignedLongSequence;

inline Range<const float> MakeRange(const Float32ListU& list) {
  if (list.IsFloat32Array()) return MakeRangeAbv(list.GetAsFloat32Array());

  return MakeRange(list.GetAsUnrestrictedFloatSequence());
}

inline Range<const int32_t> MakeRange(const Int32ListU& list) {
  if (list.IsInt32Array()) return MakeRangeAbv(list.GetAsInt32Array());

  return MakeRange(list.GetAsLongSequence());
}

inline Range<const uint32_t> MakeRange(const Uint32ListU& list) {
  if (list.IsUint32Array()) return MakeRangeAbv(list.GetAsUint32Array());

  return MakeRange(list.GetAsUnsignedLongSequence());
}

template <typename T>
inline Range<const uint8_t> MakeByteRange(const T& x) {
  const auto typed = MakeRange(x);
  return Range<const uint8_t>(
      reinterpret_cast<const uint8_t*>(typed.begin().get()),
      typed.length() * sizeof(typed[0]));
}

// -

struct TexImageSourceAdapter final : public TexImageSource {
  TexImageSourceAdapter(const dom::Nullable<dom::ArrayBufferView>* maybeView,
                        ErrorResult*) {
    if (!maybeView->IsNull()) {
      mView = &(maybeView->Value());
    }
  }

  TexImageSourceAdapter(const dom::Nullable<dom::ArrayBufferView>* maybeView,
                        GLuint viewElemOffset) {
    if (!maybeView->IsNull()) {
      mView = &(maybeView->Value());
    }
    mViewElemOffset = viewElemOffset;
  }

  TexImageSourceAdapter(const dom::ArrayBufferView* view, ErrorResult*) {
    mView = view;
  }

  TexImageSourceAdapter(const dom::ArrayBufferView* view, GLuint viewElemOffset,
                        GLuint viewElemLengthOverride = 0) {
    mView = view;
    mViewElemOffset = viewElemOffset;
    mViewElemLengthOverride = viewElemLengthOverride;
  }

  explicit TexImageSourceAdapter(const WebGLintptr* pboOffset,
                                 GLuint ignored1 = 0, GLuint ignored2 = 0) {
    mPboOffset = pboOffset;
  }

  TexImageSourceAdapter(const WebGLintptr* pboOffset, ErrorResult* ignored) {
    mPboOffset = pboOffset;
  }

  TexImageSourceAdapter(const dom::ImageBitmap* imageBitmap,
                        ErrorResult* out_error) {
    mImageBitmap = imageBitmap;
    mOut_error = out_error;
  }

  TexImageSourceAdapter(const dom::ImageData* imageData, ErrorResult*) {
    mImageData = imageData;
  }

  TexImageSourceAdapter(const dom::OffscreenCanvas* offscreenCanvas,
                        ErrorResult* const out_error) {
    mOffscreenCanvas = offscreenCanvas;
    mOut_error = out_error;
  }

  TexImageSourceAdapter(const dom::Element* domElem,
                        ErrorResult* const out_error) {
    mDomElem = domElem;
    mOut_error = out_error;
  }
};

/**
 * Base class for all IDL implementations of WebGLContext
 */
class ClientWebGLContext final : public nsICanvasRenderingContextInternal,
                                 public nsWrapperCache {
  friend class webgl::AvailabilityRunnable;
  friend class webgl::ObjectJS;
  friend class webgl::ProgramKeepAlive;
  friend class webgl::ShaderKeepAlive;
  friend class gfx::DrawTargetWebgl;

  // ----------------------------- Lifetime and DOM ---------------------------
 public:
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_WRAPPERCACHE_CLASS(ClientWebGLContext)

  JSObject* WrapObject(JSContext* cx,
                       JS::Handle<JSObject*> givenProto) override {
    if (mIsWebGL2) {
      return dom::WebGL2RenderingContext_Binding::Wrap(cx, this, givenProto);
    }
    return dom::WebGLRenderingContext_Binding::Wrap(cx, this, givenProto);
  }

  // -

 public:
  const bool mIsWebGL2;

 private:
  bool mIsCanvasDirty = false;
  uvec2 mRequestedSize = {};

 public:
  explicit ClientWebGLContext(bool webgl2);

 private:
  virtual ~ClientWebGLContext();

  const RefPtr<ClientWebGLExtensionLoseContext> mExtLoseContext;

  mutable std::shared_ptr<webgl::NotLostData> mNotLost;
  mutable GLenum mNextError = 0;
  mutable webgl::LossStatus mLossStatus = webgl::LossStatus::Ready;
  mutable bool mAwaitingRestore = false;
  // Holds Some Id if async present is used
  mutable Maybe<layers::RemoteTextureId> mLastRemoteTextureId;
  mutable Maybe<layers::RemoteTextureOwnerId> mRemoteTextureOwnerId;
  // Needs sync IPC to ensure that the remote texture exists in the
  // RemoteTextureMap.
  bool mNeedsRemoteTextureSync = true;

  // -

 public:
  const auto& Limits() const { return mNotLost->info.limits; }
  const auto& Vendor() const { return mNotLost->info.vendor; }
  // https://www.khronos.org/registry/webgl/specs/latest/1.0/#actual-context-parameters
  const WebGLContextOptions& ActualContextParameters() const {
    MOZ_ASSERT(mNotLost != nullptr);
    return mNotLost->info.options;
  }

  auto& State() { return mNotLost->state; }
  const auto& State() const {
    return const_cast<ClientWebGLContext*>(this)->State();
  }

  // -

 private:
  mutable RefPtr<webgl::AvailabilityRunnable> mAvailabilityRunnable;

 public:
  webgl::AvailabilityRunnable& EnsureAvailabilityRunnable() const;

  // -

 public:
  void EmulateLoseContext() const;
  void OnContextLoss(webgl::ContextLossReason) const;
  void RestoreContext(webgl::LossStatus requiredStatus) const;

 private:
  bool DispatchEvent(const nsAString&) const;
  void Event_webglcontextlost() const;
  void Event_webglcontextrestored() const;

  bool CreateHostContext(const uvec2& requestedSize);
  void ThrowEvent_WebGLContextCreationError(const std::string&) const;

  void UpdateCanvasParameters();

 public:
  void MarkCanvasDirty();

  void MarkContextClean() override {}

  void OnBeforePaintTransaction() override;

  mozilla::dom::WebGLChild* GetChild() const {
    if (!mNotLost) return nullptr;
    if (!mNotLost->outOfProcess) return nullptr;
    return mNotLost->outOfProcess.get();
  }

  // -------------------------------------------------------------------------
  // Client WebGL API call tracking and error message reporting
  // -------------------------------------------------------------------------
 public:
  // Remembers the WebGL function that is lowest on the stack for client-side
  // error generation.
  class FuncScope final {
   public:
    const ClientWebGLContext& mWebGL;
    const std::shared_ptr<webgl::NotLostData> mKeepNotLostOrNull;
    const char* const mFuncName;

    FuncScope(const ClientWebGLContext& webgl, const char* funcName)
        : mWebGL(webgl),
          mKeepNotLostOrNull(webgl.mNotLost),
          mFuncName(funcName) {
      // Only set if an "outer" scope hasn't already been set.
      if (!mWebGL.mFuncScope) {
        mWebGL.mFuncScope = this;
      }
    }

    ~FuncScope() {
      if (this == mWebGL.mFuncScope) {
        mWebGL.mFuncScope = nullptr;
      }
    }

    FuncScope(const FuncScope&) = delete;
    FuncScope(FuncScope&&) = delete;
  };

 protected:
  // The scope of the function at the top of the current WebGL function call
  // stack
  mutable FuncScope* mFuncScope = nullptr;

  const char* FuncName() const {
    return mFuncScope ? mFuncScope->mFuncName : nullptr;
  }

 public:
  template <typename... Args>
  void EnqueueError(const GLenum error, const char* const format,
                    const Args&... args) const {
    MOZ_ASSERT(FuncName());
    nsCString text;
    text.AppendPrintf("WebGL warning: %s: ", FuncName());

#ifdef __clang__
#  pragma clang diagnostic push
#  pragma clang diagnostic ignored "-Wformat-security"
#elif defined(__GNUC__)
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Wformat-security"
#endif
    text.AppendPrintf(format, args...);
#ifdef __clang__
#  pragma clang diagnostic pop
#elif defined(__GNUC__)
#  pragma GCC diagnostic pop
#endif

    EnqueueErrorImpl(error, text);
  }

  void EnqueueError(const webgl::ErrorInfo& info) const {
    EnqueueError(info.type, "%s", info.info.c_str());
  }

  template <typename... Args>
  void EnqueueWarning(const char* const format, const Args&... args) const {
    EnqueueError(0, format, args...);
  }

  template <typename... Args>
  void EnqueuePerfWarning(const char* const format, const Args&... args) const {
    EnqueueError(webgl::kErrorPerfWarning, format, args...);
  }

  void EnqueueError_ArgEnum(const char* argName,
                            GLenum val) const;  // Cold code.

 private:
  void EnqueueErrorImpl(GLenum errorOrZero, const nsACString&) const;

 public:
  bool ValidateArrayBufferView(const dom::ArrayBufferView& view,
                               GLuint elemOffset, GLuint elemCountOverride,
                               const GLenum errorEnum,
                               uint8_t** const out_bytes,
                               size_t* const out_byteLen) const;

 protected:
  template <typename T>
  bool ValidateNonNull(const char* const argName,
                       const dom::Nullable<T>& maybe) const {
    if (maybe.IsNull()) {
      EnqueueError(LOCAL_GL_INVALID_VALUE, "%s: Cannot be null.", argName);
      return false;
    }
    return true;
  }

  bool ValidateNonNegative(const char* argName, int64_t val) const {
    if (MOZ_UNLIKELY(val < 0)) {
      EnqueueError(LOCAL_GL_INVALID_VALUE, "`%s` must be non-negative.",
                   argName);
      return false;
    }
    return true;
  }

  bool ValidateViewType(GLenum unpackType, const TexImageSource& src) const;

  Maybe<uvec3> ValidateExtents(GLsizei width, GLsizei height, GLsizei depth,
                               GLint border) const;

  // -------------------------------------------------------------------------
  // nsICanvasRenderingContextInternal / nsAPostRefreshObserver
  // -------------------------------------------------------------------------
 public:
  bool InitializeCanvasRenderer(nsDisplayListBuilder* aBuilder,
                                layers::CanvasRenderer* aRenderer) override;

  void MarkContextCleanForFrameCapture() override {
    mFrameCaptureState = FrameCaptureState::CLEAN;
  }
  // Note that 'clean' here refers to its invalidation state, not the
  // contents of the buffer.
  Watchable<FrameCaptureState>* GetFrameCaptureState() override {
    return &mFrameCaptureState;
  }

  void OnMemoryPressure() override;
  void SetContextOptions(const WebGLContextOptions& aOptions) {
    mInitialOptions.emplace(aOptions);
  }
  const WebGLContextOptions& GetContextOptions() const {
    return mInitialOptions.ref();
  }
  NS_IMETHOD
  SetContextOptions(JSContext* cx, JS::Handle<JS::Value> options,
                    ErrorResult& aRvForDictionaryInit) override;
  NS_IMETHOD
  SetDimensions(int32_t width, int32_t height) override;
  bool UpdateWebRenderCanvasData(
      nsDisplayListBuilder* aBuilder,
      layers::WebRenderCanvasData* aCanvasData) override;

  // ------

  int32_t GetWidth() override { return AutoAssertCast(DrawingBufferSize().x); }
  int32_t GetHeight() override { return AutoAssertCast(DrawingBufferSize().y); }

  NS_IMETHOD InitializeWithDrawTarget(nsIDocShell*,
                                      NotNull<gfx::DrawTarget*>) override {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  void ResetBitmap() override;

  UniquePtr<uint8_t[]> GetImageBuffer(int32_t* out_format,
                                      gfx::IntSize* out_imageSize) override;
  NS_IMETHOD GetInputStream(const char* mimeType,
                            const nsAString& encoderOptions,
                            nsIInputStream** out_stream) override;

  already_AddRefed<mozilla::gfx::SourceSurface> GetSurfaceSnapshot(
      gfxAlphaType* out_alphaType) override;

  void SetOpaqueValueFromOpaqueAttr(bool) override{};
  bool GetIsOpaque() override { return !mInitialOptions->alpha; }

  /**
   * An abstract base class to be implemented by callers wanting to be notified
   * that a refresh has occurred. Callers must ensure an observer is removed
   * before it is destroyed.
   */
  void DidRefresh() override;

  NS_IMETHOD Redraw(const gfxRect&) override {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // ------

 protected:
  layers::LayersBackend GetCompositorBackendType() const;

  Watchable<FrameCaptureState> mFrameCaptureState = {
      FrameCaptureState::CLEAN, "ClientWebGLContext::mFrameCaptureState"};

  // -------------------------------------------------------------------------
  // WebGLRenderingContext Basic Properties and Methods
  // -------------------------------------------------------------------------
 public:
  dom::HTMLCanvasElement* GetCanvas() const { return mCanvasElement; }
  void Commit();
  void GetCanvas(
      dom::Nullable<dom::OwningHTMLCanvasElementOrOffscreenCanvas>& retval);

  GLsizei DrawingBufferWidth() {
    const FuncScope funcScope(*this, "drawingBufferWidth");
    return AutoAssertCast(DrawingBufferSize().x);
  }
  GLsizei DrawingBufferHeight() {
    const FuncScope funcScope(*this, "drawingBufferHeight");
    return AutoAssertCast(DrawingBufferSize().y);
  }
  void GetContextAttributes(dom::Nullable<dom::WebGLContextAttributes>& retval);

 private:
  webgl::SwapChainOptions PrepareAsyncSwapChainOptions(
      WebGLFramebufferJS* fb, bool webvr,
      const webgl::SwapChainOptions& options = webgl::SwapChainOptions());

 public:
  layers::TextureType GetTexTypeForSwapChain() const;
  void Present(
      WebGLFramebufferJS*, const bool webvr = false,
      const webgl::SwapChainOptions& options = webgl::SwapChainOptions());
  void Present(
      WebGLFramebufferJS*, layers::TextureType, const bool webvr = false,
      const webgl::SwapChainOptions& options = webgl::SwapChainOptions());
  void CopyToSwapChain(
      WebGLFramebufferJS*,
      const webgl::SwapChainOptions& options = webgl::SwapChainOptions());
  void EndOfFrame();
  Maybe<layers::SurfaceDescriptor> GetFrontBuffer(
      WebGLFramebufferJS*, const bool webvr = false) override;
  Maybe<layers::SurfaceDescriptor> PresentFrontBuffer(
      WebGLFramebufferJS*, layers::TextureType,
      const bool webvr = false) override;
  RefPtr<gfx::SourceSurface> GetFrontBufferSnapshot(
      bool requireAlphaPremult = true) override;

  void ClearVRSwapChain();

 private:
  RefPtr<gfx::DataSourceSurface> BackBufferSnapshot();
  [[nodiscard]] bool DoReadPixels(const webgl::ReadPixelsDesc&,
                                  Range<uint8_t>) const;
  [[nodiscard]] bool DoReadPixels(const webgl::ReadPixelsDesc&,
                                  const mozilla::ipc::Shmem&) const;
  uvec2 DrawingBufferSize();

  // -

  bool mAutoFlushPending = false;

  void AutoEnqueueFlush() {
    if (MOZ_LIKELY(mAutoFlushPending)) return;
    mAutoFlushPending = true;

    const auto weak = WeakPtr<ClientWebGLContext>(this);
    const auto DeferredFlush = [weak]() {
      const auto strong = RefPtr<ClientWebGLContext>(weak);
      if (!strong) return;
      if (!strong->mAutoFlushPending) return;
      strong->mAutoFlushPending = false;

      if (!StaticPrefs::webgl_auto_flush()) return;
      const bool flushGl = StaticPrefs::webgl_auto_flush_gl();
      strong->Flush(flushGl);
    };

    already_AddRefed<mozilla::CancelableRunnable> runnable =
        NS_NewCancelableRunnableFunction("enqueue Event_webglcontextrestored",
                                         DeferredFlush);
    NS_DispatchToCurrentThread(std::move(runnable));
  }

  void CancelAutoFlush() { mAutoFlushPending = false; }

  // -

  void AfterDrawCall() {
    if (!mNotLost) return;
    const auto& state = State();
    if (!state.mBoundDrawFb) {
      MarkCanvasDirty();
    }

    AutoEnqueueFlush();
  }

  // -------------------------------------------------------------------------
  // Client-side helper methods.  Dispatch to a Host method.
  // -------------------------------------------------------------------------

  // ------------------------- GL State -------------------------
 public:
  bool IsContextLost() const { return !mNotLost; }

  void Disable(GLenum cap) const { SetEnabledI(cap, {}, false); }
  void Enable(GLenum cap) const { SetEnabledI(cap, {}, true); }
  void SetEnabledI(GLenum cap, Maybe<GLuint> i, bool val) const;
  bool IsEnabled(GLenum cap) const;

 private:
  Maybe<double> GetNumber(GLenum pname);
  Maybe<std::string> GetString(GLenum pname);

 public:
  void GetParameter(JSContext* cx, GLenum pname,
                    JS::MutableHandle<JS::Value> retval, ErrorResult& rv,
                    bool debug = false);

  void GetBufferParameter(JSContext* cx, GLenum target, GLenum pname,
                          JS::MutableHandle<JS::Value> retval) const;

  void GetFramebufferAttachmentParameter(JSContext* cx, GLenum target,
                                         GLenum attachment, GLenum pname,
                                         JS::MutableHandle<JS::Value> retval,
                                         ErrorResult& rv) const;

  void GetRenderbufferParameter(JSContext* cx, GLenum target, GLenum pname,
                                JS::MutableHandle<JS::Value> retval) const;

  void GetIndexedParameter(JSContext* cx, GLenum target, GLuint index,
                           JS::MutableHandle<JS::Value> retval,
                           ErrorResult& rv) const;

  already_AddRefed<WebGLShaderPrecisionFormatJS> GetShaderPrecisionFormat(
      GLenum shadertype, GLenum precisiontype);

  void UseProgram(WebGLProgramJS*);
  void ValidateProgram(WebGLProgramJS&) const;

  // -

  already_AddRefed<WebGLBufferJS> CreateBuffer() const;
  already_AddRefed<WebGLFramebufferJS> CreateFramebuffer() const;
  already_AddRefed<WebGLFramebufferJS> CreateOpaqueFramebuffer(
      const webgl::OpaqueFramebufferOptions&) const;
  already_AddRefed<WebGLProgramJS> CreateProgram() const;
  already_AddRefed<WebGLQueryJS> CreateQuery() const;
  already_AddRefed<WebGLRenderbufferJS> CreateRenderbuffer() const;
  already_AddRefed<WebGLSamplerJS> CreateSampler() const;
  already_AddRefed<WebGLShaderJS> CreateShader(GLenum type) const;
  already_AddRefed<WebGLSyncJS> FenceSync(GLenum condition,
                                          GLbitfield flags) const;
  already_AddRefed<WebGLTextureJS> CreateTexture() const;
  already_AddRefed<WebGLTransformFeedbackJS> CreateTransformFeedback() const;
  already_AddRefed<WebGLVertexArrayJS> CreateVertexArray() const;

  void DeleteBuffer(WebGLBufferJS*);
  void DeleteFramebuffer(WebGLFramebufferJS*, bool canDeleteOpaque = false);
  void DeleteProgram(WebGLProgramJS*) const;
  void DeleteQuery(WebGLQueryJS*);
  void DeleteRenderbuffer(WebGLRenderbufferJS*);
  void DeleteSampler(WebGLSamplerJS*);
  void DeleteShader(WebGLShaderJS*) const;
  void DeleteSync(WebGLSyncJS*) const;
  void DeleteTexture(WebGLTextureJS*);
  void DeleteTransformFeedback(WebGLTransformFeedbackJS*);
  void DeleteVertexArray(WebGLVertexArrayJS*);

 private:
  void DoDeleteProgram(WebGLProgramJS&) const;
  void DoDeleteShader(const WebGLShaderJS&) const;

 public:
  // -

  bool IsBuffer(const WebGLBufferJS*) const;
  bool IsFramebuffer(const WebGLFramebufferJS*) const;
  bool IsProgram(const WebGLProgramJS*) const;
  bool IsQuery(const WebGLQueryJS*) const;
  bool IsRenderbuffer(const WebGLRenderbufferJS*) const;
  bool IsSampler(const WebGLSamplerJS*) const;
  bool IsShader(const WebGLShaderJS*) const;
  bool IsSync(const WebGLSyncJS*) const;
  bool IsTexture(const WebGLTextureJS*) const;
  bool IsTransformFeedback(const WebGLTransformFeedbackJS*) const;
  bool IsVertexArray(const WebGLVertexArrayJS*) const;

  // -
  // WebGLProgramJS

 private:
  const webgl::LinkResult& GetLinkResult(const WebGLProgramJS&) const;

 public:
  void AttachShader(WebGLProgramJS&, WebGLShaderJS&) const;
  void BindAttribLocation(WebGLProgramJS&, GLuint location,
                          const nsAString& name) const;
  void DetachShader(WebGLProgramJS&, const WebGLShaderJS&) const;
  void GetAttachedShaders(
      const WebGLProgramJS&,
      dom::Nullable<nsTArray<RefPtr<WebGLShaderJS>>>& retval) const;
  void LinkProgram(WebGLProgramJS&) const;
  void TransformFeedbackVaryings(WebGLProgramJS&,
                                 const dom::Sequence<nsString>& varyings,
                                 GLenum bufferMode) const;
  void UniformBlockBinding(WebGLProgramJS&, GLuint blockIndex,
                           GLuint blockBinding) const;

  // Link result reflection
  already_AddRefed<WebGLActiveInfoJS> GetActiveAttrib(const WebGLProgramJS&,
                                                      GLuint index);
  already_AddRefed<WebGLActiveInfoJS> GetActiveUniform(const WebGLProgramJS&,
                                                       GLuint index);
  void GetActiveUniformBlockName(const WebGLProgramJS&,
                                 GLuint uniformBlockIndex,
                                 nsAString& retval) const;
  void GetActiveUniformBlockParameter(JSContext* cx, const WebGLProgramJS&,
                                      GLuint uniformBlockIndex, GLenum pname,
                                      JS::MutableHandle<JS::Value> retval,
                                      ErrorResult& rv);
  void GetActiveUniforms(JSContext*, const WebGLProgramJS&,
                         const dom::Sequence<GLuint>& uniformIndices,
                         GLenum pname,
                         JS::MutableHandle<JS::Value> retval) const;
  GLint GetAttribLocation(const WebGLProgramJS&, const nsAString& name) const;
  GLint GetFragDataLocation(const WebGLProgramJS&, const nsAString& name) const;
  void GetProgramInfoLog(const WebGLProgramJS& prog, nsAString& retval) const;
  void GetProgramParameter(JSContext*, const WebGLProgramJS&, GLenum pname,
                           JS::MutableHandle<JS::Value> retval) const;
  already_AddRefed<WebGLActiveInfoJS> GetTransformFeedbackVarying(
      const WebGLProgramJS&, GLuint index);
  GLuint GetUniformBlockIndex(const WebGLProgramJS&,
                              const nsAString& uniformBlockName) const;
  void GetUniformIndices(const WebGLProgramJS&,
                         const dom::Sequence<nsString>& uniformNames,
                         dom::Nullable<nsTArray<GLuint>>& retval) const;

  // WebGLUniformLocationJS
  already_AddRefed<WebGLUniformLocationJS> GetUniformLocation(
      const WebGLProgramJS&, const nsAString& name) const;
  void GetUniform(JSContext*, const WebGLProgramJS&,
                  const WebGLUniformLocationJS&,
                  JS::MutableHandle<JS::Value> retval);

  // -
  // WebGLShaderJS

 private:
  const webgl::CompileResult& GetCompileResult(const WebGLShaderJS&) const;

 public:
  void CompileShader(WebGLShaderJS&) const;
  void GetShaderInfoLog(const WebGLShaderJS&, nsAString& retval) const;
  void GetShaderParameter(JSContext*, const WebGLShaderJS&, GLenum pname,
                          JS::MutableHandle<JS::Value> retval) const;
  void GetShaderSource(const WebGLShaderJS&, nsAString& retval) const;
  void GetTranslatedShaderSource(const WebGLShaderJS& shader,
                                 nsAString& retval) const;
  void ShaderSource(WebGLShaderJS&, const nsAString&) const;

  // -

  void BindFramebuffer(GLenum target, WebGLFramebufferJS*);

  void BlendColor(GLclampf r, GLclampf g, GLclampf b, GLclampf a);

  // -

  void BlendEquation(GLenum mode) { BlendEquationSeparate(mode, mode); }
  void BlendFunc(GLenum sfactor, GLenum dfactor) {
    BlendFuncSeparate(sfactor, dfactor, sfactor, dfactor);
  }

  void BlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha) {
    BlendEquationSeparateI({}, modeRGB, modeAlpha);
  }
  void BlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha,
                         GLenum dstAlpha) {
    BlendFuncSeparateI({}, srcRGB, dstRGB, srcAlpha, dstAlpha);
  }

  void BlendEquationSeparateI(Maybe<GLuint> buf, GLenum modeRGB,
                              GLenum modeAlpha);
  void BlendFuncSeparateI(Maybe<GLuint> buf, GLenum srcRGB, GLenum dstRGB,
                          GLenum srcAlpha, GLenum dstAlpha);

  // -

  GLenum CheckFramebufferStatus(GLenum target);

  void Clear(GLbitfield mask);

  // -

 private:
  void ClearBufferTv(GLenum buffer, GLint drawBuffer, webgl::AttribBaseType,
                     const Range<const uint8_t>& view, GLuint srcElemOffset);

 public:
  void ClearBufferfv(GLenum buffer, GLint drawBuffer, const Float32ListU& list,
                     GLuint srcElemOffset) {
    ClearBufferTv(buffer, drawBuffer, webgl::AttribBaseType::Float,
                  MakeByteRange(list), srcElemOffset);
  }
  void ClearBufferiv(GLenum buffer, GLint drawBuffer, const Int32ListU& list,
                     GLuint srcElemOffset) {
    ClearBufferTv(buffer, drawBuffer, webgl::AttribBaseType::Int,
                  MakeByteRange(list), srcElemOffset);
  }
  void ClearBufferuiv(GLenum buffer, GLint drawBuffer, const Uint32ListU& list,
                      GLuint srcElemOffset) {
    ClearBufferTv(buffer, drawBuffer, webgl::AttribBaseType::Uint,
                  MakeByteRange(list), srcElemOffset);
  }

  // -

  void ClearBufferfi(GLenum buffer, GLint drawBuffer, GLfloat depth,
                     GLint stencil);

  void ClearColor(GLclampf r, GLclampf g, GLclampf b, GLclampf a);

  void ClearDepth(GLclampf v);

  void ClearStencil(GLint v);

  void ColorMask(bool r, bool g, bool b, bool a) const {
    ColorMaskI({}, r, g, b, a);
  }
  void ColorMaskI(Maybe<GLuint> buf, bool r, bool g, bool b, bool a) const;

  void CullFace(GLenum face);

  void DepthFunc(GLenum func);

  void DepthMask(WebGLboolean b);

  void DepthRange(GLclampf zNear, GLclampf zFar);

  void Flush(bool flushGl = true);

  void Finish();

  void FrontFace(GLenum mode);

  GLenum GetError();

  void Hint(GLenum target, GLenum mode);

  void LineWidth(GLfloat width);

  void PixelStorei(GLenum pname, GLint param);

  void PolygonOffset(GLfloat factor, GLfloat units);

  void SampleCoverage(GLclampf value, WebGLboolean invert);

  void Scissor(GLint x, GLint y, GLsizei width, GLsizei height);

  // -

  void StencilFunc(GLenum func, GLint ref, GLuint mask) {
    StencilFuncSeparate(LOCAL_GL_FRONT_AND_BACK, func, ref, mask);
  }
  void StencilMask(GLuint mask) {
    StencilMaskSeparate(LOCAL_GL_FRONT_AND_BACK, mask);
  }
  void StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass) {
    StencilOpSeparate(LOCAL_GL_FRONT_AND_BACK, sfail, dpfail, dppass);
  }

  void StencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask);
  void StencilMaskSeparate(GLenum face, GLuint mask);
  void StencilOpSeparate(GLenum face, GLenum sfail, GLenum dpfail,
                         GLenum dppass);

  // -

  void Viewport(GLint x, GLint y, GLsizei width, GLsizei height);

  // ------------------------- Buffer Objects -------------------------
 public:
  void BindBuffer(GLenum target, WebGLBufferJS*);

  // -

 private:
  void BindBufferRangeImpl(const GLenum target, const GLuint index,
                           WebGLBufferJS* const buffer, const uint64_t offset,
                           const uint64_t size);

 public:
  void BindBufferBase(const GLenum target, const GLuint index,
                      WebGLBufferJS* const buffer) {
    const FuncScope funcScope(*this, "bindBufferBase");
    if (IsContextLost()) return;

    BindBufferRangeImpl(target, index, buffer, 0, 0);
  }

  void BindBufferRange(const GLenum target, const GLuint index,
                       WebGLBufferJS* const buffer, const WebGLintptr offset,
                       const WebGLsizeiptr size) {
    const FuncScope funcScope(*this, "bindBufferRange");
    if (IsContextLost()) return;

    if (buffer) {
      if (!ValidateNonNegative("offset", offset)) return;

      if (size < 1) {
        EnqueueError(LOCAL_GL_INVALID_VALUE,
                     "`size` must be positive for non-null `buffer`.");
        return;
      }
    }

    BindBufferRangeImpl(target, index, buffer, static_cast<uint64_t>(offset),
                        static_cast<uint64_t>(size));
  }

  // -

  void CopyBufferSubData(GLenum readTarget, GLenum writeTarget,
                         GLintptr readOffset, GLintptr writeOffset,
                         GLsizeiptr size);

  void BufferData(GLenum target, WebGLsizeiptr size, GLenum usage);
  void BufferData(GLenum target,
                  const dom::Nullable<dom::ArrayBuffer>& maybeSrc,
                  GLenum usage);
  void BufferData(GLenum target, const dom::ArrayBufferView& srcData,
                  GLenum usage, GLuint srcElemOffset = 0,
                  GLuint srcElemCountOverride = 0);

  void RawBufferData(GLenum target, const uint8_t* srcBytes, size_t srcLen,
                     GLenum usage);
  void RawBufferSubData(GLenum target, WebGLsizeiptr dstByteOffset,
                        const uint8_t* srcBytes, size_t srcLen,
                        bool unsynchronized = false);

  void BufferSubData(GLenum target, WebGLsizeiptr dstByteOffset,
                     const dom::ArrayBufferView& src, GLuint srcElemOffset = 0,
                     GLuint srcElemCountOverride = 0);
  void BufferSubData(GLenum target, WebGLsizeiptr dstByteOffset,
                     const dom::ArrayBuffer& src);

  void GetBufferSubData(GLenum target, GLintptr srcByteOffset,
                        const dom::ArrayBufferView& dstData,
                        GLuint dstElemOffset, GLuint dstElemCountOverride);

  // -------------------------- Framebuffer Objects --------------------------

  void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
                       GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
                       GLbitfield mask, GLenum filter);

  // -

 private:
  // `bindTarget` if non-zero allows initializing the rb/tex with that target.
  void FramebufferAttach(GLenum target, GLenum attachEnum, GLenum bindTarget,
                         WebGLRenderbufferJS*, WebGLTextureJS*,
                         uint32_t mipLevel, uint32_t zLayer,
                         uint32_t numViewLayers) const;

 public:
  void FramebufferRenderbuffer(GLenum target, GLenum attachSlot,
                               GLenum rbTarget, WebGLRenderbufferJS* rb) const {
    const FuncScope funcScope(*this, "framebufferRenderbuffer");
    if (IsContextLost()) return;
    if (rbTarget != LOCAL_GL_RENDERBUFFER) {
      EnqueueError_ArgEnum("rbTarget", rbTarget);
      return;
    }
    FramebufferAttach(target, attachSlot, rbTarget, rb, nullptr, 0, 0, 0);
  }

  void FramebufferTexture2D(GLenum target, GLenum attachSlot,
                            GLenum texImageTarget, WebGLTextureJS*,
                            GLint mipLevel) const;

  void FramebufferTextureLayer(GLenum target, GLenum attachSlot,
                               WebGLTextureJS* tex, GLint mipLevel,
                               GLint zLayer) const {
    const FuncScope funcScope(*this, "framebufferTextureLayer");
    if (IsContextLost()) return;
    FramebufferAttach(target, attachSlot, 0, nullptr, tex,
                      static_cast<uint32_t>(mipLevel),
                      static_cast<uint32_t>(zLayer), 0);
  }

  void FramebufferTextureMultiview(GLenum target, GLenum attachSlot,
                                   WebGLTextureJS* tex, GLint mipLevel,
                                   GLint zLayerBase,
                                   GLsizei numViewLayers) const {
    const FuncScope funcScope(*this, "framebufferTextureMultiview");
    if (IsContextLost()) return;
    if (tex && numViewLayers < 1) {
      EnqueueError(LOCAL_GL_INVALID_VALUE, "`numViewLayers` must be >=1.");
      return;
    }
    FramebufferAttach(target, attachSlot, 0, nullptr, tex,
                      static_cast<uint32_t>(mipLevel),
                      static_cast<uint32_t>(zLayerBase),
                      static_cast<uint32_t>(numViewLayers));
  }

  // -

  void InvalidateFramebuffer(GLenum target,
                             const dom::Sequence<GLenum>& attachments,
                             ErrorResult& unused);
  void InvalidateSubFramebuffer(GLenum target,
                                const dom::Sequence<GLenum>& attachments,
                                GLint x, GLint y, GLsizei width, GLsizei height,
                                ErrorResult& unused);

  void ReadBuffer(GLenum mode);

  // ----------------------- Renderbuffer objects -----------------------
  void GetInternalformatParameter(JSContext* cx, GLenum target,
                                  GLenum internalformat, GLenum pname,
                                  JS::MutableHandle<JS::Value> retval,
                                  ErrorResult& rv);

  void BindRenderbuffer(GLenum target, WebGLRenderbufferJS*);

  void RenderbufferStorage(GLenum target, GLenum internalFormat, GLsizei width,
                           GLsizei height) const {
    RenderbufferStorageMultisample(target, 0, internalFormat, width, height);
  }

  void RenderbufferStorageMultisample(GLenum target, GLsizei samples,
                                      GLenum internalFormat, GLsizei width,
                                      GLsizei height) const;

  // --------------------------- Texture objects ---------------------------

  void ActiveTexture(GLenum texUnit);

  void BindTexture(GLenum texTarget, WebGLTextureJS*);

  void GenerateMipmap(GLenum texTarget) const;

  void GetTexParameter(JSContext* cx, GLenum texTarget, GLenum pname,
                       JS::MutableHandle<JS::Value> retval) const;

  void TexParameterf(GLenum texTarget, GLenum pname, GLfloat param);
  void TexParameteri(GLenum texTarget, GLenum pname, GLint param);

  // -

 private:
  void TexStorage(uint8_t funcDims, GLenum target, GLsizei levels,
                  GLenum internalFormat, const ivec3& size) const;

  // Primitive tex upload functions
  void RawTexImage(uint32_t level, GLenum respecFormat, uvec3 offset,
                   const webgl::PackingInfo& pi,
                   webgl::TexUnpackBlobDesc&&) const;
  void TexImage(uint8_t funcDims, GLenum target, GLint level,
                GLenum respecFormat, const ivec3& offset,
                const Maybe<ivec3>& size, GLint border,
                const webgl::PackingInfo& pi, const TexImageSource& src) const;
  void CompressedTexImage(bool sub, uint8_t funcDims, GLenum target,
                          GLint level, GLenum format, const ivec3& offset,
                          const ivec3& size, GLint border,
                          const TexImageSource& src,
                          GLsizei pboImageSize) const;
  void CopyTexImage(uint8_t funcDims, GLenum target, GLint level,
                    GLenum respecFormat, const ivec3& dstOffset,
                    const ivec2& srcOffset, const ivec2& size,
                    GLint border) const;

 public:
  void TexStorage2D(GLenum target, GLsizei levels, GLenum internalFormat,
                    GLsizei width, GLsizei height) const {
    TexStorage(2, target, levels, internalFormat, {width, height, 1});
  }

  void TexStorage3D(GLenum target, GLsizei levels, GLenum internalFormat,
                    GLsizei width, GLsizei height, GLsizei depth) const {
    TexStorage(3, target, levels, internalFormat, {width, height, depth});
  }

  ////////////////////////////////////

  template <typename T>  // TexImageSource or WebGLintptr
  void TexImage2D(GLenum target, GLint level, GLenum internalFormat,
                  GLsizei width, GLsizei height, GLint border,
                  GLenum unpackFormat, GLenum unpackType, const T& anySrc,
                  ErrorResult& out_error) const {
    const TexImageSourceAdapter src(&anySrc, &out_error);
    TexImage(2, target, level, internalFormat, {0, 0, 0},
             Some(ivec3{width, height, 1}), border, {unpackFormat, unpackType},
             src);
  }

  void TexImage2D(GLenum target, GLint level, GLenum internalFormat,
                  GLsizei width, GLsizei height, GLint border,
                  GLenum unpackFormat, GLenum unpackType,
                  const dom::ArrayBufferView& view, GLuint viewElemOffset,
                  ErrorResult&) const {
    const TexImageSourceAdapter src(&view, viewElemOffset);
    TexImage(2, target, level, internalFormat, {0, 0, 0},
             Some(ivec3{width, height, 1}), border, {unpackFormat, unpackType},
             src);
  }

  // -

  template <typename T>  // TexImageSource or WebGLintptr
  void TexSubImage2D(GLenum target, GLint level, GLint xOffset, GLint yOffset,
                     GLsizei width, GLsizei height, GLenum unpackFormat,
                     GLenum unpackType, const T& anySrc,
                     ErrorResult& out_error) const {
    const TexImageSourceAdapter src(&anySrc, &out_error);
    TexImage(2, target, level, 0, {xOffset, yOffset, 0},
             Some(ivec3{width, height, 1}), 0, {unpackFormat, unpackType}, src);
  }

  void TexSubImage2D(GLenum target, GLint level, GLint xOffset, GLint yOffset,
                     GLsizei width, GLsizei height, GLenum unpackFormat,
                     GLenum unpackType, const dom::ArrayBufferView& view,
                     GLuint viewElemOffset, ErrorResult&) const {
    const TexImageSourceAdapter src(&view, viewElemOffset);
    TexImage(2, target, level, 0, {xOffset, yOffset, 0},
             Some(ivec3{width, height, 1}), 0, {unpackFormat, unpackType}, src);
  }

  // -

  template <typename T>  // TexImageSource or WebGLintptr
  void TexImage3D(GLenum target, GLint level, GLenum internalFormat,
                  GLsizei width, GLsizei height, GLsizei depth, GLint border,
                  GLenum unpackFormat, GLenum unpackType, const T& anySrc,
                  ErrorResult& out_error) const {
    const TexImageSourceAdapter src(&anySrc, &out_error);
    TexImage(3, target, level, internalFormat, {0, 0, 0},
             Some(ivec3{width, height, depth}), border,
             {unpackFormat, unpackType}, src);
  }

  void TexImage3D(GLenum target, GLint level, GLenum internalFormat,
                  GLsizei width, GLsizei height, GLsizei depth, GLint border,
                  GLenum unpackFormat, GLenum unpackType,
                  const dom::ArrayBufferView& view, GLuint viewElemOffset,
                  ErrorResult&) const {
    const TexImageSourceAdapter src(&view, viewElemOffset);
    TexImage(3, target, level, internalFormat, {0, 0, 0},
             Some(ivec3{width, height, depth}), border,
             {unpackFormat, unpackType}, src);
  }

  // -

  template <typename T>  // TexImageSource or WebGLintptr
  void TexSubImage3D(GLenum target, GLint level, GLint xOffset, GLint yOffset,
                     GLint zOffset, GLsizei width, GLsizei height,
                     GLsizei depth, GLenum unpackFormat, GLenum unpackType,
                     const T& anySrc, ErrorResult& out_error) const {
    const TexImageSourceAdapter src(&anySrc, &out_error);
    TexImage(3, target, level, 0, {xOffset, yOffset, zOffset},
             Some(ivec3{width, height, depth}), 0, {unpackFormat, unpackType},
             src);
  }

  void TexSubImage3D(GLenum target, GLint level, GLint xOffset, GLint yOffset,
                     GLint zOffset, GLsizei width, GLsizei height,
                     GLsizei depth, GLenum unpackFormat, GLenum unpackType,
                     const dom::Nullable<dom::ArrayBufferView>& maybeSrcView,
                     GLuint srcElemOffset, ErrorResult&) const {
    const TexImageSourceAdapter src(&maybeSrcView, srcElemOffset);
    TexImage(3, target, level, 0, {xOffset, yOffset, zOffset},
             Some(ivec3{width, height, depth}), 0, {unpackFormat, unpackType},
             src);
  }

  ////////////////////////////////////

 public:
  void CompressedTexImage2D(GLenum target, GLint level, GLenum internalFormat,
                            GLsizei width, GLsizei height, GLint border,
                            GLsizei imageSize, WebGLintptr offset) const {
    const TexImageSourceAdapter src(&offset);
    CompressedTexImage(false, 2, target, level, internalFormat, {0, 0, 0},
                       {width, height, 1}, border, src, imageSize);
  }

  void CompressedTexImage2D(GLenum target, GLint level, GLenum internalFormat,
                            GLsizei width, GLsizei height, GLint border,
                            const dom::ArrayBufferView& view,
                            GLuint viewElemOffset = 0,
                            GLuint viewElemLengthOverride = 0) const {
    const TexImageSourceAdapter src(&view, viewElemOffset,
                                    viewElemLengthOverride);
    CompressedTexImage(false, 2, target, level, internalFormat, {0, 0, 0},
                       {width, height, 1}, border, src, 0);
  }

  // -

  void CompressedTexSubImage2D(GLenum target, GLint level, GLint xOffset,
                               GLint yOffset, GLsizei width, GLsizei height,
                               GLenum unpackFormat, GLsizei imageSize,
                               WebGLintptr offset) const {
    const TexImageSourceAdapter src(&offset);
    CompressedTexImage(true, 2, target, level, unpackFormat,
                       {xOffset, yOffset, 0}, {width, height, 1}, 0, src,
                       imageSize);
  }

  void CompressedTexSubImage2D(GLenum target, GLint level, GLint xOffset,
                               GLint yOffset, GLsizei width, GLsizei height,
                               GLenum unpackFormat,
                               const dom::ArrayBufferView& view,
                               GLuint viewElemOffset = 0,
                               GLuint viewElemLengthOverride = 0) const {
    const TexImageSourceAdapter src(&view, viewElemOffset,
                                    viewElemLengthOverride);
    CompressedTexImage(true, 2, target, level, unpackFormat,
                       {xOffset, yOffset, 0}, {width, height, 1}, 0, src, 0);
  }

  // -

  void CompressedTexImage3D(GLenum target, GLint level, GLenum internalFormat,
                            GLsizei width, GLsizei height, GLsizei depth,
                            GLint border, GLsizei imageSize,
                            WebGLintptr offset) const {
    const TexImageSourceAdapter src(&offset);
    CompressedTexImage(false, 3, target, level, internalFormat, {0, 0, 0},
                       {width, height, depth}, border, src, imageSize);
  }

  void CompressedTexImage3D(GLenum target, GLint level, GLenum internalFormat,
                            GLsizei width, GLsizei height, GLsizei depth,
                            GLint border, const dom::ArrayBufferView& view,
                            GLuint viewElemOffset = 0,
                            GLuint viewElemLengthOverride = 0) const {
    const TexImageSourceAdapter src(&view, viewElemOffset,
                                    viewElemLengthOverride);
    CompressedTexImage(false, 3, target, level, internalFormat, {0, 0, 0},
                       {width, height, depth}, border, src, 0);
  }

  // -

  void CompressedTexSubImage3D(GLenum target, GLint level, GLint xOffset,
                               GLint yOffset, GLint zOffset, GLsizei width,
                               GLsizei height, GLsizei depth,
                               GLenum unpackFormat, GLsizei imageSize,
                               WebGLintptr offset) const {
    const TexImageSourceAdapter src(&offset);
    CompressedTexImage(true, 3, target, level, unpackFormat,
                       {xOffset, yOffset, zOffset}, {width, height, depth}, 0,
                       src, imageSize);
  }

  void CompressedTexSubImage3D(GLenum target, GLint level, GLint xOffset,
                               GLint yOffset, GLint zOffset, GLsizei width,
                               GLsizei height, GLsizei depth,
                               GLenum unpackFormat,
                               const dom::ArrayBufferView& view,
                               GLuint viewElemOffset = 0,
                               GLuint viewElemLengthOverride = 0) const {
    const TexImageSourceAdapter src(&view, viewElemOffset,
                                    viewElemLengthOverride);
    CompressedTexImage(true, 3, target, level, unpackFormat,
                       {xOffset, yOffset, zOffset}, {width, height, depth}, 0,
                       src, 0);
  }

  // --------------------

  void CopyTexImage2D(GLenum target, GLint level, GLenum internalFormat,
                      GLint x, GLint y, GLsizei width, GLsizei height,
                      GLint border) const {
    CopyTexImage(2, target, level, internalFormat, {0, 0, 0}, {x, y},
                 {width, height}, border);
  }

  void CopyTexSubImage2D(GLenum target, GLint level, GLint xOffset,
                         GLint yOffset, GLint x, GLint y, GLsizei width,
                         GLsizei height) const {
    CopyTexImage(2, target, level, 0, {xOffset, yOffset, 0}, {x, y},
                 {width, height}, 0);
  }

  void CopyTexSubImage3D(GLenum target, GLint level, GLint xOffset,
                         GLint yOffset, GLint zOffset, GLint x, GLint y,
                         GLsizei width, GLsizei height) const {
    CopyTexImage(3, target, level, 0, {xOffset, yOffset, zOffset}, {x, y},
                 {width, height}, 0);
  }

  // -------------------
  // legacy TexImageSource uploads without width/height.
  // The width/height params are webgl2 only, and let you do subrect
  // selection with e.g. width < UNPACK_ROW_LENGTH.

  template <typename TexImageSourceT>
  void TexImage2D(GLenum target, GLint level, GLenum internalFormat,
                  GLenum unpackFormat, GLenum unpackType,
                  const TexImageSourceT& anySrc, ErrorResult& out_error) const {
    const TexImageSourceAdapter src(&anySrc, &out_error);
    TexImage(2, target, level, internalFormat, {}, {}, 0,
             {unpackFormat, unpackType}, src);
  }

  template <typename TexImageSourceT>
  void TexSubImage2D(GLenum target, GLint level, GLint xOffset, GLint yOffset,
                     GLenum unpackFormat, GLenum unpackType,
                     const TexImageSourceT& anySrc,
                     ErrorResult& out_error) const {
    const TexImageSourceAdapter src(&anySrc, &out_error);
    TexImage(2, target, level, 0, {xOffset, yOffset, 0}, {}, 0,
             {unpackFormat, unpackType}, src);
  }

  // ------------------------ Uniforms and attributes ------------------------

 private:
  Maybe<double> GetVertexAttribPriv(GLuint index, GLenum pname);

 public:
  void GetVertexAttrib(JSContext* cx, GLuint index, GLenum pname,
                       JS::MutableHandle<JS::Value> retval, ErrorResult& rv);

 private:
  const webgl::LinkResult* GetActiveLinkResult() const {
    const auto& state = State();
    if (state.mCurrentProgram) {
      (void)GetLinkResult(*state.mCurrentProgram);
    }
    return state.mActiveLinkResult.get();
  }

  void UniformData(GLenum funcElemType, const WebGLUniformLocationJS* const loc,
                   bool transpose, const Range<const uint8_t>& bytes,
                   GLuint elemOffset = 0, GLuint elemCountOverride = 0) const;

  // -

  template <typename T>
  Maybe<Range<T>> ValidateSubrange(const Range<T>& data, size_t elemOffset,
                                   size_t elemLengthOverride = 0) const {
    auto ret = data;
    if (elemOffset > ret.length()) {
      EnqueueError(LOCAL_GL_INVALID_VALUE,
                   "`elemOffset` too large for `data`.");
      return {};
    }
    ret = {ret.begin() + elemOffset, ret.end()};
    if (elemLengthOverride) {
      if (elemLengthOverride > ret.length()) {
        EnqueueError(
            LOCAL_GL_INVALID_VALUE,
            "`elemLengthOverride` too large for `data` and `elemOffset`.");
        return {};
      }
      ret = {ret.begin().get(), elemLengthOverride};
    }
    return Some(ret);
  }

 public:
#define _(T, type_t, TYPE)                                                    \
  void Uniform1##T(const WebGLUniformLocationJS* const loc, type_t x) const { \
    const type_t arr[] = {x};                                                 \
    UniformData(TYPE, loc, false, MakeByteRange(arr));                        \
  }                                                                           \
  void Uniform2##T(const WebGLUniformLocationJS* const loc, type_t x,         \
                   type_t y) const {                                          \
    const type_t arr[] = {x, y};                                              \
    UniformData(TYPE##_VEC2, loc, false, MakeByteRange(arr));                 \
  }                                                                           \
  void Uniform3##T(const WebGLUniformLocationJS* const loc, type_t x,         \
                   type_t y, type_t z) const {                                \
    const type_t arr[] = {x, y, z};                                           \
    UniformData(TYPE##_VEC3, loc, false, MakeByteRange(arr));                 \
  }                                                                           \
  void Uniform4##T(const WebGLUniformLocationJS* const loc, type_t x,         \
                   type_t y, type_t z, type_t w) const {                      \
    const type_t arr[] = {x, y, z, w};                                        \
    UniformData(TYPE##_VEC4, loc, false, MakeByteRange(arr));                 \
  }

  _(f, float, LOCAL_GL_FLOAT)
  _(i, int32_t, LOCAL_GL_INT)
  _(ui, uint32_t, LOCAL_GL_UNSIGNED_INT)

#undef _

  // -

#define _(NT, TypeListU, TYPE)                                      \
  void Uniform##NT##v(const WebGLUniformLocationJS* const loc,      \
                      const TypeListU& list, GLuint elemOffset = 0, \
                      GLuint elemCountOverride = 0) const {         \
    UniformData(TYPE, loc, false, MakeByteRange(list), elemOffset,  \
                elemCountOverride);                                 \
  }

  _(1f, Float32ListU, LOCAL_GL_FLOAT)
  _(2f, Float32ListU, LOCAL_GL_FLOAT_VEC2)
  _(3f, Float32ListU, LOCAL_GL_FLOAT_VEC3)
  _(4f, Float32ListU, LOCAL_GL_FLOAT_VEC4)
  _(1i, Int32ListU, LOCAL_GL_INT)
  _(2i, Int32ListU, LOCAL_GL_INT_VEC2)
  _(3i, Int32ListU, LOCAL_GL_INT_VEC3)
  _(4i, Int32ListU, LOCAL_GL_INT_VEC4)
  _(1ui, Uint32ListU, LOCAL_GL_UNSIGNED_INT)
  _(2ui, Uint32ListU, LOCAL_GL_UNSIGNED_INT_VEC2)
  _(3ui, Uint32ListU, LOCAL_GL_UNSIGNED_INT_VEC3)
  _(4ui, Uint32ListU, LOCAL_GL_UNSIGNED_INT_VEC4)

#undef _

  // -

#define _(X)                                                                   \
  void UniformMatrix##X##fv(const WebGLUniformLocationJS* loc, bool transpose, \
                            const Float32ListU& list, GLuint elemOffset = 0,   \
                            GLuint elemCountOverride = 0) const {              \
    UniformData(LOCAL_GL_FLOAT_MAT##X, loc, transpose, MakeByteRange(list),    \
                elemOffset, elemCountOverride);                                \
  }

  _(2)
  _(2x3)
  _(2x4)

  _(3x2)
  _(3)
  _(3x4)

  _(4x2)
  _(4x3)
  _(4)

#undef _

  // -

  void EnableVertexAttribArray(GLuint index);

  void DisableVertexAttribArray(GLuint index);

  WebGLsizeiptr GetVertexAttribOffset(GLuint index, GLenum pname);

  // -

 private:
  void VertexAttrib4Tv(GLuint index, webgl::AttribBaseType,
                       const Range<const uint8_t>&);

 public:
  void VertexAttrib1f(GLuint index, GLfloat x) {
    VertexAttrib4f(index, x, 0, 0, 1);
  }
  void VertexAttrib2f(GLuint index, GLfloat x, GLfloat y) {
    VertexAttrib4f(index, x, y, 0, 1);
  }
  void VertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z) {
    VertexAttrib4f(index, x, y, z, 1);
  }

  void VertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z,
                      GLfloat w) {
    const float arr[4] = {x, y, z, w};
    VertexAttrib4Tv(index, webgl::AttribBaseType::Float, MakeByteRange(arr));
  }

  // -

  void VertexAttrib1fv(const GLuint index, const Float32ListU& list) {
    const FuncScope funcScope(*this, "vertexAttrib1fv");
    if (IsContextLost()) return;

    const auto range = MakeRange(list);
    if (range.length() < 1) {
      EnqueueError(LOCAL_GL_INVALID_VALUE, "Length of `list` must be >=1.");
      return;
    }

    VertexAttrib1f(index, range[0]);
  }

  void VertexAttrib2fv(const GLuint index, const Float32ListU& list) {
    const FuncScope funcScope(*this, "vertexAttrib1fv");
    if (IsContextLost()) return;

    const auto range = MakeRange(list);
    if (range.length() < 2) {
      EnqueueError(LOCAL_GL_INVALID_VALUE, "Length of `list` must be >=2.");
      return;
    }

    VertexAttrib2f(index, range[0], range[1]);
  }

  void VertexAttrib3fv(const GLuint index, const Float32ListU& list) {
    const FuncScope funcScope(*this, "vertexAttrib1fv");
    if (IsContextLost()) return;

    const auto range = MakeRange(list);
    if (range.length() < 3) {
      EnqueueError(LOCAL_GL_INVALID_VALUE, "Length of `list` must be >=3.");
      return;
    }

    VertexAttrib3f(index, range[0], range[1], range[2]);
  }

  void VertexAttrib4fv(GLuint index, const Float32ListU& list) {
    VertexAttrib4Tv(index, webgl::AttribBaseType::Float, MakeByteRange(list));
  }
  void VertexAttribI4iv(GLuint index, const Int32ListU& list) {
    VertexAttrib4Tv(index, webgl::AttribBaseType::Int, MakeByteRange(list));
  }
  void VertexAttribI4uiv(GLuint index, const Uint32ListU& list) {
    VertexAttrib4Tv(index, webgl::AttribBaseType::Uint, MakeByteRange(list));
  }

  void VertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w) {
    const int32_t arr[4] = {x, y, z, w};
    VertexAttrib4Tv(index, webgl::AttribBaseType::Int, MakeByteRange(arr));
  }
  void VertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) {
    const uint32_t arr[4] = {x, y, z, w};
    VertexAttrib4Tv(index, webgl::AttribBaseType::Uint, MakeByteRange(arr));
  }

 private:
  void VertexAttribPointerImpl(bool isFuncInt, GLuint index, GLint size,
                               GLenum type, WebGLboolean normalized,
                               GLsizei iStride, WebGLintptr iByteOffset);

 public:
  void VertexAttribIPointer(GLuint index, GLint size, GLenum type,
                            GLsizei stride, WebGLintptr byteOffset) {
    VertexAttribPointerImpl(true, index, size, type, false, stride, byteOffset);
  }

  void VertexAttribPointer(GLuint index, GLint size, GLenum type,
                           WebGLboolean normalized, GLsizei stride,
                           WebGLintptr byteOffset) {
    VertexAttribPointerImpl(false, index, size, type, normalized, stride,
                            byteOffset);
  }

  // -------------------------------- Drawing -------------------------------
 public:
  void DrawArrays(GLenum mode, GLint first, GLsizei count) {
    DrawArraysInstanced(mode, first, count, 1);
  }

  void DrawElements(GLenum mode, GLsizei count, GLenum type,
                    WebGLintptr byteOffset) {
    DrawElementsInstanced(mode, count, type, byteOffset, 1);
  }

  void DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count,
                         GLenum type, WebGLintptr byteOffset) {
    const FuncScope funcScope(*this, "drawRangeElements");
    if (end < start) {
      EnqueueError(LOCAL_GL_INVALID_VALUE, "end must be >= start.");
      return;
    }
    DrawElementsInstanced(mode, count, type, byteOffset, 1);
  }

  // ------------------------------ Readback -------------------------------
 public:
  void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height,
                  GLenum format, GLenum type,
                  const dom::Nullable<dom::ArrayBufferView>& maybeView,
                  dom::CallerType aCallerType, ErrorResult& out_error) const {
    const FuncScope funcScope(*this, "readPixels");
    if (!ValidateNonNull("pixels", maybeView)) return;
    ReadPixels(x, y, width, height, format, type, maybeView.Value(), 0,
               aCallerType, out_error);
  }

  void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height,
                  GLenum format, GLenum type, WebGLsizeiptr offset,
                  dom::CallerType aCallerType, ErrorResult& out_error) const;

  void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height,
                  GLenum format, GLenum type,
                  const dom::ArrayBufferView& dstData, GLuint dstElemOffset,
                  dom::CallerType aCallerType, ErrorResult& out_error) const;

 protected:
  bool ReadPixels_SharedPrecheck(dom::CallerType aCallerType,
                                 ErrorResult& out_error) const;

  // ------------------------------ Vertex Array ------------------------------
 public:
  void BindVertexArray(WebGLVertexArrayJS*);

  void DrawArraysInstanced(GLenum mode, GLint first, GLsizei count,
                           GLsizei primcount);

  void DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type,
                             WebGLintptr offset, GLsizei primcount);

  void VertexAttribDivisor(GLuint index, GLuint divisor);

  // --------------------------------- GL Query
  // ---------------------------------
 public:
  void GetQuery(JSContext*, GLenum target, GLenum pname,
                JS::MutableHandle<JS::Value> retval) const;
  void GetQueryParameter(JSContext*, WebGLQueryJS&, GLenum pname,
                         JS::MutableHandle<JS::Value> retval) const;
  void BeginQuery(GLenum target, WebGLQueryJS&);
  void EndQuery(GLenum target);
  void QueryCounter(WebGLQueryJS&, GLenum target) const;

  // -------------------------------- Sampler -------------------------------

  void GetSamplerParameter(JSContext*, const WebGLSamplerJS&, GLenum pname,
                           JS::MutableHandle<JS::Value> retval) const;

  void BindSampler(GLuint unit, WebGLSamplerJS*);
  void SamplerParameteri(WebGLSamplerJS&, GLenum pname, GLint param) const;
  void SamplerParameterf(WebGLSamplerJS&, GLenum pname, GLfloat param) const;

  // ------------------------------- GL Sync ---------------------------------

  GLenum ClientWaitSync(WebGLSyncJS&, GLbitfield flags, GLuint64 timeout) const;
  void GetSyncParameter(JSContext*, WebGLSyncJS&, GLenum pname,
                        JS::MutableHandle<JS::Value> retval) const;
  void WaitSync(const WebGLSyncJS&, GLbitfield flags, GLint64 timeout) const;

  // -------------------------- Transform Feedback ---------------------------

  void BindTransformFeedback(GLenum target, WebGLTransformFeedbackJS*);
  void BeginTransformFeedback(GLenum primitiveMode);
  void EndTransformFeedback();
  void PauseTransformFeedback();
  void ResumeTransformFeedback();

  // -------------------------- Opaque Framebuffers ---------------------------

  void SetFramebufferIsInOpaqueRAF(WebGLFramebufferJS*, bool);

  // ------------------------------ Extensions ------------------------------
 public:
  void GetSupportedExtensions(dom::Nullable<nsTArray<nsString>>& retval,
                              dom::CallerType callerType) const;

  bool IsSupported(WebGLExtensionID, dom::CallerType callerType =
                                         dom::CallerType::NonSystem) const;

  void GetExtension(JSContext* cx, const nsAString& name,
                    JS::MutableHandle<JSObject*> retval,
                    dom::CallerType callerType, ErrorResult& rv);

 protected:
  bool IsExtensionForbiddenForCaller(const WebGLExtensionID ext,
                                     const dom::CallerType callerType) const;

  RefPtr<ClientWebGLExtensionBase> GetExtension(WebGLExtensionID ext,
                                                dom::CallerType callerType);
  void RequestExtension(WebGLExtensionID) const;

 public:
  bool IsExtensionEnabled(const WebGLExtensionID id) const {
    return bool(mNotLost->extensions[UnderlyingValue(id)]);
  }

  void AddCompressedFormat(GLenum);

  // ---------------------------- Misc Extensions ----------------------------
 public:
  void DrawBuffers(const dom::Sequence<GLenum>& buffers);

  void GetSupportedProfilesASTC(
      dom::Nullable<nsTArray<nsString>>& retval) const;

  void MOZDebugGetParameter(JSContext* cx, GLenum pname,
                            JS::MutableHandle<JS::Value> retval,
                            ErrorResult& rv) {
    GetParameter(cx, pname, retval, rv, true);
  }

  void ProvokingVertex(GLenum rawMode) const;

  // -------------------------------------------------------------------------
  // Client-side methods.  Calls in the Host are forwarded to the client.
  // -------------------------------------------------------------------------
 public:
  void JsWarning(const std::string&) const;

  // -------------------------------------------------------------------------
  // The cross-process communication mechanism
  // -------------------------------------------------------------------------
 protected:
  template <typename ReturnType>
  friend struct WebGLClientDispatcher;

  template <typename MethodType, MethodType method, typename ReturnType,
            typename... Args>
  friend ReturnType RunOn(const ClientWebGLContext& context, Args&&... aArgs);

  // If we are running WebGL in this process then call the HostWebGLContext
  // method directly.  Otherwise, dispatch over IPC.
  template <typename MethodType, MethodType method, typename... Args>
  void Run(Args&&... aArgs) const;

  // -------------------------------------------------------------------------
  // Helpers for DOM operations, composition, actors, etc
  // -------------------------------------------------------------------------

 public:
  // https://immersive-web.github.io/webxr/#xr-compatible
  bool IsXRCompatible() const;
  already_AddRefed<dom::Promise> MakeXRCompatible(ErrorResult& aRv);

 protected:
  uint32_t GetPrincipalHashValue() const;

  // Prepare the context for capture before compositing
  void BeginComposition();

  // Clean up the context after captured for compositing
  void EndComposition();

  mozilla::dom::Document* GetOwnerDoc() const;

  mutable bool mResetLayer = true;
  Maybe<const WebGLContextOptions> mInitialOptions;
  bool mXRCompatible = false;
};

// used by DOM bindings in conjunction with GetParentObject
inline nsISupports* ToSupports(ClientWebGLContext* webgl) {
  return static_cast<nsICanvasRenderingContextInternal*>(webgl);
}

const char* GetExtensionName(WebGLExtensionID);

// -

inline bool webgl::ObjectJS::IsForContext(
    const ClientWebGLContext& context) const {
  const auto& notLost = context.mNotLost;
  if (!notLost) return false;
  if (notLost.get() != mGeneration.lock().get()) return false;
  return true;
}

void AutoJsWarning(const std::string& utf8);

}  // namespace mozilla

#endif  // CLIENTWEBGLCONTEXT_H_