drmkit-csd 0.1.2

Client-side window decorations for drmkit: themes, shadows, and title bars.
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
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! Parity port of `tests/unit/test_csd_theme.cpp` from drm-cxx @ `4a0b64a`.

use crate::{Color, ColorError, Theme, ThemeError, glass_default, glass_lite, glass_minimal};
use crate::{load_theme_file, load_theme_str};
use drmkit_fmt::fourcc::XRGB8888;

/// GBM and DRM opens share the node, so device cases serialize.
static CARD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

fn card_guard() -> std::sync::MutexGuard<'static, ()> {
    CARD_LOCK
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

fn open_card() -> Option<drmkit_core::Device> {
    let path = std::env::var("DRMKIT_TEST_CARD").unwrap_or_else(|_| "/dev/dri/card0".to_owned());
    drmkit_testkit::announce_card(&path);
    match drmkit_core::Device::open(&path) {
        Ok(device) => Some(device),
        Err(error) => {
            assert!(
                std::env::var_os("DRMKIT_REQUIRE_MASTER").is_none(),
                "{path}: {error}, but DRMKIT_REQUIRE_MASTER is set"
            );
            drmkit_testkit::skipped(&format!("no DRM device at {path} ({error})"));
            None
        }
    }
}

// --- color -------------------------------------------------------------------

/// Six digits is a color, and it is opaque.
///
/// The CSS convention, and the one a theme author expects. Defaulting to
/// transparent would make every color written the short way invisible — a
/// theme that looks like it loaded and draws nothing.
#[test]
fn six_hex_digits_are_an_opaque_color() {
    assert_eq!(
        Color::from_hex("#123456"),
        Ok(Color::new(0x12, 0x34, 0x56, 0xFF))
    );
}

/// Eight digits carries its own alpha.
#[test]
fn eight_hex_digits_carry_their_own_alpha() {
    assert_eq!(
        Color::from_hex("#12345678"),
        Ok(Color::new(0x12, 0x34, 0x56, 0x78))
    );
}

/// Case does not matter.
///
/// A hand-written theme file mixes both, and a rule against lowercase would
/// have nothing behind it.
#[test]
fn hex_digits_are_case_insensitive() {
    assert_eq!(
        Color::from_hex("#aabbccdd"),
        Color::from_hex("#AABBCCDD"),
        "the same color written two ways is the same color"
    );
    assert_eq!(
        Color::from_hex("#AaBbCcDd"),
        Ok(Color::new(0xAA, 0xBB, 0xCC, 0xDD))
    );
}

/// Anything else is refused, and says what it was given.
#[test]
fn malformed_colors_are_refused_by_what_they_were() {
    for bad in [
        "",           // nothing
        "123456",     // no hash
        "#12345",     // five digits
        "#1234567",   // seven
        "#123456789", // nine
        "#12345g",    // not hex
        "#GGGGGG",    // not hex, in the alpha-less length
    ] {
        assert_eq!(
            Color::from_hex(bad),
            Err(ColorError::Malformed {
                got: bad.to_owned()
            }),
            "{bad:?} should not parse"
        );
    }
}

/// Packing is `0xAARRGGBB`.
///
/// The layout an `ARGB8888` framebuffer word takes on a little-endian host,
/// which is what the renderer writes. Getting the channel order wrong here
/// swaps red and blue on every pixel drawn.
#[test]
fn packing_is_alpha_red_green_blue() {
    assert_eq!(
        Color::new(0x12, 0x34, 0x56, 0x78).packed_argb(),
        0x7812_3456
    );
    assert_eq!(
        Color::new(0xFF, 0x00, 0x00, 0xFF).packed_argb(),
        0xFFFF_0000,
        "opaque red, not opaque blue"
    );
}

/// Two colors are equal when every channel is.
#[test]
fn color_equality_is_every_channel() {
    let base = Color::new(1, 2, 3, 4);
    assert_eq!(base, Color::new(1, 2, 3, 4));
    for other in [
        Color::new(9, 2, 3, 4),
        Color::new(1, 9, 3, 4),
        Color::new(1, 2, 9, 4),
        Color::new(1, 2, 3, 9),
    ] {
        assert_ne!(base, other, "a channel apart is a different color");
    }
}

// --- loading ------------------------------------------------------------------

const COMPLETE: &str = r##"
name            = "round-trip-glass"
corner_radius   = 12
noise_amplitude = 0.06
shadow_extent   = 32
animation_duration_ms = 220

[title_bar]
height    = 30
font      = "Cantarell, sans-serif"
font_size = 14

[colors]
panel_top    = "#FFFFFFAA"
panel_bottom = "#FFFFFF22"
rim_focused  = "#AAAAAA88"
rim_blurred  = "#BBBBBB44"
shadow       = "#0000007F"
title_text   = "#11111111"
title_shadow = "#FFFFFFAA"

[buttons.close]
fill  = "#FF0000FF"
hover = "#FF6666FF"

[buttons.minimize]
fill  = "#FFFF00FF"
hover = "#FFFF99FF"

[buttons.maximize]
fill  = "#00FF00FF"
hover = "#99FF99FF"
"##;

/// Every field a theme has survives the round trip.
#[test]
fn a_complete_theme_round_trips() {
    let theme = load_theme_str(COMPLETE, Theme::default()).expect("valid TOML");

    assert_eq!(theme.name, "round-trip-glass");
    assert_eq!(theme.corner_radius, 12);
    assert!((theme.noise_amplitude - 0.06).abs() < f64::EPSILON);
    assert_eq!(theme.shadow_extent, 32);
    assert_eq!(theme.animation_duration_ms, 220);

    assert_eq!(theme.title_bar.height, 30);
    assert_eq!(theme.title_bar.font, "Cantarell, sans-serif");
    assert_eq!(theme.title_bar.font_size, 14);

    assert_eq!(theme.colors.panel_top, Color::new(0xFF, 0xFF, 0xFF, 0xAA));
    assert_eq!(theme.colors.shadow, Color::new(0x00, 0x00, 0x00, 0x7F));
    assert_eq!(theme.colors.title_text, Color::new(0x11, 0x11, 0x11, 0x11));

    assert_eq!(theme.buttons.close.fill, Color::new(0xFF, 0x00, 0x00, 0xFF));
    assert_eq!(
        theme.buttons.maximize.hover,
        Color::new(0x99, 0xFF, 0x99, 0xFF)
    );
}

