rizzma 1.14.1

A Rust reimplementation of the good parts of matplotlib/pyplot, with first-class wasm support.
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
//! Portable-figure tests.
//!
//! The load-bearing test is [`round_trip_is_pixel_identical`]: for a battery of
//! figures covering every artist, scale, and decoration, exporting and
//! re-importing must render a byte-identical PNG. That one assertion
//! transitively pins the entire wire model — a field dropped anywhere in the
//! spec shows up as a pixel difference.
//!
//! The rest of the suite covers what pixel identity cannot see: that bulk data
//! really travels in the binary chunk (and survives values JSON cannot express),
//! that an imported figure is still *live* under interaction, and that every
//! way an artifact can be malformed produces an error rather than a wrong
//! figure or a panic.

use crate::axis::ticker::{
    EngFormatter, FixedLocator, FuncFormatter, LogLocator, MultipleLocator, PercentFormatter,
    StrMethodFormatter,
};
use crate::core::color::Rgba;
use crate::core::{Bbox, Path, RcParams};
use crate::figure::{Axes, Event, Figure, Interactor, MouseButton};
use crate::portable::{Limits, PortableConfig, PortableError, SCHEMA_VERSION};

/// Deterministic pseudo-random values in `0.0..1.0` (no rand dependency).
fn rng(seed: u64) -> impl FnMut() -> f64 {
    let mut state = seed;
    move || {
        state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
        ((state >> 33) as f64) / ((1u64 << 31) as f64)
    }
}

fn linspace(a: f64, b: f64, n: usize) -> Vec<f64> {
    (0..n)
        .map(|i| a + (b - a) * i as f64 / (n - 1).max(1) as f64)
        .collect()
}

