lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
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
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
mod app_errors;
#[cfg(feature = "canvas")]
mod canvas;
#[cfg(all(windows, feature = "raster"))]
mod card_copies;
#[cfg(all(windows, feature = "raster"))]
mod card_frames;
#[cfg(all(test, windows, feature = "raster", feature = "media"))]
mod card_frames_tests;
#[cfg(all(test, feature = "raster", any(target_os = "macos", target_os = "ios")))]
mod cv_pixel_buffer_tests;
mod device_loss;
mod extension;
#[cfg(feature = "perf_profile")]
mod gpu_timing;
mod gradients;
#[cfg(all(test, feature = "raster"))]
mod i420_tests;
mod layers;
#[cfg(all(
  test,
  feature = "raster",
  any(all(windows, feature = "media"), target_os = "macos", target_os = "ios")
))]
mod planes_drawn;
#[cfg(test)]
mod quad_tests;
mod surface_proxy;
mod vertex;
#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
mod video_color;
#[cfg(all(test, windows, feature = "screenshot"))]
mod viewport_tests;

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
use std::ffi::c_void;
use std::time::Duration;

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
use core_foundation_sys::base::{CFAllocatorRef, CFRelease, OSStatus, kCFAllocatorDefault};
#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
use core_foundation_sys::dictionary::CFDictionaryRef;
#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
use core_video_sys::pixel_buffer::CVPixelBufferRef;
use extension::WgpuFrameExtensionEntry;
pub use extension::{SharedWgpuContext, WgpuAppError, WgpuFrameExtension, WgpuFrameInfo, WgpuViewportRect};
#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
use objc2::{rc::Retained, runtime::ProtocolObject};
use raw_window_handle::{DisplayHandle, WindowHandle};
#[cfg(feature = "raster")]
use vertex::ImageInstance;
use vertex::{Globals, GlyphInstance, QuadInstance, QuadVertex};
use wgpu::util::DeviceExt;
pub use wgpu::{
  Backend as WgpuBackend, Backends as WgpuBackends, Features as WgpuFeatures, Limits as WgpuLimits,
  PresentMode as WgpuPresentMode,
};

#[cfg(feature = "perf_profile")]
use crate::app::profile_types::RenderProfile;
#[cfg(feature = "screenshot")]
use crate::app::render_engine::RenderFrameCapture;
use crate::{
  app::{
    profile_support::{profile_elapsed, profile_if, profile_scope},
    render_engine::RenderEngine,
  },
  layout::{
    backdrop::BackdropRegion,
    backdrop_reuse::{BackdropInputs, LayerBlurInputs, PaintedDraw, backdrop_regions},
    opacity_layer::{LayerPlan, LayerStep, TargetSpace},
    render_list::RenderList,
  },
  render::glyph_batch::{GlyphRun, batch_glyph_runs, glyph_runs},
};

struct DynamicBuffer {
  buffer: Option<wgpu::Buffer>,
  capacity: wgpu::BufferAddress,
  usage: wgpu::BufferUsages,
  label: &'static str,
  last_bytes: Vec<u8>,
}

fn changed_byte_range(previous: &[u8], next: &[u8]) -> Option<(usize, usize)> {
  if previous.len() != next.len() {
    return Some((0, next.len()));
  }
  if previous == next {
    return None;
  }

  let start = previous.iter().zip(next).position(|(a, b)| a != b).unwrap_or(0);
  let end = previous
    .iter()
    .zip(next)
    .rposition(|(a, b)| a != b)
    .map(|index| index + 1)
    .unwrap_or(start + 1);
  let aligned_start = start & !3;
  let aligned_end = (end + 3).min(next.len()) & !3;
  Some((aligned_start, aligned_end.max(aligned_start + 4).min(next.len())))
}

impl DynamicBuffer {
  fn new(label: &'static str, usage: wgpu::BufferUsages) -> Self {
    Self {
      buffer: None,
      capacity: 0,
      usage,
      label,
      last_bytes: Vec::new(),
    }
  }

  fn clear(&mut self) {
    self.buffer = None;
    self.capacity = 0;
    self.last_bytes.clear();
  }

  fn write<T: bytemuck::Pod>(
    &mut self,
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    data: &[T],
  ) -> Option<&wgpu::Buffer> {
    if data.is_empty() {
      return None;
    }

    let bytes = bytemuck::cast_slice(data);
    let required = bytes.len() as wgpu::BufferAddress;
    let mut recreated = false;
    if self.capacity < required {
      self.capacity = required.next_power_of_two().max(256);
      self.buffer = Some(device.create_buffer(&wgpu::BufferDescriptor {
        label: Some(self.label),
        size: self.capacity,
        usage: self.usage | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
      }));
      recreated = true;
    }

    let buffer = self.buffer.as_ref().unwrap();
    if recreated {
      queue.write_buffer(buffer, 0, bytes);
      self.last_bytes.clear();
      self.last_bytes.extend_from_slice(bytes);
    } else if let Some((start, end)) = changed_byte_range(&self.last_bytes, bytes) {
      queue.write_buffer(buffer, start as wgpu::BufferAddress, &bytes[start..end]);
      self.last_bytes.clear();
      self.last_bytes.extend_from_slice(bytes);
    }
    Some(buffer)
  }
}

struct PreparedDraw {
  start: usize,
  count: usize,
}

enum OrderedDraw {
  Rect(usize),
  Glyph(GlyphRun),
  #[cfg(feature = "raster")]
  Image(usize),
}

impl OrderedDraw {
  /// The draw as the inputs of backdrop blurs are told from it.
  fn painted(&self) -> PaintedDraw {
    match *self {
      Self::Rect(index) => PaintedDraw::Rect(index),
      Self::Glyph(GlyphRun { start, count, .. }) => PaintedDraw::Glyphs { start, count },
      #[cfg(feature = "raster")]
      Self::Image(index) => PaintedDraw::Image(index),
    }
  }

  fn glyph_run(&self) -> Option<GlyphRun> {
    match self {
      Self::Glyph(run) => Some(*run),
      _ => None,
    }
  }
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum ActivePipeline {
  Quad,
  Glyph,
  #[cfg(feature = "raster")]
  Image,
  #[cfg(feature = "raster")]
  Nv12Image,
  #[cfg(feature = "raster")]
  I420Image,
  Layer,
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum ActiveVertexBuffer {
  CommonQuad,
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum ActiveIndexBuffer {
  CommonU16,
}

#[derive(Clone, Copy, Eq, Hash, PartialEq)]
struct ClipGlobalsKey([u32; 28]);

#[cfg(feature = "raster")]
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
enum ImageClipFormat {
  Rgba,
  Nv12,
  I420,
}

#[cfg(feature = "raster")]
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
struct ImageClipBindGroupKey {
  image_id: u64,
  frame_index: usize,
  clip: ClipGlobalsKey,
  format: ImageClipFormat,
}

#[cfg(feature = "raster")]
struct CachedRgbaFrame {
  bind_group: wgpu::BindGroup,
  view: wgpu::TextureView,
  texture: wgpu::Texture,
}

#[cfg(feature = "raster")]
enum CachedImageTexture {
  ExternalRgba {
    bind_group: wgpu::BindGroup,
    view: wgpu::TextureView,
    width: u32,
    height: u32,
    version: u64,
  },
  /// A picture of memory of three planes (I420): gray, and the two of color apart.
  I420 {
    bind_group: wgpu::BindGroup,
    y_view: wgpu::TextureView,
    u_view: wgpu::TextureView,
    v_view: wgpu::TextureView,
    textures: [wgpu::Texture; 3],
    width: u32,
    height: u32,
    frame_index: usize,
    version: u64,
  },
  /// A frame of red, green and blue in a `CVPixelBuffer` (`BGRA`), drawn where it is as a picture is: one view,
  /// of sRGB.
  #[cfg(any(target_os = "macos", target_os = "ios"))]
  CvRgba {
    bind_group: wgpu::BindGroup,
    view: wgpu::TextureView,
    _held: MacosNativeRgbaTexture,
    width: u32,
    height: u32,
    version: u64,
  },
  Rgba {
    bind_group: wgpu::BindGroup,
    view: wgpu::TextureView,
    texture: wgpu::Texture,
    animation_frames: Option<Vec<CachedRgbaFrame>>,
    width: u32,
    height: u32,
    frame_index: usize,
    version: u64,
  },
  Nv12 {
    bind_group: wgpu::BindGroup,
    /// How the shader makes colors of the samples: the matrix and whether they take the full range, as the
    /// instance's `opacity.zw` tells it (`shaders/yuv.wgsl`). BT.709 of the video range unless a frame says other.
    color: [f32; 2],
    y_view: wgpu::TextureView,
    uv_view: wgpu::TextureView,
    y_texture: wgpu::Texture,
    uv_texture: wgpu::Texture,
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    _macos_native: Option<MacosNativeNv12Texture>,
    width: u32,
    height: u32,
    frame_index: usize,
    version: u64,
  },
  /// The frames of a video that stay on the card: each of its surfaces opened once, and the one that holds the
  /// frame to draw drawn.
  #[cfg(windows)]
  Card(card_frames::Opened),
}

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
struct MacosNativeNv12Texture {
  _native: crate::images::NativeImageData,
  /// The buffer the textures are of: held for as long as they are drawn, so that what decodes does not write the
  /// next frame into it.
  _buffer: crate::images::MacosCvPixelBuffer,
  _y_cv_texture: CvMetalTexture,
  _uv_cv_texture: CvMetalTexture,
}

/// What a [`CachedImageTexture::CvRgba`] holds for as long as it is drawn: the buffer, and CoreVideo's texture of it.
#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
struct MacosNativeRgbaTexture {
  _native: crate::images::NativeImageData,
  _buffer: crate::images::MacosCvPixelBuffer,
  _cv_texture: CvMetalTexture,
}

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
struct CvMetalTexture {
  ptr: CVMetalTextureRef,
}

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
impl Drop for CvMetalTexture {
  fn drop(&mut self) {
    unsafe {
      CFRelease(self.ptr.cast());
    }
  }
}

/// The cache CoreVideo makes Metal's textures of a buffer with, for one device.
#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
struct CvMetalTextureCache {
  ptr: CVMetalTextureCacheRef,
}

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
impl Drop for CvMetalTextureCache {
  fn drop(&mut self) {
    unsafe {
      CFRelease(self.ptr.cast());
    }
  }
}

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
thread_local! {
  /// The cache of the device that draws on this thread, with the device it is of.
  static CV_TEXTURE_CACHE: std::cell::RefCell<Option<(usize, CvMetalTextureCache)>> =
    const { std::cell::RefCell::new(None) };
}

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
type CVMetalTextureCacheRef = *mut c_void;
#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
type CVMetalTextureRef = *mut c_void;

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
#[link(name = "CoreVideo", kind = "framework")]
unsafe extern "C" {
  fn CVMetalTextureCacheCreate(
    allocator: CFAllocatorRef,
    cache_attributes: CFDictionaryRef,
    metal_device: *mut c_void,
    texture_attributes: CFDictionaryRef,
    cache_out: *mut CVMetalTextureCacheRef,
  ) -> OSStatus;

  fn CVMetalTextureCacheCreateTextureFromImage(
    allocator: CFAllocatorRef,
    texture_cache: CVMetalTextureCacheRef,
    source_image: CVPixelBufferRef,
    texture_attributes: CFDictionaryRef,
    pixel_format: objc2_metal::MTLPixelFormat,
    width: usize,
    height: usize,
    plane_index: usize,
    texture_out: *mut CVMetalTextureRef,
  ) -> OSStatus;

  fn CVMetalTextureGetTexture(image: CVMetalTextureRef) -> *mut c_void;
}

/// The part of its texture `image` is drawn from: the part it asks for, within the picture's part of the
/// texture where its frames stay on the card and the picture is not all of it.
#[cfg(feature = "raster")]
fn drawn_part(
  cache: &std::collections::HashMap<u64, CachedImageTexture>,
  image: &crate::images::ImageCmd,
) -> ([f32; 2], [f32; 2]) {
  #[cfg(windows)]
  if let Some(CachedImageTexture::Card(opened)) = cache.get(&image.image_id) {
    return opened.part(image.uv_min, image.uv_max);
  }
  let _ = cache;
  (image.uv_min, image.uv_max)
}

#[cfg(feature = "raster")]
impl CachedImageTexture {
  /// Whether it is the textures of a frame that stays on the card, and `image` shows another frame now.
  #[cfg(any(target_os = "macos", target_os = "ios"))]
  fn is_another_frame_of_the_card(&self, image: &crate::images::ImageCmd) -> bool {
    match self {
      Self::Nv12 {
        _macos_native: Some(_),
        version,
        ..
      }
      | Self::CvRgba { version, .. } => *version != image.version,
      _ => false,
    }
  }

  fn is_compatible(&self, image: &crate::images::ImageCmd) -> bool {
    match self {
      Self::ExternalRgba { .. } => false,
      // Frames of a pixel buffer: the same frames while the picture is as large.
      #[cfg(any(target_os = "macos", target_os = "ios"))]
      Self::CvRgba { width, height, .. } => {
        *width == image.image_width
          && *height == image.image_height
          && image
            .native
            .as_ref()
            .is_some_and(|native| native.backend() == crate::images::NativeImageBackend::MacosCvPixelBufferNv12)
      }
      Self::Rgba {
        width,
        height,
        animation_frames,
        ..
      } => {
        image.image_format == crate::images::ImagePixelFormat::Rgba8
          && *width == image.image_width
          && *height == image.image_height
          && animation_frames.as_ref().map(Vec::len) == image.animation_frames.as_ref().map(|frames| frames.len())
          && !is_card_frames(image)
      }
      Self::I420 { width, height, .. } => {
        image.image_format == crate::images::ImagePixelFormat::I420
          && *width == image.image_width
          && *height == image.image_height
      }
      // Frames of memory are not frames of the card, though both are NV12.
      Self::Nv12 { width, height, .. } => {
        image.image_format == crate::images::ImagePixelFormat::Nv12
          && *width == image.image_width
          && *height == image.image_height
          && !is_card_frames(image)
      }
      #[cfg(windows)]
      Self::Card(opened) => {
        card_frames::of(image).is_some_and(|frames| opened.is_of(frames, (image.image_width, image.image_height)))
      }
    }
  }
}

/// Whether `image` is frames that stay on the card.
#[cfg(feature = "raster")]
fn is_card_frames(image: &crate::images::ImageCmd) -> bool {
  #[cfg(windows)]
  {
    image
      .native
      .as_ref()
      .is_some_and(|native| native.backend() == crate::images::NativeImageBackend::CardFrames)
  }
  #[cfg(not(windows))]
  {
    let _ = image;
    false
  }
}

pub struct WgpuRenderEngine {
  #[cfg(feature = "canvas")]
  canvases: Vec<crate::canvas::CanvasHandle>,
  #[cfg(feature = "canvas")]
  canvas_renderer: Option<canvas::Renderer>,
  #[cfg(feature = "canvas")]
  canvas_asset_budget: crate::canvas::CanvasAssetBudget,
  instance: Option<wgpu::Instance>,
  backends: wgpu::Backends,
  /// A device made ahead of the engine, which draws with it instead of asking for one; see [`WgpuDevice`]. Or
  /// the device of the app's other windows, which this shares.
  prepared: Option<WgpuDevice>,
  /// Whether the device is this engine's alone, and not the one the engines of the app's other windows share.
  own_device: bool,
  /// The window's physical pixels to one logical pixel, which the extensions are told.
  scale_factor: f32,
  /// The errors of the app's own calls on the device that no extension was told of yet.
  untold: app_errors::Untold,
  /// Whether the device is lost: the card was reset or taken away.
  lost: std::sync::Arc<std::sync::atomic::AtomicBool>,
  /// How many frames to let pass before a device that was not given is asked for again.
  device_wait: u32,
  /// The device's number in the order of devices and of the views apps give.
  device_number: u64,
  /// Whether the device is of another card than the one a device was lost on, which made none in time.
  displaced: bool,
  /// Whether the device was made while something held the lost one still: it is not a whole one.
  made_while_held: bool,
  /// When that card was last asked whether it makes a device again, and how long until it is asked next.
  #[cfg(not(target_arch = "wasm32"))]
  card_asked: Option<(std::time::Instant, std::time::Duration)>,
  /// Whether that card makes a device again: this engine is to be replaced by one that draws on it.
  card_is_back: bool,
  /// The slots whose views this drew: where the device is lost, their views are let go of.
  #[cfg(feature = "raster")]
  external_slots: Vec<crate::images::WgpuExternalImageWeak>,
  adapter: Option<wgpu::Adapter>,
  device: Option<wgpu::Device>,
  queue: Option<wgpu::Queue>,
  optional_device_features: wgpu::Features,
  optional_device_limits: wgpu::Limits,
  requested_present_mode: wgpu::PresentMode,
  quad_pipeline: Option<wgpu::RenderPipeline>,
  glyph_pipeline: Option<wgpu::RenderPipeline>,
  #[cfg(feature = "raster")]
  image_pipeline: Option<wgpu::RenderPipeline>,
  #[cfg(feature = "raster")]
  nv12_image_pipeline: Option<wgpu::RenderPipeline>,
  /// Pictures of three planes (I420): the NV12 shader with the two of color apart.
  #[cfg(feature = "raster")]
  i420_image_pipeline: Option<wgpu::RenderPipeline>,
  surface: Option<wgpu::Surface<'static>>,
  surface_config: Option<wgpu::SurfaceConfiguration>,
  surface_format: Option<wgpu::TextureFormat>,
  quad_bgl: Option<wgpu::BindGroupLayout>,
  glyph_bgl: Option<wgpu::BindGroupLayout>,
  #[cfg(feature = "raster")]
  image_bgl: Option<wgpu::BindGroupLayout>,
  #[cfg(feature = "raster")]
  nv12_image_bgl: Option<wgpu::BindGroupLayout>,
  #[cfg(feature = "raster")]
  i420_image_bgl: Option<wgpu::BindGroupLayout>,
  #[cfg(feature = "raster")]
  image_sampler: Option<wgpu::Sampler>,
  #[cfg(feature = "raster")]
  image_texture_cache: std::collections::HashMap<u64, CachedImageTexture>,
  /// The textures of the frames of a video that were drawn in the frame before: let go once this one is drawn.
  #[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
  retired_card_frames: Vec<CachedImageTexture>,
  /// The leases of the card's frames that are drawn no more, until the card has finished with them.
  #[cfg(all(feature = "raster", windows))]
  card_leases: card_frames::Leases,
  /// A device on each of the machine's cards, for frames the renderer's own card does not open.
  #[cfg(all(feature = "raster", windows))]
  card_readers: card_copies::Readers,
  #[cfg(feature = "raster")]
  image_clip_bind_groups: std::collections::HashMap<ImageClipBindGroupKey, wgpu::BindGroup>,
  globals_buffer: Option<wgpu::Buffer>,
  clip_globals: ClipGlobalsCache,
  quad_clip_bind_groups: std::collections::HashMap<ClipGlobalsKey, wgpu::BindGroup>,
  glyph_clip_bind_groups: std::collections::HashMap<ClipGlobalsKey, wgpu::BindGroup>,
  gradients: Option<gradients::Gradients>,
  last_globals_bytes: Vec<u8>,
  last_gradient_bytes: Vec<u8>,
  atlas_texture: Option<wgpu::Texture>,
  atlas_view: Option<wgpu::TextureView>,
  atlas_sampler: Option<wgpu::Sampler>,
  atlas_size: (u32, u32),
  atlas_version: u64,
  #[cfg(feature = "perf_profile")]
  last_profile: RenderProfile,
  #[cfg(feature = "perf_profile")]
  last_layer_profile: crate::app::profile_types::LayerProfile,
  #[cfg(feature = "perf_profile")]
  profile_context: Option<crate::app::profiler::ProfileContext>,
  /// GPU time of frames rendered while a profiling session is active.
  #[cfg(feature = "perf_profile")]
  gpu_timer: gpu_timing::GpuTimer,
  quad_bind_group: Option<wgpu::BindGroup>,
  glyph_bind_group: Option<wgpu::BindGroup>,
  vertex_buffer: Option<wgpu::Buffer>,
  index_buffer: Option<wgpu::Buffer>,
  rect_instance_buffer: DynamicBuffer,
  glyph_instance_buffer: DynamicBuffer,
  #[cfg(feature = "raster")]
  image_instance_buffer: DynamicBuffer,
  scratch_rect_instances: Vec<QuadInstance>,
  scratch_rect_draws: Vec<PreparedDraw>,
  scratch_gradient_data: Vec<[f32; 4]>,
  scratch_glyph_instances: Vec<GlyphInstance>,
  #[cfg(feature = "raster")]
  scratch_image_instances: Vec<ImageInstance>,
  scratch_ordered_draws: Vec<(usize, OrderedDraw)>,
  layer_plan: LayerPlan,
  /// Offscreen targets of faded subtrees; created by the first frame that
  /// has one.
  layer_compositor: Option<layers::LayerCompositor>,
  scratch_layer_slots: Vec<Option<usize>>,
  scratch_blur_slots: Vec<Option<layers::BlurSlots>>,
  scratch_backdrop_slots: Vec<Option<layers::BackdropSlots>>,
  scratch_backdrop_regions: Vec<Option<BackdropRegion>>,
  /// What each backdrop blur of the frame reads, to tell whether its kept
  /// result is still the blur of it.
  backdrop_inputs: BackdropInputs,
  layer_blur_inputs: LayerBlurInputs,
  width: u32,
  height: u32,
  frame_extensions: Vec<WgpuFrameExtensionEntry>,
  /// Whether the surface's texture can be copied from; `false` on WebGL.
  surface_copies: bool,
  /// A test draws as on such a surface; see `without_surface_copies`.
  #[cfg(test)]
  deny_surface_copies: bool,
  /// What a frame that is read back is painted into where it cannot; see `surface_proxy`.
  surface_proxy: Option<surface_proxy::SurfaceProxy>,
  #[cfg(feature = "screenshot")]
  pending_frame_capture: Option<RenderFrameCapture>,
}

fn default_backends() -> WgpuBackends {
  #[cfg(windows)]
  {
    WgpuBackends::DX12
  }
  #[cfg(not(windows))]
  {
    WgpuBackends::all()
  }
}

fn instance_descriptor(backends: WgpuBackends) -> wgpu::InstanceDescriptor {
  let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
  descriptor.backends = backends;
  // lurq waits for the frame latency object itself; see `wait_for_frame_latency`.
  descriptor.backend_options.dx12.latency_waitable_object = wgpu::Dx12UseFrameLatencyWaitableObject::DontWait;
  descriptor
}

/// The instances of wgpu the program has, by the backends each was made among.
#[cfg(not(target_arch = "wasm32"))]
static INSTANCES: std::sync::Mutex<Vec<(WgpuBackends, wgpu::Instance)>> = std::sync::Mutex::new(Vec::new());

/// The instance of wgpu among `backends`: one for the program, which every engine and every device made
/// ahead shares.
///
/// Each engine had its own, and so each window. Under Vulkan a program with two of them alive ended with an
/// access violation when one was let go of, on the card this was run on, each time it was tried; one
/// instance with a device for each window does not. Under Direct3D 12 either way holds.
#[cfg(not(target_arch = "wasm32"))]
fn new_instance(backends: WgpuBackends) -> wgpu::Instance {
  let mut instances = INSTANCES.lock().unwrap();
  if let Some((_, instance)) = instances.iter().find(|(among, _)| *among == backends) {
    return instance.clone();
  }
  let instance = wgpu::Instance::new(instance_descriptor(backends));
  instances.push((backends, instance.clone()));
  instance
}

/// After a device is lost, an instance of Direct3D 12 alone is made anew for what takes the device's place,
/// as it was before the instance was shared: what it knows of the cards is from before the loss. One that
/// may draw through Vulkan is kept, for a second one beside it is what ends the program there.
#[cfg(not(target_arch = "wasm32"))]
fn forget_instances_after_a_loss() {
  INSTANCES
    .lock()
    .unwrap()
    .retain(|(among, _)| among.contains(WgpuBackends::VULKAN));
}

#[cfg(target_arch = "wasm32")]
fn new_instance(backends: WgpuBackends) -> wgpu::Instance {
  wgpu::Instance::new(instance_descriptor(backends))
}

/// The instance of a page. Whether a browser has WebGPU is known only once it was asked for an adapter, and an
/// instance is of one kind from the start: with the `webgl` feature the browser is asked first, and the instance
/// is WebGL's when it has no WebGPU.
#[cfg(target_arch = "wasm32")]
async fn new_page_instance(backends: WgpuBackends) -> wgpu::Instance {
  #[cfg(feature = "webgl")]
  return wgpu::util::new_instance_with_webgpu_detection(instance_descriptor(backends)).await;
  #[cfg(not(feature = "webgl"))]
  new_instance(backends)
}

/// The device an engine asks `adapter` for: the optional features and limits as far as the adapter has them.
fn device_descriptor(
  adapter: &wgpu::Adapter,
  optional_features: wgpu::Features,
  optional_limits: &wgpu::Limits,
) -> wgpu::DeviceDescriptor<'static> {
  // A frame of a video that stays on the card is an NV12 texture, where the card has them.
  #[cfg(all(windows, feature = "raster"))]
  let optional_features = optional_features
    | wgpu::Features::TEXTURE_FORMAT_NV12
    // Under Vulkan such a frame is a texture of Direct3D given to it by its handle.
    | wgpu::Features::VULKAN_EXTERNAL_MEMORY_WIN32;
  // A frame of ten bits that stays on the card is two planes of 16-bit unorm.
  #[cfg(all(any(target_os = "macos", target_os = "ios"), feature = "raster"))]
  let optional_features = optional_features | wgpu::Features::TEXTURE_FORMAT_16BIT_NORM;
  #[cfg_attr(not(feature = "perf_profile"), allow(unused_mut))]
  let mut required_features = adapter.features() & optional_features;
  // Measures GPU time while a profiling session is active.
  #[cfg(feature = "perf_profile")]
  {
    required_features |= gpu_timing::GpuTimer::requested_features(adapter);
  }
  wgpu::DeviceDescriptor {
    label: Some("lurq"),
    required_features,
    required_limits: optional_limits.clone().or_worse_values_from(&adapter.limits()),
    ..Default::default()
  }
}

/// How long after an engine went to another card the card a device was lost on is first asked whether it
/// makes a device again, and the longest between two such questions: each takes the time of making a device.
#[cfg(not(target_arch = "wasm32"))]
const CARD_ASKED_FIRST: std::time::Duration = std::time::Duration::from_secs(3);
#[cfg(not(target_arch = "wasm32"))]
const CARD_ASKED_AT_MOST: std::time::Duration = std::time::Duration::from_secs(60);

/// A GPU device made ahead of the engine that draws with it.
///
/// An engine asks for its device when it draws the first frame and waits for
/// the answer. A browser answers through a promise, which a page cannot wait
/// for: there the app awaits [`WgpuDevice::request`] before it starts its
/// window, and gives the device to each engine with
/// [`WgpuRenderEngine::with_device`]. Elsewhere this is optional: it moves
/// the wait off the first frame.
///
/// In a browser the device is the one of the page's canvas, the canvas the
/// window then draws to: WebGPU's where the browser has it, and with the
/// `webgl` feature WebGL2's where it has not. [`WgpuDevice::backend`] says
/// which.
///
/// A device that is lost (its card was reset or taken away) is made again, once for all the engines that
/// share it: the engine that takes the place of a lost one asks this for its device, and is given another.
/// Not in a browser, where a device is not waited for.
///
/// ```no_run
/// # async fn start() {
/// use lurq::app::{
///   Tree,
///   wgpu_render::{WgpuDevice, WgpuRenderEngine},
/// };
///
/// let device = WgpuDevice::request().await.expect("a GPU device");
/// let mut tree = Tree::new();
/// tree.set_render_engine_factory(move || Box::new(WgpuRenderEngine::new().with_device(device.clone())));
/// # }
/// ```
#[derive(Clone)]
pub struct WgpuDevice {
  /// The device as it is now: another one after a loss, and none while the card gives none.
  made: std::sync::Arc<parking_lot::Mutex<Option<MadeDevice>>>,
  /// Whether the card the device was lost on makes a device again, as an engine on another card found: the
  /// device of the other card is let go of for one of that card.
  back: std::sync::Arc<std::sync::atomic::AtomicBool>,
  /// Among which the device was asked for, and is asked for again, with these features where the card has them
  /// and these limits.
  backends: WgpuBackends,
  features: wgpu::Features,
  limits: wgpu::Limits,
  backend: WgpuBackend,
  /// The surface of the page's canvas, which the adapter was asked for, until the engine that draws to the
  /// canvas takes it.
  #[cfg(target_arch = "wasm32")]
  surface: std::rc::Rc<std::cell::RefCell<Option<wgpu::Surface<'static>>>>,
}

/// The number of a device that was just made, in the order of devices and of the views apps give: a view
/// given before the device was made is not of it.
fn device_number() -> u64 {
  #[cfg(feature = "raster")]
  {
    crate::images::next_in_order()
  }
  #[cfg(not(feature = "raster"))]
  {
    0
  }
}

/// A device with what it was made of, and what says that it is lost.
#[derive(Clone)]
struct MadeDevice {
  instance: wgpu::Instance,
  adapter: wgpu::Adapter,
  device: wgpu::Device,
  queue: wgpu::Queue,
  lost: std::sync::Arc<std::sync::atomic::AtomicBool>,
  /// The device's number in the order of devices and of the views apps give.
  number: u64,
  /// Whether it is of another card than the one a device was lost on, which made none in time.
  displaced: bool,
  /// Whether it was made while something held the lost device still: it is not a whole one.
  while_held: bool,
  /// The errors of the app's own calls on it that no extension was told of yet.
  untold: app_errors::Untold,
}

/// Why [`WgpuDevice::request`] has no device: no adapter (a browser without WebGPU), or one that refused the device.
#[derive(Clone, Debug)]
pub struct WgpuDeviceError(String);

impl std::fmt::Display for WgpuDeviceError {
  fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    formatter.write_str(&self.0)
  }
}

impl std::error::Error for WgpuDeviceError {}

impl WgpuDevice {
  /// Asks for a device as an engine does for its first frame, with the default backends, features and limits.
  pub async fn request() -> Result<Self, WgpuDeviceError> {
    Self::request_with(default_backends()).await
  }