/// What a file does not say, the base says.
///
/// This is what makes a theme file worth hand-writing: a user who wants a
/// different accent writes three lines rather than forty. A loader that reset
/// the rest to zero would give them a black window with no title bar.
#[test]
fn absent_fields_inherit_from_the_base() {
    let theme = load_theme_str(r#"name = "just-a-name""#, glass_default()).expect("valid TOML");
    let base = glass_default();

    assert_eq!(theme.name, "just-a-name", "what was said is taken");
    assert_eq!(
        theme.corner_radius, base.corner_radius,
        "and what was not is inherited"
    );
    assert_eq!(theme.title_bar, base.title_bar);
    assert_eq!(theme.colors, base.colors);
    assert_eq!(theme.buttons, base.buttons);
}

/// A partial table inherits the rest of that table too.
///
/// Not just the top level: overriding one color must not clear the other six,
/// or a one-line accent change costs the whole palette.
#[test]
fn a_partial_table_inherits_its_siblings() {
    let theme = load_theme_str("[colors]\npanel_top = \"#01020304\"\n", glass_default())
        .expect("valid TOML");
    let base = glass_default();

    assert_eq!(theme.colors.panel_top, Color::new(1, 2, 3, 4));
    assert_eq!(
        theme.colors.shadow, base.colors.shadow,
        "the siblings of an overridden color are not collateral"
    );
    assert_eq!(theme.colors.title_text, base.colors.title_text);
}

/// Text that is not TOML is refused as a syntax error.
#[test]
fn text_that_is_not_toml_is_a_syntax_error() {
    let error =
        load_theme_str("this is not = = toml", Theme::default()).expect_err("that is not TOML");
    assert!(matches!(error, ThemeError::Syntax(_)), "got {error}");
}

/// A color that will not parse names its own field.
///
/// A theme has forty fields. "Invalid argument" leaves the author to bisect a
/// file by hand; naming the field is the difference between a fixable error
/// and a puzzle.
#[test]
fn a_bad_color_names_the_field_it_was_in() {
    let error = load_theme_str("[colors]\nshadow = \"not-a-color\"\n", Theme::default())
        .expect_err("that is not a color");

    match error {
        ThemeError::BadColor { field, source } => {
            assert_eq!(field, "shadow");
            assert_eq!(
                source,
                ColorError::Malformed {
                    got: "not-a-color".to_owned()
                }
            );
        }
        other => panic!("got {other}, which does not say which field"),
    }
}

/// A color field holding the wrong kind of value says so.
#[test]
fn a_color_that_is_not_a_string_names_the_field() {
    let error = load_theme_str("[colors]\nshadow = 42\n", Theme::default())
        .expect_err("a number is not a color");

    match error {
        ThemeError::WrongType { field, expected } => {
            assert_eq!(field, "shadow");
            assert!(expected.contains("RRGGBB"), "expected {expected:?} to help");
        }
        other => panic!("got {other}"),
    }
}

/// A missing file is an IO error naming the path.
#[test]
fn a_missing_theme_file_says_which_file() {
    let error = load_theme_file("/nonexistent/theme.toml", Theme::default())
        .expect_err("there is no such file");

    match error {
        ThemeError::Io { path, source } => {
            assert_eq!(path, "/nonexistent/theme.toml");
            assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
        }
        other => panic!("got {other}"),
    }
}

// --- built-in themes ----------------------------------------------------------

/// The default theme is named and complete.
#[test]
fn the_default_theme_is_named_and_populated() {
    let theme = glass_default();

    assert_eq!(theme.name, "glass-default");
    assert!(theme.corner_radius > 0);
    assert!(theme.title_bar.height > 0);
    assert!(!theme.title_bar.font.is_empty());
    assert!(
        theme.colors.panel_top.a > 0,
        "a panel nobody can see is not one"
    );
    assert!(theme.buttons.close.fill.a > 0);
}

/// The lite theme costs less than the default.
///
/// Shadow area, noise, and animation frames are the three costs that scale,
/// and "lite" means all three go down. A lite theme that only renamed itself
/// would be a promise the caller cannot collect on.
#[test]
fn the_lite_theme_is_cheaper_than_the_default() {
    let lite = glass_lite();
    let base = glass_default();

    assert_eq!(lite.name, "glass-lite");
    assert!(lite.shadow_extent < base.shadow_extent);
    assert!(lite.animation_duration_ms < base.animation_duration_ms);
    assert!(lite.noise_amplitude < base.noise_amplitude);
}

/// The minimal theme has no shadow and no animation.
///
/// The shadow *color* is cleared as well as the extent. Either alone stops it
/// drawing, but leaving a visible color behind a zero extent invites a caller
/// that raises the extent to inherit a shadow it never chose.
#[test]
fn the_minimal_theme_drops_the_shadow_and_the_animation() {
    let theme = glass_minimal();

    assert_eq!(theme.name, "glass-minimal");
    assert_eq!(theme.shadow_extent, 0);
    assert_eq!(theme.animation_duration_ms, 0);
    assert!((theme.noise_amplitude - 0.0).abs() < f64::EPSILON);
    assert_eq!(
        theme.colors.shadow.a, 0,
        "the color goes with the extent, or raising one brings back the other"
    );
    assert!(
        theme.title_bar.height > 0,
        "minimal is not undecorated -- there is still a title bar"
    );
}

/// A nested color reports its qualified name but is looked up by its own.
///
/// The two are different, and conflating them fails silently rather than
/// loudly: a button color keyed `fill` looked up as `buttons.close.fill`
/// finds nothing, an absent field inherits by design, and the theme loads
/// looking correct with the caller's button colors quietly ignored. Caught
/// exactly that way when the round-trip case came back with a default red.
#[test]
fn a_nested_button_color_is_read_and_reported_by_different_names() {
    let theme = load_theme_str("[buttons.close]\nfill = \"#010203FF\"\n", glass_default())
        .expect("valid TOML");

    assert_eq!(
        theme.buttons.close.fill,
        Color::new(1, 2, 3, 0xFF),
        "the key inside the table is `fill`; looking up the qualified name \
         finds nothing and silently inherits"
    );
    assert_eq!(
        theme.buttons.close.hover,
        glass_default().buttons.close.hover,
        "and its sibling still inherits, which is why the miss is silent"
    );

    // The label, though, is the qualified one -- an author reading
    // "fill: expected ..." would not know which of the six to look at.
    let error = load_theme_str("[buttons.close]\nfill = \"nope\"\n", glass_default())
        .expect_err("that is not a color");
    match error {
        ThemeError::BadColor { field, .. } => assert_eq!(field, "buttons.close.fill"),
        other => panic!("got {other}"),
    }
}

// --- decoration geometry ------------------------------------------------------
//
// Parity port of the `CsdDecorationGeometry` cases in
// `tests/unit/test_csd_renderer.cpp`.

use crate::decoration_geometry;

/// The panel is inset by the shadow on every side.
///
/// The shadow is drawn *outside* the panel, so the decoration is larger than
/// the window it decorates by twice the extent. A panel that started at the
/// origin would put the shadow off the top-left of its own buffer.
#[test]
fn the_panel_is_inset_by_the_shadow_on_every_side() {
    let theme = glass_default();
    let geometry = decoration_geometry(&theme, 600, 360);

    assert_eq!(geometry.panel_x, theme.shadow_extent);
    assert_eq!(geometry.panel_y, theme.shadow_extent);
    assert_eq!(geometry.panel_w, 600 - 2 * theme.shadow_extent);
    assert_eq!(geometry.panel_h, 360 - 2 * theme.shadow_extent);
}

/// With no shadow, the panel is the whole canvas.
#[test]
fn a_theme_with_no_shadow_fills_the_canvas() {
    let geometry = decoration_geometry(&glass_minimal(), 600, 360);

    assert_eq!((geometry.panel_x, geometry.panel_y), (0, 0));
    assert_eq!((geometry.panel_w, geometry.panel_h), (600, 360));
}

/// A decoration too small for its own shadow gets a zero panel, not a
/// negative one.
///
/// A negative width reaching a rasterizer is either a crash or a very large
/// unsigned number, and asking for a 30-pixel decoration under a 24-pixel
/// shadow is an ordinary mistake rather than a reason to fail.
#[test]
fn a_decoration_too_small_for_its_shadow_clamps_to_a_zero_panel() {
    let geometry = decoration_geometry(&glass_default(), 30, 30);

    assert_eq!(geometry.panel_w, 0);
    assert_eq!(geometry.panel_h, 0);
    assert!(
        geometry.panel_w >= 0 && geometry.panel_h >= 0,
        "clamped, not wrapped"
    );
}

/// A negative shadow extent is treated as none.
///
/// A hand-written theme can carry one, and a panel inset the *other* way is
/// drawn outside its own decoration — reproducing that faithfully would put
/// pixels wherever the buffer's stride happened to lead.
#[test]
fn a_negative_shadow_extent_is_treated_as_none() {
    let theme = Theme {
        shadow_extent: -20,
        ..glass_default()
    };
    let geometry = decoration_geometry(&theme, 600, 360);

    assert_eq!((geometry.panel_x, geometry.panel_y), (0, 0));
    assert_eq!((geometry.panel_w, geometry.panel_h), (600, 360));
}

/// The buttons run right to left, evenly spaced.
///
/// Close is outermost: it is the one a user reaches for by feel, so it must
/// not move when the others are absent.
#[test]
fn the_buttons_run_right_to_left_evenly_spaced() {
    let geometry = decoration_geometry(&glass_default(), 600, 360);

    assert!(geometry.close_cx > geometry.minimize_cx);
    assert!(geometry.minimize_cx > geometry.maximize_cx);
    assert_eq!(
        geometry.close_cx - geometry.minimize_cx,
        geometry.minimize_cx - geometry.maximize_cx,
        "evenly spaced, or the row looks like a mistake"
    );
}

/// Every button lands inside the title bar.
///
/// The one property that makes the row usable rather than decorative: a
/// button whose circle crosses the panel edge or the title bar's bottom is
/// clipped, and a clipped button is one a user cannot reliably hit.
#[test]
fn every_button_lands_inside_the_title_bar() {
    let theme = glass_default();
    let geometry = decoration_geometry(&theme, 600, 360);

    for (name, cx) in [
        ("close", geometry.close_cx),
        ("minimize", geometry.minimize_cx),
        ("maximize", geometry.maximize_cx),
    ] {
        assert!(
            cx - geometry.button_radius >= geometry.panel_x,
            "{name} crosses the panel's left edge"
        );
        assert!(
            cx + geometry.button_radius < geometry.panel_x + geometry.panel_w,
            "{name} crosses the panel's right edge"
        );
    }

    assert!(
        geometry.button_cy - geometry.button_radius >= geometry.panel_y,
        "the row crosses the top of the panel"
    );
    assert!(
        geometry.button_cy + geometry.button_radius < geometry.panel_y + geometry.title_bar_height,
        "the row hangs below the title bar and into the window's content"
    );
}

/// A panel too narrow for the buttons still reports where they would be.
///
/// Geometry answers where things go; whether they fit is the caller's to
/// check, which is what the case above does. Refusing here would leave a
/// caller with nothing to check.
#[test]
fn a_panel_too_narrow_for_the_buttons_still_answers() {
    let geometry = decoration_geometry(&glass_default(), 60, 360);

    assert_eq!(geometry.panel_w, 60 - 2 * glass_default().shadow_extent);
    assert!(
        geometry.maximize_cx < geometry.panel_x,
        "the leftmost button does not fit, which is exactly what a caller \
         checking the bounds needs to be able to see"
    );
}

// --- shadow cache -------------------------------------------------------------
//
// Parity port of `tests/unit/test_csd_shadow_cache.cpp`.

use crate::{DEFAULT_CAPACITY, Elevation, ShadowCache, ShadowDest, ShadowKey, theme_id};

fn key(width: u32, height: u32, elevation: Elevation, theme: &Theme) -> ShadowKey {
    ShadowKey {
        width,
        height,
        elevation,
        theme_id: theme_id(theme),
    }
}

/// A destination big enough for a patch, zeroed.
fn dest(width: u32, height: u32) -> (Vec<u8>, u32) {
    (vec![0u8; (width * height * 4) as usize], width * 4)
}

/// The same theme hashes the same, every time.
#[test]
fn a_theme_id_is_stable_across_rebuilds() {
    assert_eq!(theme_id(&glass_default()), theme_id(&glass_default()));
    assert_eq!(theme_id(&glass_minimal()), theme_id(&glass_minimal()));
}

/// A color change is a different theme.
#[test]
fn a_theme_id_changes_when_a_color_does() {
    let base = glass_default();
    let changed = Theme {
        colors: crate::Colors {
            shadow: Color::new(1, 2, 3, 4),
            ..base.colors
        },
        ..base.clone()
    };

    assert_ne!(
        theme_id(&base),
        theme_id(&changed),
        "a cached shadow drawn in the old color would outlive the change"
    );
}

/// A shadow-extent change is a different theme.
#[test]
fn a_theme_id_changes_when_the_shadow_extent_does() {
    let base = glass_default();
    let changed = Theme {
        shadow_extent: base.shadow_extent + 1,
        ..base.clone()
    };

    assert_ne!(theme_id(&base), theme_id(&changed));
}

/// The name does not change how anything looks, so it does not change the id.
///
/// Hashing it would evict every cached shadow when a caller renamed a theme —
/// a full re-blur per window, for a string.
#[test]
fn a_theme_id_ignores_the_name() {
    let base = glass_default();
    let renamed = Theme {
        name: "something-else".to_owned(),
        ..base.clone()
    };

    assert_eq!(theme_id(&base), theme_id(&renamed));
}

/// Nor does the animation duration.
#[test]
fn a_theme_id_ignores_the_animation_duration() {
    let base = glass_default();
    let quicker = Theme {
        animation_duration_ms: base.animation_duration_ms / 2,
        ..base.clone()
    };

    assert_eq!(
        theme_id(&base),
        theme_id(&quicker),
        "how long a shadow takes to fade cannot change what it looks like"
    );
}

/// Zero capacity means the default, not none.
///
/// A cache holding nothing would re-blur every shadow every frame, which is
/// the cost this type exists to remove.
#[test]
fn a_zero_capacity_cache_uses_the_default() {
    assert_eq!(ShadowCache::new(0).capacity(), DEFAULT_CAPACITY);
    assert_eq!(ShadowCache::default().capacity(), DEFAULT_CAPACITY);
}

/// An explicit capacity is respected.
#[test]
fn an_explicit_capacity_is_respected() {
    assert_eq!(ShadowCache::new(3).capacity(), 3);
}

/// Clearing empties the cache.
#[test]
fn clearing_empties_the_cache() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(4);
    let (mut pixels, stride) = dest(64, 64);
    let mut target = ShadowDest {
        pixels: &mut pixels,
        stride,
        width: 64,
        height: 64,
    };

    assert!(cache.blit_into(key(64, 64, Elevation::Focused, &theme), &theme, &mut target));
    assert_eq!(cache.len(), 1);

    cache.clear();
    assert!(cache.is_empty());
    assert!(!cache.contains(&key(64, 64, Elevation::Focused, &theme)));
}

/// A zero-sized key writes nothing.
///
/// A window being resized passes through zero, and a decoration that errored
/// on the way would flicker.
#[test]
fn a_zero_sized_shadow_writes_nothing() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(4);
    let (mut pixels, stride) = dest(64, 64);
    let mut target = ShadowDest {
        pixels: &mut pixels,
        stride,
        width: 64,
        height: 64,
    };

    assert!(!cache.blit_into(key(0, 64, Elevation::Focused, &theme), &theme, &mut target));
    assert!(!cache.blit_into(key(64, 0, Elevation::Focused, &theme), &theme, &mut target));
    assert!(cache.is_empty(), "and nothing was cached either");
}

/// A zero-sized destination writes nothing.
#[test]
fn a_zero_sized_destination_writes_nothing() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(4);
    let (mut pixels, stride) = dest(64, 64);
    let mut target = ShadowDest {
        pixels: &mut pixels,
        stride,
        width: 0,
        height: 64,
    };

    assert!(!cache.blit_into(key(64, 64, Elevation::Focused, &theme), &theme, &mut target));
}

/// The first blit renders the shadow and writes visible alpha.
#[test]
fn the_first_blit_renders_a_shadow_with_visible_alpha() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(4);
    let (mut pixels, stride) = dest(96, 96);
    let mut target = ShadowDest {
        pixels: &mut pixels,
        stride,
        width: 96,
        height: 96,
    };

    assert!(cache.blit_into(key(96, 96, Elevation::Focused, &theme), &theme, &mut target));
    assert_eq!(cache.len(), 1);

    let center = ((48 * 96) + 48) * 4;
    assert!(
        pixels[center + 3] > 0,
        "the middle of a shadow patch is where it is strongest; zero there \
         means nothing was drawn"
    );
}

/// The second blit of the same key is a hit.
#[test]
fn a_second_blit_of_the_same_shadow_is_a_hit() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(4);
    let (mut pixels, stride) = dest(64, 64);
    let shadow = key(64, 64, Elevation::Focused, &theme);

    for _ in 0..3 {
        let mut target = ShadowDest {
            pixels: &mut pixels,
            stride,
            width: 64,
            height: 64,
        };
        assert!(cache.blit_into(shadow, &theme, &mut target));
    }
    assert_eq!(cache.len(), 1, "three blits of one shadow render it once");
}