/// One figure per interesting corner of the model, each named for failure
/// messages. Every artist type, every scale, and the figure- and axes-level
/// decorations appear at least once.
fn fixtures() -> Vec<(&'static str, Figure)> {
    let mut out: Vec<(&'static str, Figure)> = Vec::new();

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&linspace(0.0, 6.0, 64), &linspace(-1.0, 1.0, 64));
    out.push(("line", fig));

    let mut fig = Figure::new(5.0, 3.5);
    let ax = fig.add_subplot(1, 1, 1);
    let x = linspace(0.0, 10.0, 200);
    let y: Vec<f64> = x.iter().map(|v| v.sin() * v).collect();
    ax.plot(&x, &y);
    ax.set_title("decay $\\alpha$");
    ax.set_xlabel("time [s]");
    ax.set_ylabel("amplitude");
    ax.grid(true);
    ax.legend(vec![(Rgba::rgb(0.1, 0.4, 0.8), "signal".to_string())]);
    fig.suptitle("figure title");
    out.push(("styled_line", fig));

    let mut fig = Figure::new(4.0, 4.0);
    let ax = fig.add_subplot(1, 1, 1);
    let mut r = rng(7);
    let xs: Vec<f64> = (0..300).map(|_| r()).collect();
    let ys: Vec<f64> = (0..300).map(|_| r()).collect();
    ax.scatter(&xs, &ys);
    out.push(("scatter", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.bar(&[0.0, 1.0, 2.0, 3.0], &[3.0, 1.0, 4.0, 1.5]);
    out.push(("bar_patches", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let data: Vec<f64> = (0..(16 * 16)).map(|i| (i as f64 * 0.13).sin()).collect();
    ax.imshow(&data, 16, 16);
    fig.colorbar("viridis", -1.0, 1.0);
    out.push(("image_colorbar", fig));

    let mut fig = Figure::new(4.5, 3.5);
    let ax = fig.add_subplot(1, 1, 1);
    let z: Vec<f64> = (0..(20 * 24))
        .map(|i| {
            let (r, c) = (i / 24, i % 24);
            (r as f64 * 0.3).sin() * (c as f64 * 0.2).cos()
        })
        .collect();
    ax.pcolormesh(&z, 20, 24);
    out.push(("quadmesh", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.loglog(&linspace(1.0, 1000.0, 50), &linspace(1.0, 1e6, 50));
    out.push(("loglog", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&linspace(-100.0, 100.0, 80), &linspace(-100.0, 100.0, 80));
    ax.set_xscale_symlog(10.0, 2.0);
    ax.set_yscale_asinh(1.0);
    out.push(("symlog_asinh", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&linspace(0.01, 0.99, 40), &linspace(0.01, 0.99, 40));
    ax.set_xscale_logit();
    out.push(("logit", fig));

    let mut fig = Figure::new(5.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0, 2.0], &[1.0, 3.0, 2.0]);
    ax.xaxis_mut()
        .set_locator(Box::new(MultipleLocator::with_offset(0.5, 0.1)));
    ax.xaxis_mut()
        .set_formatter(Box::new(StrMethodFormatter::new("{x}")));
    ax.yaxis_mut()
        .set_locator(Box::new(FixedLocator::new(vec![1.0, 2.0, 3.0])));
    ax.yaxis_mut().set_formatter(Box::new(EngFormatter::new()));
    out.push(("custom_tickers", fig));

    let mut fig = Figure::new(5.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.semilogx(&linspace(1.0, 1e4, 40), &linspace(0.0, 1.0, 40));
    ax.xaxis_mut()
        .set_locator(Box::new(LogLocator::with_subs(10.0, vec![1.0, 2.0, 5.0])));
    ax.yaxis_mut()
        .set_formatter(Box::new(PercentFormatter::fraction()));
    out.push(("log_subs_percent", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.axhline(0.5);
    ax.axvspan(0.2, 0.4);
    ax.annotate("peak", (0.5, 0.5), (0.7, 0.8));
    ax.text(0.1, 0.9, "note");
    out.push(("spans_annotations", fig));

    let mut fig = Figure::new(5.0, 4.0).with_rcparams(RcParams::dark());
    let ax = fig.add_subplot(2, 1, 1);
    ax.plot(&[0.0, 1.0, 2.0], &[0.0, 1.0, 0.5]);
    let ax = fig.add_subplot(2, 1, 2);
    ax.plot(&[0.0, 1.0, 2.0], &[2.0, 0.0, 1.0]);
    out.push(("dark_two_subplots", fig));

    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1)
        .plot(&[0.0, 1.0, 2.0], &[0.0, 1.0, 4.0]);
    fig.twinx(0);
    out.push(("twinx", fig));

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let z: Vec<f64> = (0..(30 * 30))
        .map(|i| {
            let (r, c) = ((i / 30) as f64 * 0.2 - 3.0, (i % 30) as f64 * 0.2 - 3.0);
            (-(r * r + c * c) / 4.0).exp()
        })
        .collect();
    ax.contour(&z, 30, 30);
    ax.clabel();
    out.push(("contour_labels", fig));

    out
}

#[test]
fn round_trip_is_pixel_identical() {
    for (name, fig) in fixtures() {
        let bytes = fig
            .to_portable()
            .unwrap_or_else(|e| panic!("{name}: export failed: {e}"));
        let restored =
            Figure::from_portable(&bytes).unwrap_or_else(|e| panic!("{name}: import failed: {e}"));

        let want = fig.encode_png().expect("reference png");
        let got = restored.encode_png().expect("restored png");
        assert_eq!(
            got.len(),
            want.len(),
            "{name}: restored figure rendered a different-sized png"
        );
        assert!(
            got == want,
            "{name}: restored figure is not pixel-identical"
        );
    }
}

#[test]
fn round_trip_preserves_svg_and_pdf_too() {
    // The wire model is backend-agnostic: it restores the scene, not a raster.
    let (_, fig) = fixtures()
        .into_iter()
        .find(|(n, _)| *n == "styled_line")
        .unwrap();
    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert_eq!(restored.to_svg(), fig.to_svg());
    assert_eq!(restored.to_pdf(), fig.to_pdf());
}

#[test]
fn imported_figure_is_still_interactive() {
    // The point of carrying data rather than geometry: the restored figure can
    // be panned and zoomed, revealing data the original viewport never showed,
    // and it lands in exactly the same place as the original would.
    let mut fig = Figure::new(5.0, 4.0);
    let ax = fig.add_subplot(1, 1, 1);
    let x = linspace(0.0, 20.0, 500);
    let y: Vec<f64> = x.iter().map(|v| v.sin()).collect();
    ax.plot(&x, &y);

    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();

    let drive = |figure: Figure| {
        let mut it = Interactor::new(figure);
        it.handle(Event::Wheel {
            x: 240.0,
            y: 180.0,
            dy: -3.0,
        });
        it.handle(Event::MouseDown {
            x: 240.0,
            y: 180.0,
            button: MouseButton::Left,
        });
        it.handle(Event::MouseMove { x: 300.0, y: 150.0 });
        it.handle(Event::MouseUp {
            x: 300.0,
            y: 150.0,
            button: MouseButton::Left,
        });
        let limits = it.figure().axes()[0].effective_limits();
        (limits, it.figure().encode_png().expect("png"))
    };

    let (want_limits, want_png) = drive(fig);
    let (got_limits, got_png) = drive(restored);
    assert_eq!(
        got_limits, want_limits,
        "zoom/pan diverged after a round trip"
    );
    assert!(
        got_png == want_png,
        "interacted figures rendered differently"
    );
}

#[test]
fn bulk_data_travels_in_the_binary_chunk() {
    // Vertices must not be spelled out as JSON floats: the JSON chunk should
    // stay tiny while the binary chunk carries the samples.
    let mut fig = Figure::new(4.0, 3.0);
    let x = linspace(0.0, 1.0, 20_000);
    fig.add_subplot(1, 1, 1).plot(&x, &x);

    let bytes = fig.to_portable().unwrap();
    let (json, bin) = split(&bytes);
    assert!(
        bin.len() >= 20_000 * 2 * 8,
        "expected both coordinate arrays in the binary chunk, got {} bytes",
        bin.len()
    );
    assert!(
        json.len() < 8_000,
        "json chunk should stay small, got {} bytes",
        json.len()
    );
}

#[test]
fn non_finite_samples_survive_the_round_trip() {
    // JSON cannot express NaN or infinity; the binary chunk can, and gaps in a
    // series are meaningful data, not noise.
    let mut fig = Figure::new(4.0, 3.0);
    let x = vec![0.0, 1.0, 2.0, 3.0, 4.0];
    let y = vec![0.0, f64::NAN, 2.0, f64::INFINITY, -1.0];
    fig.add_subplot(1, 1, 1).plot(&x, &y);

    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn colormap_sampled_colors_round_trip_exactly() {
    // Mesh face colors come from a colormap as f64 channels; snapping them to
    // 8-bit hex on the way out would shift pixels.
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let z: Vec<f64> = (0..(6 * 8)).map(|i| i as f64 / 47.0).collect();
    ax.pcolormesh(&z, 6, 8);

    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn save_and_load_a_file() {
    let dir = std::env::temp_dir().join("rizzma-portable-test");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("figure.riz");

    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[1.0, 0.0]);
    fig.save_portable(&path).expect("save");

    let restored = Figure::from_portable(&std::fs::read(&path).expect("read")).expect("load");
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
    std::fs::remove_file(&path).ok();
}

#[test]
fn func_formatter_fails_export_loudly() {
    // A closure cannot cross the wire. Substituting a default formatter would
    // silently relabel every tick, so export refuses instead.
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.xaxis_mut()
        .set_formatter(Box::new(FuncFormatter::from_fn(|v, _| format!("<{v}>"))));

    match fig.to_portable() {
        Err(PortableError::Unsupported(msg)) => {
            assert!(msg.contains("FuncFormatter"), "unhelpful message: {msg}");
        }
        other => panic!("expected Unsupported, got {other:?}"),
    }
}

/// The `JSON` and `BIN ` payloads of an artifact, for tests that rewrite one
/// and reframe the other unchanged.
fn split(bytes: &[u8]) -> (&[u8], &[u8]) {
    use crate::portable::container;
    let dir = container::directory(bytes, &Limits::default()).expect("valid container");
    (
        container::chunk(bytes, &dir, container::TAG_JSON).expect("json chunk"),
        container::chunk(bytes, &dir, container::TAG_BIN).unwrap_or(&[]),
    )
}

/// Reframe a (possibly doctored) spec and binary payload into an artifact.
fn reframe(json: &[u8], bin: &[u8]) -> Vec<u8> {
    use crate::portable::container;
    container::write(&[(container::TAG_JSON, json), (container::TAG_BIN, bin)])
}

/// Import `bytes` and discard the figure, so a wrongly-accepted artifact
/// formats in a panic message (`Figure` is deliberately not `Debug`).
fn import(bytes: &[u8]) -> Result<(), PortableError> {
    Figure::from_portable(bytes).map(|_| ())
}

#[test]
fn the_poster_is_what_the_renderer_would_draw() {
    // The poster is a byproduct of a figure the exporter already holds, so it
    // must be exactly the PNG that figure renders — not an approximation.
    let mut fig = Figure::new(5.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&linspace(0.0, 6.0, 50), &linspace(0.0, 1.0, 50));
    ax.set_title("decay");

    let bytes = fig.to_portable().expect("export");
    let info = crate::portable::inspect(&bytes, &Limits::default()).expect("inspect");
    let poster = info.poster(&bytes).expect("a poster by default");

    assert_eq!(&poster[..8], b"\x89PNG\r\n\x1a\n", "poster must be a PNG");
    assert!(
        poster == fig.encode_png().expect("png").as_slice(),
        "poster differs from the figure's own render"
    );
    let meta = info.meta.expect("schema 2 carries meta");
    assert_eq!(meta.poster.expect("poster ref").bytes, poster.len());
}

#[test]
fn inspect_sizes_a_card_without_a_renderer() {
    // What a host reads before deciding to fetch 370 KB of wasm: the exact box
    // to reserve, the text to announce, and something to show meanwhile.
    let mut fig = Figure::new(6.4, 4.8).with_dpi(100.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.set_title("step response");

    let cfg = PortableConfig::default().with_alt("step response rising to one");
    let bytes = fig.to_portable_with(&cfg).expect("export");
    let info = crate::portable::inspect(&bytes, &Limits::default()).expect("inspect");

    assert!(info.renderable(), "this build must render its own schema");
    let meta = info.meta.expect("meta");
    assert_eq!((meta.width_px, meta.height_px), (640, 480));
    assert_eq!(meta.alt.as_deref(), Some("step response rising to one"));
    assert_eq!(meta.title.as_deref(), Some("step response"));
    assert!(!meta.animated);
    assert_eq!(info.generator.rizzma, env!("CARGO_PKG_VERSION"));
}

#[test]
fn the_poster_can_be_turned_off() {
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[1.0, 0.0]);

    let with = fig.to_portable().expect("export");
    let without = fig
        .to_portable_with(&PortableConfig::default().with_poster(false))
        .expect("export");
    assert!(
        without.len() < with.len(),
        "dropping the poster should shrink the artifact"
    );

    let info = crate::portable::inspect(&without, &Limits::default()).expect("inspect");
    assert!(info.poster(&without).is_none());
    assert!(info.meta.expect("meta").poster.is_none());
    // Still a complete figure: the poster is a fallback, not the content.
    let restored = Figure::from_portable(&without).expect("import");
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn schema_1_artifacts_still_load() {
    // Artifacts written by 1.7.x carry no `meta` and no poster. Refusing them
    // would break every figure already archived, so the field is optional for
    // as long as SCHEMA_MIN is 1.
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1)
        .plot(&[0.0, 1.0, 2.0], &[0.0, 1.0, 4.0]);
    let current = fig.to_portable().expect("export");

    // Rewrite it as a schema-1 document: drop `meta` and the poster chunk.
    let (json, bin) = split(&current);
    let mut spec: serde_json::Value = serde_json::from_slice(json).expect("json");
    spec["schema"] = serde_json::json!(1);
    spec.as_object_mut().expect("object").remove("meta");
    let legacy = reframe(spec.to_string().as_bytes(), bin);

    let info = crate::portable::inspect(&legacy, &Limits::default()).expect("inspect");
    assert_eq!(info.schema, 1);
    assert!(info.schema_supported, "1 is still within the range");
    assert!(info.meta.is_none());

    let restored = Figure::from_portable(&legacy).expect("schema 1 must still import");
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn import_enforces_caller_budgets() {
    let bytes = sample_bytes();
    let tight = Limits::default().with_max_total_bytes(128);
    match Figure::from_portable_limited(&bytes, &tight).map(|_| ()) {
        Err(PortableError::Budget(msg)) => assert!(msg.contains("128"), "{msg}"),
        other => panic!("expected Budget, got {other:?}"),
    }
    // The default budget admits an ordinary figure.
    assert!(Figure::from_portable_limited(&bytes, &Limits::default()).is_ok());
}

/// A valid artifact to mutate in the rejection tests below.
fn sample_bytes() -> Vec<u8> {
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1)
        .plot(&[0.0, 1.0, 2.0], &[0.0, 1.0, 4.0]);
    fig.to_portable().expect("export")
}

/// Re-frame `spec_json` into a container with an empty binary chunk.
fn container_with_json(json: &str) -> Vec<u8> {
    reframe(json.as_bytes(), &[])
}

/// The artifact's spec JSON as a mutable `serde_json` value.
fn sample_spec() -> serde_json::Value {
    let bytes = sample_bytes();
    let (json, _) = split(&bytes);
    serde_json::from_slice(json).unwrap()
}

#[test]
fn rejects_bad_magic() {
    let mut bytes = sample_bytes();
    bytes[0] = b'X';
    assert!(matches!(
        Figure::from_portable(&bytes),
        Err(PortableError::Malformed(_))
    ));
}

#[test]
fn rejects_truncation() {
    let bytes = sample_bytes();
    for cut in [0, 4, 11, 20, bytes.len() / 2, bytes.len() - 1] {
        assert!(
            Figure::from_portable(&bytes[..cut]).is_err(),
            "truncating to {cut} bytes should not load"
        );
    }
}

#[test]
fn rejects_a_future_schema() {
    let mut spec = sample_spec();
    spec["schema"] = serde_json::json!(SCHEMA_VERSION + 1);
    let bytes = container_with_json(&spec.to_string());
    match import(&bytes) {
        Err(PortableError::Schema { found, max, .. }) => {
            assert_eq!(found, SCHEMA_VERSION + 1);
            assert_eq!(max, SCHEMA_VERSION);
        }
        other => panic!("expected Schema, got {other:?}"),
    }
}

#[test]
fn rejects_unknown_fields() {
    // Forward compatibility by skipping is wrong for a figure: an artist a
    // newer schema introduced would vanish without a trace.
    let mut spec = sample_spec();
    spec["figure"]["axes"][0]["lines"][0]["glow"] = serde_json::json!(true);
    let bytes = container_with_json(&spec.to_string());
    assert!(matches!(
        Figure::from_portable(&bytes),
        Err(PortableError::Json(_))
    ));
}

#[test]
fn rejects_unknown_enum_variants() {
    let mut spec = sample_spec();
    spec["figure"]["axes"][0]["xscale"] = serde_json::json!({ "hyperbolic": { "k": 2.0 } });
    let bytes = container_with_json(&spec.to_string());
    assert!(matches!(
        Figure::from_portable(&bytes),
        Err(PortableError::Json(_))
    ));
}

#[test]
fn rejects_out_of_bounds_accessors() {
    let mut spec = sample_spec();
    spec["accessors"][0]["count"] = serde_json::json!(1_000_000);
    let bytes = sample_bytes();
    let (_, bin) = split(&bytes);
    let bin = bin.to_vec();
    let reframed = reframe(spec.to_string().as_bytes(), &bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("accessor"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_a_dangling_accessor_index() {
    let mut spec = sample_spec();
    spec["figure"]["axes"][0]["lines"][0]["x"] = serde_json::json!({ "acc": 999 });
    let bytes = sample_bytes();
    let (_, bin) = split(&bytes);
    let reframed = reframe(spec.to_string().as_bytes(), bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("999"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_inconsistent_array_lengths() {
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let data: Vec<f64> = (0..12).map(|i| i as f64).collect();
    ax.imshow(&data, 3, 4);
    let bytes = fig.to_portable().unwrap();

    let (json, bin) = split(&bytes);
    let mut spec: serde_json::Value = serde_json::from_slice(json).unwrap();
    // Claim a 5x4 grid over the same 12 samples.
    spec["figure"]["axes"][0]["images"][0]["nrows"] = serde_json::json!(5);
    let reframed = reframe(spec.to_string().as_bytes(), bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("samples"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_hostile_locator_parameters() {
    // A zero step would trip a constructor assertion; the importer turns it
    // into an error rather than letting a malformed artifact panic the process.
    let mut spec = sample_spec();
    spec["figure"]["axes"][0]["xaxis"]["locator"] =
        serde_json::json!({ "multiple": { "step": 0.0, "offset": 0.0 } });
    let bytes = sample_bytes();
    let (_, bin) = split(&bytes);
    let reframed = reframe(spec.to_string().as_bytes(), bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("step"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_self_contained_chunks_this_build_cannot_honor() {
    // FONT/WASM chunks belong to a later phase; ignoring them would render
    // with the wrong font or the wrong renderer.
    let bytes = sample_bytes();
    let (json, _) = split(&bytes);
    let mut framed = reframe(json, &[]);
    // Append a FONT chunk and fix up the declared total length.
    let payload = b"not-a-font";
    framed.extend_from_slice(&(payload.len() as u32).to_le_bytes());
    framed.extend_from_slice(b"FONT");
    framed.extend_from_slice(payload);
    while !framed.len().is_multiple_of(8) {
        framed.push(0);
    }
    let total = framed.len() as u32;
    framed[8..12].copy_from_slice(&total.to_le_bytes());

    match import(&framed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("FONT"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_a_duplicate_chunk() {
    let bytes = sample_bytes();
    let (json, _) = split(&bytes);
    let mut framed = reframe(json, &[]);
    let start = framed.len();
    framed.extend_from_slice(&(json.len() as u32).to_le_bytes());
    framed.extend_from_slice(b"JSON");
    framed.extend_from_slice(json);
    while !framed.len().is_multiple_of(8) {
        framed.push(0);
    }
    assert!(framed.len() > start);
    let total = framed.len() as u32;
    framed[8..12].copy_from_slice(&total.to_le_bytes());

    match import(&framed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("duplicate"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn rejects_an_unknown_path_code() {
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.add_patch(crate::artist::Patch::new(Path::from_polyline(&[
        [0.0, 0.0],
        [1.0, 0.0],
        [1.0, 1.0],
    ])));
    ax.scatter(&[0.5], &[0.5]);
    let bytes = fig.to_portable().unwrap();
    let (json, bin) = split(&bytes);
    let spec: serde_json::Value = serde_json::from_slice(json).unwrap();

    // Find a u8 (path-code) accessor and corrupt its first byte.
    let mut bin = bin.to_vec();
    let offset = spec["accessors"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["dtype"] == "u8")
        .map(|a| a["offset"].as_u64().unwrap() as usize)
        .expect("a path-code accessor");
    bin[offset] = 200;

    let reframed = reframe(json, &bin);
    match import(&reframed) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("path code"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn error_messages_name_the_problem() {
    // These strings are what a user sees when an artifact will not load, so
    // they are part of the contract.
    let schema = PortableError::Schema {
        found: 9,
        min: 1,
        max: 2,
    };
    let text = schema.to_string();
    assert!(text.contains('9') && text.contains("1..=2"), "{text}");
    assert!(text.contains("drop content"), "{text}");
}

#[test]
fn spec_bytes_are_stable_across_a_round_trip() {
    // Export → import → export must reproduce the artifact byte-for-byte:
    // nothing is invented, reordered, or lost on the way through.
    let first = sample_bytes();
    let second = Figure::from_portable(&first)
        .unwrap()
        .to_portable()
        .unwrap();
    assert_eq!(first, second);
}

#[test]
fn json_scalars_round_trip_bit_exactly() {
    // Scalars (limits, positions, colors) travel as JSON numbers, and
    // serde_json only parses them back to the same bits with its
    // `float_roundtrip` feature enabled — without it, values land one ULP off
    // and a re-exported artifact silently differs from its original. This test
    // pins that dependency feature; it is not hypothetical, it fired once.
    let awkward = [
        0.109_999_999_999_999_99_f64,
        1.0 / 3.0,
        f64::MIN_POSITIVE,
        f64::MAX,
        std::f64::consts::PI * 1e-7,
    ];
    for v in awkward {
        let text = serde_json::to_string(&v).expect("serialize");
        let back: f64 = serde_json::from_str(&text).expect("parse");
        assert_eq!(
            back.to_bits(),
            v.to_bits(),
            "{v} did not survive a JSON round trip ({text})"
        );
    }
}

#[test]
fn declares_its_schema_and_generator() {
    let bytes = sample_bytes();
    let (json, _) = split(&bytes);
    let spec: serde_json::Value = serde_json::from_slice(json).unwrap();
    assert_eq!(spec["schema"], SCHEMA_VERSION);
    assert_eq!(spec["generator"]["rizzma"], env!("CARGO_PKG_VERSION"));
    assert_eq!(spec["renderer"]["version"], env!("CARGO_PKG_VERSION"));
}

#[test]
fn an_empty_figure_round_trips() {
    let fig = Figure::new(3.0, 2.0).with_facecolor(Rgba::rgb(0.2, 0.3, 0.4));
    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

#[test]
fn axes_added_by_rect_keep_their_position() {
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_axes(0.2, 0.3, 0.5, 0.4);
    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    let want: Bbox = fig.axes()[0].position();
    let got: Bbox = restored.axes()[0].position();
    assert_eq!(
        (got.x0, got.y0, got.x1, got.y1),
        (want.x0, want.y0, want.x1, want.y1)
    );
}

#[test]
fn axes_helper_is_reachable_for_every_artist_vec() {
    // Guards against a new artist Vec being added to `Axes` without a matching
    // wire field: the spec's own struct is exhaustive, so this compiles only
    // while the two agree.
    let mut fig = Figure::new(4.0, 3.0);
    let ax: &mut Axes = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.scatter(&[0.5], &[0.5]);
    ax.bar(&[0.0], &[1.0]);
    ax.imshow(&[1.0, 2.0, 3.0, 4.0], 2, 2);
    ax.pcolormesh(&[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], 2, 3);

    let restored = Figure::from_portable(&fig.to_portable().unwrap()).unwrap();
    assert!(restored.encode_png().unwrap() == fig.encode_png().unwrap());
}

// ---------------------------------------------------------------------------
// Inspection: reading an artifact without building a figure from it.
//
// These build artifacts by hand rather than through the exporter, so a
// malformed or future-schema document can be exercised directly — cases the
// exporter cannot produce.
// ---------------------------------------------------------------------------

use crate::portable::container::{self, TAG_BIN, TAG_JSON, TAG_PSTR};
use crate::portable::inspect;

/// A minimal but valid schema-2 spec document.
fn spec_json(poster_bytes: usize) -> String {
    let poster = if poster_bytes > 0 {
        format!(r#","poster":{{"chunk":"PSTR","mime":"image/png","bytes":{poster_bytes}}}"#)
    } else {
        r#","poster":null"#.to_string()
    };
    format!(
        r#"{{"schema":{SCHEMA_VERSION},
            "generator":{{"rizzma":"1.8.0"}},
            "renderer":{{"version":"1.8.0","sha256":"9f2c"}},
            "meta":{{"width_px":640,"height_px":480,"alt":"a figure",
                     "title":"demo"{poster},"animated":false}},
            "figure":{{"ignored":true}},
            "accessors":[]}}"#
    )
}

fn artifact(poster: &[u8], bin: &[u8]) -> Vec<u8> {
    let json = spec_json(poster.len());
    let mut chunks: Vec<([u8; 4], &[u8])> = vec![(TAG_JSON, json.as_bytes())];
    if !poster.is_empty() {
        chunks.push((TAG_PSTR, poster));
    }
    if !bin.is_empty() {
        chunks.push((TAG_BIN, bin));
    }
    container::write(&chunks)
}

#[test]
fn reads_metadata_without_the_bulk_payload() {
    // The point of the crate: learn the figure's size, alt text, and poster
    // without touching a megabyte of samples.
    let bin = vec![7u8; 1_000_000];
    let bytes = artifact(b"fake-png", &bin);
    let info = inspect(&bytes, &Limits::default()).expect("inspect");

    assert_eq!(info.schema, SCHEMA_VERSION);
    assert!(info.schema_supported && info.renderable());
    assert_eq!(info.generator.rizzma, "1.8.0");
    assert_eq!(info.renderer.version, "1.8.0");
    let meta = info.meta.as_ref().expect("schema 2 carries meta");
    assert_eq!((meta.width_px, meta.height_px), (640, 480));
    assert_eq!(meta.alt.as_deref(), Some("a figure"));
    assert_eq!(info.poster(&bytes), Some(&b"fake-png"[..]));
    assert_eq!(info.total_bytes, bytes.len());
    assert_eq!(info.chunks.len(), 3);
}

#[test]
fn a_schema_1_artifact_still_inspects() {
    // Artifacts written before the meta block must not become unreadable:
    // no size, no poster, but provenance and renderability still resolve.
    let json = r#"{"schema":1,"generator":{"rizzma":"1.7.0"},
                   "renderer":{"version":"1.7.0","sha256":null},
                   "figure":{},"accessors":[]}"#;
    let bytes = container::write(&[(TAG_JSON, json.as_bytes())]);
    let info = inspect(&bytes, &Limits::default()).expect("inspect");
    assert_eq!(info.schema, 1);
    assert!(info.schema_supported);
    assert!(info.meta.is_none());
    assert!(info.poster(&bytes).is_none());
}

#[test]
fn an_unsupported_schema_is_reported_not_refused() {
    // A host still wants the size and poster of a figure it cannot draw, so a
    // future schema is a flag rather than an error.
    let json = format!(
        r#"{{"schema":{},"generator":{{"rizzma":"9.9.9"}},
             "renderer":{{"version":"9.9.9","sha256":null}},
             "meta":{{"width_px":640,"height_px":480,"alt":null,"title":null,
                      "poster":null,"animated":true}}}}"#,
        SCHEMA_VERSION + 1
    );
    let bytes = container::write(&[(TAG_JSON, json.as_bytes())]);
    let info = inspect(&bytes, &Limits::default()).expect("inspect");
    assert_eq!(info.schema, SCHEMA_VERSION + 1);
    assert!(!info.schema_supported, "must not claim it can render this");
    assert!(!info.renderable());
    assert!(info.meta.expect("meta").animated);
}

#[test]
fn budgets_are_enforced_before_allocating() {
    let bytes = artifact(b"fake-png", &vec![0u8; 4096]);

    let tiny = Limits::default().with_max_total_bytes(64);
    match inspect(&bytes, &tiny) {
        Err(PortableError::Budget(msg)) => assert!(msg.contains("over the 64 byte limit"), "{msg}"),
        other => panic!("expected Budget, got {other:?}"),
    }

    let json_capped = Limits::default().with_max_json_bytes(10);
    assert!(matches!(
        inspect(&bytes, &json_capped),
        Err(PortableError::Budget(_))
    ));

    let pixel_capped = Limits::default().with_max_canvas_pixels(1000);
    match inspect(&bytes, &pixel_capped) {
        Err(PortableError::Budget(msg)) => assert!(msg.contains("640x480"), "{msg}"),
        other => panic!("expected Budget, got {other:?}"),
    }
}

#[test]
fn a_lying_poster_length_is_malformed() {
    // The spec says 8 bytes; the chunk holds 4. Trusting the spec would hand a
    // truncated image to a decoder.
    let json = spec_json(8);
    let bytes = container::write(&[(TAG_JSON, json.as_bytes()), (TAG_PSTR, b"abcd")]);
    match inspect(&bytes, &Limits::default()) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("poster"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn structural_corruption_is_rejected() {
    let good = artifact(b"png", b"bin");

    let mut bad_magic = good.clone();
    bad_magic[0] = b'X';
    assert!(matches!(
        inspect(&bad_magic, &Limits::default()),
        Err(PortableError::Malformed(_))
    ));

    for cut in [0, 8, 11, good.len() / 2, good.len() - 1] {
        assert!(
            inspect(&good[..cut], &Limits::default()).is_err(),
            "truncating to {cut} bytes must not inspect"
        );
    }

    // A duplicate chunk is ambiguous, so it is refused rather than guessed.
    let json = spec_json(0);
    let mut dup = container::write(&[(TAG_JSON, json.as_bytes()), (TAG_JSON, json.as_bytes())]);
    let total = dup.len() as u32;
    dup[8..12].copy_from_slice(&total.to_le_bytes());
    match inspect(&dup, &Limits::default()) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("duplicate"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn json_and_poster_precede_bulk_payloads() {
    // Writers order chunks so a partial read can paint a card; readers must
    // still tolerate any order, which the duplicate/lookup tests exercise.
    let bytes = artifact(b"png", &vec![0u8; 2048]);
    let info = inspect(&bytes, &Limits::default()).expect("inspect");
    let tags: Vec<String> = info.chunks.iter().map(container::ChunkRef::name).collect();
    assert_eq!(tags, vec!["JSON", "PSTR", "BIN "]);
}

#[test]
fn missing_json_chunk_is_refused() {
    let bytes = container::write(&[(TAG_PSTR, b"png")]);
    match inspect(&bytes, &Limits::default()) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("JSON"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// Animation: a timeline is a pure function of t, and it survives the wire.
// ---------------------------------------------------------------------------

use crate::portable::{Interp, Target, Timeline, Track};

/// A figure whose single line ramps from flat to a slope over two seconds.
fn animated_figure() -> Figure {
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0, 2.0], &[0.0, 0.0, 0.0]);
    let mut timeline = Timeline::new(2.0);
    timeline.push(
        Track::line_y(
            0,
            0,
            vec![0.0, 2.0],
            vec![vec![0.0, 0.0, 0.0], vec![0.0, 1.0, 2.0]],
        )
        .expect("track"),
    );
    fig.set_timeline(timeline);
    fig
}

#[test]
fn seeking_is_a_pure_function_of_time() {
    // The property the whole design rests on: same t, same figure. Without it
    // scrubbing is approximate and archived replay is a different picture.
    let mut a = animated_figure();
    let mut b = animated_figure();

    a.seek(0.75).expect("seek");
    b.seek(0.25).expect("seek");
    b.seek(1.9).expect("seek");
    b.seek(0.75).expect("seek"); // arrives from elsewhere, same destination
    assert_eq!(a.axes()[0].line_data(0), b.axes()[0].line_data(0));
    assert!(a.encode_png().unwrap() == b.encode_png().unwrap());
}

#[test]
fn interpolation_is_element_wise_and_endpoints_hold() {
    let mut fig = animated_figure();

    fig.seek(0.0).expect("seek");
    assert_eq!(fig.axes()[0].line_data(0).unwrap().1, vec![0.0, 0.0, 0.0]);

    fig.seek(1.0).expect("seek");
    assert_eq!(fig.axes()[0].line_data(0).unwrap().1, vec![0.0, 0.5, 1.0]);

    fig.seek(2.0).expect("seek");
    assert_eq!(fig.axes()[0].line_data(0).unwrap().1, vec![0.0, 1.0, 2.0]);
}

#[test]
fn time_outside_the_timeline_wraps_or_clamps() {
    // Looping wraps so a caller can pass a monotonic clock; non-looping clamps
    // so the end state holds rather than extrapolating data nobody drew.
    let mut looping = animated_figure();
    looping.seek(3.0).expect("seek"); // 3.0 wraps to 1.0
    assert_eq!(
        looping.axes()[0].line_data(0).unwrap().1,
        vec![0.0, 0.5, 1.0]
    );

    // Exactly `duration` is the end, not the start: seeking to the end of an
    // animation should show its end. Wrapping starts strictly past duration.
    let mut at_end = animated_figure();
    at_end.seek(2.0).expect("seek");
    assert_eq!(
        at_end.axes()[0].line_data(0).unwrap().1,
        vec![0.0, 1.0, 2.0]
    );
    let mut past_end = animated_figure();
    past_end.seek(2.5).expect("seek");
    assert_eq!(
        past_end.axes()[0].line_data(0).unwrap().1,
        vec![0.0, 0.25, 0.5]
    );

    let mut once = animated_figure();
    let held = once
        .timeline()
        .expect("timeline")
        .clone()
        .with_looping(false);
    once.set_timeline(held);
    once.seek(99.0).expect("seek");
    assert_eq!(once.axes()[0].line_data(0).unwrap().1, vec![0.0, 1.0, 2.0]);

    // A nonsense clock must not produce a nonsense figure.
    let mut nan = animated_figure();
    nan.seek(f64::NAN).expect("seek");
    assert_eq!(nan.axes()[0].line_data(0).unwrap().1, vec![0.0, 0.0, 0.0]);
}

#[test]
fn step_interpolation_holds_the_earlier_keyframe() {
    let track = Track::new(
        Target::LineY { axes: 0, index: 0 },
        vec![0.0, 1.0],
        vec![vec![1.0], vec![9.0]],
        Interp::Step,
    )
    .expect("track");
    assert_eq!(track.sample(0.0), vec![1.0]);
    assert_eq!(track.sample(0.99), vec![1.0], "step must not ramp");
    assert_eq!(track.sample(1.0), vec![9.0]);
}

#[test]
fn a_scrolling_window_is_two_keyframes_not_many_frames() {
    // The oscilloscope case: animating the view, not the data. If this needed a
    // frame per sample the artifact would be a video with extra steps.
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let x: Vec<f64> = (0..500).map(|i| i as f64 * 0.02).collect();
    let y: Vec<f64> = x.iter().map(|v| v.sin()).collect();
    ax.plot(&x, &y);

    let mut timeline = Timeline::new(10.0);
    timeline.push(Track::xlim_sweep(0, 10.0, (0.0, 2.0), (8.0, 10.0)).expect("sweep"));
    fig.set_timeline(timeline);

    fig.seek(5.0).expect("seek");
    let ((lo, hi), _) = fig.axes()[0].effective_limits();
    assert!(
        (lo - 4.0).abs() < 1e-9 && (hi - 6.0).abs() < 1e-9,
        "window should be halfway across: got ({lo}, {hi})"
    );
    assert_eq!(fig.timeline().expect("timeline").tracks[0].len(), 2);
}

#[test]
fn an_animation_survives_the_round_trip() {
    let fig = animated_figure();
    let bytes = fig.to_portable().expect("export");
    let restored = Figure::from_portable(&bytes).expect("import");

    assert_eq!(restored.timeline(), fig.timeline());

    // And it still evaluates identically after the trip.
    let (mut a, mut b) = (fig, restored);
    a.seek(1.3).expect("seek");
    b.seek(1.3).expect("seek");
    assert!(a.encode_png().unwrap() == b.encode_png().unwrap());
}

#[test]
fn an_animated_artifact_declares_itself_to_a_host() {
    // A host decides whether to show transport controls from `inspect` alone,
    // without parsing the timeline.
    let bytes = animated_figure().to_portable().expect("export");
    let info = crate::portable::inspect(&bytes, &Limits::default()).expect("inspect");
    let meta = info.meta.expect("meta");
    assert!(meta.animated);
    assert_eq!(meta.duration, 2.0);
    assert_eq!(info.schema, SCHEMA_VERSION);

    // A static figure says so, and reports no duration.
    let mut still = Figure::new(4.0, 3.0);
    still.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    let info = crate::portable::inspect(&still.to_portable().unwrap(), &Limits::default()).unwrap();
    let meta = info.meta.expect("meta");
    assert!(!meta.animated);
    assert_eq!(meta.duration, 0.0);
}

#[test]
fn ill_formed_tracks_are_refused_at_construction() {
    let target = Target::LineY { axes: 0, index: 0 };
    // Ragged frames would make the element-wise lerp undefined.
    assert!(
        Track::new(
            target,
            vec![0.0, 1.0],
            vec![vec![0.0, 0.0], vec![1.0]],
            Interp::Linear
        )
        .is_err()
    );
    // Times must be strictly increasing, or bracketing a time is ambiguous.
    assert!(
        Track::new(
            target,
            vec![1.0, 0.0],
            vec![vec![0.0], vec![1.0]],
            Interp::Linear
        )
        .is_err()
    );
    // Counts must agree.
    assert!(Track::new(target, vec![0.0], vec![], Interp::Linear).is_err());
    assert!(Track::new(target, vec![], vec![], Interp::Linear).is_err());
}

#[test]
fn a_track_pointing_at_nothing_fails_loudly() {
    // Silently skipping a track would animate a figure differently than the
    // author wrote it, with nothing to indicate anything was dropped.
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);

    let mut timeline = Timeline::new(1.0);
    timeline.push(Track::line_y(0, 7, vec![0.0], vec![vec![0.0, 0.0]]).expect("track"));
    fig.set_timeline(timeline);
    match fig.seek(0.5) {
        Err(PortableError::Malformed(msg)) => assert!(msg.contains("line 7"), "{msg}"),
        other => panic!("expected Malformed, got {other:?}"),
    }

    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    let mut timeline = Timeline::new(1.0);
    timeline.push(Track::line_y(9, 0, vec![0.0], vec![vec![0.0, 0.0]]).expect("track"));
    fig.set_timeline(timeline);
    assert!(matches!(fig.seek(0.5), Err(PortableError::Malformed(_))));
}

// ---------------------------------------------------------------------------
// Seeking a bound, interactive figure: the animation and the user share one
// view, and the user wins until they hand it back.
// ---------------------------------------------------------------------------

/// A figure whose timeline sweeps the x window AND ramps the line's y data.
fn swept_figure() -> Figure {
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let x: Vec<f64> = (0..100).map(|i| i as f64 * 0.1).collect();
    let y = vec![0.0; 100];
    ax.plot(&x, &y);
    ax.set_xlim(0.0, 2.0);
    ax.set_ylim(-1.0, 1.0);

    let mut tl = Timeline::new(10.0);
    tl.push(Track::xlim_sweep(0, 10.0, (0.0, 2.0), (8.0, 10.0)).expect("sweep"));
    tl.push(
        Track::line_y(0, 0, vec![0.0, 10.0], vec![vec![0.0; 100], vec![1.0; 100]]).expect("ramp"),
    );
    fig.set_timeline(tl);
    fig
}

/// Wheel-zoom at the axes center so the interactor takes the view.
fn zoom_center(it: &mut Interactor) {
    let (w, h) = it.figure().size_px();
    let out = it.handle(Event::Wheel {
        x: w / 2.0,
        y: h / 2.0,
        dy: -3.0,
    });
    assert_eq!(
        out,
        crate::figure::Outcome::NeedsRedraw,
        "zoom must land on the axes"
    );
}

#[test]
fn a_user_held_view_suspends_the_camera_but_not_the_data() {
    let mut it = Interactor::new(swept_figure());

    // Untouched: the sweep owns the camera.
    it.seek(5.0).expect("seek");
    let ((lo, hi), _) = it.figure().axes()[0].effective_limits();
    assert!(
        (lo - 4.0).abs() < 1e-9 && (hi - 6.0).abs() < 1e-9,
        "sweep should place the window"
    );

    // The user zooms: they now own the view.
    zoom_center(&mut it);
    let (held_x, held_y) = it.figure().axes()[0].effective_limits();

    it.seek(8.0).expect("seek");
    let (after_x, after_y) = it.figure().axes()[0].effective_limits();
    assert_eq!(
        (after_x, after_y),
        (held_x, held_y),
        "the sweep must not fight the user"
    );

    // …but the data track still advanced: the animation's content continues.
    let y = it.figure().axes()[0].line_data(0).expect("line").1;
    assert!(
        (y[0] - 0.8).abs() < 1e-9,
        "data should be at t=8 of the ramp, got {}",
        y[0]
    );
}

#[test]
fn double_click_hands_the_view_back_to_the_timeline() {
    let mut it = Interactor::new(swept_figure());
    it.seek(2.0).expect("seek");
    zoom_center(&mut it);

    // Held: the camera stays put.
    it.seek(6.0).expect("seek");
    let held = it.figure().axes()[0].effective_limits();

    // Double-click is the explicit "yours again".
    let (w, h) = it.figure().size_px();
    it.handle(Event::DoubleClick {
        x: w / 2.0,
        y: h / 2.0,
    });
    it.seek(6.0).expect("seek");
    let ((lo, hi), _) = it.figure().axes()[0].effective_limits();
    assert!(
        (lo - 4.8).abs() < 1e-9 && (hi - 6.8).abs() < 1e-9,
        "after home the sweep resumes: got ({lo}, {hi}), held was {held:?}"
    );
}

#[test]
fn seeking_without_interaction_never_marks_the_view_held() {
    // Seeks alone — however many — must not accumulate into a state where the
    // timeline blocks itself.
    let mut it = Interactor::new(swept_figure());
    for i in 0..50 {
        it.seek(f64::from(i) * 0.2).expect("seek");
    }
    it.seek(5.0).expect("seek");
    let ((lo, hi), _) = it.figure().axes()[0].effective_limits();
    assert!((lo - 4.0).abs() < 1e-9 && (hi - 6.0).abs() < 1e-9);
}

#[test]
fn a_static_figure_ignores_interactor_seek() {
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    let before = fig.encode_png().expect("png");
    let mut it = Interactor::new(fig);
    it.seek(3.0).expect("seek is a no-op without a timeline");
    assert!(it.figure().encode_png().unwrap() == before);
}

// ---------------------------------------------------------------------------
// The reversible HTML wrapper: one file a browser opens and a host ingests.
// ---------------------------------------------------------------------------

use crate::portable::{HtmlRuntime, is_raw_riz, unwrap_html, wrap_html, wrap_html_live};

#[test]
fn wrap_then_unwrap_is_byte_identical() {
    // The property the whole feature rests on: the HTML file IS the carrier of
    // the canonical artifact, not a second format that can drift from it.
    let riz = animated_figure().to_portable().expect("export");
    let html = wrap_html(&riz, &Limits::default()).expect("wrap");
    let recovered = unwrap_html(html.as_bytes(), &Limits::default()).expect("unwrap");
    assert!(
        recovered == riz,
        "strip must recover the exact artifact bytes"
    );

    // And the recovered bytes pass full validation as if they arrived raw.
    let restored = Figure::from_portable(&recovered).expect("import after unwrap");
    assert!(restored.encode_png().unwrap() == animated_figure().encode_png().unwrap());
}

#[test]
fn the_live_tier_strips_identically_and_embeds_the_runtime() {
    let riz = animated_figure().to_portable().expect("export");
    let rt = HtmlRuntime {
        wasm: b"\0asm-fake-renderer-bytes",
        glue: "export default function init() {}",
        loader: "export function mount() {}",
    };
    let html = wrap_html_live(&riz, &Limits::default(), &rt).expect("wrap");

    assert!(unwrap_html(html.as_bytes(), &Limits::default()).expect("unwrap") == riz);
    // Runtime assets travel under their own ids, base64'd, and are therefore
    // not part of the canonical carrier element.
    assert!(html.contains(r#"id="riz-rt-wasm""#));
    assert!(html.contains(r#"id="riz-rt-glue""#));
    assert!(html.contains(r#"id="riz-rt-loader""#));
    assert!(
        !html.contains("export default function init"),
        "runtime source must be base64, never raw in markup"
    );
}

#[test]
fn artifact_text_cannot_inject_into_the_wrapper() {
    // Title and alt come from the artifact and could be attacker-influenced in
    // a re-wrapping tool; they must land escaped, never as live markup.
    let mut fig = Figure::new(3.0, 2.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.set_title(r#"</script><script>alert(1)</script>"#);
    let cfg = PortableConfig::default().with_alt(r#""><img onerror=alert(2) src=x>"#);
    let riz = fig.to_portable_with(&cfg).expect("export");

    let html = wrap_html(&riz, &Limits::default()).expect("wrap");
    assert!(
        !html.contains("<script>alert"),
        "title must not close the carrier and open a script"
    );
    // `onerror=alert` may appear *inside* the quoted attribute value — that is
    // inert. What must not survive is the closing quote itself: the sequence
    // that would end the attribute and start a real element.
    assert!(
        !html.contains(r#""><img"#),
        "alt's quote must be escaped so the attribute cannot be closed"
    );
    assert!(
        html.contains("&quot;&gt;&lt;img"),
        "escaped alt should be present as text"
    );
    assert!(
        html.contains("&lt;/script&gt;"),
        "escaped title should be present as text"
    );

    // Hostile text changes nothing about the strip.
    assert!(unwrap_html(html.as_bytes(), &Limits::default()).expect("unwrap") == riz);
}

#[test]
fn base64_data_cannot_terminate_the_carrier_early() {
    // The reason encoding is a security property: whatever bytes the artifact
    // holds, the encoded payload contains no '<' and cannot close the tag.
    let riz = animated_figure().to_portable().expect("export");
    let html = wrap_html(&riz, &Limits::default()).expect("wrap");
    let open = r#"<script type="application/vnd.rizzma.figure+base64" id="riz">"#;
    let start = html.find(open).expect("carrier") + open.len();
    let end = html[start..].find("</script>").expect("terminator") + start;
    assert!(
        html[start..end]
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "+/=".contains(c)),
        "carrier payload must be pure base64"
    );
}

#[test]
fn unwrap_rejects_what_it_should() {
    let riz = animated_figure().to_portable().expect("export");
    let html = wrap_html(&riz, &Limits::default()).expect("wrap");
    let open = r#"<script type="application/vnd.rizzma.figure+base64" id="riz">"#;

    // No carrier at all.
    match unwrap_html(b"<!doctype html><p>just a page</p>", &Limits::default()) {
        Err(PortableError::Malformed(m)) => assert!(m.contains("no portable-figure"), "{m}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
    // Two carriers is ambiguous: refuse rather than guess which is canonical.
    let doubled = format!("{html}{open}AAAA</script>");
    match unwrap_html(doubled.as_bytes(), &Limits::default()) {
        Err(PortableError::Malformed(m)) => assert!(m.contains("more than one"), "{m}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
    // Unterminated element.
    let cut = &html[..html.find(open).unwrap() + open.len() + 10];
    assert!(matches!(
        unwrap_html(cut.as_bytes(), &Limits::default()),
        Err(PortableError::Malformed(_))
    ));
    // Corrupt base64.
    let broken = html.replacen(open, &format!("{open}!!"), 1);
    match unwrap_html(broken.as_bytes(), &Limits::default()) {
        Err(PortableError::Malformed(m)) => assert!(m.contains("base64"), "{m}"),
        other => panic!("expected Malformed, got {other:?}"),
    }
    // Not UTF-8 at all.
    assert!(matches!(
        unwrap_html(&[0xff, 0xfe, 0x00, 0x01], &Limits::default()),
        Err(PortableError::Malformed(_))
    ));
}

#[test]
fn raw_vs_wrapped_is_a_declared_branch_not_a_sniff() {
    let riz = animated_figure().to_portable().expect("export");
    let html = wrap_html(&riz, &Limits::default()).expect("wrap");
    assert!(is_raw_riz(&riz));
    assert!(!is_raw_riz(html.as_bytes()));
    // And the strict reader refuses the wrapped form outright: one parser
    // never accepts both, which is what keeps polyglot smuggling closed.
    assert!(matches!(
        crate::portable::inspect(html.as_bytes(), &Limits::default()),
        Err(PortableError::Malformed(_))
    ));
}

#[test]
fn wrapping_does_not_launder_a_malformed_artifact() {
    match wrap_html(b"RZFGjunk", &Limits::default()) {
        Err(PortableError::Malformed(_)) => {}
        other => panic!("expected Malformed, got {other:?}"),
    }
}

#[test]
fn unwrap_is_budgeted_before_it_allocates() {
    let riz = animated_figure().to_portable().expect("export");
    let html = wrap_html(&riz, &Limits::default()).expect("wrap");

    // Exactly at the boundary: allowed.
    let exact = Limits::default().with_max_total_bytes(riz.len());
    assert!(unwrap_html(html.as_bytes(), &exact).expect("exact fit") == riz);

    // One byte under: refused as Budget, not Malformed.
    let tight = Limits::default().with_max_total_bytes(riz.len() - 1);
    match unwrap_html(html.as_bytes(), &tight) {
        Err(PortableError::Budget(m)) => assert!(m.contains("over the"), "{m}"),
        other => panic!("expected Budget, got {other:?}"),
    }

    // The proof the budget check precedes the decode: a carrier whose payload
    // is over-budget, valid in SHAPE (length % 4 == 0, sane padding) but
    // invalid in alphabet, must fail with Budget — a decoder that ran first
    // would have reported Malformed instead.
    let open = r#"<script type="application/vnd.rizzma.figure+base64" id="riz">"#;
    let junk = "!".repeat(4_096);
    let page = format!("<!doctype html>{open}{junk}</script>");
    let tiny = Limits::default().with_max_total_bytes(64);
    match unwrap_html(page.as_bytes(), &tiny) {
        Err(PortableError::Budget(_)) => {}
        other => panic!("size must be checked before decoding; got {other:?}"),
    }
}

#[test]
fn padding_cannot_bypass_the_budget() {
    // The bypass a review caught in the first budgeted version: a payload of
    // nothing but '=' made padding == len, the saturating subtraction computed
    // a decoded size of zero, and any budget passed — while the decoder could
    // still reserve proportionally to the encoded input. Shape validation now
    // refuses it outright, allocation-free.
    let open = r#"<script type="application/vnd.rizzma.figure+base64" id="riz">"#;
    let tiny = Limits::default().with_max_total_bytes(64);

    // All padding, length divisible by 4: refused for its shape.
    let all_eq = format!("<!doctype html>{open}{}</script>", "=".repeat(4_096));
    match unwrap_html(all_eq.as_bytes(), &tiny) {
        Err(PortableError::Malformed(m)) => assert!(m.contains("padding"), "{m}"),
        other => panic!("all-padding payload must be Malformed pre-decode, got {other:?}"),
    }

    // Padding buried mid-payload: also a shape violation.
    let mid_eq = format!("<!doctype html>{open}AA==AAAA</script>");
    match unwrap_html(mid_eq.as_bytes(), &tiny) {
        Err(PortableError::Malformed(m)) => assert!(m.contains("padding"), "{m}"),
        other => panic!("mid-payload padding must be Malformed, got {other:?}"),
    }

    // Length not divisible by 4: refused before any size arithmetic.
    let ragged = format!("<!doctype html>{open}AAAAA</script>");
    match unwrap_html(ragged.as_bytes(), &tiny) {
        Err(PortableError::Malformed(m)) => assert!(m.contains("multiple of 4"), "{m}"),
        other => panic!("ragged length must be Malformed, got {other:?}"),
    }

    // Three trailing '=' with valid length: more padding than base64 allows.
    let over_pad = format!("<!doctype html>{open}AAAAA===</script>");
    match unwrap_html(over_pad.as_bytes(), &tiny) {
        Err(PortableError::Malformed(m)) => assert!(m.contains("padding"), "{m}"),
        other => panic!("triple padding must be Malformed, got {other:?}"),
    }
}

/// A figure with one line driven by a `(time, position)` grid — the wave whose
/// wavelength is a slider — plus a second line driven by a plain control track.
fn controlled_figure() -> Figure {
    use crate::portable::{Control, Grid, Interp, Target};

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0, 2.0], &[0.0, 0.0, 0.0]);
    ax.plot(&[0.0, 1.0, 2.0], &[1.0, 1.0, 1.0]);
    fig.set_timeline(Timeline::new(2.0));

    // Grid: value = t * 10 + p, per element — easy to predict at any (t, p).
    let mut shape = Control::new("shape", 0.0, 4.0, 2.0).expect("control");
    shape.push_grid(
        Grid::new(
            Target::LineY { axes: 0, index: 0 },
            vec![0.0, 2.0],
            vec![0.0, 4.0],
            vec![
                vec![vec![0.0; 3], vec![4.0; 3]],
                vec![vec![20.0; 3], vec![24.0; 3]],
            ],
            Interp::Linear,
        )
        .expect("grid"),
    );
    fig.add_control(shape).expect("add");

    // Track: line 1 is flat at the control's value.
    let mut level = Control::new("level", 0.0, 10.0, 1.0).expect("control");
    level.push_track(
        Track::new(
            Target::LineY { axes: 0, index: 1 },
            vec![0.0, 10.0],
            vec![vec![0.0; 3], vec![10.0; 3]],
            Interp::Linear,
        )
        .expect("track"),
    );
    fig.add_control(level).expect("add");
    fig
}

#[test]
fn controls_and_the_clock_compose_as_one_pure_function() {
    // The property design/12 §3 rests on: displayed state is a function of
    // (t, control values), so the order the user reached them in cannot show.
    let mut a = controlled_figure();
    let mut b = controlled_figure();

    a.seek(1.0).expect("seek");
    a.set_control(0, 2.0).expect("control");
    a.set_control(1, 7.0).expect("control");

    b.set_control(1, 3.0).expect("control");
    b.set_control(0, 0.5).expect("control");
    b.seek(0.25).expect("seek");
    b.set_control(1, 7.0).expect("control");
    b.set_control(0, 2.0).expect("control");
    b.seek(1.0).expect("seek");

    assert_eq!(a.axes()[0].line_data(0), b.axes()[0].line_data(0));
    assert_eq!(a.axes()[0].line_data(1), b.axes()[0].line_data(1));
    // t = 1.0, shape = 2.0: bilinear centre of the lattice, 10 + 2.
    assert_eq!(a.axes()[0].line_data(0).unwrap().1, vec![12.0; 3]);
    assert_eq!(a.axes()[0].line_data(1).unwrap().1, vec![7.0; 3]);
}

#[test]
fn grid_samples_bilinearly_and_clamps_at_the_lattice_edge() {
    use crate::portable::{Grid, Interp, Target};

    let grid = Grid::new(
        Target::LineY { axes: 0, index: 0 },
        vec![0.0, 2.0],
        vec![1.0, 3.0],
        vec![
            vec![vec![0.0, 100.0], vec![4.0, 100.0]],
            vec![vec![20.0, 100.0], vec![24.0, 100.0]],
        ],
        Interp::Linear,
    )
    .expect("grid");

    assert_eq!(grid.sample(1.0, 2.0), vec![12.0, 100.0]); // dead centre
    assert_eq!(grid.sample(0.0, 1.0), vec![0.0, 100.0]); // corner
    assert_eq!(grid.sample(-5.0, 0.0), vec![0.0, 100.0]); // clamped low
    assert_eq!(grid.sample(99.0, 99.0), vec![24.0, 100.0]); // clamped high
    assert_eq!(grid.sample(0.5, 3.0), vec![9.0, 100.0]); // one axis interior
}

#[test]
fn grid_step_interp_holds_the_earlier_lattice_cell() {
    use crate::portable::{Grid, Interp, Target};

    let grid = Grid::new(
        Target::LineY { axes: 0, index: 0 },
        vec![0.0, 2.0],
        vec![0.0, 4.0],
        vec![vec![vec![1.0], vec![2.0]], vec![vec![3.0], vec![4.0]]],
        Interp::Step,
    )
    .expect("grid");

    assert_eq!(grid.sample(1.9, 3.9), vec![1.0]); // holds (0, 0) until crossed
    assert_eq!(grid.sample(2.0, 3.9), vec![3.0]);
    assert_eq!(grid.sample(2.0, 4.0), vec![4.0]);
}

#[test]
fn malformed_grids_are_refused() {
    use crate::portable::{Grid, Interp, Target};
    let target = Target::LineY { axes: 0, index: 0 };

    for (times, positions, frames) in [
        // Ragged frame.
        (
            vec![0.0, 1.0],
            vec![0.0],
            vec![vec![vec![1.0, 2.0]], vec![vec![1.0]]],
        ),
        // Row count disagrees with the time axis.
        (vec![0.0, 1.0], vec![0.0], vec![vec![vec![1.0]]]),
        // Row width disagrees with the position axis.
        (vec![0.0], vec![0.0, 1.0], vec![vec![vec![1.0]]]),
        // Non-increasing axis.
        (
            vec![1.0, 1.0],
            vec![0.0],
            vec![vec![vec![1.0]], vec![vec![1.0]]],
        ),
        // Empty axis.
        (vec![], vec![0.0], vec![]),
    ] {
        assert!(matches!(
            Grid::new(target, times, positions, frames, Interp::Linear),
            Err(PortableError::Unsupported(_))
        ));
    }
}

#[test]
fn control_positions_normalize_to_something_drawable() {
    use crate::portable::Control;

    let c = Control::new("λ", 1.0, 3.0, 2.0).expect("control");
    assert_eq!(c.normalize(2.5), 2.5);
    assert_eq!(c.normalize(-10.0), 1.0);
    assert_eq!(c.normalize(10.0), 3.0);
    // A nonsense slider should not produce a nonsense figure.
    assert_eq!(c.normalize(f64::NAN), 2.0);

    let stepped = Control::new("n", 0.0, 10.0, 0.0)
        .expect("control")
        .with_step(2.0)
        .expect("step");
    assert_eq!(stepped.normalize(3.1), 4.0);
    assert_eq!(stepped.normalize(2.9), 2.0);

    assert!(Control::new("bad", 3.0, 1.0, 2.0).is_err());
    assert!(Control::new("out", 0.0, 1.0, 5.0).is_err());
    assert!(
        Control::new("s", 0.0, 1.0, 0.0)
            .expect("control")
            .with_step(-1.0)
            .is_err()
    );
}

#[test]
fn controls_round_trip_and_start_at_their_defaults() {
    let mut fig = controlled_figure();
    fig.set_control(0, 4.0).expect("control");
    fig.set_control(1, 9.0).expect("control");

    let bytes = fig.to_portable().expect("export");
    let restored = Figure::from_portable(&bytes).expect("import");

    // The declaration travels; the live positions are session state and do
    // not — a fresh import starts at the authored defaults.
    assert_eq!(restored.controls(), fig.controls());
    assert_eq!(restored.control_values(), &[2.0, 1.0]);

    // And the restored controls drive the figure identically.
    let mut a = fig;
    let mut b = restored;
    for f in [&mut a, &mut b] {
        f.set_control(0, 1.0).expect("control");
        f.set_control(1, 5.0).expect("control");
        f.seek(0.5).expect("seek");
    }
    assert_eq!(a.axes()[0].line_data(0), b.axes()[0].line_data(0));
    assert_eq!(a.axes()[0].line_data(1), b.axes()[0].line_data(1));
}

#[test]
fn a_grid_only_figure_still_animates() {
    // The wave whose only time-dependence is inside a control's grid: the
    // timeline carries no tracks, but the clock still moves the figure, so
    // every "should this play" gate must say yes.
    let fig = controlled_figure();
    assert!(fig.timeline().is_some_and(Timeline::is_empty));
    assert!(fig.is_animated());

    let bytes = fig.to_portable().expect("export");
    let info = crate::portable::inspect(&bytes, &Limits::default()).expect("inspect");
    assert!(
        info.meta.expect("meta").animated,
        "inspect must report a grid-only figure animated"
    );

    // And the grid actually moves under the clock at a fixed control value.
    let mut fig = Figure::from_portable(&bytes).expect("import");
    fig.seek(0.0).expect("seek");
    let at0 = fig.axes()[0].line_data(0).unwrap().1;
    fig.seek(1.0).expect("seek");
    assert_ne!(fig.axes()[0].line_data(0).unwrap().1, at0);
}

#[test]
fn bad_control_indices_and_targets_fail_loudly() {
    use crate::portable::{Control, Interp, Target, Track};

    let mut fig = controlled_figure();
    assert!(matches!(
        fig.set_control(5, 1.0),
        Err(PortableError::Malformed(_))
    ));

    // A control track addressing a line that does not exist is refused at
    // declaration — add_control is one of the three acceptance gates (with
    // export and import) that make an accepted figure total.
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 0.0]);
    let mut c = Control::new("ghost", 0.0, 1.0, 0.0).expect("control");
    c.push_track(
        Track::new(
            Target::LineY { axes: 0, index: 7 },
            vec![0.0],
            vec![vec![0.0, 0.0]],
            Interp::Linear,
        )
        .expect("track"),
    );
    let err = match fig.add_control(c) {
        Err(e) => e,
        Ok(_) => panic!("a ghost target must not be accepted"),
    };
    assert!(err.to_string().contains("line 7"), "{err}");

    // And a stride disagreeing with the artist is refused the same way.
    let mut c = Control::new("wide", 0.0, 1.0, 0.0).expect("control");
    c.push_track(
        Track::new(
            Target::LineY { axes: 0, index: 0 },
            vec![0.0],
            vec![vec![0.0; 5]], // the line holds 2 points
            Interp::Linear,
        )
        .expect("track"),
    );
    let err = match fig.add_control(c) {
        Err(e) => e,
        Ok(_) => panic!("a lying stride must not be accepted"),
    };
    assert!(err.to_string().contains("stride 5"), "{err}");
}

#[test]
fn the_live_wrapper_emits_host_side_sliders() {
    let mut fig = controlled_figure();
    fig.seek(0.0).expect("seek");
    let riz = fig.to_portable().expect("export");
    let limits = Limits::default();
    let rt = crate::portable::HtmlRuntime {
        wasm: b"\0asm fake",
        glue: "// glue",
        loader: "// loader",
    };
    let page = crate::portable::wrap_html_live(&riz, &limits, &rt).expect("wrap");
    assert!(page.contains("riz-controls"));
    assert!(page.contains("setControl"));
    // The poster tier carries no slider scaffolding beyond the shared style.
    let poster = crate::portable::wrap_html(&riz, &limits).expect("wrap");
    assert!(!poster.contains("setControl"));
}

#[test]
fn forged_tracks_and_grids_are_an_import_error_not_a_panic() {
    use crate::portable::{Timeline, Track};

    // Honest export refuses these figures outright, so the forgery happens at
    // the byte level — patching the JSON chunk of a valid artifact, exactly
    // what a hand-crafted file delivers. Before import validation, each
    // panicked in sample(): indexing values[] past its end, or times[0] of an
    // empty axis.
    let mut fig = animated_figure();
    fig.set_timeline({
        let mut tl = Timeline::new(2.0);
        tl.push(
            Track::line_y(0, 0, vec![0.0, 2.0], vec![vec![0.0; 3], vec![1.0; 3]]).expect("track"),
        );
        tl
    });
    let bytes = fig.to_portable().expect("export");

    // A stride that lies about the value count.
    let forged = reforge_json(&bytes, |json| {
        json.replace("\"stride\":3", "\"stride\":300")
    });
    let Err(err) = Figure::from_portable(&forged) else {
        panic!("a lying stride must not import");
    };
    assert!(
        matches!(&err, PortableError::Malformed(m) if m.contains("stride")),
        "{err}"
    );

    // An empty keyframe axis.
    let forged = reforge_json(&bytes, |json| {
        json.replace("\"times\":[0.0,2.0]", "\"times\":[]")
    });
    assert!(Figure::from_portable(&forged).is_err());

    // A control grid whose lattice lies about its value count, forged into a
    // control-bearing artifact.
    let fig = controlled_figure();
    let bytes = fig.to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| {
        json.replace("\"positions\":[0.0,4.0]", "\"positions\":[0.0,2.0,4.0]")
    });
    let Err(err) = Figure::from_portable(&forged) else {
        panic!("a lying lattice must not import");
    };
    assert!(
        matches!(&err, PortableError::Malformed(m) if m.contains("lattice")),
        "{err}"
    );

    // A control range gone non-finite.
    let forged = reforge_json(&bytes, |json| {
        json.replace(
            "\"label\":\"level\",\"min\":0.0",
            "\"label\":\"level\",\"min\":null",
        )
    });
    assert!(Figure::from_portable(&forged).is_err());
}

/// Rebuild `bytes` with its JSON chunk passed through `patch` — the test
/// harness for hand-crafted artifacts that no honest exporter will produce.
fn reforge_json(bytes: &[u8], patch: impl Fn(String) -> String) -> Vec<u8> {
    use crate::portable::container;
    let dir = container::directory(bytes, &Limits::default()).expect("directory");
    let json = std::str::from_utf8(
        container::chunk(bytes, &dir, container::TAG_JSON).expect("json chunk"),
    )
    .expect("utf8");
    let patched = patch(json.to_string());
    assert_ne!(json, patched, "the patch must change the document");
    let chunks: Vec<([u8; 4], Vec<u8>)> = dir
        .iter()
        .map(|c| {
            let payload = if c.tag == container::TAG_JSON {
                patched.clone().into_bytes()
            } else {
                container::chunk(bytes, &dir, c.tag)
                    .expect("chunk")
                    .to_vec()
            };
            (c.tag, payload)
        })
        .collect();
    let borrowed: Vec<([u8; 4], &[u8])> = chunks.iter().map(|(t, p)| (*t, p.as_slice())).collect();
    container::write(&borrowed)
}

#[test]
fn inspect_reports_the_control_manifest_typed() {
    // A host validates once and persists the manifest without JSON pokes:
    // declaration order, layout fields only, no track data parsed.
    let fig = controlled_figure();
    let bytes = fig.to_portable().expect("export");
    let info = crate::portable::inspect(&bytes, &Limits::default()).expect("inspect");

    assert_eq!(info.controls.len(), 2);
    assert_eq!(info.controls[0].label, "shape");
    assert_eq!(
        (
            info.controls[0].min,
            info.controls[0].max,
            info.controls[0].default
        ),
        (0.0, 4.0, 2.0)
    );
    assert_eq!(info.controls[0].step, None);
    assert_eq!(info.controls[1].label, "level");

    // A static artifact reports an empty manifest, not an error.
    let mut plain = Figure::new(4.0, 3.0);
    plain.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    let bytes = plain.to_portable().expect("export");
    let info = crate::portable::inspect(&bytes, &Limits::default()).expect("inspect");
    assert!(info.controls.is_empty());

    // And a forged nonsense range fails at inspect, before a host persists it.
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    let mut c = crate::portable::Control::new("ok", 0.0, 1.0, 0.5).expect("control");
    c.default = 9.0;
    fig.add_control(c)
        .expect("targets are fine; the range is the forgery");
    let bytes = fig.to_portable().expect("export");
    let err = crate::portable::inspect(&bytes, &Limits::default())
        .expect_err("nonsense range must not inspect");
    assert!(
        matches!(&err, PortableError::Malformed(m) if m.contains("control 0")),
        "{err}"
    );
}

#[test]
fn set_control_echoes_the_position_actually_applied() {
    use crate::portable::{Control, Interp, Target, Track};

    // The echo is the normalization policy's single source of truth: a host
    // shows what came back, never what it sent.
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 0.0]);
    let mut c = Control::new("n", 0.0, 10.0, 4.0)
        .expect("control")
        .with_step(2.0)
        .expect("step");
    c.push_track(
        Track::new(
            Target::LineY { axes: 0, index: 0 },
            vec![0.0, 10.0],
            vec![vec![0.0; 2], vec![10.0; 2]],
            Interp::Linear,
        )
        .expect("track"),
    );
    fig.add_control(c).expect("add");

    assert_eq!(fig.set_control(0, 3.1).expect("set"), 4.0); // snapped up
    assert_eq!(fig.set_control(0, 2.9).expect("set"), 2.0); // snapped down
    assert_eq!(fig.set_control(0, -50.0).expect("set"), 0.0); // clamped
    assert_eq!(fig.set_control(0, f64::NAN).expect("set"), 4.0); // defaulted
    // The figure reflects the echoed value, not the requested one.
    assert_eq!(fig.control_values(), &[4.0]);
    assert_eq!(fig.axes()[0].line_data(0).unwrap().1, vec![4.0; 2]);

    // The interactor echoes identically through the user-view wrapper.
    let mut it = Interactor::new(fig);
    assert_eq!(it.set_control(0, 9.9).expect("set"), 10.0);
}

#[test]
fn schema_cannot_be_under_declared() {
    // Schema is the compatibility decision: a host selects a runtime from the
    // declaration. A forged "schema 3" document carrying controls would render
    // on a schema-4 runtime while a host that correctly picked a schema-3
    // runtime watches it rejected for the unknown field. Both inspection and
    // import refuse the lie.
    let bytes = controlled_figure().to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| json.replace("\"schema\":21", "\"schema\":3"));

    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("an under-declared schema must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 4")),
            "{err}"
        );
    }

    // The same floor applies one level down: a timeline needs schema 3.
    let bytes = animated_figure().to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| json.replace("\"schema\":21", "\"schema\":2"));
    let Err(err) = Figure::from_portable(&forged) else {
        panic!("a timeline under schema 3 must not import");
    };
    assert!(
        matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 3")),
        "{err}"
    );
    assert!(crate::portable::inspect(&forged, &Limits::default()).is_err());

    // Minor ticks are schema 5; a schema-4 runtime would reject the field.
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.minorticks_on();
    let bytes = fig.to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| json.replace("\"schema\":21", "\"schema\":4"));
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("minor ticks under schema 5 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 5")),
            "{err}"
        );
    }

    // Text sizes are schema 6; a schema-5 runtime would reject the field.
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    fig.suptitle("sized").set_suptitle_size(20.0);
    let bytes = fig.to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| json.replace("\"schema\":21", "\"schema\":5"));
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("text sizes under schema 6 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 6")),
            "{err}"
        );
    }

    // Scatter legend samples and the artist order are schema 7.
    let bytes = scatter_legend_figure().to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| json.replace("\"schema\":21", "\"schema\":6"));
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("legend markers under schema 7 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 7")),
            "{err}"
        );
    }

    // Figure text and figure axis labels are schema 8.
    let bytes = figure_text_figure().to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| json.replace("\"schema\":21", "\"schema\":7"));
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("figure text under schema 8 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 8")),
            "{err}"
        );
    }

    // Image norms and extreme colors are schema 9.
    let bytes = image_norm_figure().to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| json.replace("\"schema\":21", "\"schema\":8"));
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("image norms under schema 9 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 9")),
            "{err}"
        );
    }

    // Colorbars and recorded color scales are schema 10.
    let bytes = colorbar_figure().to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| json.replace("\"schema\":21", "\"schema\":9"));
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("colorbars under schema 10 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 10")),
            "{err}"
        );
    }

    // An astronomical image normalization is schema 11.
    let bytes = astro_figure().to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| {
        json.replace("\"schema\":21", "\"schema\":10")
    });
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("an image normalization under schema 11 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 11")),
            "{err}"
        );
    }
}

/// A star-field image through ZScale and a histogram-equalization stretch,
/// with a colorbar.
fn astro_figure() -> Figure {
    use crate::core::color::{ImageNormalize, Interval, Stretch};
    use crate::figure::Mappable;
    let sky: Vec<f64> = (0..100)
        .map(|i| 100.0 + f64::from(i % 9) + if i == 44 { 4e4 } else { 0.0 })
        .collect();
    let mut fig = Figure::new(3.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.imshow(&sky, 10, 10)
        .cmap("gray")
        .norm(ImageNormalize::new(
            Interval::zscale(),
            Stretch::histeq(&sky),
        ));
    ax.colorbar(Mappable::Image(0));
    fig
}

#[test]
fn turning_line_simplification_off_survives_export() {
    use crate::core::rcparams::RcParams;
    let rc = RcParams {
        path_simplify: false,
        ..RcParams::default()
    };
    let mut fig = Figure::new(4.0, 3.0).with_rcparams(rc);
    let x: Vec<f64> = (0..3000).map(f64::from).collect();
    let y: Vec<f64> = x.iter().map(|v| (v * 0.37).sin()).collect();
    fig.add_subplot(1, 1, 1).plot(&x, &y);

    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    // The imported axes draw unsimplified too, so the render is the same.
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    let forged = reforge_json(&bytes, |json| {
        json.replace("\"schema\":21", "\"schema\":11")
    });
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("a simplification setting under schema 12 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 12")),
            "{err}"
        );
    }
}

#[test]
fn sky_projection_axes_round_trip() {
    use crate::figure::Mappable;
    use crate::figure::sky::SkyProjection;
    use std::f64::consts::PI;
    let lon: Vec<f64> = (0..=12).map(|i| -PI + f64::from(i) * PI / 6.0).collect();
    let lat: Vec<f64> = (0..=6)
        .map(|i| -PI / 2.0 + f64::from(i) * PI / 6.0)
        .collect();
    let c: Vec<f64> = (0..72).map(|k| f64::from(k % 7)).collect();
    let mut fig = Figure::new(6.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.set_sky_projection(SkyProjection::Aitoff).grid(true);
    ax.pcolormesh_xy(&lon, &lat, &c, "magma");
    ax.plot(&[-2.0, 2.0], &[0.5, -0.5]);
    ax.colorbar(Mappable::Mesh(0));

    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.axes()[0].sky_projection(), Some(SkyProjection::Aitoff));
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    let forged = reforge_json(&bytes, |json| {
        json.replace("\"schema\":21", "\"schema\":12")
    });
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("a sky projection under schema 13 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 13")),
            "{err}"
        );
    }
}