  /// [`Self::request`] among `backends` only. In a browser, `WgpuBackends::GL` asks for WebGL2 also where there
  /// is WebGPU, and `WgpuBackends::BROWSER_WEBGPU` for WebGPU alone.
  pub async fn request_with(backends: WgpuBackends) -> Result<Self, WgpuDeviceError> {
    let (features, limits) = (wgpu::Features::empty(), wgpu::Limits::default());
    #[cfg(not(target_arch = "wasm32"))]
    let made = Self::ask(backends, features, &limits).await?;
    #[cfg(target_arch = "wasm32")]
    let (made, surface) = Self::ask(backends).await?;
    Ok(Self {
      backend: made.adapter.get_info().backend,
      // In a browser nothing of wgpu's goes to another thread, and this is shared as on any system.
      #[allow(clippy::arc_with_non_send_sync)]
      made: std::sync::Arc::new(parking_lot::Mutex::new(Some(made))),
      back: std::sync::Arc::default(),
      backends,
      features,
      limits,
      #[cfg(target_arch = "wasm32")]
      surface: std::rc::Rc::new(std::cell::RefCell::new(Some(surface))),
    })
  }

  /// The device an engine made for itself, to be shared with the engines of the app's other windows.
  #[cfg(not(target_arch = "wasm32"))]
  fn of_engine(made: MadeDevice, backends: WgpuBackends, features: wgpu::Features, limits: wgpu::Limits) -> Self {
    Self {
      backend: made.adapter.get_info().backend,
      made: std::sync::Arc::new(parking_lot::Mutex::new(Some(made))),
      back: std::sync::Arc::default(),
      backends,
      features,
      limits,
    }
  }

  /// Asks for an adapter among `backends` and its device, as an engine does for its first frame.
  #[cfg(not(target_arch = "wasm32"))]
  async fn ask(
    backends: WgpuBackends,
    features: wgpu::Features,
    limits: &wgpu::Limits,
  ) -> Result<MadeDevice, WgpuDeviceError> {
    let instance = new_instance(backends);
    // After a loss, the card the device was lost on is asked first, and waited for a little.
    let describe = |adapter: &wgpu::Adapter| device_descriptor(adapter, features, limits);
    let (adapter, device, queue, displaced, while_held) =
      match device_loss::the_card_again(&instance, None, describe).await {
        device_loss::Again::Card(adapter, device, queue, held) => (adapter, device, queue, false, held),
        device_loss::Again::Wait => {
          return Err(WgpuDeviceError(
            "the card a device was lost on makes none yet".to_owned(),
          ));
        }
        device_loss::Again::Elsewhere(adapter, device, queue) => (adapter, device, queue, true, false),
        device_loss::Again::Unasked => {
          let (adapter, device, queue) = Self::ask_of(&instance, None, features, limits).await?;
          (adapter, device, queue, false, false)
        }
      };
    let lost = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let untold = app_errors::Untold::default();
    // Where it is lost, the engines that draw with it are replaced, and are given another.
    device_loss::watch(&device, &lost, &adapter, &untold);
    Ok(MadeDevice {
      instance,
      adapter,
      device,
      queue,
      lost,
      number: device_number(),
      displaced,
      while_held,
      untold,
    })
  }

  /// Asks for an adapter among `backends` for the page's canvas, and its device.
  #[cfg(target_arch = "wasm32")]
  async fn ask(backends: WgpuBackends) -> Result<(MadeDevice, wgpu::Surface<'static>), WgpuDeviceError> {
    // WebGL gives a device for a canvas, so the page's canvas is there before the device is.
    #[cfg(target_arch = "wasm32")]
    let (instance, surface) = {
      let instance = new_page_instance(backends).await;
      let canvas = crate::app::web_canvas::page_canvas()
        .ok_or_else(|| WgpuDeviceError("the page has no document to put a canvas in".to_owned()))?;
      // The handles are given as a window's are: wgpu's own implementation takes no canvas without a display
      // handle, which `SurfaceTarget::Canvas` leaves out. The surface keeps its own reference to the canvas.
      let value: &wasm_bindgen::JsValue = &canvas;
      let window = raw_window_handle::WebCanvasWindowHandle::new(std::ptr::NonNull::from(value).cast());
      let display = raw_window_handle::WebDisplayHandle::new();
      let surface = unsafe {
        instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {
          raw_display_handle: Some(display.into()),
          raw_window_handle: window.into(),
        })
      }
      .map_err(|error| WgpuDeviceError(format!("the page's canvas cannot be drawn to: {error}")))?;
      (instance, surface)
    };
    let (adapter, device, queue) = Self::ask_of(
      &instance,
      Some(&surface),
      wgpu::Features::empty(),
      &wgpu::Limits::default(),
    )
    .await?;
    let lost = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let untold = app_errors::Untold::default();
    // A device lost here is not made again; what the app does wrong on it ends nothing.
    device_loss::watch(&device, &lost, &adapter, &untold);
    let made = MadeDevice {
      instance,
      adapter,
      device,
      queue,
      lost,
      number: device_number(),
      displaced: false,
      while_held: false,
      untold,
    };
    Ok((made, surface))
  }

  /// The adapter of `instance` that draws to `surface`, or any where there is none to draw to yet, and its
  /// device.
  async fn ask_of(
    instance: &wgpu::Instance,
    surface: Option<&wgpu::Surface<'static>>,
    features: wgpu::Features,
    limits: &wgpu::Limits,
  ) -> Result<(wgpu::Adapter, wgpu::Device, wgpu::Queue), WgpuDeviceError> {
    let adapter = instance
      .request_adapter(&wgpu::RequestAdapterOptions {
        power_preference: wgpu::PowerPreference::default(),
        compatible_surface: surface,
        force_fallback_adapter: false,
      })
      .await
      .map_err(|error| WgpuDeviceError(format!("no suitable GPU adapter found: {error}")))?;
    let (device, queue) = adapter
      .request_device(&device_descriptor(&adapter, features, limits))
      .await
      .map_err(|error| WgpuDeviceError(format!("failed to create device: {error}")))?;
    Ok((adapter, device, queue))
  }

  /// The device as it is now. One that is lost is let go of and another asked for, once for all that share
  /// this; `None` while the card gives none, as Direct3D says it does not while anything holds the lost one.
  /// One of another card, taken because the first card made none in time, is let go of the same way once
  /// an engine found that the first card makes a device again.
  fn current(&self) -> Option<MadeDevice> {
    #[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
    let mut made = self.made.lock();
    #[cfg(not(target_arch = "wasm32"))]
    {
      let back = self.back.swap(false, std::sync::atomic::Ordering::AcqRel);
      if made.as_ref().is_some_and(|made| {
        device_loss::is_lost(&made.device, &made.lost) || (back && (made.displaced || made.while_held))
      }) {
        *made = None;
      }
      if made.is_none() {
        *made = pollster::block_on(Self::ask(self.backends, self.features, &self.limits)).ok();
      }
    }
    made.clone()
  }

  /// What the device draws through: `WgpuBackend::BrowserWebGpu` or `WgpuBackend::Gl` in a browser.
  pub fn backend(&self) -> WgpuBackend {
    self.backend
  }
}

/// A device the engines of an app's windows share: one an engine on the thread that draws them asked for itself,
/// as long as one of them draws with it.
#[cfg(not(target_arch = "wasm32"))]
struct SharedDevice {
  backends: WgpuBackends,
  features: wgpu::Features,
  limits: wgpu::Limits,
  backend: WgpuBackend,
  made: std::sync::Weak<parking_lot::Mutex<Option<MadeDevice>>>,
  back: std::sync::Weak<std::sync::atomic::AtomicBool>,
}

#[cfg(not(target_arch = "wasm32"))]
thread_local! {
  /// The devices the engines on this thread share, by what they were asked for with.
  static SHARED_DEVICES: std::cell::RefCell<Vec<SharedDevice>> = const { std::cell::RefCell::new(Vec::new()) };
}

#[cfg(not(target_arch = "wasm32"))]
impl WgpuDevice {
  /// The device another engine on this thread draws with, asked for among `backends` with `features` and
  /// `limits`, while one does.
  fn shared(backends: WgpuBackends, features: wgpu::Features, limits: &wgpu::Limits) -> Option<Self> {
    SHARED_DEVICES.with_borrow_mut(|shared| {
      shared.retain(|device| device.made.strong_count() > 0);
      let device = shared
        .iter()
        .find(|device| device.backends == backends && device.features == features && device.limits == *limits)?;
      Some(Self {
        made: device.made.upgrade()?,
        back: device.back.upgrade()?,
        backends,
        features,
        limits: limits.clone(),
        backend: device.backend,
      })
    })
  }

  /// Offers this device to the engines made on this thread after it, while one draws with it.
  fn share(&self) {
    SHARED_DEVICES.with_borrow_mut(|shared| {
      shared.push(SharedDevice {
        backends: self.backends,
        features: self.features,
        limits: self.limits.clone(),
        backend: self.backend,
        made: std::sync::Arc::downgrade(&self.made),
        back: std::sync::Arc::downgrade(&self.back),
      })
    });
  }
}

/// Runs `call` on an extension as the app's: as the engine of the device numbered `number` (a view it gives a slot
/// is of that device), and in error scopes of `device` where there is one that lives, whose errors the extension
/// is told of after the call.
fn run_extension(
  entry: &mut WgpuFrameExtensionEntry,
  device: Option<&wgpu::Device>,
  untold: &app_errors::Untold,
  number: u64,
  call: impl FnOnce(&mut dyn WgpuFrameExtension),
) {
  let extension = &mut *entry.extension;
  #[cfg(feature = "raster")]
  let within = |run: &mut dyn FnMut()| crate::images::for_device(number, run);
  #[cfg(not(feature = "raster"))]
  let within = |run: &mut dyn FnMut()| {
    let _ = number;
    run()
  };
  let mut call = Some(call);
  let mut run = || {
    if let Some(call) = call.take() {
      call(&mut *extension)
    }
  };
  let errors = match device {
    Some(device) => app_errors::caught(device, untold, || within(&mut run)).1,
    None => {
      app_errors::apps(|| within(&mut run));
      Vec::new()
    }
  };
  for error in &errors {
    app_errors::apps(|| entry.extension.error(error));
  }
}

impl Default for WgpuRenderEngine {
  fn default() -> Self {
    WgpuRenderEngine::new()
  }
}

impl WgpuRenderEngine {
  pub fn new() -> Self {
    Self {
      #[cfg(feature = "canvas")]
      canvases: Vec::new(),
      #[cfg(feature = "canvas")]
      canvas_renderer: None,
      #[cfg(feature = "canvas")]
      canvas_asset_budget: Default::default(),
      instance: None,
      backends: default_backends(),
      prepared: None,
      own_device: false,
      scale_factor: 1.0,
      untold: app_errors::Untold::default(),
      lost: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
      device_wait: 0,
      device_number: 0,
      displaced: false,
      made_while_held: false,
      #[cfg(not(target_arch = "wasm32"))]
      card_asked: None,
      card_is_back: false,
      #[cfg(feature = "raster")]
      external_slots: Vec::new(),
      adapter: None,
      device: None,
      queue: None,
      optional_device_features: wgpu::Features::empty(),
      optional_device_limits: wgpu::Limits::default(),
      requested_present_mode: wgpu::PresentMode::Fifo,
      quad_pipeline: None,
      glyph_pipeline: None,
      #[cfg(feature = "raster")]
      image_pipeline: None,
      #[cfg(feature = "raster")]
      nv12_image_pipeline: None,
      #[cfg(feature = "raster")]
      i420_image_pipeline: None,
      surface: None,
      surface_config: None,
      surface_format: None,
      quad_bgl: None,
      glyph_bgl: None,
      #[cfg(feature = "raster")]
      image_bgl: None,
      #[cfg(feature = "raster")]
      nv12_image_bgl: None,
      #[cfg(feature = "raster")]
      i420_image_bgl: None,
      #[cfg(feature = "raster")]
      image_sampler: None,
      #[cfg(feature = "raster")]
      image_texture_cache: std::collections::HashMap::new(),
      #[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
      retired_card_frames: Vec::new(),
      #[cfg(all(feature = "raster", windows))]
      card_leases: card_frames::Leases::default(),
      #[cfg(all(feature = "raster", windows))]
      card_readers: card_copies::Readers::default(),
      #[cfg(feature = "raster")]
      image_clip_bind_groups: std::collections::HashMap::new(),
      globals_buffer: None,
      clip_globals: ClipGlobalsCache::default(),
      quad_clip_bind_groups: std::collections::HashMap::new(),
      glyph_clip_bind_groups: std::collections::HashMap::new(),
      gradients: None,
      last_globals_bytes: Vec::new(),
      last_gradient_bytes: Vec::new(),
      atlas_texture: None,
      atlas_view: None,
      atlas_sampler: None,
      atlas_size: (0, 0),
      atlas_version: 0,
      #[cfg(feature = "perf_profile")]
      last_profile: RenderProfile::default(),
      #[cfg(feature = "perf_profile")]
      last_layer_profile: Default::default(),
      #[cfg(feature = "perf_profile")]
      profile_context: None,
      #[cfg(feature = "perf_profile")]
      gpu_timer: gpu_timing::GpuTimer::new(),
      quad_bind_group: None,
      glyph_bind_group: None,
      vertex_buffer: None,
      index_buffer: None,
      rect_instance_buffer: DynamicBuffer::new("lurq_ordered_rect_instances", wgpu::BufferUsages::VERTEX),
      glyph_instance_buffer: DynamicBuffer::new("lurq_ordered_glyph_instances", wgpu::BufferUsages::VERTEX),
      #[cfg(feature = "raster")]
      image_instance_buffer: DynamicBuffer::new("lurq_image_instances", wgpu::BufferUsages::VERTEX),
      scratch_rect_instances: Vec::new(),
      scratch_rect_draws: Vec::new(),
      scratch_gradient_data: Vec::new(),
      scratch_glyph_instances: Vec::new(),
      #[cfg(feature = "raster")]
      scratch_image_instances: Vec::new(),
      scratch_ordered_draws: Vec::new(),
      layer_plan: LayerPlan::default(),
      layer_compositor: None,
      scratch_layer_slots: Vec::new(),
      scratch_blur_slots: Vec::new(),
      scratch_backdrop_slots: Vec::new(),
      scratch_backdrop_regions: Vec::new(),
      backdrop_inputs: BackdropInputs::default(),
      layer_blur_inputs: LayerBlurInputs::default(),
      width: 800,
      height: 600,
      frame_extensions: Vec::new(),
      surface_copies: true,
      #[cfg(test)]
      deny_surface_copies: false,
      surface_proxy: None,
      #[cfg(feature = "screenshot")]
      pending_frame_capture: None,
    }
  }

  /// Opacity-layer textures the engine keeps pooled.
  #[cfg(all(test, feature = "screenshot"))]
  pub(crate) fn layer_texture_count(&self) -> usize {
    self
      .layer_compositor
      .as_ref()
      .map_or(0, layers::LayerCompositor::texture_count)
  }