/// Focused and blurred are different shadows.
///
/// They differ in strength, which is what makes the focused window read as
/// nearer. Sharing a cache entry would make every window look focused.
#[test]
fn focused_and_blurred_are_separate_entries() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(4);
    let (mut focused_px, stride) = dest(64, 64);
    let (mut blurred_px, _) = dest(64, 64);

    let mut target = ShadowDest {
        pixels: &mut focused_px,
        stride,
        width: 64,
        height: 64,
    };
    cache.blit_into(key(64, 64, Elevation::Focused, &theme), &theme, &mut target);
    let mut target = ShadowDest {
        pixels: &mut blurred_px,
        stride,
        width: 64,
        height: 64,
    };
    cache.blit_into(key(64, 64, Elevation::Blurred, &theme), &theme, &mut target);

    assert_eq!(cache.len(), 2, "two elevations, two shadows");
    assert_ne!(
        focused_px, blurred_px,
        "and they must actually differ, or the elevation says nothing"
    );

    let center = ((32 * 64) + 32) * 4 + 3;
    assert!(
        focused_px[center] > blurred_px[center],
        "the focused shadow is the stronger one"
    );
}

/// Past capacity, the least recently used goes.
#[test]
fn the_least_recently_used_shadow_is_evicted() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(2);
    let (mut pixels, stride) = dest(64, 64);

    for size in [32u32, 48, 64] {
        let mut target = ShadowDest {
            pixels: &mut pixels,
            stride,
            width: 64,
            height: 64,
        };
        cache.blit_into(
            key(size, size, Elevation::Focused, &theme),
            &theme,
            &mut target,
        );
    }

    assert_eq!(cache.len(), 2, "the cap holds");
    assert!(
        !cache.contains(&key(32, 32, Elevation::Focused, &theme)),
        "the oldest went"
    );
    assert!(cache.contains(&key(64, 64, Elevation::Focused, &theme)));
}

/// Using a shadow again makes it recent.
///
/// Without this the LRU would evict whatever the caller draws every frame and
/// keep whatever it drew once — the opposite of a cache.
#[test]
fn using_a_shadow_again_keeps_it_from_eviction() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(2);
    let (mut pixels, stride) = dest(64, 64);
    let blit = |cache: &mut ShadowCache, size: u32, pixels: &mut Vec<u8>| {
        let mut target = ShadowDest {
            pixels,
            stride,
            width: 64,
            height: 64,
        };
        cache.blit_into(
            key(size, size, Elevation::Focused, &theme),
            &theme,
            &mut target,
        );
    };

    blit(&mut cache, 32, &mut pixels);
    blit(&mut cache, 48, &mut pixels);
    // Touch the older one, then add a third.
    blit(&mut cache, 32, &mut pixels);
    blit(&mut cache, 64, &mut pixels);

    assert!(
        cache.contains(&key(32, 32, Elevation::Focused, &theme)),
        "32 was used most recently before the eviction, so it stays"
    );
    assert!(
        !cache.contains(&key(48, 48, Elevation::Focused, &theme)),
        "48 was the stalest"
    );
}

/// A theme with no shadow produces a transparent patch.
#[test]
fn a_theme_with_no_shadow_produces_nothing_visible() {
    let theme = glass_minimal();
    let mut cache = ShadowCache::new(2);
    let (mut pixels, stride) = dest(64, 64);
    let mut target = ShadowDest {
        pixels: &mut pixels,
        stride,
        width: 64,
        height: 64,
    };

    assert!(cache.blit_into(key(64, 64, Elevation::Focused, &theme), &theme, &mut target));
    assert!(
        pixels.iter().all(|byte| *byte == 0),
        "a zero-alpha shadow color must write nothing visible, whatever the \
         extent says"
    );
}

/// A destination smaller than the patch is clipped, not overrun.
///
/// The alternative is writing past the caller's buffer, which is the one
/// outcome worse than a clipped shadow.
#[test]
fn a_destination_smaller_than_the_patch_is_clipped() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(2);
    let (mut pixels, stride) = dest(32, 32);
    let mut target = ShadowDest {
        pixels: &mut pixels,
        stride,
        width: 32,
        height: 32,
    };

    assert!(cache.blit_into(key(96, 96, Elevation::Focused, &theme), &theme, &mut target));
    assert_eq!(pixels.len(), 32 * 32 * 4, "nothing grew the destination");
}

/// A cross fade blends the two endpoints, and clamps outside them.
///
/// `t` past the ends is a caller bug — an animation that overshoots —
/// and extrapolating a color past its endpoints produces values that are not
/// a shadow at all.
#[test]
fn a_cross_fade_blends_between_its_endpoints() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(4);
    let focused = key(64, 64, Elevation::Focused, &theme);
    let blurred = key(64, 64, Elevation::Blurred, &theme);
    let center = ((32 * 64) + 32) * 4 + 3;

    let sample = |cache: &mut ShadowCache, t: f32| {
        let (mut pixels, stride) = dest(64, 64);
        let mut target = ShadowDest {
            pixels: &mut pixels,
            stride,
            width: 64,
            height: 64,
        };
        assert!(cache.blit_cross_fade(focused, blurred, &theme, &mut target, t));
        pixels[center]
    };

    let at_start = sample(&mut cache, 0.0);
    let midway = sample(&mut cache, 0.5);
    let at_end = sample(&mut cache, 1.0);

    assert!(at_start > at_end, "focused is the stronger endpoint");
    assert!(
        midway < at_start && midway > at_end,
        "halfway is between them, not at one of them"
    );
    assert_eq!(
        sample(&mut cache, -5.0),
        at_start,
        "clamped, not extrapolated"
    );
    assert_eq!(sample(&mut cache, 5.0), at_end);
}

// --- animator -----------------------------------------------------------------
//
// Parity port of `tests/unit/test_csd_animator.cpp`.

use crate::{Dirty, HoverButton, PROGRESS_UNSET, WindowAnim, WindowState, ease_out_cubic};
use std::time::Duration;

const MS: fn(u64) -> Duration = Duration::from_millis;

/// The ease hits both endpoints exactly.
///
/// Not "close enough": a window that settled at 0.999 focused would never
/// quite look focused, and one that started at 0.001 would flicker.
#[test]
fn the_ease_hits_both_endpoints_exactly() {
    assert!((ease_out_cubic(0.0) - 0.0).abs() < f32::EPSILON);
    assert!((ease_out_cubic(1.0) - 1.0).abs() < f32::EPSILON);
}

/// Input outside `0..=1` is clamped, not extrapolated.
///
/// An animator that overshoots its duration would otherwise carry past the
/// target and the window would visibly bounce.
#[test]
fn the_ease_clamps_rather_than_extrapolating() {
    assert!((ease_out_cubic(-5.0) - 0.0).abs() < f32::EPSILON);
    assert!((ease_out_cubic(-0.001) - 0.0).abs() < f32::EPSILON);
    assert!((ease_out_cubic(5.0) - 1.0).abs() < f32::EPSILON);
}

/// It only ever increases.
#[test]
fn the_ease_never_goes_backwards() {
    let mut previous = ease_out_cubic(0.0);
    for step in 1..=100u8 {
        let current = ease_out_cubic(f32::from(step) / 100.0);
        assert!(
            current >= previous,
            "eased backwards at {step}: {current} < {previous}"
        );
        previous = current;
    }
}

/// It is fast at the start.
///
/// That is what "ease out" means, and it is the half a user notices: the
/// change is announced immediately and arrives gently.
#[test]
fn the_ease_is_fast_at_the_start() {
    assert!(
        ease_out_cubic(0.25) > 0.5,
        "a quarter of the way through time should be past halfway in value"
    );
    assert!(ease_out_cubic(0.5) > 0.8);
}

/// A new animator is settled at its focus, not animating toward it.
///
/// A window that appears focused should be drawn focused, not fade in from
/// unfocused on its first frame.
#[test]
fn a_new_animator_is_settled_not_animating() {
    let focused = WindowAnim::new(true);
    assert!((focused.focus_progress() - 1.0).abs() < f32::EPSILON);
    assert!(!focused.is_animating());

    let blurred = WindowAnim::new(false);
    assert!((blurred.focus_progress() - 0.0).abs() < f32::EPSILON);
    assert!(!blurred.is_animating());
}

/// Retargeting to the current target does nothing.
///
/// A caller that reports focus every frame would otherwise restart the
/// timeline every frame, and the window would never finish transitioning.
#[test]
fn retargeting_to_the_same_focus_does_nothing() {
    let mut anim = WindowAnim::new(false);
    anim.retarget_focus(false);
    assert!(!anim.is_animating());

    anim.retarget_focus(true);
    assert!(anim.is_animating());
    anim.tick(MS(50), MS(200));
    let midway = anim.focus_progress();

    anim.retarget_focus(true);
    assert!(
        (anim.focus_progress() - midway).abs() < f32::EPSILON,
        "a redundant retarget must not restart the run"
    );
}

/// Retargeting starts a run.
#[test]
fn retargeting_focus_starts_a_run() {
    let mut anim = WindowAnim::new(false);
    anim.retarget_focus(true);

    assert!(anim.is_animating());
    assert!(
        (anim.focus_progress() - 0.0).abs() < f32::EPSILON,
        "and does not jump -- the run has not been ticked yet"
    );
}

/// A full duration reaches the target.
#[test]
fn a_full_duration_reaches_the_target() {
    let mut anim = WindowAnim::new(false);
    anim.retarget_focus(true);

    let still_going = anim.tick(MS(200), MS(200));

    assert!((anim.focus_progress() - 1.0).abs() < f32::EPSILON);
    assert!(!still_going, "and reports that it has finished");
    assert!(!anim.is_animating());
}

/// A tick past the duration clamps to the target.
#[test]
fn a_tick_past_the_duration_clamps_to_the_target() {
    let mut anim = WindowAnim::new(false);
    anim.retarget_focus(true);

    anim.tick(MS(10_000), MS(200));

    assert!(
        (anim.focus_progress() - 1.0).abs() < f32::EPSILON,
        "a dropped frame must not carry the window past focused"
    );
}

/// Progress only increases across a run.
#[test]
fn progress_only_increases_across_a_run() {
    let mut anim = WindowAnim::new(false);
    anim.retarget_focus(true);

    let mut previous = anim.focus_progress();
    for _ in 0..20 {
        anim.tick(MS(10), MS(200));
        assert!(
            anim.focus_progress() >= previous,
            "went backwards mid-run: {} < {previous}",
            anim.focus_progress()
        );
        previous = anim.focus_progress();
    }
}

/// Retargeting mid-flight eases from where the value is.
///
/// Not from zero. A window that loses focus halfway through gaining it should
/// fade back from half-lit; snapping to unfocused first would flash.
#[test]
fn retargeting_mid_flight_eases_from_where_it_is() {
    let mut anim = WindowAnim::new(false);
    anim.retarget_focus(true);
    anim.tick(MS(100), MS(200));
    let midway = anim.focus_progress();
    assert!(midway > 0.0 && midway < 1.0, "genuinely mid-flight");

    anim.retarget_focus(false);
    assert!(
        (anim.focus_progress() - midway).abs() < f32::EPSILON,
        "the retarget itself must not move the value"
    );

    anim.tick(MS(10), MS(200));
    assert!(
        anim.focus_progress() < midway,
        "and it heads back down from there rather than snapping to zero"
    );
}

/// Nothing is hovered to begin with.
#[test]
fn nothing_is_hovered_to_begin_with() {
    let anim = WindowAnim::default();
    assert_eq!(anim.hover_painted(), HoverButton::None);
    assert!((anim.hover_progress() - 0.0).abs() < f32::EPSILON);
}

/// Entering a button starts it from zero and finishes at one.
#[test]
fn entering_a_button_runs_from_zero_to_one() {
    let mut anim = WindowAnim::default();
    anim.retarget_hover(HoverButton::Close);

    assert_eq!(anim.hover_painted(), HoverButton::Close);
    assert!((anim.hover_progress() - 0.0).abs() < f32::EPSILON);

    anim.tick(MS(200), MS(200));
    assert!((anim.hover_progress() - 1.0).abs() < f32::EPSILON);
    assert_eq!(anim.hover_painted(), HoverButton::Close);
}