#[test]
fn polygon_collections_round_trip() {
    use crate::figure::Mappable;
    let polygons = vec![
        vec![[0.0, 0.0], [1.0, 0.0], [0.5, 1.0]],
        vec![[1.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0]],
        vec![[2.5, 0.2], [3.5, 0.2], [3.0, 0.9]],
    ];
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.poly_collection(&polygons, &[1.0, f64::NAN, 3.0], "magma")
        .set_edgecolor(Some(Rgba::BLACK))
        .set_zorder(3.0);
    ax.colorbar(Mappable::Polygons(0));

    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.axes()[0].poly_collections[0].len(), 3);
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    let forged = reforge_json(&bytes, |json| {
        json.replace("\"schema\":21", "\"schema\":13")
    });
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("polygon collections under schema 14 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 14")),
            "{err}"
        );
    }
}

#[test]
fn custom_colormaps_round_trip() {
    use crate::core::color::{ColorMapping, LinearSegmentedColormap, ListedColormap};
    use crate::figure::Mappable;
    let five = ListedColormap::from_colors(&[
        Rgba::BLACK,
        Rgba::RED,
        Rgba::new(0.1, 0.7, 0.3, 1.0),
        Rgba::BLUE,
        Rgba::WHITE,
    ]);
    let ramp = ListedColormap::from_fn(|t| Rgba::rgb(t, 0.5 * t, 1.0 - t));
    // Registered only in this process: the artifact must carry its colors.
    assert!(crate::core::color::register_colormap(
        "round_trip_only",
        LinearSegmentedColormap::from_list(&[(0.0, Rgba::BLUE), (1.0, Rgba::RED)]),
    ));
    let data: Vec<f64> = (0..48).map(f64::from).collect();
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.imshow(&data, 6, 8).cmap(five);
    ax.scatter_mapped(&data, &data, &data, ColorMapping::new(ramp));
    ax.pcolormesh_mapped(&data, 6, 8, "round_trip_only_r");
    ax.colorbar(Mappable::Collection(0));

    let bytes = fig.to_portable().expect("export");
    let json = String::from_utf8_lossy(&bytes);
    assert!(
        json.contains("\"lut:"),
        "custom maps travel as their colors"
    );
    assert!(
        !json.contains("round_trip_only"),
        "registered names travel as colors"
    );
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    let forged = reforge_json(&bytes, |json| {
        json.replace("\"schema\":21", "\"schema\":14")
    });
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("an embedded colormap under schema 14 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 15")),
            "{err}"
        );
    }

    let corrupt = reforge_json(&bytes, |json| json.replacen("\"lut:", "\"lut:zz", 1));
    assert!(matches!(
        Figure::from_portable(&corrupt),
        Err(PortableError::Malformed(m)) if m.contains("embedded colormap")
    ));
}