  /// Backdrop blurs the last frame put back from a kept texture, then the
  /// textures kept.
  #[cfg(all(test, feature = "screenshot"))]
  pub(crate) fn backdrop_reuse(&self) -> (usize, usize) {
    self.layer_compositor.as_ref().map_or((0, 0), |compositor| {
      let (reused, kept, _) = compositor.backdrop_stats();
      (reused, kept)
    })
  }

  /// Select backends before rendering the first frame. Instance creation is lazy,
  /// so excluded backend loaders are never initialized by this engine.
  ///
  /// Windows defaults to DX12: independent Vulkan instances can race in the
  /// platform loader during concurrent window teardown. Other platforms retain
  /// wgpu's full backend selection. Vulkan remains an explicit opt-in on Windows.
  /// Panics if this engine has already initialized a GPU instance.
  pub fn with_backends(mut self, backends: WgpuBackends) -> Self {
    assert!(self.instance.is_none(), "select WGPU backends before rendering");
    self.backends = backends;
    self
  }

  /// Draws with a device made ahead ([`WgpuDevice::request`]) instead of
  /// asking for one at the first frame: what a browser needs, where the
  /// engine cannot wait for the device. The backends, optional features and
  /// limits are then the device's, not this engine's.
  /// Panics if this engine has already initialized a GPU instance.
  pub fn with_device(mut self, device: WgpuDevice) -> Self {
    assert!(self.instance.is_none(), "give the WGPU device before rendering");
    self.prepared = Some(device);
    self
  }

  /// Draws as on a surface whose texture cannot be copied from, as WebGL's: a frame that is read back is
  /// painted beside the surface.
  #[cfg(all(test, feature = "screenshot"))]
  pub(crate) fn without_surface_copies(mut self) -> Self {
    self.deny_surface_copies = true;
    self
  }

  /// Draws with a device of this engine's own, where it would share the one the engines of the app's other windows
  /// draw with. An engine made without [`with_device`](Self::with_device) takes the device of another engine on
  /// its thread that was asked for among the same backends with the same optional features and limits, while one
  /// draws with it, and asks for one otherwise: so a view of one device can be shown in every window of the app.
  /// A device of its own is for a window that must not wait on the others' work, or that draws on another card.
  /// In a browser there is one window and its device is given.
  pub fn with_own_device(mut self) -> Self {
    self.own_device = true;
    self
  }

  pub fn with_frame_extension(mut self, extension: impl WgpuFrameExtension + 'static) -> Self {
    self.add_frame_extension(extension);
    self
  }

  pub fn with_optional_device_features(mut self, features: WgpuFeatures) -> Self {
    self.optional_device_features |= features;
    self
  }

  pub fn with_optional_device_limits(mut self, limits: WgpuLimits) -> Self {
    self.optional_device_limits = limits;
    self
  }

  pub fn with_present_mode(mut self, present_mode: WgpuPresentMode) -> Self {
    self.requested_present_mode = present_mode;
    self
  }

  /// How many charged bytes of uploaded Canvas images and text this renderer
  /// keeps between frames; 64 MiB by default. See [`CanvasAssetBudget`] for
  /// how a frame that needs more is handled.
  ///
  /// [`CanvasAssetBudget`]: crate::canvas::CanvasAssetBudget
  #[cfg(feature = "canvas")]
  pub fn with_canvas_asset_budget(mut self, budget: crate::canvas::CanvasAssetBudget) -> Self {
    self.canvas_asset_budget = budget;
    self
  }

  pub fn add_frame_extension(&mut self, extension: impl WgpuFrameExtension + 'static) {
    self
      .frame_extensions
      .push(WgpuFrameExtensionEntry::new(Box::new(extension)));
  }

  fn shared_context(&self) -> Option<SharedWgpuContext> {
    Some(SharedWgpuContext {
      instance: self.instance.clone()?,
      adapter: self.adapter.clone()?,
      device: self.device.clone()?,
      queue: self.queue.clone()?,
      surface_format: self.surface_format?,
      number: self.device_number,
    })
  }

  fn prepare_frame_extensions(&mut self, list: &RenderList) {
    if self.frame_extensions.is_empty() {
      return;
    }
    let Some(gpu) = self.shared_context() else {
      return;
    };
    let frame = WgpuFrameInfo::new(list, self.width, self.height, self.scale_factor);
    // What the app did wrong on the device outside the extensions' calls since the last frame.
    let untold = self.untold.take();
    for entry in &mut self.frame_extensions {
      if !entry.initialized {
        run_extension(
          entry,
          Some(&gpu.device),
          &self.untold,
          self.device_number,
          |extension| extension.initialize(&gpu),
        );
        entry.initialized = true;
      }
      for error in &untold {
        app_errors::apps(|| entry.extension.error(error));
      }
      run_extension(
        entry,
        Some(&gpu.device),
        &self.untold,
        self.device_number,
        |extension| extension.prepare(&gpu, frame),
      );
    }
  }

  /// Tells each extension that was initialized that its device is lost, once, and lets go of the views of
  /// that device in the slots this drew: an extension that was told lets go of what it made, and what it
  /// left in a slot is held by nothing of the app's.
  fn tell_extensions_of_loss(&mut self) {
    for entry in &mut self.frame_extensions {
      if entry.initialized && !entry.told_lost {
        entry.told_lost = true;
        // Nothing is asked of a device that is lost: no scope is pushed on it.
        run_extension(entry, None, &self.untold, self.device_number, |extension| {
          extension.device_lost()
        });
      }
    }
    #[cfg(feature = "raster")]
    for slot in self.external_slots.drain(..) {
      if let Some(slot) = slot.upgrade() {
        slot.forget_view_of(self.device_number);
      }
    }
  }

  fn release_gpu_resources(&mut self) {
    if let Some(device) = &self.device {
      device_loss::asked(device, Some(&self.lost), wgpu::PollType::Poll);
    }

    // An engine whose device is lost is let go of before it draws again: its extensions are told here.
    let lost = self.device_is_lost();
    if lost {
      self.tell_extensions_of_loss();
    }
    let device = self.device.clone().filter(|_| !lost);
    for entry in &mut self.frame_extensions {
      if entry.initialized {
        run_extension(entry, device.as_ref(), &self.untold, self.device_number, |extension| {
          extension.shutdown()
        });
        entry.initialized = false;
      }
    }

    #[cfg(feature = "raster")]
    {
      self.image_texture_cache.clear();
      self.image_clip_bind_groups.clear();
    }
    self.clip_globals.clear();
    self.quad_clip_bind_groups.clear();
    self.glyph_clip_bind_groups.clear();

    self.quad_bind_group = None;
    self.glyph_bind_group = None;
    self.layer_compositor = None;
    #[cfg(feature = "raster")]
    {
      self.image_sampler = None;
      self.image_bgl = None;
      self.nv12_image_bgl = None;
      self.i420_image_bgl = None;
      self.image_pipeline = None;
      self.nv12_image_pipeline = None;
      self.i420_image_pipeline = None;
    }

    self.vertex_buffer = None;
    self.index_buffer = None;
    self.rect_instance_buffer.clear();
    self.glyph_instance_buffer.clear();
    #[cfg(feature = "raster")]
    self.image_instance_buffer.clear();
    self.globals_buffer = None;
    self.gradients = None;
    self.surface_proxy = None;
    self.last_globals_bytes.clear();
    self.last_gradient_bytes.clear();
    self.atlas_view = None;
    self.atlas_texture = None;
    self.atlas_sampler = None;

    self.quad_pipeline = None;
    self.glyph_pipeline = None;
    self.quad_bgl = None;
    self.glyph_bgl = None;

    self.surface_config = None;
    self.surface = None;
    self.surface_format = None;
    #[cfg(feature = "canvas")]
    {
      self.canvas_renderer = None;
    }
    #[cfg(feature = "perf_profile")]
    self.gpu_timer.release();
    self.queue = None;
    self.device = None;
    self.adapter = None;
  }

  fn create_surface(&self, window: WindowHandle<'_>, display: DisplayHandle<'_>) -> wgpu::Surface<'static> {
    // The page's canvas has its surface since the device was asked for.
    #[cfg(target_arch = "wasm32")]
    if let Some(surface) = self
      .prepared
      .as_ref()
      .and_then(|prepared| prepared.surface.borrow_mut().take())
    {
      return surface;
    }
    let handles = WindowDisplayPair { window, display };
    let surface_target = unsafe { wgpu::SurfaceTargetUnsafe::from_display_and_window(&handles, &handles) }.unwrap();
    unsafe { self.instance.as_ref().unwrap().create_surface_unsafe(surface_target) }.unwrap()
  }

  fn configure_surface(
    &mut self,
    surface: wgpu::Surface<'static>,
    adapter: &wgpu::Adapter,
    device: &wgpu::Device,
  ) -> wgpu::TextureFormat {
    let caps = surface.get_capabilities(adapter);
    let format = self
      .surface_format
      .filter(|format| caps.formats.contains(format))
      .or_else(|| caps.formats.iter().copied().find(|format| !format.is_srgb()))
      .unwrap_or(caps.formats[0]);
    let target_format = render_target_format(format);

    // A backdrop blur and a capture copy the frame out of the surface's texture, where that can be copied
    // from. WebGL's cannot: there a frame that is read is painted beside the surface; see `surface_proxy`.
    self.surface_copies = caps.usages.contains(wgpu::TextureUsages::COPY_SRC);
    #[cfg(test)]
    if self.deny_surface_copies {
      self.surface_copies = false;
    }
    let config = wgpu::SurfaceConfiguration {
      usage: if self.surface_copies {
        wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC
      } else {
        wgpu::TextureUsages::RENDER_ATTACHMENT
      },
      format,
      width: self.width.max(1),
      height: self.height.max(1),
      present_mode: supported_present_mode(self.requested_present_mode, &caps.present_modes),
      alpha_mode: caps.alpha_modes[0],
      view_formats: if target_format == format {
        vec![]
      } else {
        vec![target_format]
      },
      desired_maximum_frame_latency: SURFACE_FRAME_LATENCY,
    };
    surface.configure(device, &config);
    self.surface = Some(surface);
    self.surface_config = Some(config);
    self.surface_format = Some(format);
    target_format
  }

  /// Whether the next `render` reconfigures the surface to the latest `resize`.
  fn surface_size_pending(&self) -> bool {
    self
      .surface_config
      .as_ref()
      .is_some_and(|config| (config.width, config.height) != (self.width, self.height))
  }

  /// Reconfigures the surface once for however many `resize` calls arrived since the last frame.
  fn apply_pending_surface_size(&mut self) {
    if !self.surface_size_pending() {
      return;
    }
    if let (Some(config), Some(device), Some(surface)) = (&mut self.surface_config, &self.device, &self.surface) {
      config.width = self.width;
      config.height = self.height;
      surface.configure(device, config);
    }
    // A window of another size has other pixels behind its glass.
    if let Some(compositor) = self.layer_compositor.as_mut() {
      compositor.forget_backdrops();
    }
  }

  /// On another card than the one a device was lost on, asks that card from time to time whether it makes a
  /// device again, less and less often. Once it does, this engine is to be replaced: the one that takes its
  /// place draws on that card, where the frames of a decoder on it stay, and the window is drawn by the
  /// card it was drawn by before the loss.
  ///
  /// And with a device made while something held the lost one still, which is not a whole one, sees whether
  /// the lost one is gone: this engine is to be replaced then too, by one with a device made after it.
  #[cfg(not(target_arch = "wasm32"))]
  fn look_for_the_card(&mut self) {
    if self.card_is_back {
      return;
    }
    if self.made_while_held && !device_loss::a_lost_device_is_held() {
      self.card_is_back = true;
      if let Some(given) = &self.prepared {
        given.back.store(true, std::sync::atomic::Ordering::Release);
      }
      return;
    }
    if !self.displaced {
      return;
    }
    let Some((asked, every)) = self.card_asked else {
      return;
    };
    if asked.elapsed() < every {
      return;
    }
    self.card_asked = Some((std::time::Instant::now(), (every * 2).min(CARD_ASKED_AT_MOST)));
    let Some(instance) = self.instance.clone() else {
      return;
    };
    let (features, limits) = (self.optional_device_features, self.optional_device_limits.clone());
    let describe = move |adapter: &wgpu::Adapter| device_descriptor(adapter, features, &limits);
    if pollster::block_on(device_loss::the_card_gives(&instance, describe)) {
      self.card_is_back = true;
      // A device this was given is let go of for one of that card, for all that share it.
      if let Some(given) = &self.prepared {
        given.back.store(true, std::sync::atomic::Ordering::Release);
      }
    }
  }

  /// Whether the device this draws with is lost.
  fn device_is_lost(&self) -> bool {
    self
      .device
      .as_ref()
      .is_some_and(|device| device_loss::is_lost(device, &self.lost))
  }

  /// Asks for the adapter that draws to `surface` and its device, and waits for them. `None` where a device
  /// was lost in this program and the card gives none yet: it is asked for again some frames later.
  #[cfg(not(target_arch = "wasm32"))]
  fn request_device(&mut self, surface: &wgpu::Surface<'static>) -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> {
    // After a loss, the card the device was lost on is asked first, and waited for a little: asked for any
    // card, the window would go to another one while something of the app holds the lost device still.
    let (features, limits) = (self.optional_device_features, self.optional_device_limits.clone());
    let describe = move |adapter: &wgpu::Adapter| device_descriptor(adapter, features, &limits);
    let instance = self.instance.clone().unwrap();
    match pollster::block_on(device_loss::the_card_again(&instance, Some(surface), describe)) {
      device_loss::Again::Card(adapter, device, queue, held) => {
        self.made_while_held = held;
        return Some((adapter, device, queue));
      }
      device_loss::Again::Wait => return None,
      device_loss::Again::Elsewhere(adapter, device, queue) => {
        self.displaced = true;
        return Some((adapter, device, queue));
      }
      device_loss::Again::Unasked => {}
    }
    let adapter = pollster::block_on(
      self
        .instance
        .as_ref()
        .unwrap()
        .request_adapter(&wgpu::RequestAdapterOptions {
          power_preference: wgpu::PowerPreference::default(),
          compatible_surface: Some(surface),
          force_fallback_adapter: false,
        }),
    );
    if adapter.is_err() && device_loss::happened() {
      return None;
    }
    let adapter = adapter.expect("no suitable GPU adapter found");
    let made = pollster::block_on(adapter.request_device(&device_descriptor(
      &adapter,
      self.optional_device_features,
      &self.optional_device_limits,
    )));
    if made.is_err() && device_loss::happened() {
      return None;
    }
    let (device, queue) = made.expect("failed to create device");
    Some((adapter, device, queue))
  }

  /// A browser answers through a promise, which a frame cannot wait for.
  #[cfg(target_arch = "wasm32")]
  fn request_device(
    &mut self,
    _surface: &wgpu::Surface<'static>,
  ) -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> {
    panic!(
      "in a browser the GPU device comes from a promise: await `WgpuDevice::request()` before the window starts and \
       give the device with `WgpuRenderEngine::with_device`"
    );
  }

  fn ensure_initialized(&mut self, window: WindowHandle<'_>, display: DisplayHandle<'_>) {
    if self.device.is_some() && self.surface.is_some() {
      return;
    }

    // A device that was not given is not asked for in every frame.
    if self.device_wait > 0 {
      self.device_wait -= 1;
      return;
    }

    // The device of the app's other windows, where one draws with a device asked for as this one would be.
    #[cfg(not(target_arch = "wasm32"))]
    let shared = self.prepared.is_none() && !self.own_device && self.device.is_none() && {
      self.prepared = WgpuDevice::shared(
        self.backends,
        self.optional_device_features,
        &self.optional_device_limits,
      );
      self.prepared.is_some()
    };
    // A device this was given, as it is now: another one where the first was lost.
    let given = match &self.prepared {
      Some(prepared) if self.device.is_none() => match prepared.current() {
        Some(made) => Some(made),
        None => {
          self.device_wait = 15;
          return;
        }
      },
      _ => None,
    };
    if self.instance.is_none() {
      self.instance = Some(match &given {
        Some(made) => made.instance.clone(),
        None => new_instance(self.backends),
      });
    }
    let surface = self.create_surface(window, display);
    // A device of another window whose card cannot draw to this one's: this window asks for one of its own.
    #[cfg(not(target_arch = "wasm32"))]
    if shared
      && given
        .as_ref()
        .is_some_and(|made| !made.adapter.is_surface_supported(&surface))
    {
      drop(surface);
      self.prepared = None;
      self.instance = None;
      self.own_device = true;
      return self.ensure_initialized(window, display);
    }

    if let (Some(adapter), Some(device)) = (self.adapter.clone(), self.device.clone()) {
      self.configure_surface(surface, &adapter, &device);
      return;
    }

    let (adapter, device, queue) = match given {
      Some(made) => {
        // All that share the device lose it together, and are told of the app's errors on it together.
        self.lost = made.lost;
        self.untold = made.untold;
        self.device_number = made.number;
        self.displaced = made.displaced;
        self.made_while_held = made.while_held;
        (made.adapter, made.device, made.queue)
      }
      None => {
        let Some(made) = self.request_device(&surface) else {
          self.device_wait = 15;
          return;
        };
        // The device is this engine's own: where it is lost, another engine takes this one's place.
        device_loss::watch(&made.1, &self.lost, &made.0, &self.untold);
        self.device_number = device_number();
        // And the device of the engines of the app's other windows made after this one.
        #[cfg(not(target_arch = "wasm32"))]
        if !self.own_device {
          let device = WgpuDevice::of_engine(
            MadeDevice {
              instance: self.instance.clone().expect("the instance the device was asked of"),
              adapter: made.0.clone(),
              device: made.1.clone(),
              queue: made.2.clone(),
              lost: self.lost.clone(),
              number: self.device_number,
              displaced: self.displaced,
              while_held: self.made_while_held,
              untold: self.untold.clone(),
            },
            self.backends,
            self.optional_device_features,
            self.optional_device_limits.clone(),
          );
          device.share();
          self.prepared = Some(device);
        }
        made
      }
    };
    // On another card than the one a device was lost on: that card is looked for from here.
    #[cfg(not(target_arch = "wasm32"))]
    if self.displaced {
      self.card_asked = Some((std::time::Instant::now(), CARD_ASKED_FIRST));
    }
    // What decodes a video decodes on the card this draws on, and its frames stay there.
    #[cfg(all(windows, feature = "raster"))]
    if !card_frames::announce(&device) {
      card_frames::announce_vulkan(&device, &adapter);
    }
    // On Metal the buffer the system's decoder gives is drawn where it is.
    #[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
    crate::images::set_cv_pixel_buffer_frames_drawn(unsafe { device.as_hal::<wgpu_hal::api::Metal>() }.is_some());

    let format = self.configure_surface(surface, &adapter, &device);
    let config = self.surface_config.as_ref().unwrap();

    // --- Quad pipeline ---
    // The gradients are a storage buffer, or a texture where the device has no storage buffers.
    let gradients_in_texture = gradients::in_texture(&device);
    let quad_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
      label: Some("lurq_quad_bgl"),
      entries: &[
        wgpu::BindGroupLayoutEntry {
          binding: 0,
          visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
          ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Uniform,
            has_dynamic_offset: false,
            min_binding_size: None,
          },
          count: None,
        },
        gradients::layout_entry(gradients_in_texture),
      ],
    });

    let quad_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
      label: Some("lurq_quad_shader"),
      source: wgpu::ShaderSource::Wgsl(gradients::quad_shader(gradients_in_texture)),
    });

    let quad_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
      label: Some("lurq_quad_pl"),
      bind_group_layouts: &[Some(&quad_bgl)],
      immediate_size: 0,
    });

    let quad_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
      label: Some("lurq_quad_pipeline"),
      layout: Some(&quad_pipeline_layout),
      vertex: wgpu::VertexState {
        module: &quad_shader,
        entry_point: Some("vs_main"),
        buffers: &[QuadVertex::desc(), QuadInstance::desc()],
        compilation_options: Default::default(),
      },
      fragment: Some(wgpu::FragmentState {
        module: &quad_shader,
        entry_point: Some("fs_main"),
        targets: &[Some(wgpu::ColorTargetState {
          format,
          blend: Some(wgpu::BlendState::ALPHA_BLENDING),
          write_mask: wgpu::ColorWrites::ALL,
        })],
        compilation_options: Default::default(),
      }),
      primitive: wgpu::PrimitiveState {
        topology: wgpu::PrimitiveTopology::TriangleList,
        ..Default::default()
      },
      depth_stencil: None,
      multisample: wgpu::MultisampleState::default(),
      multiview_mask: None,
      cache: None,
    });

    // --- Glyph pipeline ---
    let glyph_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
      label: Some("lurq_glyph_bgl"),
      entries: &[
        wgpu::BindGroupLayoutEntry {
          binding: 0,
          visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
          ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Uniform,
            has_dynamic_offset: false,
            min_binding_size: None,
          },
          count: None,
        },
        wgpu::BindGroupLayoutEntry {
          binding: 1,
          visibility: wgpu::ShaderStages::FRAGMENT,
          ty: wgpu::BindingType::Texture {
            sample_type: wgpu::TextureSampleType::Float { filterable: true },
            view_dimension: wgpu::TextureViewDimension::D2,
            multisampled: false,
          },
          count: None,
        },
        wgpu::BindGroupLayoutEntry {
          binding: 2,
          visibility: wgpu::ShaderStages::FRAGMENT,
          ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
          count: None,
        },
      ],
    });

    let glyph_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
      label: Some("lurq_glyph_shader"),
      source: wgpu::ShaderSource::Wgsl(include_str!("shaders/glyph.wgsl").into()),
    });

    let glyph_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
      label: Some("lurq_glyph_pl"),
      bind_group_layouts: &[Some(&glyph_bgl)],
      immediate_size: 0,
    });

    let glyph_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
      label: Some("lurq_glyph_pipeline"),
      layout: Some(&glyph_pipeline_layout),
      vertex: wgpu::VertexState {
        module: &glyph_shader,
        entry_point: Some("vs_main"),
        buffers: &[QuadVertex::desc(), GlyphInstance::desc()],
        compilation_options: Default::default(),
      },
      fragment: Some(wgpu::FragmentState {
        module: &glyph_shader,
        entry_point: Some("fs_main"),
        targets: &[Some(wgpu::ColorTargetState {
          format,
          blend: Some(wgpu::BlendState::ALPHA_BLENDING),
          write_mask: wgpu::ColorWrites::ALL,
        })],
        compilation_options: Default::default(),
      }),
      primitive: wgpu::PrimitiveState {
        topology: wgpu::PrimitiveTopology::TriangleList,
        ..Default::default()
      },
      depth_stencil: None,
      multisample: wgpu::MultisampleState::default(),
      multiview_mask: None,
      cache: None,
    });

    // --- Image pipeline ---
    #[cfg(feature = "raster")]
    let (
      image_pipeline,
      nv12_image_pipeline,
      image_bgl,
      nv12_image_bgl,
      image_sampler,
      i420_image_pipeline,
      i420_image_bgl,
    ) = {
      use vertex::ImageInstance;
      let image_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("lurq_image_bgl"),
        entries: &[
          wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
            ty: wgpu::BindingType::Buffer {
              ty: wgpu::BufferBindingType::Uniform,
              has_dynamic_offset: false,
              min_binding_size: None,
            },
            count: None,
          },
          wgpu::BindGroupLayoutEntry {
            binding: 1,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
              sample_type: wgpu::TextureSampleType::Float { filterable: true },
              view_dimension: wgpu::TextureViewDimension::D2,
              multisampled: false,
            },
            count: None,
          },
          wgpu::BindGroupLayoutEntry {
            binding: 2,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
            count: None,
          },
        ],
      });
      let nv12_image_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("lurq_nv12_image_bgl"),
        entries: &[
          wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
            ty: wgpu::BindingType::Buffer {
              ty: wgpu::BufferBindingType::Uniform,
              has_dynamic_offset: false,
              min_binding_size: None,
            },
            count: None,
          },
          wgpu::BindGroupLayoutEntry {
            binding: 1,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
              sample_type: wgpu::TextureSampleType::Float { filterable: true },
              view_dimension: wgpu::TextureViewDimension::D2,
              multisampled: false,
            },
            count: None,
          },
          wgpu::BindGroupLayoutEntry {
            binding: 2,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
              sample_type: wgpu::TextureSampleType::Float { filterable: true },
              view_dimension: wgpu::TextureViewDimension::D2,
              multisampled: false,
            },
            count: None,
          },
          wgpu::BindGroupLayoutEntry {
            binding: 3,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
            count: None,
          },
        ],
      });
      let image_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("lurq_image_shader"),
        source: wgpu::ShaderSource::Wgsl(include_str!("shaders/image.wgsl").into()),
      });
      let nv12_image_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("lurq_nv12_image_shader"),
        source: wgpu::ShaderSource::Wgsl(
          // After the shader: its `diagnostic` directive is first in the module.
          concat!(
            include_str!("shaders/image_nv12.wgsl"),
            include_str!("shaders/yuv.wgsl")
          )
          .into(),
        ),
      });
      let image_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("lurq_image_pl"),
        bind_group_layouts: &[Some(&image_bgl)],
        immediate_size: 0,
      });
      let nv12_image_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("lurq_nv12_image_pl"),
        bind_group_layouts: &[Some(&nv12_image_bgl)],
        immediate_size: 0,
      });
      let image_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("lurq_image_pipeline"),
        layout: Some(&image_pipeline_layout),
        vertex: wgpu::VertexState {
          module: &image_shader,
          entry_point: Some("vs_main"),
          buffers: &[QuadVertex::desc(), ImageInstance::desc()],
          compilation_options: Default::default(),
        },
        fragment: Some(wgpu::FragmentState {
          module: &image_shader,
          entry_point: Some("fs_main"),
          targets: &[Some(wgpu::ColorTargetState {
            format,
            blend: Some(wgpu::BlendState::ALPHA_BLENDING),
            write_mask: wgpu::ColorWrites::ALL,
          })],
          compilation_options: Default::default(),
        }),
        primitive: wgpu::PrimitiveState {
          topology: wgpu::PrimitiveTopology::TriangleList,
          ..Default::default()
        },
        depth_stencil: None,
        multisample: wgpu::MultisampleState::default(),
        multiview_mask: None,
        cache: None,
      });
      let nv12_image_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("lurq_nv12_image_pipeline"),
        layout: Some(&nv12_image_pipeline_layout),
        vertex: wgpu::VertexState {
          module: &nv12_image_shader,
          entry_point: Some("vs_main"),
          buffers: &[QuadVertex::desc(), ImageInstance::desc()],
          compilation_options: Default::default(),
        },
        fragment: Some(wgpu::FragmentState {
          module: &nv12_image_shader,
          entry_point: Some("fs_main"),
          targets: &[Some(wgpu::ColorTargetState {
            format,
            blend: Some(wgpu::BlendState::ALPHA_BLENDING),
            write_mask: wgpu::ColorWrites::ALL,
          })],
          compilation_options: Default::default(),
        }),
        primitive: wgpu::PrimitiveState {
          topology: wgpu::PrimitiveTopology::TriangleList,
          ..Default::default()
        },
        depth_stencil: None,
        multisample: wgpu::MultisampleState::default(),
        multiview_mask: None,
        cache: None,
      });
      // Three planes: the gray and the two of color apart, each a texture of one channel.
      let i420_image_bgl = {
        let plane = |binding| wgpu::BindGroupLayoutEntry {
          binding,
          visibility: wgpu::ShaderStages::FRAGMENT,
          ty: wgpu::BindingType::Texture {
            sample_type: wgpu::TextureSampleType::Float { filterable: true },
            view_dimension: wgpu::TextureViewDimension::D2,
            multisampled: false,
          },
          count: None,
        };
        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
          label: Some("lurq_i420_image_bgl"),
          entries: &[
            wgpu::BindGroupLayoutEntry {
              binding: 0,
              visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
              ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
              },
              count: None,
            },
            plane(1),
            plane(2),
            plane(3),
            wgpu::BindGroupLayoutEntry {
              binding: 4,
              visibility: wgpu::ShaderStages::FRAGMENT,
              ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
              count: None,
            },
          ],
        })
      };
      let i420_image_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("lurq_i420_image_shader"),
        source: wgpu::ShaderSource::Wgsl(i420_shader_source().into()),
      });
      let i420_image_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some("lurq_i420_image_pl"),
        bind_group_layouts: &[Some(&i420_image_bgl)],
        immediate_size: 0,
      });
      let i420_image_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("lurq_i420_image_pipeline"),
        layout: Some(&i420_image_pipeline_layout),
        vertex: wgpu::VertexState {
          module: &i420_image_shader,
          entry_point: Some("vs_main"),
          buffers: &[QuadVertex::desc(), ImageInstance::desc()],
          compilation_options: Default::default(),
        },
        fragment: Some(wgpu::FragmentState {
          module: &i420_image_shader,
          entry_point: Some("fs_main"),
          targets: &[Some(wgpu::ColorTargetState {
            format,
            blend: Some(wgpu::BlendState::ALPHA_BLENDING),
            write_mask: wgpu::ColorWrites::ALL,
          })],
          compilation_options: Default::default(),
        }),
        primitive: wgpu::PrimitiveState {
          topology: wgpu::PrimitiveTopology::TriangleList,
          ..Default::default()
        },
        depth_stencil: None,
        multisample: wgpu::MultisampleState::default(),
        multiview_mask: None,
        cache: None,
      });
      let image_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
        label: Some("lurq_image_sampler"),
        mag_filter: wgpu::FilterMode::Linear,
        min_filter: wgpu::FilterMode::Linear,
        address_mode_u: wgpu::AddressMode::ClampToEdge,
        address_mode_v: wgpu::AddressMode::ClampToEdge,
        ..Default::default()
      });
      (
        image_pipeline,
        nv12_image_pipeline,
        image_bgl,
        nv12_image_bgl,
        image_sampler,
        i420_image_pipeline,
        i420_image_bgl,
      )
    };

    // --- Persistent uniform/storage buffers ---
    let globals_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
      label: Some("lurq_globals"),
      contents: bytemuck::bytes_of(&Globals::unclipped(config.width as f32, config.height as f32)),
      usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
    });

    let mut gradients = gradients::Gradients::new(&device);
    gradients.write(&queue, &[[0.0; 4]]);

    let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
      label: Some("lurq_atlas_sampler"),
      mag_filter: wgpu::FilterMode::Linear,
      min_filter: wgpu::FilterMode::Linear,
      ..Default::default()
    });

    let quad_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
      label: Some("lurq_quad_bg"),
      layout: &quad_bgl,
      entries: &[
        wgpu::BindGroupEntry {
          binding: 0,
          resource: globals_buffer.as_entire_binding(),
        },
        wgpu::BindGroupEntry {
          binding: 1,
          resource: gradients.binding(),
        },
      ],
    });

    // --- Shared vertex/index buffers ---
    let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
      label: Some("lurq_quad_verts"),
      contents: bytemuck::cast_slice(&QuadVertex::CORNERS),
      usage: wgpu::BufferUsages::VERTEX,
    });

    let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
      label: Some("lurq_quad_idx"),
      contents: bytemuck::cast_slice(&QuadVertex::INDICES),
      usage: wgpu::BufferUsages::INDEX,
    });

    #[cfg(feature = "perf_profile")]
    self.gpu_timer.configure(&adapter, &device, &queue);
    self.adapter = Some(adapter);
    self.device = Some(device);
    self.queue = Some(queue);
    self.quad_pipeline = Some(quad_pipeline);
    self.glyph_pipeline = Some(glyph_pipeline);
    #[cfg(feature = "raster")]
    {
      self.image_pipeline = Some(image_pipeline);
      self.nv12_image_pipeline = Some(nv12_image_pipeline);
      self.i420_image_pipeline = Some(i420_image_pipeline);
    }
    self.quad_bgl = Some(quad_bgl);
    self.glyph_bgl = Some(glyph_bgl);
    #[cfg(feature = "raster")]
    {
      self.image_bgl = Some(image_bgl);
      self.nv12_image_bgl = Some(nv12_image_bgl);
      self.i420_image_bgl = Some(i420_image_bgl);
    }
    #[cfg(feature = "raster")]
    {
      self.image_sampler = Some(image_sampler);
    }
    self.globals_buffer = Some(globals_buffer);
    self.gradients = Some(gradients);
    self.atlas_sampler = Some(atlas_sampler);
    self.quad_bind_group = Some(quad_bind_group);
    self.vertex_buffer = Some(vertex_buffer);
    self.index_buffer = Some(index_buffer);
  }

  /// The texture a frame is drawn into when the surface gives none and a capture waits for that frame: AppKit hands
  /// out no drawable while the window is occluded, and the capture would otherwise wait until it shows again.
  #[cfg_attr(not(feature = "screenshot"), allow(unused_variables))]
  fn offscreen_capture_target(
    &self,
    device: &wgpu::Device,
    config: &wgpu::SurfaceConfiguration,
  ) -> Option<FrameTarget> {
    #[cfg(feature = "screenshot")]
    if self.pending_frame_capture.is_some() {
      return Some(FrameTarget::Offscreen(device.create_texture(
        &wgpu::TextureDescriptor {
          label: Some("lurq_offscreen_capture_frame"),
          size: wgpu::Extent3d {
            width: config.width,
            height: config.height,
            depth_or_array_layers: 1,
          },
          mip_level_count: 1,
          sample_count: 1,
          dimension: wgpu::TextureDimension::D2,
          format: config.format,
          usage: config.usage,
          view_formats: &config.view_formats,
        },
      )));
    }
    None
  }
}