/// Leaving fades the button that was left, then stops drawing it.
///
/// The painted button is not the target. Setting the target to `None` and
/// drawing that immediately would make the highlight vanish rather than fade.
#[test]
fn leaving_fades_the_button_that_was_left() {
    let mut anim = WindowAnim::default();
    anim.retarget_hover(HoverButton::Minimize);
    anim.tick(MS(200), MS(200));
    assert!((anim.hover_progress() - 1.0).abs() < f32::EPSILON);

    anim.retarget_hover(HoverButton::None);
    assert_eq!(
        anim.hover_painted(),
        HoverButton::Minimize,
        "still drawn, because it is still fading"
    );

    anim.tick(MS(100), MS(200));
    assert!(anim.hover_progress() < 1.0, "and fading");
    assert_eq!(anim.hover_painted(), HoverButton::Minimize);

    anim.tick(MS(200), MS(200));
    assert!((anim.hover_progress() - 0.0).abs() < f32::EPSILON);
    assert_eq!(
        anim.hover_painted(),
        HoverButton::None,
        "once faded out, it stops being drawn at all"
    );
}

/// Moving between buttons restarts on the new one.
///
/// They are different highlights in different places; carrying the old one's
/// progress across would make the new button appear already half-lit.
#[test]
fn moving_between_buttons_restarts_on_the_new_one() {
    let mut anim = WindowAnim::default();
    anim.retarget_hover(HoverButton::Close);
    anim.tick(MS(200), MS(200));
    assert!((anim.hover_progress() - 1.0).abs() < f32::EPSILON);

    anim.retarget_hover(HoverButton::Maximize);

    assert_eq!(anim.hover_painted(), HoverButton::Maximize);
    assert!(
        (anim.hover_progress() - 0.0).abs() < f32::EPSILON,
        "the new button lights from nothing, not from the old one's value"
    );
}

/// Snapping jumps to the targets and runs nothing.
#[test]
fn snapping_jumps_to_the_targets() {
    let mut anim = WindowAnim::new(false);
    anim.retarget_focus(true);
    anim.retarget_hover(HoverButton::Close);
    assert!(anim.is_animating());

    anim.snap();

    assert!((anim.focus_progress() - 1.0).abs() < f32::EPSILON);
    assert!((anim.hover_progress() - 1.0).abs() < f32::EPSILON);
    assert_eq!(anim.hover_painted(), HoverButton::Close);
    assert!(!anim.is_animating());
}

/// A zero duration snaps.
///
/// The documented way to turn animations off — `glass-minimal` sets it — not
/// an edge case being tolerated.
#[test]
fn a_zero_duration_snaps() {
    let mut anim = WindowAnim::new(false);
    anim.retarget_focus(true);

    let still_going = anim.tick(MS(16), Duration::ZERO);

    assert!((anim.focus_progress() - 1.0).abs() < f32::EPSILON);
    assert!(!still_going);
    assert!(!anim.is_animating());
}

/// Applying writes the animator's progress into the state.
///
/// Including the *painted* button rather than the target, so the renderer
/// draws the one that is fading rather than nothing.
#[test]
fn applying_mirrors_the_progress_into_the_state() {
    let mut anim = WindowAnim::new(false);
    anim.retarget_focus(true);
    anim.retarget_hover(HoverButton::Minimize);
    anim.tick(MS(100), MS(200));

    let mut state = WindowState::default();
    assert!((state.focus_progress - PROGRESS_UNSET).abs() < f32::EPSILON);

    anim.apply_to(&mut state);

    assert!((state.focus_progress - anim.focus_progress()).abs() < f32::EPSILON);
    assert!((state.hover_progress - anim.hover_progress()).abs() < f32::EPSILON);
    assert_eq!(state.hover, HoverButton::Minimize);
}

/// A fresh state is entirely dirty, and the bits are separable.
///
/// Nothing has been drawn yet, so every part of it is new. The separability
/// is what the mask is for: redrawing because the pointer moved costs a
/// rounded-rect fill, redrawing because the geometry changed costs a blur.
#[test]
fn a_fresh_state_is_dirty_and_the_bits_are_separable() {
    let state = WindowState::default();
    assert!(state.dirty.intersects(Dirty::GEOMETRY));
    assert!(state.dirty.intersects(Dirty::HOVER));

    assert!(Dirty::NONE.is_empty());
    assert!(
        !Dirty::HOVER.intersects(Dirty::GEOMETRY),
        "one bit is not another"
    );
    assert!(
        Dirty::HOVER.union(Dirty::FOCUS).intersects(Dirty::FOCUS),
        "and a union carries both"
    );
}

// --- overlay reservation ------------------------------------------------------
//
// Parity port of `tests/unit/test_csd_overlay_reservation.cpp`.

use crate::{OverlayReservation, ReserveError};
use drmkit_planes::{PlaneCapabilities, PlaneRegistry, PlaneType};

/// A plane on the CRTCs in `crtcs`, at `zpos`, taking `XRGB8888`.
fn overlay(id: u32, crtcs: u32, zpos: Option<u64>) -> PlaneCapabilities {
    PlaneCapabilities {
        id,
        possible_crtcs: crtcs,
        plane_type: PlaneType::Overlay,
        formats: vec![XRGB8888],
        zpos_min: zpos,
        zpos_max: zpos,
        ..PlaneCapabilities::default()
    }
}

/// The reference shape: two overlays per CRTC, on two CRTCs, none shared.
fn partitioned() -> PlaneRegistry {
    PlaneRegistry::from_capabilities(vec![
        overlay(10, 0b01, Some(1)),
        overlay(11, 0b01, Some(2)),
        overlay(20, 0b10, Some(1)),
        overlay(21, 0b10, Some(2)),
    ])
}

/// Each CRTC reserves from its own planes, without affecting the other.
#[test]
fn each_crtc_reserves_without_touching_the_other() {
    let registry = partitioned();
    let mut reservation = OverlayReservation::new();

    let first = reservation
        .reserve(&registry, 0, XRGB8888, 2, 0)
        .expect("two overlays on CRTC 0");
    let second = reservation
        .reserve(&registry, 1, XRGB8888, 2, 0)
        .expect("two on CRTC 1, which the first reservation cannot have taken");

    assert_eq!(first, vec![10, 11]);
    assert_eq!(second, vec![20, 21]);
    assert_eq!(reservation.all_reserved(), vec![10, 11, 20, 21]);
}

/// Asking for more than exist is a shortfall, and changes nothing.
///
/// A caller can ask again for fewer, or draw into the window instead. A
/// partial reservation would leave it working out which decoration to drop.
#[test]
fn asking_for_more_planes_than_exist_is_a_shortfall() {
    let registry = partitioned();
    let mut reservation = OverlayReservation::new();

    let error = reservation
        .reserve(&registry, 0, XRGB8888, 3, 0)
        .expect_err("CRTC 0 has two overlays");

    assert_eq!(
        error,
        ReserveError::Shortfall {
            crtc_index: 0,
            wanted: 3,
            found: 2
        }
    );
    assert!(
        reservation.all_reserved().is_empty(),
        "a shortfall must not leave planes claimed that nobody is using"
    );
}

/// A plane reachable from two CRTCs goes to whoever claims it first.
///
/// The second CRTC must not be offered it again — two CRTCs scanning out of
/// one plane is not something the hardware can do, and the refusal has to
/// happen here rather than at the commit.
#[test]
fn a_shared_plane_goes_to_whoever_claims_it_first() {
    // Both planes reachable from both CRTCs.
    let registry = PlaneRegistry::from_capabilities(vec![
        overlay(30, 0b11, Some(1)),
        overlay(31, 0b11, Some(2)),
    ]);
    let mut reservation = OverlayReservation::new();

    let first = reservation
        .reserve(&registry, 0, XRGB8888, 2, 0)
        .expect("CRTC 0 takes the pool");
    assert_eq!(first, vec![30, 31]);

    let error = reservation
        .reserve(&registry, 1, XRGB8888, 1, 0)
        .expect_err("there is nothing left");
    assert_eq!(
        error,
        ReserveError::Shortfall {
            crtc_index: 1,
            wanted: 1,
            found: 0
        }
    );
}

/// Releasing gives the planes back.
#[test]
fn releasing_frees_the_planes_for_another_crtc() {
    let registry = PlaneRegistry::from_capabilities(vec![overlay(30, 0b11, Some(1))]);
    let mut reservation = OverlayReservation::new();

    reservation
        .reserve(&registry, 0, XRGB8888, 1, 0)
        .expect("CRTC 0 takes it");
    assert!(reservation.reserve(&registry, 1, XRGB8888, 1, 0).is_err());

    reservation.release(0);

    assert_eq!(
        reservation.reserve(&registry, 1, XRGB8888, 1, 0),
        Ok(vec![30]),
        "released means available"
    );
    assert!(reservation.reserved_for(0).is_empty());
}

/// Releasing twice, or a CRTC that never reserved, is a no-op.
///
/// Both are what a caller tearing down an output does, sometimes twice.
#[test]
fn releasing_is_idempotent() {
    let registry = partitioned();
    let mut reservation = OverlayReservation::new();
    reservation
        .reserve(&registry, 0, XRGB8888, 1, 0)
        .expect("one overlay");

    reservation.release(0);
    reservation.release(0);
    reservation.release(99);

    assert!(reservation.all_reserved().is_empty());
}

/// Reserving again replaces what the CRTC held.
///
/// A caller responding to a mode change asks with a new count; the old claim
/// would otherwise keep planes it no longer wants out of everyone else's
/// reach.
#[test]
fn reserving_again_replaces_the_previous_claim() {
    let registry = partitioned();
    let mut reservation = OverlayReservation::new();

    reservation
        .reserve(&registry, 0, XRGB8888, 2, 0)
        .expect("both");
    let narrowed = reservation
        .reserve(&registry, 0, XRGB8888, 1, 0)
        .expect("now just one");

    assert_eq!(narrowed.len(), 1);
    assert_eq!(
        reservation.all_reserved(),
        narrowed,
        "the plane it gave up is available again, not still claimed"
    );
}

/// A zpos floor excludes planes that cannot sit above the window.
///
/// A decoration below the content it decorates is invisible, so a caller that
/// knows the window's stacking position says so here rather than discovering
/// it on screen.
#[test]
fn a_zpos_floor_excludes_planes_below_it() {
    let registry = PlaneRegistry::from_capabilities(vec![
        overlay(10, 0b01, Some(1)),
        overlay(11, 0b01, Some(5)),
    ]);
    let mut reservation = OverlayReservation::new();

    let claimed = reservation
        .reserve(&registry, 0, XRGB8888, 1, 4)
        .expect("one plane sits at or above 4");

    assert_eq!(claimed, vec![11], "not the one at zpos 1");
}

/// A plane that cannot scan the format out is not a candidate.
#[test]
fn a_plane_that_cannot_take_the_format_is_not_a_candidate() {
    let mut wrong_format = overlay(11, 0b01, Some(2));
    wrong_format.formats = vec![drmkit_fmt::fourcc::NV12];
    let registry = PlaneRegistry::from_capabilities(vec![overlay(10, 0b01, Some(1)), wrong_format]);
    let mut reservation = OverlayReservation::new();

    let error = reservation
        .reserve(&registry, 0, XRGB8888, 2, 0)
        .expect_err("only one plane takes XRGB8888");

    assert_eq!(
        error,
        ReserveError::Shortfall {
            crtc_index: 0,
            wanted: 2,
            found: 1
        }
    );
}

/// A plane with no zpos is skipped when a floor was asked for.
///
/// It cannot be *shown* to sit above anything. Admitting it would put a
/// decoration wherever the plane's fixed position happens to be, which on a
/// driver with no settable zpos is exactly the case the floor exists for.
#[test]
fn a_plane_without_a_zpos_is_skipped_when_a_floor_is_required() {
    let registry = PlaneRegistry::from_capabilities(vec![overlay(10, 0b01, None)]);
    let mut reservation = OverlayReservation::new();

    assert!(
        reservation.reserve(&registry, 0, XRGB8888, 1, 1).is_err(),
        "it cannot be shown to be above zpos 1"
    );
}

/// With no floor asked for, a plane without a zpos is fine.
///
/// The caller said it does not care where the decoration sits, and refusing
/// here would leave every driver with no settable zpos unable to reserve
/// anything at all.
#[test]
fn a_plane_without_a_zpos_is_admitted_when_no_floor_is_required() {
    let registry = PlaneRegistry::from_capabilities(vec![overlay(10, 0b01, None)]);
    let mut reservation = OverlayReservation::new();

    assert_eq!(
        reservation.reserve(&registry, 0, XRGB8888, 1, 0),
        Ok(vec![10])
    );
}