#[test]
fn axisbelow_round_trips_and_is_written_only_when_set() {
    use crate::core::rcparams::AxisBelow;
    let gridded = |axisbelow: Option<AxisBelow>| {
        let mut fig = Figure::new(4.0, 3.0);
        let ax = fig.add_subplot(1, 1, 1);
        ax.bar(&[1.0, 2.0], &[2.0, 1.0]);
        ax.grid(true);
        if let Some(axisbelow) = axisbelow {
            ax.set_axisbelow(axisbelow);
        }
        fig
    };
    let default = gridded(None).to_portable().expect("export");
    assert!(!String::from_utf8_lossy(&default).contains("axisbelow"));

    let fig = gridded(Some(AxisBelow::Below));
    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.axes()[0].axisbelow, AxisBelow::Below);
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    let forged = reforge_json(&bytes, |json| {
        json.replace("\"schema\":21", "\"schema\":15")
    });
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("an axisbelow under schema 16 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 16")),
            "{err}"
        );
    }
}

#[test]
fn line_markers_round_trip() {
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0, 2.0, 3.0], &[1.0, 3.0, 2.0, 4.0])
        .set_marker("D")
        .set_markersize(9.0)
        .set_markerfacecolor(Rgba::RED)
        .set_markevery(2)
        .set_label("marked");
    ax.legend_auto();

    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.axes()[0].lines()[0].marker(), Some('D'));
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    let forged = reforge_json(&bytes, |json| {
        json.replace("\"schema\":21", "\"schema\":16")
    });
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("line markers under schema 17 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 17")),
            "{err}"
        );
    }
    let bad = reforge_json(&bytes, |json| {
        json.replacen("\"code\":\"D\"", "\"code\":\"Q\"", 1)
    });
    assert!(matches!(
        Figure::from_portable(&bad),
        Err(PortableError::Malformed(m)) if m.contains("not drawable")
    ));
}