/// How many frames may wait for the display. One keeps input closest to the screen. On iOS that gives the layer
/// two drawables, and a frame then waits for the one on screen to come back: measured on an iPhone, every
/// present took two refreshes, 30 frames a second on a 60 Hz display.
#[cfg(not(target_os = "ios"))]
const SURFACE_FRAME_LATENCY: u32 = 1;
#[cfg(target_os = "ios")]
const SURFACE_FRAME_LATENCY: u32 = 2;

fn supported_present_mode(requested: wgpu::PresentMode, supported: &[wgpu::PresentMode]) -> wgpu::PresentMode {
  match requested {
    wgpu::PresentMode::AutoVsync | wgpu::PresentMode::AutoNoVsync => requested,
    requested if supported.contains(&requested) => requested,
    _ => wgpu::PresentMode::Fifo,
  }
}

/// Waits until a DX12 swap chain is ready for the next frame, before `get_current_texture`.
///
/// With wgpu's default `Dx12UseFrameLatencyWaitableObject::Wait`, `get_current_texture` waits on the
/// swap chain's frame latency object while it holds the device's fence lock. That wait lasts until
/// vblank, and `Queue::submit` needs the same lock, so no other thread can submit work meanwhile.
/// The instance is created with `DontWait`, and this waits on the same object with no wgpu lock held.
/// It does nothing on other backends, or when the surface has no swap chain yet.
fn wait_for_frame_latency(surface: &wgpu::Surface<'_>) {
  #[cfg(windows)]
  {
    use windows::Win32::System::Threading::WaitForSingleObject;

    // wgpu-core's own frame timeout for `get_current_texture`.
    const FRAME_LATENCY_WAIT_TIMEOUT_MS: u32 = 1000;

    // SAFETY: the HAL surface is only read. The handle belongs to the swap chain, which lurq
    // reconfigures only on this thread, so it stays open through the wait below.
    let handle = unsafe { surface.as_hal::<wgpu::hal::api::Dx12>() }.and_then(|hal| unsafe { hal.waitable_handle() });
    if let Some(handle) = handle {
      // SAFETY: `handle` is the swap chain's frame latency waitable object, a valid handle.
      unsafe { WaitForSingleObject(handle, FRAME_LATENCY_WAIT_TIMEOUT_MS) };
    }
  }
  #[cfg(not(windows))]
  let _ = surface;
}

struct WindowDisplayPair<'a> {
  window: WindowHandle<'a>,
  display: DisplayHandle<'a>,
}

impl raw_window_handle::HasWindowHandle for WindowDisplayPair<'_> {
  fn window_handle(&self) -> Result<WindowHandle<'_>, raw_window_handle::HandleError> {
    Ok(self.window)
  }
}

impl raw_window_handle::HasDisplayHandle for WindowDisplayPair<'_> {
  fn display_handle(&self) -> Result<DisplayHandle<'_>, raw_window_handle::HandleError> {
    Ok(self.display)
  }
}

impl Drop for WgpuRenderEngine {
  fn drop(&mut self) {
    let _own = app_errors::OwnWork::begin();
    self.release_gpu_resources();
  }
}

#[cfg(test)]
mod extension_tests {
  use super::{WgpuFrameExtension, WgpuRenderEngine};
  use crate::app::render_engine::RenderEngine;

  struct ContinuousExtension;

  impl WgpuFrameExtension for ContinuousExtension {
    fn wants_redraw(&self) -> bool {
      true
    }
  }

  #[test]
  fn frame_extension_can_drive_host_redraws() {
    let renderer = WgpuRenderEngine::new().with_frame_extension(ContinuousExtension);
    assert!(renderer.wants_redraw());
  }

  /// Writes down what it is told, in the order it is told it.
  struct Told(std::sync::Arc<std::sync::Mutex<Vec<&'static str>>>);

  impl WgpuFrameExtension for Told {
    fn device_lost(&mut self) {
      self.0.lock().unwrap().push("device lost");
    }

    fn shutdown(&mut self) {
      self.0.lock().unwrap().push("shutdown");
    }
  }

  /// An engine with a device and an extension that was initialized with it, and what the extension is told.
  fn with_a_device() -> Option<(WgpuRenderEngine, std::sync::Arc<std::sync::Mutex<Vec<&'static str>>>)> {
    let instance = super::new_instance(super::default_backends());
    let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
    let (device, queue) = pollster::block_on(adapter.request_device(&super::device_descriptor(
      &adapter,
      wgpu::Features::empty(),
      &wgpu::Limits::default(),
    )))
    .ok()?;
    let told = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let mut engine = WgpuRenderEngine::new().with_frame_extension(Told(told.clone()));
    (engine.device, engine.queue) = (Some(device), Some(queue));
    engine.frame_extensions[0].initialized = true;
    Some((engine, told))
  }

  #[test]
  fn an_extension_is_told_once_that_its_device_is_lost_before_it_is_shut_down() {
    let Some((mut engine, told)) = with_a_device() else {
      eprintln!("skipped: no card to make a device on");
      return;
    };
    // The loss is found, as its card or wgpu says it.
    engine.lost.store(true, std::sync::atomic::Ordering::Release);
    assert!(engine.lost());
    engine.tell_extensions_of_loss();
    engine.tell_extensions_of_loss();
    assert_eq!(*told.lock().unwrap(), ["device lost"], "told once");
    drop(engine);
    assert_eq!(*told.lock().unwrap(), ["device lost", "shutdown"]);
  }

  #[test]
  fn an_extension_is_told_of_the_loss_by_an_engine_let_go_of_before_it_draws_again() {
    let Some((engine, told)) = with_a_device() else {
      eprintln!("skipped: no card to make a device on");
      return;
    };
    engine.lost.store(true, std::sync::atomic::Ordering::Release);
    // The tree lets go of a lost engine in the pass that finds it, with no frame between.
    drop(engine);
    assert_eq!(*told.lock().unwrap(), ["device lost", "shutdown"]);
  }

  #[test]
  fn an_extension_whose_device_lives_is_only_shut_down() {
    let Some((engine, told)) = with_a_device() else {
      eprintln!("skipped: no card to make a device on");
      return;
    };
    drop(engine);
    assert_eq!(*told.lock().unwrap(), ["shutdown"]);
  }

  #[test]
  fn an_extension_that_was_never_initialized_is_told_nothing() {
    let told = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let engine = WgpuRenderEngine::new().with_frame_extension(Told(told.clone()));
    engine.lost.store(true, std::sync::atomic::Ordering::Release);
    drop(engine);
    assert!(told.lock().unwrap().is_empty());
  }
}

impl RenderEngine for WgpuRenderEngine {
  fn profile_backend(&self) -> &'static str {
    "wgpu"
  }
  #[cfg(feature = "perf_profile")]
  fn set_profile_context(&mut self, context: crate::app::profiler::ProfileContext) {
    self.profile_context = Some(context);
  }
  #[cfg(feature = "canvas")]
  fn prepare_canvases(&mut self, canvases: &[crate::canvas::CanvasHandle]) {
    self.canvases.clear();
    self
      .canvases
      .extend(canvases.iter().filter(|c| !c.status().software).cloned());
  }
  fn resize(&mut self, width: u32, height: u32) {
    self.width = width.max(1);
    self.height = height.max(1);
    self.clip_globals.clear();
    self.quad_clip_bind_groups.clear();
    self.glyph_clip_bind_groups.clear();
    #[cfg(feature = "raster")]
    self.image_clip_bind_groups.clear();
    // The surface is reconfigured by the next `render`, not here. Reconfiguring waits for the GPU and
    // recreates the swapchain, and a live resize can deliver hundreds of size events per frame (Windows
    // replays the ones queued during a modal sizing loop back to back), which stalled for seconds.
  }

  fn set_scale_factor(&mut self, scale_factor: f32) {
    self.scale_factor = scale_factor;
  }

  fn draws_tooling(&mut self) {
    // The app's extensions are the app's windows': they are never initialized for this one.
    self.frame_extensions.clear();
  }

  fn render(&mut self, list: &RenderList, window: WindowHandle<'_>, display: DisplayHandle<'_>) -> bool {
    // An error of what is asked of wgpu from here is lurq's, but in the extensions' calls.
    let _own = app_errors::OwnWork::begin();
    // A device that is lost is asked nothing more: what it answers is errors.
    if self.device_is_lost() {
      self.tell_extensions_of_loss();
      #[cfg(feature = "screenshot")]
      if let Some(capture) = self.pending_frame_capture.take() {
        capture.target.fail("the graphics device was lost");
      }
      return false;
    }
    #[cfg(not(target_arch = "wasm32"))]
    self.look_for_the_card();
    let _total_start = profile_scope!();
    let _init_start = profile_scope!();
    #[cfg(feature = "perf_profile")]
    let _init_phase = self
      .profile_context
      .as_ref()
      .map(|context| context.phase(crate::app::profiler::Phase::RenderInit));
    self.ensure_initialized(window, display);
    // After a loss the card may give no device yet: the frame is not drawn, and is asked for again.
    if self.device.is_none() || self.surface.is_none() {
      #[cfg(feature = "screenshot")]
      if let Some(capture) = self.pending_frame_capture.take() {
        capture.target.fail("the graphics device was lost");
      }
      return false;
    }
    self.apply_pending_surface_size();
    let _init_dur = profile_elapsed!(_init_start);
    #[cfg(feature = "perf_profile")]
    drop(_init_phase);
    // Queries only while a session is active; otherwise this does no GPU work.
    #[cfg(feature = "perf_profile")]
    self
      .gpu_timer
      .begin_frame(self.device.as_ref().unwrap(), self.profile_context.as_ref());
    self.prepare_frame_extensions(list);
    // What the frame before this one no longer drew has been drawn by the card by now.
    #[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
    self.retired_card_frames.clear();
    #[cfg(feature = "perf_profile")]
    let mut _canvas_profile = crate::app::profile_types::CanvasProfile::default();
    #[cfg(feature = "canvas")]
    if !self.canvases.is_empty() || self.canvas_renderer.is_some() {
      let _canvas_start = profile_scope!();
      let device = self.device.as_ref().unwrap();
      let queue = self.queue.as_ref().unwrap();
      let renderer = self
        .canvas_renderer
        .get_or_insert_with(|| canvas::Renderer::new(device, queue).with_asset_budget(self.canvas_asset_budget));
      #[cfg(feature = "perf_profile")]
      {
        renderer.profile_context = self.profile_context.clone();
        renderer.gpu_marks = self.gpu_timer.canvas_marks();
      }
      renderer.process(device, queue, &self.canvases);
      #[cfg(feature = "perf_profile")]
      {
        self.gpu_timer.canvas_done(renderer.gpu_marks.take());
        _canvas_profile = renderer.profile;
        _canvas_profile.total = profile_elapsed!(_canvas_start);
      }
    }

    #[cfg(feature = "raster")]
    {
      // Resized and removed canvases release their old image IDs. Match DX12's
      // per-frame ownership so those backing textures cannot accumulate.
      let live_images: std::collections::HashSet<u64> = list.images.iter().map(|image| image.image_id).collect();
      self.image_texture_cache.retain(|id, _| live_images.contains(id));
      self
        .image_clip_bind_groups
        .retain(|key, _| live_images.contains(&key.image_id));
    }

    let device = self.device.as_ref().unwrap();
    let queue = self.queue.as_ref().unwrap();
    let surface = self.surface.as_ref().unwrap();
    let config = self.surface_config.as_ref().unwrap();
    let vtx_buf = self.vertex_buffer.as_ref().unwrap();
    let idx_buf = self.index_buffer.as_ref().unwrap();

    let _acquire_start = profile_scope!();
    #[cfg(feature = "perf_profile")]
    let _acquire_phase = self
      .profile_context
      .as_ref()
      .map(|context| context.phase(crate::app::profiler::Phase::RenderAcquire));
    wait_for_frame_latency(surface);
    let output = match surface.get_current_texture() {
      wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => {
        FrameTarget::Surface(texture)
      }
      // The surface fell out of sync with the window — common on Vulkan during a
      // live resize (VK_ERROR_OUT_OF_DATE_KHR). Reconfigure to the current size
      // and retry once; without this the frame is skipped and the window stalls
      // (and stays stalled) while resizing.
      wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
        surface.configure(device, config);
        wait_for_frame_latency(surface);
        match surface.get_current_texture() {
          wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => {
            FrameTarget::Surface(texture)
          }
          _ => match self.offscreen_capture_target(device, config) {
            Some(target) => target,
            None => return false,
          },
        }
      }
      _ => match self.offscreen_capture_target(device, config) {
        Some(target) => target,
        None => {
          profile_if! {
            self.last_profile = RenderProfile {
              init: _init_dur,
              acquire: profile_elapsed!(_acquire_start),
              total: profile_elapsed!(_total_start),
              ..RenderProfile::default()
            };
          }
          return false;
        }
      },
    };
    let view = output.texture().create_view(&wgpu::TextureViewDescriptor {
      format: Some(render_target_format(config.format)),
      ..Default::default()
    });
    let _acquire_dur = profile_elapsed!(_acquire_start);
    #[cfg(feature = "perf_profile")]
    drop(_acquire_phase);