/// Planes come back in zpos order, and the order is stable.
///
/// A caller stacks decorations by index, so two planes at the same zpos
/// coming back in registry order would make the stack differ run to run.
#[test]
fn reserved_planes_come_back_in_a_stable_zpos_order() {
    // Deliberately out of order, and with a tie.
    let registry = PlaneRegistry::from_capabilities(vec![
        overlay(30, 0b01, Some(5)),
        overlay(10, 0b01, Some(1)),
        overlay(20, 0b01, Some(1)),
    ]);
    let mut reservation = OverlayReservation::new();

    let claimed = reservation
        .reserve(&registry, 0, XRGB8888, 3, 0)
        .expect("all three");

    assert_eq!(
        claimed,
        vec![10, 20, 30],
        "zpos first, then id -- the tie has to break the same way every time"
    );
    assert_eq!(reservation.reserved_for(0), claimed.as_slice());
}

/// Reserving nothing succeeds, and still records the CRTC.
///
/// A caller that asked for none has a reservation; it is just empty.
#[test]
fn reserving_nothing_succeeds() {
    let registry = partitioned();
    let mut reservation = OverlayReservation::new();

    assert_eq!(
        reservation.reserve(&registry, 0, XRGB8888, 0, 0),
        Ok(Vec::new())
    );
    assert!(reservation.reserved_for(0).is_empty());
    assert!(reservation.all_reserved().is_empty());
}

/// A CRTC that never reserved holds nothing.
#[test]
fn a_crtc_that_never_reserved_holds_nothing() {
    let reservation = OverlayReservation::new();
    assert!(reservation.reserved_for(0).is_empty());
    assert!(reservation.all_reserved().is_empty());
}

/// A primary plane is never a candidate.
///
/// It carries the window. Reserving it for a decoration would leave the
/// content with nowhere to go.
#[test]
fn a_primary_plane_is_never_reserved() {
    let mut primary = overlay(10, 0b01, Some(0));
    primary.plane_type = PlaneType::Primary;
    let registry = PlaneRegistry::from_capabilities(vec![primary, overlay(11, 0b01, Some(1))]);
    let mut reservation = OverlayReservation::new();

    let claimed = reservation
        .reserve(&registry, 0, XRGB8888, 1, 0)
        .expect("the overlay");

    assert_eq!(claimed, vec![11], "the primary is not on offer");
}

// --- renderer -----------------------------------------------------------------
//
// Parity port of the `CsdRenderer` and `CsdRendererDraw` cases in
// `tests/unit/test_csd_renderer.cpp`.

use crate::{Canvas, DrawError, Renderer, RendererConfig};

const W: u32 = 240;
const H: u32 = 160;

/// A canvas and its backing bytes.
fn canvas() -> Vec<u8> {
    vec![0u8; (W * H * 4) as usize]
}

/// Draw a decoration and hand back the pixels.
fn render(theme: &Theme, state: &WindowState) -> Vec<u8> {
    let mut pixels = canvas();
    let mut shadows = ShadowCache::new(4);
    let mut target = Canvas {
        pixels: &mut pixels,
        stride: W * 4,
        width: W,
        height: H,
    };
    Renderer::default()
        .draw(theme, state, &mut target, &mut shadows)
        .expect("a 240x160 canvas is drawable");
    pixels
}

/// The alpha byte at a pixel.
fn alpha_at(pixels: &[u8], x: u32, y: u32) -> u8 {
    pixels[((y * W + x) * 4 + 3) as usize]
}

/// A renderer builds with defaults, and reports no font.
///
/// Text is not implemented — a font stack is a separate dependency and a
/// separate decision — so `has_font` answers false rather than having a
/// caller reserve title-bar width for something that never appears.
#[test]
fn a_renderer_builds_and_reports_no_font() {
    let renderer = Renderer::default();
    assert!(!renderer.has_font());
    assert_eq!(renderer.font_path(), None);

    let configured = Renderer::new(RendererConfig {
        font_path: Some("/usr/share/fonts/x.ttf".to_owned()),
    });
    assert_eq!(configured.font_path(), Some("/usr/share/fonts/x.ttf"));
    assert!(
        !configured.has_font(),
        "a path is not a loaded font, and saying otherwise would be a lie a \
         caller lays out against"
    );
}

/// An empty canvas is refused.
///
/// A window mid-resize passes through zero. Reporting success on a loop that
/// wrote nothing would have the caller present an unpainted buffer believing
/// it had been drawn.
#[test]
fn an_empty_canvas_is_refused() {
    let mut shadows = ShadowCache::new(2);
    let mut nothing: Vec<u8> = Vec::new();
    let mut target = Canvas {
        pixels: &mut nothing,
        stride: 0,
        width: 0,
        height: 0,
    };

    assert_eq!(
        Renderer::default().draw(
            &glass_default(),
            &WindowState::default(),
            &mut target,
            &mut shadows
        ),
        Err(DrawError::EmptyCanvas)
    );
}

/// A canvas shorter than its own stride and height is refused.
#[test]
fn a_canvas_shorter_than_it_claims_is_refused() {
    let mut shadows = ShadowCache::new(2);
    let mut pixels = vec![0u8; 16];
    let mut target = Canvas {
        pixels: &mut pixels,
        stride: W * 4,
        width: W,
        height: H,
    };

    let error = Renderer::default()
        .draw(
            &glass_default(),
            &WindowState::default(),
            &mut target,
            &mut shadows,
        )
        .expect_err("sixteen bytes is not a 240x160 canvas");

    assert!(
        matches!(error, DrawError::Undersized { got: 16, .. }),
        "got {error}, which does not say what was wrong with the canvas"
    );
}

/// The middle of the panel is painted.
#[test]
fn the_middle_of_the_panel_is_painted() {
    let state = WindowState {
        title: "test".to_owned(),
        focused: true,
        ..WindowState::default()
    };
    let pixels = render(&glass_default(), &state);

    assert!(
        alpha_at(&pixels, W / 2, H / 2) > 0,
        "the center of a decoration is inside its panel; zero alpha there \
         means nothing was drawn at all"
    );
}

/// The extreme corner stays clear.
///
/// The shadow fades toward the edges and the panel is inset from them, so the
/// very corner of the canvas is outside both. Something opaque there means
/// the panel is being drawn at the wrong origin.
#[test]
fn the_far_corner_stays_transparent() {
    let state = WindowState {
        focused: true,
        ..WindowState::default()
    };
    let pixels = render(&glass_default(), &state);

    assert_eq!(
        alpha_at(&pixels, 0, 0),
        0,
        "the top-left of the canvas is beyond the shadow's reach"
    );
}

/// The same inputs draw the same bytes.
///
/// What lets a caller skip a redraw it knows would change nothing, and why
/// the panel's dither is a hash of the coordinate rather than a random
/// number.
#[test]
fn drawing_is_deterministic() {
    let state = WindowState {
        focused: true,
        ..WindowState::default()
    };

    let first = render(&glass_default(), &state);
    let second = render(&glass_default(), &state);

    assert_eq!(
        first, second,
        "two draws of one decoration must be byte-identical, or every \
         redraw-skipping optimization above this is unsound"
    );
}

/// Focused and blurred decorations differ.
///
/// The rim color is the cue that tells a user where their keystrokes are
/// going. Two windows that looked identical would make it useless.
#[test]
fn a_focused_decoration_differs_from_a_blurred_one() {
    let theme = glass_default();
    let focused = render(
        &theme,
        &WindowState {
            focused: true,
            ..WindowState::default()
        },
    );
    let blurred = render(
        &theme,
        &WindowState {
            focused: false,
            ..WindowState::default()
        },
    );

    assert_ne!(focused, blurred, "the two must not look the same");

    // Specifically at the rim, and against a theme with **no shadow**.
    //
    // Two confounds had to go for this to mean anything. Comparing whole
    // buffers passes on the shadow alone, since focused and blurred use
    // different elevations. And sampling the rim under a shadowed theme still
    // passes, because the rim is composited *over* a shadow that itself
    // differs -- so an identical rim color still produces different bytes.
    // Both verified by injecting a rim that ignores focus, which passed until
    // the shadow was taken out from under it.
    let unshadowed = glass_minimal();
    let focused = render(
        &unshadowed,
        &WindowState {
            focused: true,
            ..WindowState::default()
        },
    );
    let blurred = render(
        &unshadowed,
        &WindowState {
            focused: false,
            ..WindowState::default()
        },
    );
    let differs_at_rim = (0..W).any(|x| {
        let offset = (x * 4) as usize;
        focused[offset..offset + 4] != blurred[offset..offset + 4]
    });
    assert!(
        differs_at_rim,
        "the rim is the cue that says where keystrokes are going; it has to \
         be the thing that changes, not the shadow behind it"
    );
}

/// Hovering a button changes pixels at that button, and not at the others.
#[test]
fn hovering_a_button_changes_that_button_and_no_other() {
    let theme = glass_default();
    let geometry = decoration_geometry(&theme, W, H);
    let plain = render(&theme, &WindowState::default());
    let hovered = render(
        &theme,
        &WindowState {
            hover: HoverButton::Close,
            hover_progress: 1.0,
            ..WindowState::default()
        },
    );

    let at = |pixels: &[u8], cx: i32| {
        let x = u32::try_from(cx).expect("on canvas");
        let y = u32::try_from(geometry.button_cy).expect("on canvas");
        let offset = ((y * W + x) * 4) as usize;
        pixels[offset..offset + 4].to_vec()
    };

    assert_ne!(
        at(&plain, geometry.close_cx),
        at(&hovered, geometry.close_cx),
        "the hovered button has to light, or hover means nothing"
    );
    assert_eq!(
        at(&plain, geometry.minimize_cx),
        at(&hovered, geometry.minimize_cx),
        "and only that one -- lighting every button on any hover would be \
         worse than lighting none"
    );
}

/// Drawing populates the shadow cache.
///
/// The blur is the expensive part, and it happening through the cache is what
/// makes the second frame cheap.
#[test]
fn drawing_populates_the_shadow_cache() {
    let mut pixels = canvas();
    let mut shadows = ShadowCache::new(4);
    assert!(shadows.is_empty());

    let mut target = Canvas {
        pixels: &mut pixels,
        stride: W * 4,
        width: W,
        height: H,
    };
    Renderer::default()
        .draw(
            &glass_default(),
            &WindowState {
                focused: true,
                ..WindowState::default()
            },
            &mut target,
            &mut shadows,
        )
        .expect("drawable");

    assert_eq!(shadows.len(), 1, "the shadow went through the cache");
}

/// A theme with no shadow draws no shadow and still draws a panel.
#[test]
fn a_theme_with_no_shadow_still_draws_its_panel() {
    let pixels = render(
        &glass_minimal(),
        &WindowState {
            focused: true,
            ..WindowState::default()
        },
    );

    assert!(alpha_at(&pixels, W / 2, H / 2) > 0, "the panel is there");
    assert!(
        alpha_at(&pixels, 0, H / 2) > 0,
        "and with no shadow inset it reaches the canvas edge -- sampled at \
         mid-height, because the panel is still rounded and the literal \
         corner is outside it"
    );
    assert_eq!(
        alpha_at(&pixels, 0, 0),
        0,
        "the corner is clear even with no shadow, because the panel is rounded"
    );
}

/// A decoration too small for its own shadow draws nothing rather than
/// panicking.
#[test]
fn a_decoration_too_small_for_its_shadow_draws_nothing() {
    let theme = glass_default();
    let mut pixels = vec![0u8; (16 * 16 * 4) as usize];
    let mut shadows = ShadowCache::new(2);
    let mut target = Canvas {
        pixels: &mut pixels,
        stride: 16 * 4,
        width: 16,
        height: 16,
    };

    Renderer::default()
        .draw(&theme, &WindowState::default(), &mut target, &mut shadows)
        .expect("a zero panel is not an error");
}

// --- presenter tier -----------------------------------------------------------
//
// Parity port of `tests/unit/test_csd_probe_presenter.cpp`.

use crate::{
    PlaneError, PlaneSlot, PropertyWrite, SurfaceRef, Tier, choose_presenter_tier, compute_writes,
};