#[test]
fn quivers_round_trip() {
    use crate::figure::{QuiverAngles, QuiverOptions, QuiverPivot, QuiverUnits};
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    let options = QuiverOptions::new()
        .scale_units(QuiverUnits::Xy)
        .angles(QuiverAngles::Xy)
        .scale(1.0)
        .pivot(QuiverPivot::Middle)
        .color(Rgba::RED);
    ax.quiver_with(
        &[0.0, 1.0],
        &[0.0, 1.0],
        &[1.0, -0.5],
        &[0.5, 0.25],
        &options,
    )
    .set_zorder(3.0);

    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    let forged = reforge_json(&bytes, |json| {
        json.replace("\"schema\":21", "\"schema\":17")
    });
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("quivers under schema 17 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 18")),
            "{err}"
        );
    }
    let ragged = reforge_json(&bytes, |json| {
        json.replacen(
            "{\"dtype\":\"f64\",\"count\":2,\"offset\":32}",
            "{\"dtype\":\"f64\",\"count\":1,\"offset\":32}",
            1,
        )
    });
    assert!(matches!(
        Figure::from_portable(&ragged),
        Err(PortableError::Malformed(m)) if m.contains("differ in length")
    ));
}

#[test]
fn collection_joins_round_trip() {
    use crate::figure::ErrorbarOptions;
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.errorbar_with(
        &[1.0, 2.0],
        &[3.0, 4.0],
        &[0.5, 0.5],
        &ErrorbarOptions::new().uplims(&[true, false]),
    );
    ax.scatter(&[1.5], &[3.5]).set_edgecolors(vec![Rgba::RED]);

    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    let forged = reforge_json(&bytes, |json| {
        json.replace("\"schema\":21", "\"schema\":18")
    });
    for result in [
        Figure::from_portable(&forged).map(|_| ()),
        crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("collection joins under schema 18 must not be accepted");
        };
        assert!(
            matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 19")),
            "{err}"
        );
    }
}