    let vw = config.width as f32;
    let vh = config.height as f32;
    let globals_buffer = self.globals_buffer.as_ref().unwrap();

    let globals = Globals::unclipped(vw, vh);
    let _globals_start = profile_scope!();
    let globals_bytes = bytemuck::bytes_of(&globals);
    if self.last_globals_bytes.as_slice() != globals_bytes {
      queue.write_buffer(globals_buffer, 0, globals_bytes);
      self.last_globals_bytes.clear();
      self.last_globals_bytes.extend_from_slice(globals_bytes);
    }
    let _globals_dur = profile_elapsed!(_globals_start);

    // Atlas — recreate texture only if size changed
    let _atlas_start = profile_scope!();
    let mut _atlas_upload_bytes = 0usize;
    let mut _atlas_upload_rects = 0usize;
    let mut _atlas_full_uploads = 0usize;
    let atlas = &list.atlas;
    let atlas_recreated = self.atlas_size != (atlas.width, atlas.height);
    if atlas_recreated {
      let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("lurq_atlas"),
        size: wgpu::Extent3d {
          width: atlas.width,
          height: atlas.height,
          depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8UnormSrgb,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
      });
      let view = texture.create_view(&Default::default());
      let glyph_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("lurq_glyph_bg"),
        layout: self.glyph_bgl.as_ref().unwrap(),
        entries: &[
          wgpu::BindGroupEntry {
            binding: 0,
            resource: globals_buffer.as_entire_binding(),
          },
          wgpu::BindGroupEntry {
            binding: 1,
            resource: wgpu::BindingResource::TextureView(&view),
          },
          wgpu::BindGroupEntry {
            binding: 2,
            resource: wgpu::BindingResource::Sampler(self.atlas_sampler.as_ref().unwrap()),
          },
        ],
      });
      self.atlas_texture = Some(texture);
      self.atlas_view = Some(view);
      self.glyph_bind_group = Some(glyph_bind_group);
      self.glyph_clip_bind_groups.clear();
      self.atlas_size = (atlas.width, atlas.height);
    }
    if atlas_recreated || self.atlas_version != atlas.version {
      // The atlas is shared across windows; this engine's texture may be
      // several versions behind, so apply the log's rects newer than *our*
      // uploaded version — or the full atlas when the log no longer covers
      // the gap.
      let pending = if atlas_recreated {
        None
      } else {
        crate::app::glyph_engine::atlas_rects_to_apply(atlas, self.atlas_version)
      };
      let upload_full_atlas = pending.is_none();
      if upload_full_atlas {
        _atlas_upload_bytes = wgpu_staged_texture_bytes(atlas.width * 4, atlas.height);
        _atlas_upload_rects = 1;
        _atlas_full_uploads = 1;
        queue.write_texture(
          wgpu::TexelCopyTextureInfo {
            texture: self.atlas_texture.as_ref().unwrap(),
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
          },
          &atlas.data,
          wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(atlas.width * 4),
            rows_per_image: Some(atlas.height),
          },
          wgpu::Extent3d {
            width: atlas.width,
            height: atlas.height,
            depth_or_array_layers: 1,
          },
        );
      } else {
        for rect in pending.unwrap_or_default() {
          if rect.width == 0 || rect.height == 0 || rect.x >= atlas.width || rect.y >= atlas.height {
            continue;
          }
          let width = rect.width.min(atlas.width - rect.x);
          let height = rect.height.min(atlas.height - rect.y);
          let row_bytes = atlas.width as usize * 4;
          let rect_x_bytes = rect.x as usize * 4;
          let width_bytes = width as usize * 4;
          let start = rect.y as usize * row_bytes + rect_x_bytes;
          let end = start + (height as usize - 1) * row_bytes + width_bytes;
          if end > atlas.data.len() {
            continue;
          }
          _atlas_upload_bytes += wgpu_staged_texture_bytes(width * 4, height);
          _atlas_upload_rects += 1;
          queue.write_texture(
            wgpu::TexelCopyTextureInfo {
              texture: self.atlas_texture.as_ref().unwrap(),
              mip_level: 0,
              origin: wgpu::Origin3d {
                x: rect.x,
                y: rect.y,
                z: 0,
              },
              aspect: wgpu::TextureAspect::All,
            },
            &atlas.data[start..end],
            wgpu::TexelCopyBufferLayout {
              offset: 0,
              bytes_per_row: Some(atlas.width * 4),
              rows_per_image: Some(height),
            },
            wgpu::Extent3d {
              width,
              height,
              depth_or_array_layers: 1,
            },
          );
        }
      }
      self.atlas_version = atlas.version;
    }
    let _atlas_dur = profile_elapsed!(_atlas_start);

    let _encode_start = profile_scope!();
    #[cfg(feature = "perf_profile")]
    let _encode_phase = self
      .profile_context
      .as_ref()
      .map(|context| context.phase(crate::app::profiler::Phase::RenderEncode));
    let mut _buffer_upload_dur = Duration::default();
    let mut _image_texture_upload_dur = Duration::default();

    self.scratch_rect_instances.clear();
    self.scratch_rect_draws.clear();
    self.scratch_rect_draws.reserve(list.rects.len());
    self.scratch_gradient_data.clear();
    for r in &list.rects {
      let start = self.scratch_rect_instances.len();
      if let Some(shadow) = &r.shadow {
        self.scratch_rect_instances.push(QuadInstance::box_shadow(r, shadow));
        self.scratch_rect_draws.push(PreparedDraw { start, count: 1 });
        continue;
      }
      let gradient_offset = match &r.gradient {
        Some(gradient) => crate::layout::render_list::encode_gradient(&mut self.scratch_gradient_data, gradient),
        None => -1.0,
      };
      self.scratch_rect_instances.push(QuadInstance {
        pos: [r.x, r.y],
        size: [r.width, r.height],
        color: r.color.to_linear_f32_array(),
        radii_h: r.radii,
        radii_v: r.radii,
        stroke: [0.0; 4],
        pattern: [0.0; 4],
        transform: r.transform,
        xf_origin: r.transform_origin,
        shadow_sigma: 0.0,
        gradient_offset,
      });
      if r.stroke.iter().any(|s| *s > 0.0) {
        self.scratch_rect_instances.push(QuadInstance {
          pos: [r.x, r.y],
          size: [r.width, r.height],
          color: r.stroke_color.to_linear_f32_array(),
          radii_h: r.radii,
          radii_v: r.radii,
          stroke: r.stroke,
          // A stroke's pattern: its dash, its gap, and the edge its radii are at.
          pattern: [
            0.0,
            r.stroke_style.dash[0],
            r.stroke_style.dash[1],
            r.stroke_style.radii_at,
          ],
          transform: r.transform,
          xf_origin: r.transform_origin,
          shadow_sigma: 0.0,
          gradient_offset: crate::layout::render_list::encode_stroke_colors(
            &mut self.scratch_gradient_data,
            &r.stroke_style,
          ),
        });
      }
      self.scratch_rect_draws.push(PreparedDraw {
        start,
        count: self.scratch_rect_instances.len() - start,
      });
    }
    let _rect_upload_start = profile_scope!();
    let rect_instance_buf = self
      .rect_instance_buffer
      .write(device, queue, &self.scratch_rect_instances);
    _buffer_upload_dur += profile_elapsed!(_rect_upload_start);

    // Storage buffers must be non-empty; a single zeroed vec4 is enough when
    // no rect uses a gradient (their `gradient_offset` is -1 and the shader
    // never reads it).
    if self.scratch_gradient_data.is_empty() {
      self.scratch_gradient_data.push([0.0; 4]);
    }
    let gradient_bytes = bytemuck::cast_slice(&self.scratch_gradient_data);
    let gradients = self.gradients.as_mut().unwrap();
    let gradient_recreated = gradients.reserve(device, self.scratch_gradient_data.len());
    if gradient_recreated {
      let quad_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("lurq_quad_bg"),
        layout: self.quad_bgl.as_ref().unwrap(),
        entries: &[
          wgpu::BindGroupEntry {
            binding: 0,
            resource: self.globals_buffer.as_ref().unwrap().as_entire_binding(),
          },
          wgpu::BindGroupEntry {
            binding: 1,
            resource: gradients.binding(),
          },
        ],
      });
      self.quad_bind_group = Some(quad_bind_group);
      self.quad_clip_bind_groups.clear();
    }
    let _gradient_upload_start = profile_scope!();
    if gradient_recreated || self.last_gradient_bytes.as_slice() != gradient_bytes {
      gradients.write(queue, &self.scratch_gradient_data);
      self.last_gradient_bytes.clear();
      self.last_gradient_bytes.extend_from_slice(gradient_bytes);
    }
    let gradients = self.gradients.as_ref().unwrap();
    _buffer_upload_dur += profile_elapsed!(_gradient_upload_start);

    self.scratch_glyph_instances.clear();
    self.scratch_glyph_instances.reserve(list.glyphs.len());
    let atlas_inverse = [
      1.0 / list.atlas.width.max(1) as f32,
      1.0 / list.atlas.height.max(1) as f32,
    ];
    self
      .scratch_glyph_instances
      .extend(list.glyphs.iter().map(|g| GlyphInstance {
        pos: [g.x, g.y],
        size: [g.width, g.height],
        color: g.color,
        uv_min: [g.atlas_min[0] * atlas_inverse[0], g.atlas_min[1] * atlas_inverse[1]],
        uv_max: [g.atlas_max[0] * atlas_inverse[0], g.atlas_max[1] * atlas_inverse[1]],
        transform: g.transform,
        xf_origin: g.transform_origin,
        sharpness: g.sharpness,
        color_glyph: if g.color_glyph { 1.0 } else { 0.0 },
        shadow_sigma: g.shadow_sigma,
      }));
    let _glyph_upload_start = profile_scope!();
    let glyph_instance_buf = self
      .glyph_instance_buffer
      .write(device, queue, &self.scratch_glyph_instances);
    _buffer_upload_dur += profile_elapsed!(_glyph_upload_start);

    #[cfg(feature = "raster")]
    let _image_upload_start = profile_scope!();
    // The frames that stay on the card: their surfaces are opened once, and the frame to draw is taken now, for
    // the part of its texture an image is drawn from is the frame's to say. A frame of another card is sent
    // from memory here, before anything is drawn.
    #[cfg(all(feature = "raster", windows))]
    if let (Some(image_bgl), Some(nv12_image_bgl), Some(image_sampler)) = (
      self.image_bgl.as_ref(),
      self.nv12_image_bgl.as_ref(),
      self.image_sampler.as_ref(),
    ) {
      let bind = |first: &wgpu::TextureView, second: Option<&wgpu::TextureView>| {
        let globals = wgpu::BindGroupEntry {
          binding: 0,
          resource: globals_buffer.as_entire_binding(),
        };
        let view = |binding, view| wgpu::BindGroupEntry {
          binding,
          resource: wgpu::BindingResource::TextureView(view),
        };
        let sampler = |binding| wgpu::BindGroupEntry {
          binding,
          resource: wgpu::BindingResource::Sampler(image_sampler),
        };
        match second {
          Some(second) => device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("lurq_card_frame_planes_bg"),
            layout: nv12_image_bgl,
            entries: &[globals, view(1, first), view(2, second), sampler(3)],
          }),
          None => device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("lurq_card_frame_bg"),
            layout: image_bgl,
            entries: &[globals, view(1, first), sampler(2)],
          }),
        }
      };
      for img in &list.images {
        let Some(frames) = card_frames::of(img) else {
          continue;
        };
        let kept = self
          .image_texture_cache
          .get(&img.image_id)
          .is_some_and(|cached| cached.is_compatible(img));
        if !kept {
          self.image_texture_cache.remove(&img.image_id);
          self.image_clip_bind_groups.clear();
          let size = (img.image_width, img.image_height);
          // Kept though nothing opens them: they are not asked for again in each frame.
          let opened =
            card_frames::Opened::open(device, frames, size, &self.card_leases, &mut self.card_readers, &bind);
          self
            .image_texture_cache
            .insert(img.image_id, CachedImageTexture::Card(opened));
        }
        if let Some(CachedImageTexture::Card(opened)) = self.image_texture_cache.get_mut(&img.image_id) {
          opened.pick(queue);
        }
      }
    }

    #[cfg(feature = "raster")]
    let image_instance_buf = {
      self.scratch_image_instances.clear();
      self.scratch_image_instances.reserve(list.images.len());
      let cache = &self.image_texture_cache;
      self.scratch_image_instances.extend(list.images.iter().map(|img| {
        let (uv_min, uv_max) = drawn_part(cache, img);
        let [matrix, full_range] = match cache.get(&img.image_id) {
          Some(CachedImageTexture::Nv12 { color, .. }) => *color,
          #[cfg(windows)]
          Some(CachedImageTexture::Card(opened)) => opened.colors().shader(),
          _ => [0.0, 0.0],
        };
        ImageInstance {
          pos: [img.x, img.y],
          size: [img.width, img.height],
          opacity: [img.opacity, canvas_image_flag(&img.native), matrix, full_range],
          transform: img.transform,
          xf_origin: img.transform_origin,
          uv_min,
          uv_max,
          radii: img.radii,
        }
      }));
      self
        .image_instance_buffer
        .write(device, queue, &self.scratch_image_instances)
    };
    #[cfg(feature = "raster")]
    {
      _buffer_upload_dur += profile_elapsed!(_image_upload_start);
    }

    // Draws in paint order, across the pipelines.
    self.scratch_ordered_draws.clear();
    self.scratch_ordered_draws.reserve(
      list.rects.len() + list.glyphs.len() + {
        #[cfg(feature = "raster")]
        {
          list.images.len()
        }
        #[cfg(not(feature = "raster"))]
        {
          0
        }
      },
    );
    for (index, rect) in list.rects.iter().enumerate() {
      self.scratch_ordered_draws.push((rect.order, OrderedDraw::Rect(index)));
    }
    glyph_runs(
      &list.glyphs,
      |clip| {
        scissor_rect(clip, vw, vh)
          .map(|(x, y, width, height)| [x as f32, y as f32, (x + width) as f32, (y + height) as f32])
      },
      |order, run| self.scratch_ordered_draws.push((order, OrderedDraw::Glyph(run))),
    );
    #[cfg(feature = "raster")]
    for (index, image) in list.images.iter().enumerate() {
      self
        .scratch_ordered_draws
        .push((image.order, OrderedDraw::Image(index)));
    }
    self.scratch_ordered_draws.sort_by_key(|(order, _)| *order);
    let ordered_draws = std::mem::take(&mut self.scratch_ordered_draws);

    // Faded subtrees paint into offscreen layers first, each before the
    // target it is composited into; the window's pass comes last. Without
    // layers the plan is the window's pass alone.
    let mut layer_plan = std::mem::take(&mut self.layer_plan);
    layer_plan.build(
      ordered_draws.len(),
      |index| ordered_draws[index].0,
      &list.layers,
      &list.backdrops,
    );
    self.scratch_layer_slots.clear();
    self.scratch_blur_slots.clear();
    self.scratch_backdrop_slots.clear();
    if layer_plan.has_layers() || layer_plan.has_backdrops() {
      let format = render_target_format(config.format);
      if self
        .layer_compositor
        .as_ref()
        .is_none_or(|compositor| compositor.format() != format)
      {
        self.layer_compositor = Some(layers::LayerCompositor::new(device, format));
      }
    }
    if let Some(compositor) = self.layer_compositor.as_mut() {
      compositor.begin_frame();
      // A backdrop blur reads the target its step is in. One whose kept
      // result is still the blur of what it reads takes that; the others run.
      // So does a blurred layer, which is not painted when its kept result
      // is still the blur of what it holds.
      let window = [config.width, config.height];
      backdrop_regions(list, &layer_plan, window, &mut self.scratch_backdrop_regions);
      self.backdrop_inputs.describe(
        list,
        &layer_plan,
        ordered_draws.len(),
        |index| ordered_draws[index].1.painted(),
        &self.scratch_backdrop_regions,
        window,
      );
      self.layer_blur_inputs.describe(
        list,
        &layer_plan,
        ordered_draws.len(),
        |index| ordered_draws[index].1.painted(),
        &self.scratch_backdrop_regions,
        window,
      );
      compositor.acquire_layers(
        device,
        list,
        &layer_plan,
        &self.layer_blur_inputs,
        window,
        &mut self.scratch_layer_slots,
        &mut self.scratch_blur_slots,
      );
      compositor.acquire_backdrops(
        device,
        &self.scratch_backdrop_regions,
        &self.backdrop_inputs,
        window,
        &mut self.scratch_backdrop_slots,
      );
    }

    // A frame that is read back, by a backdrop blur of the window or a capture, is painted beside a surface
    // whose texture cannot be copied from, and put onto it in a last pass; see `surface_proxy`.
    let mut frame_is_read = false;
    if !self.surface_copies {
      frame_is_read = layer_plan
        .targets()
        .iter()
        .filter(|target| target.layer.is_none())
        .flat_map(|target| layer_plan.steps(target))
        .any(|step| {
          matches!(step, LayerStep::Backdrop(index)
            if self.scratch_backdrop_slots.get(*index).copied().flatten().is_some_and(|slots| slots.runs()))
        });
      #[cfg(feature = "screenshot")]
      {
        frame_is_read |= self.pending_frame_capture.is_some();
      }
    }
    if frame_is_read {
      let format = render_target_format(config.format);
      if !self
        .surface_proxy
        .as_ref()
        .is_some_and(|proxy| proxy.fits(format, config.width, config.height))
      {
        self.surface_proxy = Some(surface_proxy::SurfaceProxy::new(
          device,
          format,
          config.width,
          config.height,
        ));
      }
    }
    let surface_proxy = self.surface_proxy.as_ref().filter(|_| frame_is_read);
    let (window_texture, window_view) = match surface_proxy {
      Some(proxy) => (proxy.texture(), proxy.view()),
      None => (output.texture(), &view),
    };

    let mut encoder = device.create_command_encoder(&Default::default());
    #[cfg(feature = "perf_profile")]
    let target_count = layer_plan.targets().len();
    #[cfg(feature = "perf_profile")]
    let mut _draw_calls = 0usize;
    #[cfg(feature = "perf_profile")]
    let mut _layers = crate::app::profile_types::LayerProfile::default();
    for (target_index, target) in layer_plan.targets().iter().enumerate() {
      let layer_slot = self.scratch_layer_slots.get(target_index).copied().flatten();
      // A blurred layer put back from its kept blur, and what it holds, are not painted.
      if target.layer.is_some() && layer_slot.is_none() {
        continue;
      }
      let (space, target_view, clear) = match (target.layer, layer_slot, self.layer_compositor.as_ref()) {
        (Some(layer), Some(slot), Some(compositor)) => (
          compositor.space(slot, &list.layers[layer]),
          compositor.view(slot).clone(),
          wgpu::Color::TRANSPARENT,
        ),
        _ => (
          TargetSpace::window(vw, vh),
          window_view.clone(),
          wgpu_clear_color(list.clear_color),
        ),
      };
      // A backdrop blur that runs ends the target's pass, reads what it
      // painted and starts another that keeps it, so a target is painted in
      // one pass more than it has backdrop blurs that run.
      #[cfg_attr(
        not(feature = "perf_profile"),
        allow(unused_variables, unused_assignments, unused_mut)
      )]
      let mut backdrops_left = layer_plan
        .steps(target)
        .iter()
        .filter(|step| {
          matches!(step, LayerStep::Backdrop(index)
            if self.scratch_backdrop_slots.get(*index).copied().flatten().is_some_and(|slots| slots.runs()))
        })
        .count();
      macro_rules! begin_target_pass {
        ($load:expr, $first:expr) => {
          encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some(if target.layer.is_some() {
              "lurq_layer_pass"
            } else {
              "lurq_pass"
            }),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
              view: &target_view,
              depth_slice: None,
              resolve_target: None,
              ops: wgpu::Operations {
                load: $load,
                store: wgpu::StoreOp::Store,
              },
            })],
            // The UI's GPU time: the first pass's start to the end of the
            // window's last pass.
            #[cfg(feature = "perf_profile")]
            timestamp_writes: self.gpu_timer.ui_pass_writes(
              $first && target_index == 0,
              target_index + 1 == target_count && backdrops_left == 0,
            ),
            ..Default::default()
          })
        };
      }
      let mut pass = begin_target_pass!(wgpu::LoadOp::Clear(clear), true);
      profile_if! { _layers.render_passes += 1; }

      let mut active_pipeline = None;
      let mut active_vertex_buffer = None;
      let mut active_index_buffer = None;

      for step in layer_plan.steps(target) {
        let range = match step {
          LayerStep::Draws(range) => range.clone(),
          LayerStep::Backdrop(index) => {
            let (Some(backdrop), Some(compositor)) = (
              self.scratch_backdrop_slots.get(*index).copied().flatten(),
              self.layer_compositor.as_ref(),
            ) else {
              continue;
            };
            if backdrop.runs() {
              let (target_texture, target_origin) = match (target.layer, layer_slot) {
                (Some(layer), Some(slot)) => (compositor.texture(slot), list.layers[layer].painted().0),
                _ => (window_texture, [0, 0]),
              };
              drop(pass);
              let _blur_passes = compositor.prepare_backdrop(
                queue,
                &mut encoder,
                vtx_buf,
                idx_buf,
                target_texture,
                target_origin,
                &backdrop,
              );
              backdrops_left -= 1;
              pass = begin_target_pass!(wgpu::LoadOp::Load, false);
              profile_if! {
                _layers.render_passes += _blur_passes + 1;
                _layers.blur_draws += _blur_passes;
                _layers.target_copies += 1;
                _layers.backdrops_blurred += 1;
              }
              // A new pass starts with nothing bound.
              active_vertex_buffer = None;
              active_index_buffer = None;
            } else {
              // Its kept result is put back in the pass, as it is.
              profile_if! { _layers.backdrops_reused += 1; }
            }
            if active_vertex_buffer != Some(ActiveVertexBuffer::CommonQuad) {
              pass.set_vertex_buffer(0, vtx_buf.slice(..));
              active_vertex_buffer = Some(ActiveVertexBuffer::CommonQuad);
            }
            if active_index_buffer != Some(ActiveIndexBuffer::CommonU16) {
              pass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint16);
              active_index_buffer = Some(ActiveIndexBuffer::CommonU16);
            }
            active_pipeline = Some(ActivePipeline::Layer);
            if set_scissor(&mut pass, space.layer_rect(backdrop.bounds()), &space) {
              compositor.composite_backdrop(queue, &mut pass, &backdrop, &space);
              profile_if! {
                _draw_calls += 2;
                _layers.blur_draws += 2;
              }
            }
            continue;
          }
          LayerStep::Composite(child) => {
            let child_layer = layer_plan.targets()[*child].layer;
            let child_slot = self.scratch_layer_slots.get(*child).copied().flatten();
            let child_blur = self.scratch_blur_slots.get(*child).copied().flatten();
            let (Some(layer), Some(compositor)) = (child_layer, self.layer_compositor.as_ref()) else {
              continue;
            };
            // A blurred layer needs its blur, painted now or kept; another its own texture.
            if child_blur.is_none() && child_slot.is_none() {
              continue;
            }
            let layer = &list.layers[layer];
            if !set_scissor(&mut pass, space.layer_rect(layer.bounds), &space) {
              continue;
            }
            if active_vertex_buffer != Some(ActiveVertexBuffer::CommonQuad) {
              pass.set_vertex_buffer(0, vtx_buf.slice(..));
              active_vertex_buffer = Some(ActiveVertexBuffer::CommonQuad);
            }
            if active_index_buffer != Some(ActiveIndexBuffer::CommonU16) {
              pass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint16);
              active_index_buffer = Some(ActiveIndexBuffer::CommonU16);
            }
            match (child_blur, child_slot) {
              (Some(blur_slots), _) => {
                compositor.composite_blurred(queue, &mut pass, &blur_slots, layer, &space);
                profile_if! { _layers.blur_draws += 1; }
              }
              (None, Some(slot)) => compositor.composite(queue, &mut pass, slot, layer, &space),
              (None, None) => {}
            }
            profile_if! { _draw_calls += 1; }
            active_pipeline = Some(ActivePipeline::Layer);
            continue;
          }
        };
        let draws = &ordered_draws[range];
        let mut next_draw = 0;
        while let Some((_, draw)) = draws.get(next_draw) {
          next_draw += 1;
          match draw {
            OrderedDraw::Rect(index) => {
              let r = &list.rects[*index];
              if !set_scissor(&mut pass, space.clip(r.clip), &space) {
                continue;
              }
              let prepared = &self.scratch_rect_draws[*index];
              let start = (prepared.start * std::mem::size_of::<QuadInstance>()) as wgpu::BufferAddress;
              let end =
                ((prepared.start + prepared.count) * std::mem::size_of::<QuadInstance>()) as wgpu::BufferAddress;
              if active_pipeline != Some(ActivePipeline::Quad) {
                pass.set_pipeline(self.quad_pipeline.as_ref().unwrap());
                active_pipeline = Some(ActivePipeline::Quad);
              }
              if needs_clip_globals(r.clip, &space) {
                let (clip_key, clip_globals) = self.clip_globals.get(device, r.clip, &space);
                let clip_bind_group = self.quad_clip_bind_groups.entry(clip_key).or_insert_with(|| {
                  device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("lurq_quad_clip_bg"),
                    layout: self.quad_bgl.as_ref().unwrap(),
                    entries: &[
                      wgpu::BindGroupEntry {
                        binding: 0,
                        resource: clip_globals.as_entire_binding(),
                      },
                      wgpu::BindGroupEntry {
                        binding: 1,
                        resource: gradients.binding(),
                      },
                    ],
                  })
                });
                pass.set_bind_group(0, &*clip_bind_group, &[]);
              } else {
                pass.set_bind_group(0, self.quad_bind_group.as_ref().unwrap(), &[]);
              }
              if active_vertex_buffer != Some(ActiveVertexBuffer::CommonQuad) {
                pass.set_vertex_buffer(0, vtx_buf.slice(..));
                active_vertex_buffer = Some(ActiveVertexBuffer::CommonQuad);
              }
              pass.set_vertex_buffer(1, rect_instance_buf.unwrap().slice(start..end));
              if active_index_buffer != Some(ActiveIndexBuffer::CommonU16) {
                pass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint16);
                active_index_buffer = Some(ActiveIndexBuffer::CommonU16);
              }
              pass.draw_indexed(0..6, 0, 0..prepared.count as u32);
              profile_if! { _draw_calls += 1; }
            }
            OrderedDraw::Glyph(run) => {
              // The texts painted next join this draw: those under its clip,
              // or any that no clip cuts when none cuts this one.
              let following = draws[next_draw..].iter().map(|(_, draw)| draw.glyph_run());
              let batch = batch_glyph_runs(&list.glyphs, *run, following, space.is_window());
              next_draw += batch.joined;
              let (start, count) = (run.start, batch.count);
              let glyph_slice = &list.glyphs[start..start + count];
              let clip = if batch.unclipped {
                crate::layout::quad::ClipRect::default()
              } else {
                glyph_slice[0].clip
              };
              if glyph_slice.is_empty() || !set_scissor(&mut pass, space.clip(clip), &space) {
                continue;
              }
              let start_byte = (start * std::mem::size_of::<GlyphInstance>()) as wgpu::BufferAddress;
              let end_byte = ((start + count) * std::mem::size_of::<GlyphInstance>()) as wgpu::BufferAddress;
              if active_pipeline != Some(ActivePipeline::Glyph) {
                pass.set_pipeline(self.glyph_pipeline.as_ref().unwrap());
                active_pipeline = Some(ActivePipeline::Glyph);
              }
              if needs_clip_globals(clip, &space) {
                let (clip_key, clip_globals) = self.clip_globals.get(device, clip, &space);
                let clip_bind_group = self.glyph_clip_bind_groups.entry(clip_key).or_insert_with(|| {
                  device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("lurq_glyph_clip_bg"),
                    layout: self.glyph_bgl.as_ref().unwrap(),
                    entries: &[
                      wgpu::BindGroupEntry {
                        binding: 0,
                        resource: clip_globals.as_entire_binding(),
                      },
                      wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(self.atlas_view.as_ref().unwrap()),
                      },
                      wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::Sampler(self.atlas_sampler.as_ref().unwrap()),
                      },
                    ],
                  })
                });
                pass.set_bind_group(0, &*clip_bind_group, &[]);
              } else {
                pass.set_bind_group(0, self.glyph_bind_group.as_ref().unwrap(), &[]);
              }
              if active_vertex_buffer != Some(ActiveVertexBuffer::CommonQuad) {
                pass.set_vertex_buffer(0, vtx_buf.slice(..));
                active_vertex_buffer = Some(ActiveVertexBuffer::CommonQuad);
              }
              pass.set_vertex_buffer(1, glyph_instance_buf.unwrap().slice(start_byte..end_byte));
              if active_index_buffer != Some(ActiveIndexBuffer::CommonU16) {
                pass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint16);
                active_index_buffer = Some(ActiveIndexBuffer::CommonU16);
              }
              pass.draw_indexed(0..6, 0, 0..count as u32);
              profile_if! { _draw_calls += 1; }
            }
            #[cfg(feature = "raster")]
            OrderedDraw::Image(index) => {
              let img = &list.images[*index];
              let image_bgl = self.image_bgl.as_ref().unwrap().clone();
              let nv12_image_bgl = self.nv12_image_bgl.as_ref().unwrap().clone();
              let image_sampler = self.image_sampler.as_ref().unwrap().clone();
              let image_pipeline = self.image_pipeline.as_ref().unwrap().clone();
              let nv12_image_pipeline = self.nv12_image_pipeline.as_ref().unwrap().clone();
              let i420_image_bgl = self.i420_image_bgl.as_ref().unwrap().clone();
              let i420_image_pipeline = self.i420_image_pipeline.as_ref().unwrap().clone();

              let external_wgpu_image = img
                .native
                .as_ref()
                .filter(|native| native.backend() == crate::images::NativeImageBackend::WgpuExternalRgba);
              #[cfg(feature = "canvas")]
              let canvas_image = img
                .native
                .as_ref()
                .filter(|n| n.backend() == crate::images::NativeImageBackend::Canvas);
              #[cfg(not(feature = "canvas"))]
              let canvas_image: Option<&crate::images::NativeImageData> = None;
              #[cfg(feature = "canvas")]
              if let Some(native) = canvas_image {
                let snapshot = native
                  .payload::<crate::canvas::CanvasWeak>()
                  .and_then(|c| c.upgrade())
                  .and_then(|c| self.canvas_renderer.as_ref()?.snapshot(&c));
                let Some(snapshot) = snapshot else {
                  continue;
                };
                let current = self.image_texture_cache.get(&img.image_id).is_some_and(
                  |c| matches!(c,CachedImageTexture::ExternalRgba {version,..} if *version==snapshot.version),
                );
                if !current {
                  let Some(made) = create_external_rgba_cached_image_texture(
                    device,
                    &image_bgl,
                    &image_sampler,
                    globals_buffer,
                    snapshot,
                  ) else {
                    continue;
                  };
                  self.image_texture_cache.insert(img.image_id, made);
                  self.image_clip_bind_groups.clear();
                }
              }
              if let Some(native) = external_wgpu_image {
                let slot = native.payload::<crate::images::WgpuExternalImageState>();
                let Some(snapshot) = slot.and_then(crate::images::WgpuExternalImageState::snapshot) else {
                  self.image_texture_cache.remove(&img.image_id);
                  continue;
                };
                // A view the app gave before a loss is of the lost device, and of the instance of wgpu that
                // went with it: nothing is asked of wgpu with it, and nothing is drawn of it until the app
                // gives one of this device.
                if !snapshot.is_of(self.device_number) {
                  self.image_texture_cache.remove(&img.image_id);
                  continue;
                }
                let is_current = self.image_texture_cache.get(&img.image_id).is_some_and(|cached| {
                  matches!(
                    cached,
                    CachedImageTexture::ExternalRgba {
                      width,
                      height,
                      version,
                      ..
                    } if *width == snapshot.width && *height == snapshot.height && *version == snapshot.version
                  )
                });
                if !is_current {
                  // And one of another device all the same, given late by something of the app that was not
                  // told of the loss, is refused by this device, which ends nothing.
                  let Some(made) = create_external_rgba_cached_image_texture(
                    device,
                    &image_bgl,
                    &image_sampler,
                    globals_buffer,
                    snapshot,
                  ) else {
                    self.image_texture_cache.remove(&img.image_id);
                    continue;
                  };
                  self.image_texture_cache.insert(img.image_id, made);
                  self.image_clip_bind_groups.clear();
                  // Its view is this device's to let go of, should the device be lost.
                  if let Some(slot) = slot {
                    self.external_slots.retain(|known| known.upgrade().is_some());
                    if !self.external_slots.iter().any(|known| known.is(slot)) {
                      self.external_slots.push(slot.downgrade());
                    }
                  }
                }
              } else if canvas_image.is_none()
                && !self
                  .image_texture_cache
                  .get(&img.image_id)
                  .is_some_and(|cached| cached.is_compatible(img))
              {
                self.image_texture_cache.remove(&img.image_id);
                self.image_clip_bind_groups.clear();
              }
              // A frame of a video that stays on the card is another buffer with each frame: its textures are
              // made anew of the one shown now. Those of the frame before are kept until the next frame is
              // drawn, which the card may still be drawing them for.
              #[cfg(any(target_os = "macos", target_os = "ios"))]
              if self
                .image_texture_cache
                .get(&img.image_id)
                .is_some_and(|cached| cached.is_another_frame_of_the_card(img))
                && let Some(before) = self.image_texture_cache.remove(&img.image_id)
              {
                self.retired_card_frames.push(before);
                self.image_clip_bind_groups.clear();
              }

              if external_wgpu_image.is_none()
                && canvas_image.is_none()
                && !is_card_frames(img)
                && !self.image_texture_cache.contains_key(&img.image_id)
              {
                let _image_texture_upload_start = profile_scope!();
                let cached = match img.image_format {
                  crate::images::ImagePixelFormat::Rgba8 => Some(create_rgba_cached_image_texture(
                    device,
                    queue,
                    &image_bgl,
                    &image_sampler,
                    globals_buffer,
                    img,
                  )),
                  crate::images::ImagePixelFormat::I420 => create_i420_cached_image_texture(
                    device,
                    queue,
                    &i420_image_bgl,
                    &image_sampler,
                    globals_buffer,
                    img,
                  ),
                  crate::images::ImagePixelFormat::Nv12 => create_nv12_cached_image_texture(
                    device,
                    queue,
                    &nv12_image_bgl,
                    &image_bgl,
                    &image_sampler,
                    globals_buffer,
                    img,
                  ),
                };
                _image_texture_upload_dur += profile_elapsed!(_image_texture_upload_start);
                let Some(cached) = cached else {
                  continue;
                };
                self.image_texture_cache.insert(img.image_id, cached);
                self.image_clip_bind_groups.clear();
              }

              let Some(cached) = self.image_texture_cache.get_mut(&img.image_id) else {
                continue;
              };
              match cached {
                CachedImageTexture::ExternalRgba { .. } => {}
                #[cfg(any(target_os = "macos", target_os = "ios"))]
                CachedImageTexture::CvRgba { .. } => {}
                CachedImageTexture::Rgba {
                  texture,
                  animation_frames,
                  frame_index,
                  version,
                  ..
                } => {
                  if animation_frames.is_some() {
                    *frame_index = img.frame_index;
                    *version = img.version;
                  } else if *frame_index != img.frame_index || *version != img.version {
                    let _image_texture_upload_start = profile_scope!();
                    write_rgba_image_texture(queue, texture, img);
                    _image_texture_upload_dur += profile_elapsed!(_image_texture_upload_start);
                    *frame_index = img.frame_index;
                    *version = img.version;
                  }
                }
                CachedImageTexture::Nv12 {
                  y_texture,
                  uv_texture,
                  frame_index,
                  version,
                  ..
                } => {
                  if img.native.is_none() && (*frame_index != img.frame_index || *version != img.version) {
                    let _image_texture_upload_start = profile_scope!();
                    if !write_nv12_image_textures(queue, y_texture, uv_texture, img) {
                      _image_texture_upload_dur += profile_elapsed!(_image_texture_upload_start);
                      continue;
                    }
                    _image_texture_upload_dur += profile_elapsed!(_image_texture_upload_start);
                    *frame_index = img.frame_index;
                    *version = img.version;
                  }
                }
                CachedImageTexture::I420 {
                  textures,
                  frame_index,
                  version,
                  ..
                } => {
                  if *frame_index != img.frame_index || *version != img.version {
                    let _image_texture_upload_start = profile_scope!();
                    if !write_i420_image_textures(queue, textures, img) {
                      _image_texture_upload_dur += profile_elapsed!(_image_texture_upload_start);
                      continue;
                    }
                    _image_texture_upload_dur += profile_elapsed!(_image_texture_upload_start);
                    *frame_index = img.frame_index;
                    *version = img.version;
                  }
                }
                // Nothing is sent to the card for a frame that is there already.
                #[cfg(windows)]
                CachedImageTexture::Card(_) => {}
              }

              if !set_scissor(&mut pass, space.clip(img.clip), &space) {
                continue;
              }

              // A card's frame of red, green and blue is drawn as a texture the app gave is: one view, bound.
              #[cfg(windows)]
              let card_rgba = match &*cached {
                CachedImageTexture::Card(opened) if opened.is_rgba() => match opened.drawn() {
                  Some((surface, slot)) => Some((&slot.bind_group, &slot.first, surface)),
                  None => continue,
                },
                _ => None,
              };
              #[cfg(not(windows))]
              let card_rgba: Option<(&wgpu::BindGroup, &wgpu::TextureView, usize)> = None;
              let one_view = match (&*cached, card_rgba) {
                (_, Some(found)) => Some(found),
                (CachedImageTexture::ExternalRgba { bind_group, view, .. }, None) => Some((bind_group, view, 0)),
                #[cfg(any(target_os = "macos", target_os = "ios"))]
                (CachedImageTexture::CvRgba { bind_group, view, .. }, None) => Some((bind_group, view, 0)),
                _ => None,
              };

              match &*cached {
                _ if one_view.is_some() => {
                  let (bind_group, view, frame) = one_view.expect("just found");
                  if active_pipeline != Some(ActivePipeline::Image) {
                    pass.set_pipeline(&image_pipeline);
                    active_pipeline = Some(ActivePipeline::Image);
                  }
                  if needs_clip_globals(img.clip, &space) {
                    let (clip_key, clip_globals) = self.clip_globals.get(device, img.clip, &space);
                    let bind_key = ImageClipBindGroupKey {
                      image_id: img.image_id,
                      frame_index: frame,
                      clip: clip_key,
                      format: ImageClipFormat::Rgba,
                    };
                    let clip_bind_group = self.image_clip_bind_groups.entry(bind_key).or_insert_with(|| {
                      device.create_bind_group(&wgpu::BindGroupDescriptor {
                        label: Some("lurq_external_image_clip_bg"),
                        layout: &image_bgl,
                        entries: &[
                          wgpu::BindGroupEntry {
                            binding: 0,
                            resource: clip_globals.as_entire_binding(),
                          },
                          wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(view),
                          },
                          wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::Sampler(&image_sampler),
                          },
                        ],
                      })
                    });
                    pass.set_bind_group(0, &*clip_bind_group, &[]);
                  } else {
                    pass.set_bind_group(0, &*bind_group, &[]);
                  }
                }
                CachedImageTexture::Rgba {
                  bind_group,
                  view,
                  animation_frames,
                  ..
                } => {
                  let (bind_group, view) = animation_frames
                    .as_ref()
                    .and_then(|frames| frames.get(img.frame_index))
                    .map(|frame| (&frame.bind_group, &frame.view))
                    .unwrap_or((bind_group, view));
                  if active_pipeline != Some(ActivePipeline::Image) {
                    pass.set_pipeline(&image_pipeline);
                    active_pipeline = Some(ActivePipeline::Image);
                  }
                  if needs_clip_globals(img.clip, &space) {
                    let (clip_key, clip_globals) = self.clip_globals.get(device, img.clip, &space);
                    let bind_key = ImageClipBindGroupKey {
                      image_id: img.image_id,
                      frame_index: img.frame_index,
                      clip: clip_key,
                      format: ImageClipFormat::Rgba,
                    };
                    let clip_bind_group = self.image_clip_bind_groups.entry(bind_key).or_insert_with(|| {
                      device.create_bind_group(&wgpu::BindGroupDescriptor {
                        label: Some("lurq_image_clip_bg"),
                        layout: &image_bgl,
                        entries: &[
                          wgpu::BindGroupEntry {
                            binding: 0,
                            resource: clip_globals.as_entire_binding(),
                          },
                          wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(view),
                          },
                          wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::Sampler(&image_sampler),
                          },
                        ],
                      })
                    });
                    pass.set_bind_group(0, &*clip_bind_group, &[]);
                  } else {
                    pass.set_bind_group(0, bind_group, &[]);
                  }
                }
                CachedImageTexture::I420 {
                  bind_group,
                  y_view,
                  u_view,
                  v_view,
                  ..
                } => {
                  if active_pipeline != Some(ActivePipeline::I420Image) {
                    pass.set_pipeline(&i420_image_pipeline);
                    active_pipeline = Some(ActivePipeline::I420Image);
                  }
                  if needs_clip_globals(img.clip, &space) {
                    let (clip_key, clip_globals) = self.clip_globals.get(device, img.clip, &space);
                    let bind_key = ImageClipBindGroupKey {
                      image_id: img.image_id,
                      frame_index: img.frame_index,
                      clip: clip_key,
                      format: ImageClipFormat::I420,
                    };
                    let clip_bind_group = self.image_clip_bind_groups.entry(bind_key).or_insert_with(|| {
                      i420_bind_group(
                        device,
                        &i420_image_bgl,
                        clip_globals,
                        [y_view, u_view, v_view],
                        &image_sampler,
                      )
                    });
                    pass.set_bind_group(0, &*clip_bind_group, &[]);
                  } else {
                    pass.set_bind_group(0, bind_group, &[]);
                  }
                }
                nv12 => {
                  // The two planes to draw, and which frame they are: of memory's one texture, or of the card's
                  // texture that is shown now.
                  let (bind_group, y_view, uv_view, frame) = match nv12 {
                    CachedImageTexture::Nv12 {
                      bind_group,
                      y_view,
                      uv_view,
                      ..
                    } => (&*bind_group, &*y_view, &*uv_view, img.frame_index),
                    #[cfg(windows)]
                    CachedImageTexture::Card(opened) => {
                      let Some((surface, slot)) = opened.drawn() else {
                        continue;
                      };
                      let Some(color) = slot.second.as_ref() else {
                        continue;
                      };
                      (&slot.bind_group, &slot.first, color, surface)
                    }
                    _ => continue,
                  };
                  if active_pipeline != Some(ActivePipeline::Nv12Image) {
                    pass.set_pipeline(&nv12_image_pipeline);
                    active_pipeline = Some(ActivePipeline::Nv12Image);
                  }
                  if needs_clip_globals(img.clip, &space) {
                    let (clip_key, clip_globals) = self.clip_globals.get(device, img.clip, &space);
                    let bind_key = ImageClipBindGroupKey {
                      image_id: img.image_id,
                      frame_index: frame,
                      clip: clip_key,
                      format: ImageClipFormat::Nv12,
                    };
                    let clip_bind_group = self.image_clip_bind_groups.entry(bind_key).or_insert_with(|| {
                      device.create_bind_group(&wgpu::BindGroupDescriptor {
                        label: Some("lurq_nv12_image_clip_bg"),
                        layout: &nv12_image_bgl,
                        entries: &[
                          wgpu::BindGroupEntry {
                            binding: 0,
                            resource: clip_globals.as_entire_binding(),
                          },
                          wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(y_view),
                          },
                          wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::TextureView(uv_view),
                          },
                          wgpu::BindGroupEntry {
                            binding: 3,
                            resource: wgpu::BindingResource::Sampler(&image_sampler),
                          },
                        ],
                      })
                    });
                    pass.set_bind_group(0, &*clip_bind_group, &[]);
                  } else {
                    pass.set_bind_group(0, &*bind_group, &[]);
                  }
                }
              }
              let image_instance_stride = std::mem::size_of::<ImageInstance>() as wgpu::BufferAddress;
              let image_instance_start = *index as wgpu::BufferAddress * image_instance_stride;
              let image_instance_end = image_instance_start + image_instance_stride;
              if active_vertex_buffer != Some(ActiveVertexBuffer::CommonQuad) {
                pass.set_vertex_buffer(0, vtx_buf.slice(..));
                active_vertex_buffer = Some(ActiveVertexBuffer::CommonQuad);
              }
              pass.set_vertex_buffer(
                1,
                image_instance_buf
                  .unwrap()
                  .slice(image_instance_start..image_instance_end),
              );
              if active_index_buffer != Some(ActiveIndexBuffer::CommonU16) {
                pass.set_index_buffer(idx_buf.slice(..), wgpu::IndexFormat::Uint16);
                active_index_buffer = Some(ActiveIndexBuffer::CommonU16);
              }
              pass.draw_indexed(0..6, 0, 0..1);
              profile_if! { _draw_calls += 1; }
            }
          }
        }
      }
      drop(pass);
      // A blurred layer is reduced and blurred along x once it is painted;
      // the pass compositing it blurs along y.
      if let (Some(slot), Some(blur_slots), Some(compositor)) = (
        layer_slot,
        self.scratch_blur_slots.get(target_index).copied().flatten(),
        self.layer_compositor.as_ref(),
      ) {
        let _blur_passes = compositor.prepare_blur(queue, &mut encoder, vtx_buf, idx_buf, slot, &blur_slots);
        profile_if! {
          _layers.render_passes += _blur_passes;
          _layers.blur_draws += _blur_passes;
        }
      }
    }
    if let Some(compositor) = self.layer_compositor.as_mut() {
      compositor.end_frame();
      profile_if! {
        (_layers.textures, _layers.texture_bytes) = compositor.texture_stats();
        (_, _layers.kept_textures, _layers.kept_texture_bytes) = compositor.backdrop_stats();
      }
    }
    if self.clip_globals.end_frame() {
      let clip_globals = &self.clip_globals;
      self.quad_clip_bind_groups.retain(|key, _| clip_globals.contains(key));
      self.glyph_clip_bind_groups.retain(|key, _| clip_globals.contains(key));
      #[cfg(feature = "raster")]
      self
        .image_clip_bind_groups
        .retain(|key, _| clip_globals.contains(&key.clip));
    }
    self.scratch_ordered_draws = ordered_draws;
    self.layer_plan = layer_plan;
    let _encode_dur = profile_elapsed!(_encode_start);
    #[cfg(feature = "perf_profile")]
    drop(_encode_phase);

    #[cfg(feature = "screenshot")]
    let frame_capture = self
      .pending_frame_capture
      .take()
      .and_then(|capture| encode_wgpu_frame_capture(device, &mut encoder, window_texture, config.format, capture));
    if let Some(proxy) = surface_proxy {
      proxy.put_onto(&mut encoder, &view);
    }

    #[cfg(feature = "perf_profile")]
    self.gpu_timer.resolve(&mut encoder);

    let _submit_start = profile_scope!();
    #[cfg(feature = "perf_profile")]
    let _submit_phase = self
      .profile_context
      .as_ref()
      .map(|context| context.phase(crate::app::profiler::Phase::RenderSubmit));
    queue.submit(std::iter::once(encoder.finish()));
    // The card's frames that were drawn before this one are let go of once the card has done this far.
    #[cfg(all(feature = "raster", windows))]
    self.card_leases.let_go_after(queue);
    // The textures the frame blurred backdrops into hold them from here on.
    if let Some(compositor) = self.layer_compositor.as_mut() {
      compositor.frame_submitted();
    }
    let _submit_dur = profile_elapsed!(_submit_start);
    #[cfg(feature = "perf_profile")]
    drop(_submit_phase);
    #[cfg(feature = "perf_profile")]
    self.gpu_timer.submitted();

    #[cfg(feature = "screenshot")]
    if let Some(frame_capture) = frame_capture {
      frame_capture.start(device.clone(), self.lost.clone());
    }

    let _present_start = profile_scope!();
    #[cfg(feature = "perf_profile")]
    let _present_phase = self
      .profile_context
      .as_ref()
      .map(|context| context.phase(crate::app::profiler::Phase::RenderPresent));
    // A device may be lost while its frame is drawn: what it was given to do tells. wgpu neither presents nor
    // discards a frame of a lost device, and keeps it; let go of with that frame out, the surface ends the
    // program under Vulkan (`Trying to destroy a SwapchainAcquireSemaphore that is still in use by a
    // SurfaceTexture`), and the engine that is to take this one's place never comes. The frame's texture is
    // destroyed first, which is what gives the frame back.
    if self.device_is_lost() {
      output.texture().destroy();
    }
    output.present();
    let _present_dur = profile_elapsed!(_present_start);
    #[cfg(feature = "perf_profile")]
    drop(_present_phase);

    profile_if! {
      self.last_profile = RenderProfile {
        init: _init_dur,
        acquire: _acquire_dur,
        canvas: _canvas_profile,
        globals_upload: _globals_dur,
        atlas_upload: _atlas_dur,
        glyph_atlas_upload_bytes: _atlas_upload_bytes,
        glyph_atlas_upload_rects: _atlas_upload_rects,
        glyph_atlas_full_uploads: _atlas_full_uploads,
        glyph_atlas_arena_uploads: 0,
        glyph_atlas_dedicated_uploads: 0,
        draw_calls: _draw_calls,
        buffer_upload: _buffer_upload_dur,
        image_upload: _image_texture_upload_dur,
        encode: _encode_dur,
        submit: _submit_dur,
        present: _present_dur,
        total: profile_elapsed!(_total_start),
      };
      self.last_layer_profile = _layers;
    }
    true
  }

  #[cfg(feature = "screenshot")]
  fn supports_frame_capture(&self) -> bool {
    true
  }

  #[cfg(feature = "screenshot")]
  fn render_with_capture(
    &mut self,
    list: &RenderList,
    window: WindowHandle<'_>,
    display: DisplayHandle<'_>,
    capture: Option<RenderFrameCapture>,
  ) -> bool {
    if let Some(previous) = std::mem::replace(&mut self.pending_frame_capture, capture) {
      previous.target.fail("superseded before a frame was rendered");
    }
    self.render(list, window, display)
  }

  /// Also where the device is whole and of another card than the one a device was lost on, once that card
  /// makes a device again: the engine that takes this one's place draws on it.
  /// Every engine on another card says so once one of them found that: a window that is not drawn now asks
  /// nothing, and goes back with the one that asked.
  fn lost(&self) -> bool {
    #[cfg(not(target_arch = "wasm32"))]
    if self.displaced && device_loss::the_card_gave() {
      return true;
    }
    self.device_is_lost() || self.card_is_back
  }

  fn release_window_surface(&mut self) {
    let _own = app_errors::OwnWork::begin();
    if let Some(device) = &self.device {
      device_loss::asked(device, Some(&self.lost), wgpu::PollType::Poll);
    }
    self.surface_config = None;
    self.surface = None;
  }

  fn wants_redraw(&self) -> bool {
    self.frame_extensions.iter().any(|entry| entry.extension.wants_redraw())
  }

  #[cfg(feature = "perf_profile")]
  fn last_profile(&self) -> Option<RenderProfile> {
    Some(self.last_profile)
  }

  #[cfg(feature = "perf_profile")]
  fn layer_profile(&self) -> Option<crate::app::profile_types::LayerProfile> {
    Some(self.last_layer_profile)
  }
}