/// Enough reservable planes means a plane per decoration.
#[test]
fn enough_planes_means_a_plane_each() {
    assert_eq!(choose_presenter_tier(3, 3, true), Some(Tier::Plane));
    assert_eq!(
        choose_presenter_tier(5, 3, false),
        Some(Tier::Plane),
        "with a plane each, no canvas is needed"
    );
}

/// Too few planes but a canvas means compositing.
#[test]
fn too_few_planes_with_a_canvas_means_compositing() {
    assert_eq!(choose_presenter_tier(1, 3, true), Some(Tier::Composite));
    assert_eq!(choose_presenter_tier(0, 1, true), Some(Tier::Composite));
}

/// Neither a plane each nor a canvas means neither tier.
///
/// `None` rather than `Fb`: the framebuffer tier is what a caller falls back
/// *to* when KMS has nothing, not one of the KMS options being chosen among.
#[test]
fn no_planes_and_no_canvas_chooses_nothing() {
    assert_eq!(choose_presenter_tier(0, 1, false), None);
    assert_eq!(choose_presenter_tier(1, 3, false), None);
}

/// Wanting no decorations is never the plane tier.
///
/// Reserving zero planes trivially succeeds, and answering Plane on that
/// basis would have a caller build a plane presenter with no slots.
#[test]
fn wanting_no_decorations_is_never_the_plane_tier() {
    assert_eq!(choose_presenter_tier(4, 0, true), Some(Tier::Composite));
    assert_eq!(choose_presenter_tier(4, 0, false), None);
}

// --- plane presenter ----------------------------------------------------------
//
// Parity port of `tests/unit/test_csd_presenter_plane.cpp`.

fn slot(plane_id: u32) -> PlaneSlot {
    PlaneSlot {
        plane_id,
        crtc_id: 99,
        fb_id_prop: 1,
        crtc_id_prop: 2,
        crtc_x_prop: 3,
        crtc_y_prop: 4,
        crtc_w_prop: 5,
        crtc_h_prop: 6,
        src_x_prop: 7,
        src_y_prop: 8,
        src_w_prop: 9,
        src_h_prop: 10,
        ..PlaneSlot::default()
    }
}

fn surface(fb_id: u32, x: i32, y: i32) -> SurfaceRef {
    SurfaceRef {
        fb_id,
        width: 64,
        height: 32,
        x,
        y,
        generation: 0,
    }
}

/// Whether a write for this object and property exists, and its value.
fn value_of(writes: &[PropertyWrite], object_id: u32, property_id: u32) -> Option<u64> {
    writes
        .iter()
        .find(|w| w.object_id == object_id && w.property_id == property_id)
        .map(|w| w.value)
}

/// More decorations than planes is refused.
///
/// Truncating would leave windows silently undecorated, and the caller
/// reserved the planes knowing how many it wanted.
#[test]
fn more_decorations_than_planes_is_refused() {
    let error = compute_writes(&[slot(10)], &[surface(1, 0, 0), surface(2, 0, 0)])
        .expect_err("two decorations, one plane");

    assert_eq!(
        error,
        PlaneError::TooManySurfaces {
            surfaces: 2,
            slots: 1
        }
    );
}

/// No slots and no surfaces is trivially nothing.
#[test]
fn no_slots_and_no_surfaces_writes_nothing() {
    assert_eq!(compute_writes(&[], &[]), Ok(Vec::new()));
}

/// An armed slot gets its geometry, with the source in 16.16.
#[test]
fn an_armed_slot_gets_its_geometry() {
    let writes = compute_writes(&[slot(10)], &[surface(77, 5, 9)]).expect("one each");

    assert_eq!(value_of(&writes, 10, 1), Some(77), "FB_ID");
    assert_eq!(value_of(&writes, 10, 2), Some(99), "CRTC_ID");
    assert_eq!(value_of(&writes, 10, 3), Some(5), "CRTC_X");
    assert_eq!(value_of(&writes, 10, 4), Some(9), "CRTC_Y");
    assert_eq!(value_of(&writes, 10, 5), Some(64), "CRTC_W");
    assert_eq!(value_of(&writes, 10, 6), Some(32), "CRTC_H");
    assert_eq!(
        value_of(&writes, 10, 9),
        Some(64 << 16),
        "SRC_W is 16.16 fixed point, not pixels"
    );
    assert_eq!(value_of(&writes, 10, 10), Some(32 << 16), "SRC_H likewise");
}

/// A surface with no framebuffer disarms its slot.
///
/// Leaving the plane alone would have it go on scanning out last frame's
/// buffer, so a window that closed would leave its decoration on screen.
#[test]
fn a_surface_with_no_framebuffer_disarms_its_slot() {
    let writes = compute_writes(&[slot(10)], &[surface(0, 0, 0)]).expect("one slot");

    assert_eq!(value_of(&writes, 10, 1), Some(0), "FB_ID cleared");
    assert_eq!(
        value_of(&writes, 10, 2),
        Some(0),
        "and unbound from the CRTC"
    );
    assert_eq!(
        writes.len(),
        2,
        "and nothing else -- describing geometry for a framebuffer that is \
         not there says nothing"
    );
}

/// A zero-sized surface is a disarm too.
#[test]
fn a_zero_sized_surface_disarms_its_slot() {
    let empty = SurfaceRef {
        fb_id: 7,
        width: 0,
        height: 32,
        ..SurfaceRef::default()
    };
    let writes = compute_writes(&[slot(10)], &[empty]).expect("one slot");

    assert_eq!(writes.len(), 2, "disarmed, not drawn at zero width");
    assert_eq!(value_of(&writes, 10, 1), Some(0));
}

/// Slots past the surfaces are disarmed.
#[test]
fn slots_past_the_surfaces_are_disarmed() {
    let writes = compute_writes(&[slot(10), slot(20), slot(30)], &[surface(77, 0, 0)])
        .expect("one of three");

    assert_eq!(value_of(&writes, 10, 1), Some(77), "the first is armed");
    assert_eq!(value_of(&writes, 20, 1), Some(0), "the tail is not");
    assert_eq!(value_of(&writes, 30, 1), Some(0));
    assert_eq!(value_of(&writes, 30, 2), Some(0));
}

/// The optional properties are written when the plane has them.
#[test]
fn the_optional_properties_are_written_when_present() {
    let with_extras = PlaneSlot {
        blend_mode_prop: 20,
        blend_mode_value: 3,
        alpha_prop: 21,
        zpos_prop: 22,
        zpos_value: 7,
        ..slot(10)
    };
    let writes = compute_writes(&[with_extras], &[surface(77, 0, 0)]).expect("one slot");

    assert_eq!(value_of(&writes, 10, 20), Some(3), "blend mode");
    assert_eq!(
        value_of(&writes, 10, 21),
        Some(0xFFFF),
        "fully opaque -- the decoration's own alpha is in its pixels, and a \
         per-plane alpha on top would fade the whole thing"
    );
    assert_eq!(value_of(&writes, 10, 22), Some(7), "zpos");
}

/// A property the plane does not expose is not written.
///
/// A zero id means absent, and writing to object zero is an `EINVAL` that
/// takes the whole commit down rather than just this plane.
#[test]
fn a_property_the_plane_lacks_is_not_written() {
    let writes = compute_writes(&[slot(10)], &[surface(77, 0, 0)]).expect("one slot");

    assert!(
        !writes.iter().any(|w| w.property_id == 0),
        "a write to property zero would take down every layer in the commit, \
         not just this one"
    );
    assert_eq!(
        writes.len(),
        10,
        "the ten mandatory properties, and no more"
    );
}

/// A negative position is carried as two's complement.
///
/// A decoration may sit partly off the left or top edge, and the kernel clips
/// it. Clamping to zero here would move it instead.
#[test]
fn a_negative_position_is_carried_through() {
    let writes = compute_writes(&[slot(10)], &[surface(77, -4, -8)]).expect("one slot");

    assert_eq!(
        value_of(&writes, 10, 3),
        Some(i64::from(-4).cast_unsigned())
    );
    assert_eq!(
        value_of(&writes, 10, 4),
        Some(i64::from(-8).cast_unsigned())
    );
}

/// A default surface reference names nothing.
#[test]
fn a_default_surface_reference_is_not_armed() {
    assert!(!SurfaceRef::default().is_armed());
    assert!(surface(1, 0, 0).is_armed());
}

// --- composite damage ---------------------------------------------------------
//
// Parity port of the `CsdCompositeDamage` cases in
// `tests/unit/test_csd_presenter_composite.cpp`.

use crate::{DamageRect, DamageSlot, compute_damage, intersect_rect, union_rect};

const CANVAS_W: u32 = 200;
const CANVAS_H: u32 = 100;

fn armed(x: i32, y: i32, w: u32, h: u32, generation: u64) -> DamageSlot {
    DamageSlot {
        armed: true,
        x,
        y,
        w,
        h,
        generation,
    }
}

fn damage(prev: &[DamageSlot], cur: &[DamageSlot]) -> DamageRect {
    compute_damage(prev, cur, CANVAS_W, CANVAS_H)
}

/// The first frame damages the whole canvas.
///
/// Nothing is on it yet, so everything has to be painted.
#[test]
fn the_first_frame_damages_the_whole_canvas() {
    let region = damage(&[], &[armed(0, 0, 10, 10, 1)]);

    assert_eq!(
        region,
        DamageRect {
            x: 0,
            y: 0,
            w: CANVAS_W,
            h: CANVAS_H
        }
    );
}

/// A different number of slots damages everything.
///
/// The slots are compared pairwise by index, so a count change makes the
/// pairing meaningless — comparing slot 2 against what used to be slot 3
/// reports changes in the wrong places and misses real ones.
#[test]
fn a_change_in_slot_count_damages_the_whole_canvas() {
    let before = [armed(0, 0, 10, 10, 1)];
    let after = [armed(0, 0, 10, 10, 1), armed(50, 50, 10, 10, 1)];

    assert_eq!(damage(&before, &after).w, CANVAS_W);
    assert_eq!(damage(&after, &before).w, CANVAS_W);
}

/// Nothing changing damages nothing.
///
/// The whole point: a frame where no decoration moved or repainted costs no
/// compositing at all.
#[test]
fn nothing_changing_damages_nothing() {
    let slots = [armed(10, 10, 20, 20, 5), armed(80, 40, 30, 30, 9)];

    assert!(damage(&slots, &slots).is_empty());
}

/// A move damages both the old footprint and the new.
///
/// The old has to be vacated or the decoration leaves a copy of itself
/// behind; the new has to be painted. One rectangle covering both is what a
/// row-wise repaint wants.
#[test]
fn a_move_damages_the_old_footprint_and_the_new() {
    let before = [armed(10, 10, 20, 20, 1)];
    let after = [armed(50, 10, 20, 20, 1)];

    let region = damage(&before, &after);

    assert_eq!(region.x, 10, "starts at the old left edge");
    assert_eq!(region.w, 60, "and reaches the new right edge");
    assert_eq!(region.y, 10);
    assert_eq!(region.h, 20);
}

/// A repaint in place damages that slot.
///
/// Same rectangle, different generation. Without the generation this looks
/// unchanged, and a decoration whose pixels changed would never be
/// recomposited.
#[test]
fn a_repaint_in_place_damages_its_slot() {
    let before = [armed(10, 10, 20, 20, 1)];
    let after = [armed(10, 10, 20, 20, 2)];

    assert_eq!(
        damage(&before, &after),
        DamageRect {
            x: 10,
            y: 10,
            w: 20,
            h: 20
        }
    );
}

/// A window opening damages where it appeared; closing damages where it was.
#[test]
fn opening_damages_the_new_rectangle_and_closing_the_old() {
    let empty = [DamageSlot::default()];
    let present = [armed(30, 20, 40, 25, 1)];

    let opened = damage(&empty, &present);
    assert_eq!(
        opened,
        DamageRect {
            x: 30,
            y: 20,
            w: 40,
            h: 25
        }
    );

    let closed = damage(&present, &empty);
    assert_eq!(
        closed, opened,
        "the same region has to be repainted either way"
    );
}