#[test]
fn log_ticks_round_trip() {
    for min_exponent in [0, 2] {
        let mut fig = Figure::new(4.0, 3.0).with_rcparams(RcParams {
            axes_formatter_min_exponent: min_exponent,
            ..RcParams::default()
        });
        let ax = fig.add_subplot(1, 1, 1);
        ax.plot(&[1.0, 10.0, 1e4], &[1.0, 2.0, 3.0]);
        ax.set_xscale_log(10.0);

        let bytes = fig.to_portable().expect("export");
        let back = Figure::from_portable(&bytes).expect("import");
        assert_eq!(back.to_portable().expect("re-export"), bytes);
        assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

        let forged = reforge_json(&bytes, |json| {
            json.replace("\"schema\":21", "\"schema\":19")
        });
        for result in [
            Figure::from_portable(&forged).map(|_| ()),
            crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
        ] {
            let Err(err) = result else {
                panic!("log ticks under schema 19 must not be accepted");
            };
            assert!(
                matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 20")),
                "{err}"
            );
        }
    }
}

#[test]
fn line_styles_round_trip() {
    use crate::render::{CapStyle, JoinStyle};
    let custom = RcParams {
        lines_solid_capstyle: CapStyle::Round,
        lines_dash_joinstyle: JoinStyle::Bevel,
        ..RcParams::default()
    };
    for (rc, guarded) in [(RcParams::default(), false), (custom, true)] {
        let mut fig = Figure::new(4.0, 3.0).with_rcparams(rc);
        let ax = fig.add_subplot(1, 1, 1);
        ax.plot(&[0.0, 1.0, 2.0], &[0.0, 2.0, 1.0]);
        ax.plot(&[0.0, 1.0, 2.0], &[1.0, 0.0, 2.0])
            .set_dashes(Some((0.0, vec![6.0, 3.0])));

        let bytes = fig.to_portable().expect("export");
        let back = Figure::from_portable(&bytes).expect("import");
        assert_eq!(back.to_portable().expect("re-export"), bytes);
        assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

        let forged = reforge_json(&bytes, |json| {
            json.replace("\"schema\":21", "\"schema\":20")
        });
        if !guarded {
            // Default styles write nothing new; declared older, the dashed
            // line takes the solid cap and join, as it did then.
            let old = Figure::from_portable(&forged).expect("schema 20 loads");
            assert_ne!(old.encode_png().unwrap(), fig.encode_png().unwrap());
            continue;
        }
        for result in [
            Figure::from_portable(&forged).map(|_| ()),
            crate::portable::inspect(&forged, &Limits::default()).map(|_| ()),
        ] {
            let Err(err) = result else {
                panic!("line styles under schema 20 must not be accepted");
            };
            assert!(
                matches!(&err, PortableError::Malformed(m) if m.contains("requiring schema 21")),
                "{err}"
            );
        }
    }
}