/// Where a frame is drawn: the window surface's texture, or a texture of the surface's size and format that a capture
/// is taken from and that is never shown.
enum FrameTarget {
  Surface(wgpu::SurfaceTexture),
  Offscreen(wgpu::Texture),
}

impl FrameTarget {
  fn texture(&self) -> &wgpu::Texture {
    match self {
      Self::Surface(output) => &output.texture,
      Self::Offscreen(texture) => texture,
    }
  }

  fn present(self) {
    if let Self::Surface(output) = self {
      output.present();
    }
  }
}

#[cfg(feature = "screenshot")]
struct WgpuFrameCaptureReadback {
  buffer: wgpu::Buffer,
  format: wgpu::TextureFormat,
  padded_bytes_per_row: u32,
  capture: RenderFrameCapture,
}

#[cfg(feature = "screenshot")]
impl WgpuFrameCaptureReadback {
  fn start(self, device: wgpu::Device, lost: std::sync::Arc<std::sync::atomic::AtomicBool>) {
    std::thread::spawn(move || {
      let slice = self.buffer.slice(..);
      let (sender, receiver) = std::sync::mpsc::channel();
      slice.map_async(wgpu::MapMode::Read, move |result| {
        let _ = sender.send(result);
      });
      // A device that is lost gives no pixels, and asking it would end this thread with nothing said to
      // whoever waits for the screenshot.
      if !device_loss::asked(&device, Some(&lost), wgpu::PollType::wait_indefinitely()) {
        self.capture.target.fail("the graphics device was lost");
        return;
      }
      match receiver.recv() {
        Ok(Ok(())) => {}
        Ok(Err(error)) => {
          self
            .capture
            .target
            .fail(format!("failed to map screenshot readback buffer: {error:?}"));
          return;
        }
        Err(error) => {
          self
            .capture
            .target
            .fail(format!("failed to receive screenshot readback result: {error}"));
          return;
        }
      }

      let data = slice.get_mapped_range();
      let bgra = matches!(
        self.format,
        wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb
      );
      let pixels = crate::app::frame_capture::capture_rows_to_rgba(
        &data,
        self.padded_bytes_per_row as usize,
        self.capture.width,
        self.capture.height,
        bgra,
      );
      drop(data);
      self.buffer.unmap();

      crate::app::frame_capture::finish_capture(pixels, &self.capture);
    });
  }
}