/// Damage is clamped to the canvas.
///
/// A decoration partly off-screen has a footprint that is not, and a repaint
/// loop handed those bounds would run off the end of the buffer.
#[test]
fn damage_is_clamped_to_the_canvas() {
    let before = [DamageSlot::default()];
    let after = [armed(-20, -10, 60, 40, 1)];

    let region = damage(&before, &after);

    assert_eq!(region.x, 0, "not negative");
    assert_eq!(region.y, 0);
    assert_eq!(region.w, 40, "and only the part that is on the canvas");
    assert_eq!(region.h, 30);
}

/// A decoration entirely off the canvas damages nothing.
#[test]
fn a_decoration_entirely_off_the_canvas_damages_nothing() {
    let before = [DamageSlot::default()];
    let after = [armed(500, 500, 10, 10, 1)];

    assert!(damage(&before, &after).is_empty());
}

/// A union covers both rectangles, and an empty one contributes nothing.
#[test]
fn a_union_covers_both_and_ignores_an_empty_one() {
    let a = DamageRect {
        x: 0,
        y: 0,
        w: 10,
        h: 10,
    };
    let b = DamageRect {
        x: 90,
        y: 40,
        w: 10,
        h: 10,
    };

    let both = union_rect(a, b);
    assert_eq!(both.x, 0);
    assert_eq!(both.y, 0);
    assert_eq!(both.w, 100);
    assert_eq!(both.h, 50);

    assert_eq!(union_rect(a, DamageRect::default()), a);
    assert_eq!(union_rect(DamageRect::default(), b), b);
}

/// An intersection is the overlap, and disjoint rectangles have none.
#[test]
fn an_intersection_is_the_overlap() {
    let region = DamageRect {
        x: 10,
        y: 10,
        w: 50,
        h: 50,
    };

    assert_eq!(
        intersect_rect(0, 0, 20, 20, region),
        DamageRect {
            x: 10,
            y: 10,
            w: 10,
            h: 10
        }
    );
    assert!(
        intersect_rect(100, 100, 10, 10, region).is_empty(),
        "disjoint rectangles overlap in nothing"
    );
}

// --- framebuffer presenter ----------------------------------------------------
//
// Parity port of `tests/unit/test_csd_presenter_fb.cpp`.

use crate::{BlitItem, FbTarget, compose_into_framebuffer, fb_fourcc_for};
use drmkit_fmt::fourcc;

/// 32bpp with red above blue is `RGB`-ordered.
#[test]
fn thirty_two_bpp_with_red_above_blue_is_rgb_ordered() {
    assert_eq!(fb_fourcc_for(32, 16, 0, 0), Some(fourcc::XRGB8888));
    assert_eq!(
        fb_fourcc_for(32, 16, 0, 8),
        Some(fourcc::ARGB8888),
        "a transparency field means the fourth byte is alpha, not padding"
    );
}

/// 32bpp with red below blue is `BGR`-ordered.
///
/// Getting this backwards swaps red and blue on every pixel, which is the one
/// thing fbdev reports that cannot be inferred from the byte width.
#[test]
fn thirty_two_bpp_with_red_below_blue_is_bgr_ordered() {
    assert_eq!(fb_fourcc_for(32, 0, 16, 0), Some(fourcc::XBGR8888));
    assert_eq!(fb_fourcc_for(32, 0, 16, 8), Some(fourcc::ABGR8888));
}

/// 16bpp is 565, in whichever order.
#[test]
fn sixteen_bpp_is_565() {
    assert_eq!(fb_fourcc_for(16, 11, 0, 0), Some(fourcc::RGB565));
    assert_eq!(fb_fourcc_for(16, 0, 11, 0), Some(fourcc::BGR565));
}

/// A depth this cannot describe is refused.
///
/// A caller handed a guess would write 32-bit pixels into a 24-bit buffer, and
/// the result is not a wrong color but a sheared image — every row lands at
/// the wrong offset.
#[test]
fn a_depth_that_cannot_be_described_is_refused() {
    assert_eq!(fb_fourcc_for(24, 16, 0, 0), None);
    assert_eq!(fb_fourcc_for(8, 0, 0, 0), None);
    assert_eq!(fb_fourcc_for(0, 0, 0, 0), None);
}

const FB_W: u32 = 8;
const FB_H: u32 = 4;

/// An opaque `ARGB8888` source pixel, as a one-pixel item.
fn one_pixel(argb: [u8; 4]) -> Vec<u8> {
    argb.to_vec()
}

/// Blit one opaque pixel at an offset.
#[test]
fn one_opaque_pixel_lands_at_its_offset() {
    let pixel = one_pixel([0x10, 0x20, 0x30, 0xFF]); // B, G, R, A
    let items = [BlitItem {
        pixels: &pixel,
        stride: 4,
        width: 1,
        height: 1,
        fourcc: fourcc::ARGB8888,
        x: 3,
        y: 2,
    }];
    let mut framebuffer = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut shadow = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut target = FbTarget {
        pixels: &mut framebuffer,
        stride: FB_W * 4,
        width: FB_W,
        height: FB_H,
        fourcc: fourcc::XRGB8888,
    };

    compose_into_framebuffer(
        &mut target,
        &mut shadow,
        &items,
        DamageRect {
            x: 0,
            y: 0,
            w: FB_W,
            h: FB_H,
        },
    );

    let at = ((2 * FB_W + 3) * 4) as usize;
    assert_eq!(
        &framebuffer[at..at + 3],
        &[0x10, 0x20, 0x30],
        "the pixel is where it was placed, in the destination's own order"
    );
    assert_eq!(&framebuffer[0..4], &[0, 0, 0, 0], "and nowhere else");
}

/// A `BGR`-ordered destination gets its channels swapped.
///
/// The blend happens in `ARGB8888` because it needs a consistent order and an
/// alpha channel; the conversion is what puts it in the destination's terms.
/// Skipping it swaps red and blue on every pixel.
#[test]
fn a_bgr_destination_has_its_channels_swapped() {
    let pixel = one_pixel([0x10, 0x20, 0x30, 0xFF]);
    let items = [BlitItem {
        pixels: &pixel,
        stride: 4,
        width: 1,
        height: 1,
        fourcc: fourcc::ARGB8888,
        x: 0,
        y: 0,
    }];
    let mut framebuffer = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut shadow = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut target = FbTarget {
        pixels: &mut framebuffer,
        stride: FB_W * 4,
        width: FB_W,
        height: FB_H,
        fourcc: fourcc::XBGR8888,
    };

    compose_into_framebuffer(
        &mut target,
        &mut shadow,
        &items,
        DamageRect {
            x: 0,
            y: 0,
            w: FB_W,
            h: FB_H,
        },
    );

    assert_eq!(
        &framebuffer[0..3],
        &[0x30, 0x20, 0x10],
        "red and blue exchanged relative to the ARGB source"
    );
}

/// A shadow too small for the framebuffer does nothing.
///
/// Compositing into it would run off the end. Doing nothing is the only safe
/// answer, and the caller sized it.
#[test]
fn a_shadow_too_small_for_the_framebuffer_does_nothing() {
    let pixel = one_pixel([0xFF, 0xFF, 0xFF, 0xFF]);
    let items = [BlitItem {
        pixels: &pixel,
        stride: 4,
        width: 1,
        height: 1,
        fourcc: fourcc::ARGB8888,
        x: 0,
        y: 0,
    }];
    let mut framebuffer = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut shadow = vec![0u8; 16];
    let mut target = FbTarget {
        pixels: &mut framebuffer,
        stride: FB_W * 4,
        width: FB_W,
        height: FB_H,
        fourcc: fourcc::XRGB8888,
    };

    compose_into_framebuffer(
        &mut target,
        &mut shadow,
        &items,
        DamageRect {
            x: 0,
            y: 0,
            w: FB_W,
            h: FB_H,
        },
    );

    assert!(framebuffer.iter().all(|b| *b == 0), "nothing was written");
}

/// Only the damaged rows are converted.
///
/// The blend is already confined to the damage; converting the whole buffer
/// afterwards would make the damage tracking pointless, since the conversion
/// costs about what the blend does per row.
#[test]
fn only_the_damaged_rows_are_converted() {
    let pixels = vec![0xFFu8; (FB_W * FB_H * 4) as usize];
    let items = [BlitItem {
        pixels: &pixels,
        stride: FB_W * 4,
        width: FB_W,
        height: FB_H,
        fourcc: fourcc::ARGB8888,
        x: 0,
        y: 0,
    }];
    // Pre-filled with a sentinel, which is the case that matters: an fbdev
    // mapping already holds the rest of the screen. A zeroed framebuffer
    // cannot tell "left alone" from "converted from an empty shadow" -- the
    // first version of this case could not, and converting every row passed
    // it.
    let mut framebuffer = vec![0xAAu8; (FB_W * FB_H * 4) as usize];
    let mut shadow = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut target = FbTarget {
        pixels: &mut framebuffer,
        stride: FB_W * 4,
        width: FB_W,
        height: FB_H,
        fourcc: fourcc::XRGB8888,
    };

    // Only row 1.
    compose_into_framebuffer(
        &mut target,
        &mut shadow,
        &items,
        DamageRect {
            x: 0,
            y: 1,
            w: FB_W,
            h: 1,
        },
    );

    let row = |n: u32| {
        let start = (n * FB_W * 4) as usize;
        framebuffer[start..start + (FB_W * 4) as usize].to_vec()
    };
    assert!(
        row(1).iter().any(|b| *b != 0),
        "the damaged row was written"
    );
    assert!(
        row(0).iter().all(|b| *b == 0xAA),
        "the row above still holds what was already on screen -- converting \
         it would paint the shadow's empty pixels over the rest of the display"
    );
    assert!(row(3).iter().all(|b| *b == 0xAA), "and the row below");
}

/// Empty damage does nothing at all.
#[test]
fn empty_damage_composites_nothing() {
    let pixels = vec![0xFFu8; (FB_W * FB_H * 4) as usize];
    let items = [BlitItem {
        pixels: &pixels,
        stride: FB_W * 4,
        width: FB_W,
        height: FB_H,
        fourcc: fourcc::ARGB8888,
        x: 0,
        y: 0,
    }];
    let mut framebuffer = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut shadow = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut target = FbTarget {
        pixels: &mut framebuffer,
        stride: FB_W * 4,
        width: FB_W,
        height: FB_H,
        fourcc: fourcc::XRGB8888,
    };

    compose_into_framebuffer(&mut target, &mut shadow, &items, DamageRect::default());

    assert!(
        framebuffer.iter().all(|b| *b == 0),
        "a frame where nothing changed costs nothing, which is the whole \
         reason damage is tracked"
    );
}

/// A decoration outside the damage contributes nothing.
#[test]
fn a_decoration_outside_the_damage_contributes_nothing() {
    let pixel = one_pixel([0xFF, 0xFF, 0xFF, 0xFF]);
    let items = [BlitItem {
        pixels: &pixel,
        stride: 4,
        width: 1,
        height: 1,
        fourcc: fourcc::ARGB8888,
        x: 7,
        y: 3,
    }];
    let mut framebuffer = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut shadow = vec![0u8; (FB_W * FB_H * 4) as usize];
    let mut target = FbTarget {
        pixels: &mut framebuffer,
        stride: FB_W * 4,
        width: FB_W,
        height: FB_H,
        fourcc: fourcc::XRGB8888,
    };

    // Damage the top-left corner; the decoration is at the bottom-right.
    compose_into_framebuffer(
        &mut target,
        &mut shadow,
        &items,
        DamageRect {
            x: 0,
            y: 0,
            w: 2,
            h: 1,
        },
    );

    let at = ((3 * FB_W + 7) * 4) as usize;
    assert_eq!(
        &framebuffer[at..at + 4],
        &[0, 0, 0, 0],
        "outside the damage means outside this frame's work"
    );
}

// --- composite presenter, canvas writes ---------------------------------------
//
// Parity port of the `CsdComputeCanvasWrites` cases in
// `tests/unit/test_csd_presenter_composite.cpp`.

use crate::compute_canvas_writes;