#[test]
fn image_normalize_round_trips() {
    let fig = astro_figure();
    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());
}

/// Two colorbarred panels: an image through a log norm, and a mapped scatter
/// with its bar below.
fn colorbar_figure() -> Figure {
    use crate::core::color::{ColorMapping, LogNorm, TwoSlopeNorm};
    use crate::figure::{ColorbarLocation, Mappable};
    let mut fig = Figure::new(6.0, 3.0);
    let data: Vec<f64> = (0..36).map(|i| 1.5f64.powi(i)).collect();
    let ax = fig.add_subplot(1, 2, 1);
    ax.imshow(&data, 6, 6).norm(LogNorm::new(1.0, 1e6));
    ax.colorbar(Mappable::Image(0)).set_label("flux");
    let ax = fig.add_subplot(1, 2, 2);
    ax.scatter_mapped(
        &[0.0, 1.0, 2.0],
        &[1.0, 0.0, 2.0],
        &[-1.0, 0.5, 4.0],
        ColorMapping::new("RdBu").norm(TwoSlopeNorm::new(-1.0, 0.0, 4.0)),
    );
    ax.colorbar(Mappable::Collection(0))
        .set_location(ColorbarLocation::Bottom)
        .set_shrink(0.8);
    fig
}

#[test]
fn colorbars_round_trip() {
    let fig = colorbar_figure();
    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());
    assert_eq!(back.colorbar_ticks(1), fig.colorbar_ticks(1));
}