#[cfg(feature = "screenshot")]
fn encode_wgpu_frame_capture(
  device: &wgpu::Device,
  encoder: &mut wgpu::CommandEncoder,
  texture: &wgpu::Texture,
  format: wgpu::TextureFormat,
  capture: RenderFrameCapture,
) -> Option<WgpuFrameCaptureReadback> {
  if capture.width == 0 || capture.height == 0 {
    capture.target.fail("capture region is empty");
    return None;
  }

  let bytes_per_pixel = 4_u32;
  let unpadded_bytes_per_row = capture.width * bytes_per_pixel;
  let padded_bytes_per_row =
    crate::app::frame_capture::align_capture_row_pitch(unpadded_bytes_per_row, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
  let buffer_size = padded_bytes_per_row as u64 * capture.height as u64;
  let buffer = device.create_buffer(&wgpu::BufferDescriptor {
    label: Some("lurq_screenshot_frame_capture"),
    size: buffer_size,
    usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
    mapped_at_creation: false,
  });

  encoder.copy_texture_to_buffer(
    wgpu::TexelCopyTextureInfo {
      texture,
      mip_level: 0,
      origin: wgpu::Origin3d {
        x: capture.x,
        y: capture.y,
        z: 0,
      },
      aspect: wgpu::TextureAspect::All,
    },
    wgpu::TexelCopyBufferInfo {
      buffer: &buffer,
      layout: wgpu::TexelCopyBufferLayout {
        offset: 0,
        bytes_per_row: Some(padded_bytes_per_row),
        rows_per_image: Some(capture.height),
      },
    },
    wgpu::Extent3d {
      width: capture.width,
      height: capture.height,
      depth_or_array_layers: 1,
    },
  );

  Some(WgpuFrameCaptureReadback {
    buffer,
    format,
    padded_bytes_per_row,
    capture,
  })
}

#[cfg(feature = "raster")]
fn create_external_rgba_cached_image_texture(
  device: &wgpu::Device,
  image_bgl: &wgpu::BindGroupLayout,
  image_sampler: &wgpu::Sampler,
  globals_buffer: &wgpu::Buffer,
  snapshot: crate::images::WgpuExternalImageSnapshot,
) -> Option<CachedImageTexture> {
  // The view may be of another device: one an app gave before a loss, which nothing of this device binds.
  let bind_group = device_loss::taken(device, || {
    device.create_bind_group(&wgpu::BindGroupDescriptor {
      label: Some("lurq_external_img_bg"),
      layout: image_bgl,
      entries: &[
        wgpu::BindGroupEntry {
          binding: 0,
          resource: globals_buffer.as_entire_binding(),
        },
        wgpu::BindGroupEntry {
          binding: 1,
          resource: wgpu::BindingResource::TextureView(&snapshot.view),
        },
        wgpu::BindGroupEntry {
          binding: 2,
          resource: wgpu::BindingResource::Sampler(image_sampler),
        },
      ],
    })
  })?;
  Some(CachedImageTexture::ExternalRgba {
    bind_group,
    view: snapshot.view,
    width: snapshot.width,
    height: snapshot.height,
    version: snapshot.version,
  })
}

#[cfg(feature = "raster")]
fn create_rgba_cached_image_texture(
  device: &wgpu::Device,
  queue: &wgpu::Queue,
  image_bgl: &wgpu::BindGroupLayout,
  image_sampler: &wgpu::Sampler,
  globals_buffer: &wgpu::Buffer,
  image: &crate::images::ImageCmd,
) -> CachedImageTexture {
  let frame = create_rgba_frame_texture(
    device,
    queue,
    image_bgl,
    image_sampler,
    globals_buffer,
    image.image_width,
    image.image_height,
    &image.data,
  );
  let animation_frames = image.animation_frames.as_ref().and_then(|frames| {
    (frames.len() > 1).then(|| {
      frames
        .iter()
        .map(|frame| {
          create_rgba_frame_texture(
            device,
            queue,
            image_bgl,
            image_sampler,
            globals_buffer,
            image.image_width,
            image.image_height,
            frame,
          )
        })
        .collect()
    })
  });

  CachedImageTexture::Rgba {
    bind_group: frame.bind_group,
    view: frame.view,
    texture: frame.texture,
    animation_frames,
    width: image.image_width,
    height: image.image_height,
    frame_index: image.frame_index,
    version: image.version,
  }
}

#[cfg(feature = "raster")]
fn create_rgba_frame_texture(
  device: &wgpu::Device,
  queue: &wgpu::Queue,
  image_bgl: &wgpu::BindGroupLayout,
  image_sampler: &wgpu::Sampler,
  globals_buffer: &wgpu::Buffer,
  width: u32,
  height: u32,
  data: &[u8],
) -> CachedRgbaFrame {
  let texture = device.create_texture(&wgpu::TextureDescriptor {
    label: Some("lurq_img"),
    size: wgpu::Extent3d {
      width,
      height,
      depth_or_array_layers: 1,
    },
    mip_level_count: 1,
    sample_count: 1,
    dimension: wgpu::TextureDimension::D2,
    format: wgpu::TextureFormat::Rgba8UnormSrgb,
    usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
    view_formats: &[],
  });
  write_rgba_texture_data(queue, &texture, width, height, data);
  let view = texture.create_view(&Default::default());
  let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
    label: Some("lurq_img_bg"),
    layout: image_bgl,
    entries: &[
      wgpu::BindGroupEntry {
        binding: 0,
        resource: globals_buffer.as_entire_binding(),
      },
      wgpu::BindGroupEntry {
        binding: 1,
        resource: wgpu::BindingResource::TextureView(&view),
      },
      wgpu::BindGroupEntry {
        binding: 2,
        resource: wgpu::BindingResource::Sampler(image_sampler),
      },
    ],
  });
  CachedRgbaFrame {
    bind_group,
    view,
    texture,
  }
}

#[cfg(feature = "raster")]
fn create_nv12_cached_image_texture(
  device: &wgpu::Device,
  queue: &wgpu::Queue,
  nv12_image_bgl: &wgpu::BindGroupLayout,
  #[cfg_attr(not(any(target_os = "macos", target_os = "ios")), allow(unused_variables))]
  image_bgl: &wgpu::BindGroupLayout,
  image_sampler: &wgpu::Sampler,
  globals_buffer: &wgpu::Buffer,
  image: &crate::images::ImageCmd,
) -> Option<CachedImageTexture> {
  if image.image_width == 0 || image.image_height == 0 {
    return None;
  }
  // A pixel buffer's frame, of any size: its planes are opened as they are, or its one of red, green and blue.
  #[cfg(any(target_os = "macos", target_os = "ios"))]
  if matches!(
    image.native.as_ref().map(crate::images::NativeImageData::backend),
    Some(crate::images::NativeImageBackend::MacosCvPixelBufferNv12)
  ) {
    return create_macos_native_nv12_cached_image_texture(
      device,
      nv12_image_bgl,
      image_bgl,
      image_sampler,
      globals_buffer,
      image,
    );
  }
  if !image.image_width.is_multiple_of(2) || !image.image_height.is_multiple_of(2) {
    return None;
  }
  // The frames of the card are opened before the images are drawn, and are not made here.
  if is_card_frames(image) {
    return None;
  }

  let y_texture = device.create_texture(&wgpu::TextureDescriptor {
    label: Some("lurq_nv12_y"),
    size: wgpu::Extent3d {
      width: image.image_width,
      height: image.image_height,
      depth_or_array_layers: 1,
    },
    mip_level_count: 1,
    sample_count: 1,
    dimension: wgpu::TextureDimension::D2,
    format: wgpu::TextureFormat::R8Unorm,
    usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
    view_formats: &[],
  });
  let uv_texture = device.create_texture(&wgpu::TextureDescriptor {
    label: Some("lurq_nv12_uv"),
    size: wgpu::Extent3d {
      width: image.image_width / 2,
      height: image.image_height / 2,
      depth_or_array_layers: 1,
    },
    mip_level_count: 1,
    sample_count: 1,
    dimension: wgpu::TextureDimension::D2,
    format: wgpu::TextureFormat::Rg8Unorm,
    usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
    view_formats: &[],
  });
  if !write_nv12_image_textures(queue, &y_texture, &uv_texture, image) {
    return None;
  }
  let y_view = y_texture.create_view(&Default::default());
  let uv_view = uv_texture.create_view(&Default::default());
  let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
    label: Some("lurq_nv12_img_bg"),
    layout: nv12_image_bgl,
    entries: &[
      wgpu::BindGroupEntry {
        binding: 0,
        resource: globals_buffer.as_entire_binding(),
      },
      wgpu::BindGroupEntry {
        binding: 1,
        resource: wgpu::BindingResource::TextureView(&y_view),
      },
      wgpu::BindGroupEntry {
        binding: 2,
        resource: wgpu::BindingResource::TextureView(&uv_view),
      },
      wgpu::BindGroupEntry {
        binding: 3,
        resource: wgpu::BindingResource::Sampler(image_sampler),
      },
    ],
  });
  Some(CachedImageTexture::Nv12 {
    bind_group,
    color: [0.0, 0.0],
    y_view,
    uv_view,
    y_texture,
    uv_texture,
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    _macos_native: None,
    width: image.image_width,
    height: image.image_height,
    frame_index: image.frame_index,
    version: image.version,
  })
}

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
fn create_macos_native_nv12_cached_image_texture(
  device: &wgpu::Device,
  nv12_image_bgl: &wgpu::BindGroupLayout,
  image_bgl: &wgpu::BindGroupLayout,
  image_sampler: &wgpu::Sampler,
  globals_buffer: &wgpu::Buffer,
  image: &crate::images::ImageCmd,
) -> Option<CachedImageTexture> {
  let native = image.native.as_ref()?.clone();
  // One buffer the app gave, or the frame of a video that is shown now: none before its first.
  let buffer = match native.payload::<crate::images::CvPixelBufferFrames>() {
    Some(frames) => frames.shown()?,
    None => native
      .payload::<crate::images::MacosCvPixelBufferNv12Image>()?
      .pixel_buffer
      .clone(),
  };
  // A frame of red, green and blue is a picture, of one view.
  // SAFETY: the buffer is held for as long as this runs.
  if unsafe { video_color::is_bgra(buffer.as_ptr()) } {
    return create_macos_native_bgra_cached_image_texture(
      device,
      image_bgl,
      image_sampler,
      globals_buffer,
      image,
      native,
      buffer,
    );
  }
  // SAFETY: as above.
  let color = unsafe { video_color::of(buffer.as_ptr()) }?;
  // Ten bits are the high ones of sixteen, which a texture of 16-bit unorm reads as the same fraction of the range.
  let ((y_metal, y_format), (uv_metal, uv_format)) = if color.ten_bit {
    if !device.features().contains(wgpu::Features::TEXTURE_FORMAT_16BIT_NORM) {
      return None;
    }
    (
      (objc2_metal::MTLPixelFormat::R16Unorm, wgpu::TextureFormat::R16Unorm),
      (objc2_metal::MTLPixelFormat::RG16Unorm, wgpu::TextureFormat::Rg16Unorm),
    )
  } else {
    (
      (objc2_metal::MTLPixelFormat::R8Unorm, wgpu::TextureFormat::R8Unorm),
      (objc2_metal::MTLPixelFormat::RG8Unorm, wgpu::TextureFormat::Rg8Unorm),
    )
  };
  let (y_texture, y_cv_texture) = create_macos_native_plane_texture(
    device,
    buffer.as_ptr(),
    image.image_width,
    image.image_height,
    0,
    y_metal,
    y_format,
    "lurq_macos_nv12_y",
  )?;
  // A picture of an odd width or height has its last column or row of color too.
  let (uv_texture, uv_cv_texture) = create_macos_native_plane_texture(
    device,
    buffer.as_ptr(),
    image.image_width.div_ceil(2),
    image.image_height.div_ceil(2),
    1,
    uv_metal,
    uv_format,
    "lurq_macos_nv12_uv",
  )?;
  let y_view = y_texture.create_view(&Default::default());
  let uv_view = uv_texture.create_view(&Default::default());
  let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
    label: Some("lurq_macos_nv12_img_bg"),
    layout: nv12_image_bgl,
    entries: &[
      wgpu::BindGroupEntry {
        binding: 0,
        resource: globals_buffer.as_entire_binding(),
      },
      wgpu::BindGroupEntry {
        binding: 1,
        resource: wgpu::BindingResource::TextureView(&y_view),
      },
      wgpu::BindGroupEntry {
        binding: 2,
        resource: wgpu::BindingResource::TextureView(&uv_view),
      },
      wgpu::BindGroupEntry {
        binding: 3,
        resource: wgpu::BindingResource::Sampler(image_sampler),
      },
    ],
  });
  Some(CachedImageTexture::Nv12 {
    bind_group,
    color: color.shader(),
    y_view,
    uv_view,
    y_texture,
    uv_texture,
    _macos_native: Some(MacosNativeNv12Texture {
      _native: native,
      _buffer: buffer,
      _y_cv_texture: y_cv_texture,
      _uv_cv_texture: uv_cv_texture,
    }),
    width: image.image_width,
    height: image.image_height,
    frame_index: image.frame_index,
    version: image.version,
  })
}