/// The canvas is armed full-screen and unscaled.
///
/// There is no per-decoration geometry here, which is the difference from the
/// plane tier: the positioning already happened during the blend, and the
/// canvas is the size of the mode by construction.
#[test]
fn the_canvas_is_armed_full_screen_and_unscaled() {
    let canvas = PlaneSlot {
        plane_id: 7,
        crtc_id: 42,
        ..slot(7)
    };
    let writes = compute_canvas_writes(&canvas, 1234, 1920, 1080);

    assert_eq!(writes.len(), 10, "ten properties arm a plane, no more");
    assert_eq!(value_of(&writes, 7, canvas.fb_id_prop), Some(1234));
    assert_eq!(value_of(&writes, 7, canvas.crtc_id_prop), Some(42));
    assert_eq!(value_of(&writes, 7, canvas.crtc_x_prop), Some(0));
    assert_eq!(value_of(&writes, 7, canvas.crtc_y_prop), Some(0));
    assert_eq!(value_of(&writes, 7, canvas.crtc_w_prop), Some(1920));
    assert_eq!(value_of(&writes, 7, canvas.crtc_h_prop), Some(1080));
    assert_eq!(value_of(&writes, 7, canvas.src_x_prop), Some(0));
    assert_eq!(value_of(&writes, 7, canvas.src_y_prop), Some(0));
    assert_eq!(
        value_of(&writes, 7, canvas.src_w_prop),
        Some(1920 << 16),
        "16.16 fixed point -- pixels here would ask for a source region 65536 \
         times too small"
    );
    assert_eq!(value_of(&writes, 7, canvas.src_h_prop), Some(1080 << 16));
}

/// Every write targets the canvas plane and nothing else.
#[test]
fn every_canvas_write_targets_the_canvas_plane() {
    let canvas = PlaneSlot {
        plane_id: 3,
        ..slot(3)
    };
    let writes = compute_canvas_writes(&canvas, 55, 640, 480);

    assert!(
        writes.iter().all(|w| w.object_id == 3),
        "a write aimed at another object would program a plane the composite \
         tier does not own"
    );
}

/// The framebuffer id is written verbatim, zero included.
///
/// A zero framebuffer takes the canvas plane down, which is what a caller
/// with nothing to show wants. Suppressing it would leave the previous canvas
/// armed and the last frame's decorations on screen after every window has
/// closed.
#[test]
fn the_canvas_framebuffer_is_written_verbatim() {
    let canvas = PlaneSlot {
        plane_id: 1,
        ..slot(1)
    };

    assert_eq!(
        value_of(
            &compute_canvas_writes(&canvas, 0, 800, 600),
            1,
            canvas.fb_id_prop
        ),
        Some(0)
    );
    assert_eq!(
        value_of(
            &compute_canvas_writes(&canvas, 99, 800, 600),
            1,
            canvas.fb_id_prop
        ),
        Some(99)
    );
}

// --- decoration surface -------------------------------------------------------
//
// Parity port of `tests/unit/test_csd_surface.cpp`.
//
// Upstream's `MoveCtorPreservesEmpty` and `MoveAssignPreservesEmpty` have no
// counterpart: they check that a moved-from husk stays safe, and Rust's move
// semantics do not produce one. `CreateAgainstNonDrmFdFails` likewise — a
// drmkit `Device` exists only where an open succeeded.

use crate::{SURFACE_FOURCC, Surface, SurfaceConfig, SurfaceError};

/// A default surface holds nothing, and says so consistently.
#[test]
fn a_default_surface_holds_nothing() {
    let surface = Surface::default();

    assert!(surface.is_empty());
    assert_eq!(surface.fb_id(), 0, "zero is what disarms a plane");
    assert_eq!(surface.width(), 0);
    assert_eq!(surface.height(), 0);
    assert_eq!(surface.stride(), 0);
    assert_eq!(surface.generation(), 0);
}

/// The format is `ARGB8888`, empty or not.
///
/// A decoration is translucent by design — the panel is a gradient with
/// alpha, the shadow is nothing but alpha — so a format without an alpha
/// channel cannot represent one. An empty surface still answers, because a
/// caller laying out a decoration it has not allocated yet needs to know what
/// it will be.
#[test]
fn the_format_is_always_argb8888() {
    assert_eq!(Surface::default().format(), SURFACE_FOURCC);
    assert_eq!(SURFACE_FOURCC, drmkit_fmt::fourcc::ARGB8888);
}

/// Painting an empty surface is an error, not a panic.
#[test]
fn painting_an_empty_surface_is_refused() {
    let mut surface = Surface::default();

    assert!(matches!(
        surface.paint(drmkit_dumb::MapAccess::ReadWrite),
        Err(SurfaceError::Empty)
    ));
    assert_eq!(
        surface.generation(),
        0,
        "a refused paint is not a paint -- counting it would report a change \
         that never happened"
    );
}

/// Forgetting an empty surface is a no-op.
///
/// What a caller tearing down twice does.
#[test]
fn forgetting_an_empty_surface_is_harmless() {
    let mut surface = Surface::default();
    surface.forget();
    surface.forget();
    assert!(surface.is_empty());
}

/// A zero dimension is refused, and says which.
#[test]
fn a_zero_dimension_is_refused_by_name() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    for (field, config) in [
        (
            "width",
            SurfaceConfig {
                width: 0,
                height: 64,
            },
        ),
        (
            "height",
            SurfaceConfig {
                width: 64,
                height: 0,
            },
        ),
    ] {
        let error =
            Surface::create(&device, config).expect_err("a zero dimension is not a surface");
        assert!(
            matches!(error, SurfaceError::Invalid { field: named } if named == field),
            "asked about {field} and got {error}"
        );
    }
}

/// A real surface reports its shape and a usable framebuffer.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_real_surface_reports_its_shape_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let surface = Surface::create(
        &device,
        SurfaceConfig {
            width: 64,
            height: 32,
        },
    )
    .expect("a 64x32 ARGB8888 surface");

    assert!(!surface.is_empty());
    assert_eq!(surface.width(), 64);
    assert_eq!(surface.height(), 32);
    assert!(surface.stride() >= 64 * 4);
    assert_ne!(
        surface.fb_id(),
        0,
        "a decoration with no framebuffer cannot reach a plane"
    );
}

/// Painting bumps the generation, which is what makes a repaint visible.
///
/// A decoration at the same place with different pixels looks unchanged to
/// the damage tracker otherwise, and is never recomposited.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn painting_bumps_the_generation_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let mut surface = Surface::create(
        &device,
        SurfaceConfig {
            width: 64,
            height: 32,
        },
    )
    .expect("a surface");

    assert_eq!(surface.generation(), 0);
    {
        let _mapping = surface.paint(drmkit_dumb::MapAccess::Write).expect("map");
    }
    assert_eq!(surface.generation(), 1);
    {
        let _mapping = surface
            .paint(drmkit_dumb::MapAccess::ReadWrite)
            .expect("map");
    }
    assert_eq!(surface.generation(), 2);

    {
        let _mapping = surface.paint(drmkit_dumb::MapAccess::Read).expect("map");
    }
    assert_eq!(
        surface.generation(),
        2,
        "reading is not painting -- counting it would recomposite a \
         decoration that nobody touched"
    );
}

/// A forgotten surface is empty again, and answers like one.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn forgetting_a_real_surface_empties_it_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let mut surface = Surface::create(
        &device,
        SurfaceConfig {
            width: 64,
            height: 32,
        },
    )
    .expect("a surface");
    assert!(!surface.is_empty());

    surface.forget();

    assert!(surface.is_empty());
    assert_eq!(surface.fb_id(), 0);
    assert!(matches!(
        surface.paint(drmkit_dumb::MapAccess::ReadWrite),
        Err(SurfaceError::Empty)
    ));
}

/// Exporting an empty surface is refused.
#[test]
fn exporting_an_empty_surface_is_refused() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    assert!(matches!(
        Surface::default().export(&device),
        Err(SurfaceError::Empty)
    ));
}

// --- parity with the reference's arithmetic -------------------------------------

/// The id is the reference's hash: each 32-bit field most significant byte
/// first. Computed independently of this code, so a byte-order slip in either
/// direction fails here.
#[test]
#[cfg(target_endian = "little")]
fn a_theme_id_is_the_references_hash() {
    let theme = Theme {
        corner_radius: 0x0102_0304,
        shadow_extent: 0x0a0b_0c0d,
        noise_amplitude: 0.25,
        title_bar: crate::TitleBar {
            height: 0x1122_3344,
            font: String::new(),
            font_size: 0x5566_7788,
        },
        ..Theme::default()
    };
    assert_eq!(theme_id(&theme), 0x5dff_0f09_bf68_a248);
}

/// A color is hex digits and nothing else. A sign is not a digit, though
/// the integer parser would take one.
#[test]
fn a_color_with_a_sign_in_it_is_malformed() {
    for hex in ["#+1+2+3", "#+12345", "#12+345", "#+1234567"] {
        assert!(
            matches!(Color::from_hex(hex), Err(ColorError::Malformed { .. })),
            "{hex}"
        );
    }
}

/// Geometry never panics, however large a theme's extent or title bar.
#[test]
fn an_enormous_shadow_or_title_bar_does_not_overflow_the_geometry() {
    let theme = Theme {
        shadow_extent: i32::MAX,
        title_bar: crate::TitleBar {
            height: i32::MAX,
            font: String::new(),
            font_size: 13,
        },
        ..Theme::default()
    };
    let geometry = decoration_geometry(&theme, 1000, 1000);
    assert_eq!(geometry.panel_w, 0, "two extents leave no room for a panel");
}

/// A noise amplitude past one is full strength, as the reference clamps it.
#[test]
fn a_noise_amplitude_past_one_is_full_strength() {
    let base = Color::new(128, 128, 128, 255);
    for (x, y) in [(0, 0), (3, 7), (100, 41)] {
        assert_eq!(
            crate::renderer::dither(base, x, y, 4.0),
            crate::renderer::dither(base, x, y, 1.0),
            "({x}, {y})"
        );
    }
}

/// A shadow is composited over what is already there, as the reference
/// composites it, not copied over it: where the shadow is faint, the
/// destination shows through.
#[test]
fn a_shadow_is_composited_over_the_destination() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(2);
    let patch = key(64, 64, Elevation::Focused, &theme);

    let (mut clear, stride) = dest(64, 64);
    assert!(cache.blit_into(
        patch,
        &theme,
        &mut ShadowDest {
            pixels: &mut clear,
            stride,
            width: 64,
            height: 64,
        }
    ));
    let mut white = vec![0xFF_u8; clear.len()];
    assert!(cache.blit_into(
        patch,
        &theme,
        &mut ShadowDest {
            pixels: &mut white,
            stride,
            width: 64,
            height: 64,
        }
    ));

    // The corner is as far from the panel as the patch goes: next to no
    // shadow, so next to all of the white.
    assert!(clear[3] < 0x80, "the corner is faint: {}", clear[3]);
    assert!(
        white[0] > 0x80,
        "white shows through a faint shadow: {}",
        white[0]
    );
}

/// The two ends of a cross-fade must be the same size, as the reference
/// requires; otherwise nothing is written.
#[test]
fn a_cross_fade_of_two_sizes_writes_nothing() {
    let theme = glass_default();
    let mut cache = ShadowCache::new(4);
    let (mut pixels, stride) = dest(64, 64);
    let written = cache.blit_cross_fade(
        key(64, 64, Elevation::Blurred, &theme),
        key(48, 48, Elevation::Focused, &theme),
        &theme,
        &mut ShadowDest {
            pixels: &mut pixels,
            stride,
            width: 64,
            height: 64,
        },
        0.5,
    );
    assert!(!written);
    assert!(
        pixels.iter().all(|byte| *byte == 0),
        "the destination is untouched"
    );
}

/// An exported surface is close-on-exec, as the reference exports it.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn an_exported_surface_is_close_on_exec_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let surface = Surface::create(
        &device,
        SurfaceConfig {
            width: 64,
            height: 32,
        },
    )
    .expect("a 64x32 ARGB8888 surface");

    let fd = surface.export(&device).expect("export");
    let flags = rustix::io::fcntl_getfd(&fd).expect("fcntl");
    assert!(flags.contains(rustix::io::FdFlags::CLOEXEC));
}