#[test]
fn a_colorbar_naming_a_missing_artist_is_refused() {
    let bytes = colorbar_figure().to_portable().expect("export");
    let forged = reforge_json(&bytes, |json| {
        json.replace("\"mappable\":{\"image\":0}", "\"mappable\":{\"image\":3}")
    });
    assert_ne!(forged, bytes, "the forgery must change the artifact");
    let Err(err) = Figure::from_portable(&forged) else {
        panic!("a colorbar describing no artist must not import");
    };
    assert!(
        matches!(&err, PortableError::Malformed(m) if m.contains("not a colormapped artist")),
        "{err}"
    );
}

/// An image through a symlog norm with every extreme color set.
fn image_norm_figure() -> Figure {
    use crate::core::color::SymLogNorm;
    let data: Vec<f64> = (0..48)
        .map(|i| {
            if i == 7 {
                f64::NAN
            } else {
                (f64::from(i) - 20.0).powi(3)
            }
        })
        .collect();
    let mut fig = Figure::new(3.0, 3.0);
    fig.add_subplot(1, 1, 1)
        .imshow(&data, 6, 8)
        .cmap("RdBu")
        .norm(SymLogNorm::new(2.0, -500.0, 500.0).with_linscale(0.5))
        .bad(Rgba::BLACK)
        .over(Rgba::GREEN)
        .under(Rgba::BLUE);
    fig
}

#[test]
fn image_norms_round_trip() {
    let fig = image_norm_figure();
    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    // A plain image writes neither schema-9 field.
    let mut plain = Figure::new(3.0, 3.0);
    plain
        .add_subplot(1, 1, 1)
        .imshow(&[0.0, 1.0, 2.0, 3.0], 2, 2);
    let plain = plain.to_portable().expect("export");
    let json = String::from_utf8_lossy(&plain);
    assert!(!json.contains("\"norm\""));
    assert!(!json.contains("\"extremes\""));
}

/// Two subplots sharing figure axis labels, with styled free text.
fn figure_text_figure() -> Figure {
    use crate::figure::{HorizontalAlignment, TextBoxStyle, VerticalAlignment};
    let mut fig = Figure::new(5.0, 3.0);
    fig.add_subplot(1, 2, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    fig.add_subplot(1, 2, 2).plot(&[0.0, 1.0], &[1.0, 0.0]);
    fig.supxlabel("time (s)");
    fig.supylabel("volts").set_size(11.0);
    fig.text(0.99, 0.99, "run 7")
        .set_ha(HorizontalAlignment::Right)
        .set_va(VerticalAlignment::Top)
        .set_rotation(15.0)
        .set_color(Rgba::RED)
        .set_bbox(Some(TextBoxStyle::default()));
    fig
}

#[test]
fn figure_text_round_trips() {
    let fig = figure_text_figure();
    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());
    assert_eq!(back.texts(), fig.texts());

    // A figure without figure text writes none of the schema-8 fields.
    let mut plain = Figure::new(4.0, 3.0);
    plain.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    let plain = plain.to_portable().expect("export");
    let json = String::from_utf8_lossy(&plain);
    assert!(!json.contains("\"texts\""));
    assert!(!json.contains("supxlabel"));
    assert!(!json.contains("supylabel"));
}

/// A scatter added before a line, both labelled, with an automatic legend.
fn scatter_legend_figure() -> Figure {
    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.scatter(&[0.0, 1.0, 2.0], &[1.0, 0.0, 2.0])
        .set_sizes(vec![4.0, 10.0])
        .set_label("data");
    ax.plot(&[0.0, 2.0], &[0.0, 2.0]).set_label("model");
    ax.legend_auto();
    fig
}

#[test]
fn scatter_legend_round_trips() {
    let fig = scatter_legend_figure();
    let bytes = fig.to_portable().expect("export");
    let json = String::from_utf8_lossy(&bytes);
    assert!(json.contains("\"artist_order\":[\"collection\",\"line\"]"));
    assert!(json.contains("\"label\":\"data\",\"marker\":{"));

    let mut back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);
    assert_eq!(back.encode_png().unwrap(), fig.encode_png().unwrap());

    // The imported axes still knows the scatter came first.
    let ax = &mut back.axes_mut()[0];
    ax.legend_auto();
    let labels: Vec<&str> = ax.legend.iter().map(|e| e.label.as_str()).collect();
    assert_eq!(labels, ["data", "model"]);

    // Lines-then-patches-then-collections, with line-only legends, writes
    // neither schema-7 field.
    let mut plain = Figure::new(4.0, 3.0);
    let ax = plain.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]).set_label("line");
    ax.scatter(&[0.0, 1.0], &[1.0, 0.0]);
    ax.legend_auto();
    let plain = plain.to_portable().expect("export");
    let json = String::from_utf8_lossy(&plain);
    assert!(!json.contains("artist_order"));
    assert!(json.contains("\"label\":\"line\"}]"));
}

#[test]
fn text_sizes_round_trip() {
    let mut fig = Figure::new(4.0, 3.0);
    fig.suptitle("Amps").set_suptitle_size(22.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 1.0], &[0.0, 1.0]);
    ax.set_text_size(15.0).text(0.2, 0.5, "big");
    ax.set_text_size(7.0);

    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);

    // Default sizes write no schema-6 fields.
    let mut plain = Figure::new(4.0, 3.0);
    plain.suptitle("Amps");
    plain.add_subplot(1, 1, 1).text(0.2, 0.5, "default");
    let plain = plain.to_portable().expect("export");
    let json = String::from_utf8_lossy(&plain);
    assert!(!json.contains("suptitle_size"), "{json}");
    assert!(!json.contains("text_size"), "{json}");
}

#[test]
fn minor_ticks_and_title_style_round_trip() {
    use crate::axis::ticker::MultipleLocator;

    let mut fig = Figure::new(4.0, 3.0);
    let ax = fig.add_subplot(1, 1, 1);
    ax.plot(&[0.0, 10.0], &[0.0, 1.0]);
    ax.minorticks_on()
        .minor_grid_with(Rgba::BLACK, 0.3, 0.2)
        .set_title("styled")
        .set_title_size(7.0);
    ax.yaxis_mut()
        .set_minor_locator(Box::new(MultipleLocator::new(0.05)))
        .set_minor_tick_params(1.5, 0.4);
    ax.xaxis_mut().tick_top();

    let bytes = fig.to_portable().expect("export");
    let back = Figure::from_portable(&bytes).expect("import");
    assert_eq!(back.to_portable().expect("re-export"), bytes);

    // A figure without the new styling exports no schema-5 fields at all.
    let mut plain = Figure::new(4.0, 3.0);
    plain.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    let plain = plain.to_portable().expect("export");
    let json = String::from_utf8_lossy(&plain);
    assert!(!json.contains("\"minor\""), "{json}");
    assert!(!json.contains("title_style"), "{json}");
}

#[test]
fn the_control_manifest_answers_to_its_own_budgets() {
    use crate::portable::Control;

    // Each control becomes host-materialized state — a persisted manifest
    // entry, a DOM slider — so count and label size answer to their own
    // limits, not to whatever the JSON allowance happens to admit.
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    for i in 0..3 {
        fig.add_control(Control::new(&format!("c{i}"), 0.0, 1.0, 0.5).expect("control"))
            .expect("add");
    }
    let bytes = fig.to_portable().expect("export");

    let tight = Limits::default().with_max_controls(2);
    for result in [
        Figure::from_portable_limited(&bytes, &tight).map(|_| ()),
        crate::portable::inspect(&bytes, &tight).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("3 controls must not pass a 2-control budget");
        };
        assert!(
            matches!(&err, PortableError::Budget(m) if m.contains("3 controls")),
            "{err}"
        );
    }
    // Exactly at the limit passes.
    let exact = Limits::default().with_max_controls(3);
    assert!(crate::portable::inspect(&bytes, &exact).is_ok());
    assert!(Figure::from_portable_limited(&bytes, &exact).is_ok());

    // Labels: at the byte limit passes, one byte over refuses.
    let mut fig = Figure::new(4.0, 3.0);
    fig.add_subplot(1, 1, 1).plot(&[0.0, 1.0], &[0.0, 1.0]);
    fig.add_control(Control::new("12345678", 0.0, 1.0, 0.5).expect("control"))
        .expect("add");
    let bytes = fig.to_portable().expect("export");
    assert!(
        crate::portable::inspect(&bytes, &Limits::default().with_max_control_label_bytes(8))
            .is_ok()
    );
    let tight = Limits::default().with_max_control_label_bytes(7);
    for result in [
        Figure::from_portable_limited(&bytes, &tight).map(|_| ()),
        crate::portable::inspect(&bytes, &tight).map(|_| ()),
    ] {
        let Err(err) = result else {
            panic!("an 8-byte label must not pass a 7-byte budget");
        };
        assert!(
            matches!(&err, PortableError::Budget(m) if m.contains("label")),
            "{err}"
        );
    }
}