/// The texture of a frame of red, green and blue in a pixel buffer, read as sRGB, as a picture's is.
#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
fn create_macos_native_bgra_cached_image_texture(
  device: &wgpu::Device,
  image_bgl: &wgpu::BindGroupLayout,
  image_sampler: &wgpu::Sampler,
  globals_buffer: &wgpu::Buffer,
  image: &crate::images::ImageCmd,
  native: crate::images::NativeImageData,
  buffer: crate::images::MacosCvPixelBuffer,
) -> Option<CachedImageTexture> {
  let (texture, cv_texture) = create_macos_native_plane_texture(
    device,
    buffer.as_ptr(),
    image.image_width,
    image.image_height,
    0,
    objc2_metal::MTLPixelFormat::BGRA8Unorm_sRGB,
    wgpu::TextureFormat::Bgra8UnormSrgb,
    "lurq_macos_bgra",
  )?;
  let view = texture.create_view(&Default::default());
  let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
    label: Some("lurq_macos_bgra_img_bg"),
    layout: image_bgl,
    entries: &[
      wgpu::BindGroupEntry {
        binding: 0,
        resource: globals_buffer.as_entire_binding(),
      },
      wgpu::BindGroupEntry {
        binding: 1,
        resource: wgpu::BindingResource::TextureView(&view),
      },
      wgpu::BindGroupEntry {
        binding: 2,
        resource: wgpu::BindingResource::Sampler(image_sampler),
      },
    ],
  });
  Some(CachedImageTexture::CvRgba {
    bind_group,
    view,
    _held: MacosNativeRgbaTexture {
      _native: native,
      _buffer: buffer,
      _cv_texture: cv_texture,
    },
    width: image.image_width,
    height: image.image_height,
    version: image.version,
  })
}

#[cfg(all(feature = "raster", any(target_os = "macos", target_os = "ios")))]
fn create_macos_native_plane_texture(
  device: &wgpu::Device,
  pixel_buffer: CVPixelBufferRef,
  width: u32,
  height: u32,
  plane_index: usize,
  metal_format: objc2_metal::MTLPixelFormat,
  wgpu_format: wgpu::TextureFormat,
  label: &'static str,
) -> Option<(wgpu::Texture, CvMetalTexture)> {
  // wgpu 29 returns a HAL guard and uses objc2 Metal protocol objects.
  // Clone the retained device before releasing the guard; the CoreVideo cache
  // and textures must originate from the same Metal device as wgpu.
  let raw_device = unsafe { device.as_hal::<wgpu_hal::api::Metal>() }?.raw_device().clone();
  // One cache of textures for a device, kept: a video asks it for two textures a frame.
  let device_ptr = Retained::as_ptr(&raw_device) as usize;
  let cache = CV_TEXTURE_CACHE.with(|kept| {
    let mut kept = kept.borrow_mut();
    if let Some((of, cache)) = kept.as_ref()
      && *of == device_ptr
    {
      return Some(cache.ptr);
    }
    let mut cache = std::ptr::null_mut();
    let status = unsafe {
      CVMetalTextureCacheCreate(
        kCFAllocatorDefault,
        std::ptr::null(),
        Retained::as_ptr(&raw_device).cast_mut().cast(),
        std::ptr::null(),
        &mut cache,
      )
    };
    if status != 0 || cache.is_null() {
      return None;
    }
    *kept = Some((device_ptr, CvMetalTextureCache { ptr: cache }));
    Some(cache)
  })?;

  let mut cv_texture = std::ptr::null_mut();
  let status = unsafe {
    CVMetalTextureCacheCreateTextureFromImage(
      kCFAllocatorDefault,
      cache,
      pixel_buffer,
      std::ptr::null(),
      metal_format,
      width as usize,
      height as usize,
      plane_index,
      &mut cv_texture,
    )
  };
  if status != 0 || cv_texture.is_null() {
    return None;
  }

  let metal_texture_ptr = unsafe { CVMetalTextureGetTexture(cv_texture) };
  if metal_texture_ptr.is_null() {
    unsafe {
      CFRelease(cv_texture.cast());
    }
    return None;
  }
  // CVMetalTextureGetTexture returns a borrowed Objective-C texture. Retain it
  // for wgpu independently of the CVMetalTexture owner retained below.
  let metal_texture: Retained<ProtocolObject<dyn objc2_metal::MTLTexture>> =
    unsafe { Retained::retain(metal_texture_ptr.cast()).expect("non-null CoreVideo Metal texture") };
  let hal_texture = unsafe {
    wgpu_hal::metal::Device::texture_from_raw(
      metal_texture,
      wgpu_format,
      objc2_metal::MTLTextureType::Type2D,
      1,
      1,
      wgpu_hal::CopyExtent {
        width,
        height,
        depth: 1,
      },
    )
  };
  let texture = unsafe {
    device.create_texture_from_hal::<wgpu_hal::api::Metal>(
      hal_texture,
      &wgpu::TextureDescriptor {
        label: Some(label),
        size: wgpu::Extent3d {
          width,
          height,
          depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu_format,
        usage: wgpu::TextureUsages::TEXTURE_BINDING,
        view_formats: &[],
      },
    )
  };
  Some((texture, CvMetalTexture { ptr: cv_texture }))
}

#[cfg(feature = "raster")]
fn write_rgba_image_texture(queue: &wgpu::Queue, texture: &wgpu::Texture, image: &crate::images::ImageCmd) {
  write_rgba_texture_data(queue, texture, image.image_width, image.image_height, &image.data);
}

#[cfg(feature = "raster")]
fn write_rgba_texture_data(queue: &wgpu::Queue, texture: &wgpu::Texture, width: u32, height: u32, data: &[u8]) {
  queue.write_texture(
    wgpu::TexelCopyTextureInfo {
      texture,
      mip_level: 0,
      origin: wgpu::Origin3d::ZERO,
      aspect: wgpu::TextureAspect::All,
    },
    data,
    wgpu::TexelCopyBufferLayout {
      offset: 0,
      bytes_per_row: Some(width * 4),
      rows_per_image: Some(height),
    },
    wgpu::Extent3d {
      width,
      height,
      depth_or_array_layers: 1,
    },
  );
}

/// The shader of a picture of three planes: the NV12 one, with the two of color read from two textures.
#[cfg(feature = "raster")]
fn i420_shader_source() -> String {
  let nv12 = concat!(
    include_str!("shaders/image_nv12.wgsl"),
    include_str!("shaders/yuv.wgsl")
  );
  let bindings = "@group(0) @binding(2) var uv_tex: texture_2d<f32>;\n@group(0) @binding(3) var img_sampler: sampler;";
  let sample = "let uv = textureSample(uv_tex, img_sampler, in.uv).rg;";
  assert!(
    nv12.contains(bindings) && nv12.contains(sample),
    "the NV12 shader reads its color as it did"
  );
  nv12
    .replace(
      bindings,
      "@group(0) @binding(2) var u_tex: texture_2d<f32>;\n@group(0) @binding(3) var v_tex: texture_2d<f32>;\n\
       @group(0) @binding(4) var img_sampler: sampler;",
    )
    .replace(
      sample,
      "let uv = vec2<f32>(textureSample(u_tex, img_sampler, in.uv).r, textureSample(v_tex, img_sampler, in.uv).r);",
    )
}

/// The bind group of a picture of three planes, with the globals of its draw.
#[cfg(feature = "raster")]
fn i420_bind_group(
  device: &wgpu::Device,
  layout: &wgpu::BindGroupLayout,
  globals: &wgpu::Buffer,
  planes: [&wgpu::TextureView; 3],
  sampler: &wgpu::Sampler,
) -> wgpu::BindGroup {
  let view = |binding, view| wgpu::BindGroupEntry {
    binding,
    resource: wgpu::BindingResource::TextureView(view),
  };
  device.create_bind_group(&wgpu::BindGroupDescriptor {
    label: Some("lurq_i420_image_bg"),
    layout,
    entries: &[
      wgpu::BindGroupEntry {
        binding: 0,
        resource: globals.as_entire_binding(),
      },
      view(1, planes[0]),
      view(2, planes[1]),
      view(3, planes[2]),
      wgpu::BindGroupEntry {
        binding: 4,
        resource: wgpu::BindingResource::Sampler(sampler),
      },
    ],
  })
}

/// The textures of a picture of memory of three planes, with its first frame in them.
#[cfg(feature = "raster")]
fn create_i420_cached_image_texture(
  device: &wgpu::Device,
  queue: &wgpu::Queue,
  i420_image_bgl: &wgpu::BindGroupLayout,
  image_sampler: &wgpu::Sampler,
  globals_buffer: &wgpu::Buffer,
  image: &crate::images::ImageCmd,
) -> Option<CachedImageTexture> {
  let (width, height) = (image.image_width, image.image_height);
  if width == 0 || height == 0 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
    return None;
  }
  let plane = |label, width, height| {
    device.create_texture(&wgpu::TextureDescriptor {
      label: Some(label),
      size: wgpu::Extent3d {
        width,
        height,
        depth_or_array_layers: 1,
      },
      mip_level_count: 1,
      sample_count: 1,
      dimension: wgpu::TextureDimension::D2,
      format: wgpu::TextureFormat::R8Unorm,
      usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
      view_formats: &[],
    })
  };
  let textures = [
    plane("lurq_i420_y", width, height),
    plane("lurq_i420_u", width / 2, height / 2),
    plane("lurq_i420_v", width / 2, height / 2),
  ];
  if !write_i420_image_textures(queue, &textures, image) {
    return None;
  }
  let [y_view, u_view, v_view] = textures
    .each_ref()
    .map(|texture| texture.create_view(&Default::default()));
  let bind_group = i420_bind_group(
    device,
    i420_image_bgl,
    globals_buffer,
    [&y_view, &u_view, &v_view],
    image_sampler,
  );
  Some(CachedImageTexture::I420 {
    bind_group,
    y_view,
    u_view,
    v_view,
    textures,
    width,
    height,
    frame_index: image.frame_index,
    version: image.version,
  })
}

/// Sends the three planes of `image` to its textures as they are laid out: no pass over them on the processor.
#[cfg(feature = "raster")]
fn write_i420_image_textures(
  queue: &wgpu::Queue,
  textures: &[wgpu::Texture; 3],
  image: &crate::images::ImageCmd,
) -> bool {
  let (width, height) = (image.image_width, image.image_height);
  let gray = width as usize * height as usize;
  let color = gray / 4;
  if image.data.len() < gray + 2 * color {
    return false;
  }
  let planes = [
    (&textures[0], 0, width, height),
    (&textures[1], gray, width / 2, height / 2),
    (&textures[2], gray + color, width / 2, height / 2),
  ];
  for (texture, start, plane_width, plane_height) in planes {
    queue.write_texture(
      texture.as_image_copy(),
      &image.data[start..start + plane_width as usize * plane_height as usize],
      wgpu::TexelCopyBufferLayout {
        offset: 0,
        bytes_per_row: Some(plane_width),
        rows_per_image: Some(plane_height),
      },
      wgpu::Extent3d {
        width: plane_width,
        height: plane_height,
        depth_or_array_layers: 1,
      },
    );
  }
  true
}

#[cfg(feature = "raster")]
fn write_nv12_image_textures(
  queue: &wgpu::Queue,
  y_texture: &wgpu::Texture,
  uv_texture: &wgpu::Texture,
  image: &crate::images::ImageCmd,
) -> bool {
  let y_len = image.image_width as usize * image.image_height as usize;
  let uv_len = y_len / 2;
  if image.data.len() < y_len + uv_len {
    return false;
  }
  queue.write_texture(
    wgpu::TexelCopyTextureInfo {
      texture: y_texture,
      mip_level: 0,
      origin: wgpu::Origin3d::ZERO,
      aspect: wgpu::TextureAspect::All,
    },
    &image.data[..y_len],
    wgpu::TexelCopyBufferLayout {
      offset: 0,
      bytes_per_row: Some(image.image_width),
      rows_per_image: Some(image.image_height),
    },
    wgpu::Extent3d {
      width: image.image_width,
      height: image.image_height,
      depth_or_array_layers: 1,
    },
  );
  queue.write_texture(
    wgpu::TexelCopyTextureInfo {
      texture: uv_texture,
      mip_level: 0,
      origin: wgpu::Origin3d::ZERO,
      aspect: wgpu::TextureAspect::All,
    },
    &image.data[y_len..y_len + uv_len],
    wgpu::TexelCopyBufferLayout {
      offset: 0,
      bytes_per_row: Some(image.image_width),
      rows_per_image: Some(image.image_height / 2),
    },
    wgpu::Extent3d {
      width: image.image_width / 2,
      height: image.image_height / 2,
      depth_or_array_layers: 1,
    },
  );
  true
}

/// The format lurq renders the surface through: the surface's own format
/// without an sRGB suffix. Shaders write sRGB-encoded colour, so alpha blending
/// mixes encoded values like CSS instead of linear light.
fn render_target_format(surface_format: wgpu::TextureFormat) -> wgpu::TextureFormat {
  surface_format.remove_srgb_suffix()
}

/// The clear value for the non-sRGB render target: the colour's sRGB channels.
fn wgpu_clear_color(color: crate::node::color::Color) -> wgpu::Color {
  let [r, g, b, a] = color.to_f32_array();
  wgpu::Color {
    r: r as f64,
    g: g as f64,
    b: b as f64,
    a: a as f64,
  }
}

/// Globals for a draw clipped by `clip`, already in `space`'s pixels.
fn globals_for_clip(clip: crate::layout::quad::ClipRect, space: &TargetSpace) -> Globals {
  Globals::for_clip(space.viewport(), clip)
}

fn rounded_clip_needs_shader(clip: crate::layout::quad::ClipRect) -> bool {
  clip.is_rounded()
}

/// Whether a draw into `space` needs globals of its own: the shared ones
/// describe the whole window and no rounded clip.
fn needs_clip_globals(clip: crate::layout::quad::ClipRect, space: &TargetSpace) -> bool {
  !space.is_window() || rounded_clip_needs_shader(clip)
}

/// Frames a clip's globals may stay unused before their buffer is released.
/// Layers that move create globals of their own every frame.
const CLIP_GLOBALS_IDLE_FRAMES: u64 = 120;

/// Uniform buffers holding the globals of clipped draws and of draws into
/// layers, keyed by their contents.
#[derive(Default)]
struct ClipGlobalsCache {
  buffers: std::collections::HashMap<ClipGlobalsKey, (wgpu::Buffer, u64)>,
  frame: u64,
}

impl ClipGlobalsCache {
  /// The globals of a draw into `space` clipped by `clip` (window pixels).
  fn get(
    &mut self,
    device: &wgpu::Device,
    clip: crate::layout::quad::ClipRect,
    space: &TargetSpace,
  ) -> (ClipGlobalsKey, &wgpu::Buffer) {
    let globals = globals_for_clip(space.clip(clip), space);
    let key = clip_globals_key(&globals);
    let frame = self.frame;
    let (buffer, last_used) = self.buffers.entry(key).or_insert_with(|| {
      let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
        label: Some("lurq_clip_globals"),
        contents: bytemuck::bytes_of(&globals),
        usage: wgpu::BufferUsages::UNIFORM,
      });
      (buffer, frame)
    });
    *last_used = frame;
    (key, buffer)
  }

  fn contains(&self, key: &ClipGlobalsKey) -> bool {
    self.buffers.contains_key(key)
  }

  fn clear(&mut self) {
    self.buffers.clear();
  }

  /// Releases globals unused for a while; returns whether any were, so bind
  /// groups built on them can be dropped too.
  fn end_frame(&mut self) -> bool {
    let frame = self.frame;
    self.frame += 1;
    let before = self.buffers.len();
    self
      .buffers
      .retain(|_, (_, last_used)| frame - *last_used <= CLIP_GLOBALS_IDLE_FRAMES);
    self.buffers.len() != before
  }
}

fn clip_globals_key(globals: &Globals) -> ClipGlobalsKey {
  ClipGlobalsKey(bytemuck::cast(*globals))
}

/// Scissors to `clip`, already in `space`'s pixels.
fn set_scissor(pass: &mut wgpu::RenderPass<'_>, clip: crate::layout::quad::ClipRect, space: &TargetSpace) -> bool {
  let Some((x, y, width, height)) = scissor_rect(clip, space.width, space.height) else {
    return false;
  };
  pass.set_scissor_rect(x, y, width, height);
  true
}

fn scissor_rect(clip: crate::layout::quad::ClipRect, vw: f32, vh: f32) -> Option<(u32, u32, u32, u32)> {
  let viewport_w = vw.ceil().max(1.0) as u32;
  let viewport_h = vh.ceil().max(1.0) as u32;

  if clip.active {
    let left = clip.x.floor().max(0.0);
    let top = clip.y.floor().max(0.0);
    let right = (clip.x + clip.width).ceil().clamp(0.0, viewport_w as f32);
    let bottom = (clip.y + clip.height).ceil().clamp(0.0, viewport_h as f32);
    if right <= left || bottom <= top {
      return None;
    }

    let cx = left as u32;
    let cy = top as u32;
    if cx >= viewport_w || cy >= viewport_h {
      return None;
    }
    let cw = ((right - left).ceil() as u32).min(viewport_w.saturating_sub(cx));
    let ch = ((bottom - top).ceil() as u32).min(viewport_h.saturating_sub(cy));
    if cw == 0 || ch == 0 {
      return None;
    }
    Some((cx, cy, cw, ch))
  } else {
    Some((0, 0, viewport_w, viewport_h))
  }
}

fn wgpu_staged_texture_bytes(row_bytes: u32, height: u32) -> usize {
  align_up_usize(row_bytes as usize, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize) * height as usize
}

fn align_up_usize(value: usize, alignment: usize) -> usize {
  debug_assert!(alignment > 0);
  value.div_ceil(alignment) * alignment
}

#[cfg(test)]
mod tests {
  use crate::{app::render_engine::RenderEngine, layout::quad::ClipRect};

  #[test]
  fn backends_are_selected_without_initializing_excluded_loaders() {
    let engine = super::WgpuRenderEngine::new();
    assert!(engine.instance.is_none());
    #[cfg(windows)]
    assert_eq!(engine.backends, super::WgpuBackends::DX12);
    let engine = engine.with_backends(super::WgpuBackends::VULKAN);
    assert!(engine.instance.is_none());
    assert_eq!(engine.backends, super::WgpuBackends::VULKAN);
  }

  #[test]
  fn scissor_expands_fractional_clip_to_include_bottom_right_edge() {
    assert_eq!(
      super::scissor_rect(ClipRect::rect(10.6, 20.2, 30.1, 40.6), 100.0, 100.0,),
      Some((10, 20, 31, 41))
    );
  }

  #[test]
  fn resize_defers_surface_reconfiguration_to_the_next_frame() {
    let mut engine = super::WgpuRenderEngine::new();
    engine.surface_config = Some(wgpu::SurfaceConfiguration {
      usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
      format: wgpu::TextureFormat::Bgra8UnormSrgb,
      width: 800,
      height: 600,
      present_mode: wgpu::PresentMode::Fifo,
      alpha_mode: wgpu::CompositeAlphaMode::Opaque,
      view_formats: vec![],
      desired_maximum_frame_latency: 1,
    });

    // A burst of size events (a live resize) only records the latest size.
    for width in (804..=1400).step_by(4) {
      engine.resize(width, 600);
    }

    let config = engine.surface_config.as_ref().unwrap();
    assert_eq!((config.width, config.height), (800, 600));
    assert_eq!((engine.width, engine.height), (1400, 600));
    assert!(engine.surface_size_pending());

    engine.resize(800, 600);
    assert!(!engine.surface_size_pending(), "back at the configured size");
  }

  #[test]
  fn resize_before_initialization_sets_initial_surface_size() {
    let mut engine = super::WgpuRenderEngine::new();

    engine.resize(1440, 900);

    assert_eq!(engine.width, 1440);
    assert_eq!(engine.height, 900);
  }

  #[test]
  fn staged_texture_bytes_uses_wgpu_row_alignment() {
    assert_eq!(super::wgpu_staged_texture_bytes(1, 3), 256 * 3);
    assert_eq!(super::wgpu_staged_texture_bytes(256, 2), 256 * 2);
    assert_eq!(super::wgpu_staged_texture_bytes(257, 2), 512 * 2);
  }

  #[test]
  fn requested_present_mode_falls_back_only_when_unsupported() {
    use super::WgpuPresentMode;

    assert_eq!(
      super::supported_present_mode(
        WgpuPresentMode::Mailbox,
        &[WgpuPresentMode::Fifo, WgpuPresentMode::Mailbox],
      ),
      WgpuPresentMode::Mailbox
    );
    assert_eq!(
      super::supported_present_mode(WgpuPresentMode::Mailbox, &[WgpuPresentMode::Fifo]),
      WgpuPresentMode::Fifo
    );
  }
}

#[cfg(feature = "raster")]
fn canvas_image_flag(native: &Option<crate::images::NativeImageData>) -> f32 {
  #[cfg(feature = "canvas")]
  if native
    .as_ref()
    .is_some_and(|n| n.backend() == crate::images::NativeImageBackend::Canvas)
  {
    return 1.;
  }
  // A card's frame of red, green and blue is in a texture whose format does not say that its bytes are encoded
  // as a screen's are, which they are, as a canvas's: taken for bytes of linear light, the frame was drawn
  // lighter than it is (a red of 255, 24, 0 as 255, 86, 0).
  #[cfg(windows)]
  if native
    .as_ref()
    .and_then(|n| n.payload::<crate::images::CardFrames>())
    .is_some_and(crate::images::CardFrames::is_rgba)
  {
    return 1.;
  }
  let _ = native;
  0.
}