slintplot-gallery 0.4.2

Sample browser for SlintPlot: every chart type, with live data editing, themes and dark mode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
//! A sample browser for SlintPlot.
//!
//! `cargo run -p gallery` opens it; `cargo run -p gallery -- --snapshot <dir>`
//! renders every sample to PNG files instead.

mod code;
#[cfg(not(target_arch = "wasm32"))]
mod dock_icon;
#[cfg(not(target_arch = "wasm32"))]
mod snapshot;
mod stream_model;
#[cfg(not(target_arch = "wasm32"))]
mod video;

use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Duration;

use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel};
use stream_model::StreamModel;

slint::include_modules!();
include!(concat!(env!("OUT_DIR"), "/sample_code.rs"));

/// Opens the code panel on the current sample's code, with its data now.
fn open_code(ui: &Gallery) {
    ui.set_code_files(code::sample_files(ui, &ui.get_sample()));
    ui.set_code_open(true);
}

/// The Gantt sample's release plan: label, group, start and end in days
/// after 15 December 2026, and the share done.
const RELEASE_PLAN: [(&str, &str, f32, f32, f32); 17] = [
    ("User research", "Design", 0.0, 10.0, 1.0),
    ("Wireframes", "Design", 7.0, 21.0, 1.0),
    ("Visual design", "Design", 17.0, 31.0, 0.6),
    ("Design review", "Design", 31.0, 31.0, 1.0),
    ("Backend API", "Build", 21.0, 56.0, 0.9),
    ("Database migration", "Build", 24.0, 38.0, 1.0),
    ("Web app", "Build", 28.0, 63.0, 0.7),
    ("Mobile apps (iOS and Android)", "Build", 35.0, 70.0, 0.5),
    ("Feature freeze", "Build", 70.0, 70.0, 0.0),
    ("Automated tests", "Test", 42.0, 77.0, 0.4),
    ("QA and bug fixing", "Test", 56.0, 84.0, 0.0),
    ("Public beta", "Test", 70.0, 84.0, 0.0),
    ("Security audit", "Test", 63.0, 73.0, 0.0),
    ("Docs and website", "Launch", 70.0, 88.0, 0.0),
    ("Marketing campaign", "Launch", 77.0, 95.0, 0.0),
    ("App store review", "Launch", 84.0, 89.0, 0.0),
    ("Release", "Launch", 91.0, 91.0, 0.0),
];

const MONTHS: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];
/// The languages of the "languages" sample's picker, in its order.
const LANGUAGES: [ChartLanguage; 14] = [
    ChartLanguage::English,
    ChartLanguage::Danish,
    ChartLanguage::German,
    ChartLanguage::Spanish,
    ChartLanguage::French,
    ChartLanguage::Italian,
    ChartLanguage::Dutch,
    ChartLanguage::Norwegian,
    ChartLanguage::Polish,
    ChartLanguage::Portuguese,
    ChartLanguage::Finnish,
    ChartLanguage::Swedish,
    ChartLanguage::Japanese,
    ChartLanguage::Chinese,
];
/// The "languages" sample's own texts in each of `LANGUAGES`: the title, and
/// the names of the two datasets, which are also the axis titles.
const LANGUAGE_TEXTS: [(&str, &str, &str); 14] = [
    (
        "Visitors and conversion rate",
        "Visitors",
        "Conversion rate",
    ),
    (
        "Besøgende og konverteringsrate",
        "Besøgende",
        "Konverteringsrate",
    ),
    (
        "Besucher und Konversionsrate",
        "Besucher",
        "Konversionsrate",
    ),
    (
        "Visitantes y tasa de conversión",
        "Visitantes",
        "Tasa de conversión",
    ),
    (
        "Visiteurs et taux de conversion",
        "Visiteurs",
        "Taux de conversion",
    ),
    (
        "Visitatori e tasso di conversione",
        "Visitatori",
        "Tasso di conversione",
    ),
    ("Bezoekers en conversieratio", "Bezoekers", "Conversieratio"),
    (
        "Besøkende og konverteringsrate",
        "Besøkende",
        "Konverteringsrate",
    ),
    (
        "Odwiedzający i współczynnik konwersji",
        "Odwiedzający",
        "Współczynnik konwersji",
    ),
    (
        "Visitantes e taxa de conversão",
        "Visitantes",
        "Taxa de conversão",
    ),
    ("Kävijät ja konversioaste", "Kävijät", "Konversioaste"),
    (
        "Besökare och konverteringsgrad",
        "Besökare",
        "Konverteringsgrad",
    ),
    ("訪問者数とコンバージョン率", "訪問者数", "コンバージョン率"),
    ("访客数与转化率", "访客数", "转化率"),
];
const SKILLS: [&str; 7] = [
    "Eating",
    "Drinking",
    "Sleeping",
    "Designing",
    "Coding",
    "Cycling",
    "Running",
];
/// The radial bar sample: daily goals reached, in percent.
const GOALS: [(&str, f32); 5] = [
    ("Steps", 86.0),
    ("Active minutes", 64.0),
    ("Sleep", 92.0),
    ("Water", 45.0),
    ("Reading", 30.0),
];
/// The radial bar sample: how customers contacted support, in percent of
/// those asked.
const CHANNELS: [(&str, f32); 6] = [
    ("Email", 34.0),
    ("Live chat", 27.0),
    ("Phone", 19.0),
    ("Help center", 12.0),
    ("Social media", 5.0),
    ("Forum", 3.0),
];
// Product categories, not colors: the slices take the theme's colors.
fn rgb(rgb: u32) -> slint::Color {
    slint::Color::from_rgb_u8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8)
}

const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const SHORT_MONTHS: [&str; 12] = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];

/// One segmented ring chart's data in the gallery.
struct RingSample {
    values: Vec<Vec<f32>>,
    x_labels: Vec<String>,
    y_labels: Vec<String>,
    /// The text in the middle.
    total: String,
}
const SLICE_NAMES: [&str; 8] = [
    "Books", "Games", "Music", "Movies", "Apps", "Toys", "Sports", "Garden",
];

/// The data actions most samples offer.
const DATA_ACTIONS: &[&str] = &[
    "Randomize",
    "Add dataset",
    "Add data",
    "Remove dataset",
    "Remove data",
];

/// The live data sample's buttons: pause, and the update rates.
const LIVE_ACTIONS: &[&str] = &[
    "Pause / resume",
    "10 updates/s",
    "30 updates/s",
    "60 updates/s",
];

/// Seconds the live data sample keeps.
const LIVE_SECONDS: u32 = 60;

/// Seconds since an arbitrary start, to measure update rates. The browser
/// has no `Instant`.
fn now() -> f64 {
    #[cfg(not(target_arch = "wasm32"))]
    {
        static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
        START
            .get_or_init(std::time::Instant::now)
            .elapsed()
            .as_secs_f64()
    }
    #[cfg(target_arch = "wasm32")]
    {
        js_sys::Date::now() / 1000.0
    }
}

/// The live data sample: three sensors whose values stream into ring buffers.
struct Live {
    /// Updates per second.
    rate: u32,
    paused: bool,
    /// Seconds after the time origin of the newest values.
    time: f32,
    last: [f32; 3],
    models: Vec<Rc<StreamModel<ChartXY>>>,
    /// Updates since `since`, for the measured rate.
    updates: u32,
    since: f64,
    /// A click's readout in the status, and when the stats first found it.
    clicked: Option<(SharedString, f64)>,
}

/// How a sample's data looks.
#[derive(Clone, Copy, PartialEq)]
enum Shape {
    /// Values per month, as in most samples.
    Months { datasets: usize, min: f32, max: f32 },
    /// One value per skill.
    Skills,
    /// Pie, doughnut and polar area slices.
    Slices,
    /// Scatter points.
    Points,
    /// Bubbles with a radius.
    Bubbles,
    /// A long random walk.
    Series { count: usize },
    /// Monthly values growing over several orders of magnitude.
    Exponential,
    /// Points every `step` seconds after the time origin.
    TimeSeries { count: usize, step: f32 },
    /// Activity by weekday and hour.
    Matrix,
    /// A symmetric correlation matrix, from -1 to 1.
    Correlation,
    /// Sales by product and region, with their growth.
    Sales,
    /// One value per day for a year.
    Calendar,
    /// Survey answers per group, shown as shares of 100%.
    Survey,
    /// Grouped items for a treemap.
    Treemap,
    /// The population table as a hierarchy: continents, regions, countries.
    Sunburst,
    /// Website visitors through the steps to a purchase.
    Funnel,
    /// A profit and loss statement.
    Waterfall,
    /// Life expectancy per country in two years.
    Dumbbell,
    /// One value on a gauge.
    Gauge,
    /// A project plan, written in the gallery's .slint file.
    Gantt,
    /// Measures against their targets.
    Bullet,
    /// Sensors streaming new values.
    Live,
    /// Daily prices of a made-up stock, with a moving average.
    Candles,
    /// Goals reached, and survey shares, as radial bars.
    RadialBar,
    /// Segmented rings colored by category.
    SegmentedRing,
    /// Segmented rings colored on a scale.
    SegmentedScale,
    /// Tile grids on a scale.
    TileScale,
    /// Tile grids by category.
    TileClasses,
}

/// Population in millions (2025 estimates), by continent.
const POPULATION: [(&str, &str, f32); 18] = [
    ("Asia", "India", 1464.0),
    ("Asia", "China", 1416.0),
    ("Asia", "Indonesia", 285.0),
    ("Asia", "Pakistan", 255.0),
    ("Asia", "Bangladesh", 175.0),
    ("Asia", "Japan", 123.0),
    ("Asia", "Philippines", 116.0),
    ("Africa", "Nigeria", 237.0),
    ("Africa", "Ethiopia", 135.0),
    ("Africa", "Egypt", 118.0),
    ("Africa", "DR Congo", 112.0),
    ("Americas", "United States", 347.0),
    ("Americas", "Brazil", 212.0),
    ("Americas", "Mexico", 132.0),
    ("Europe", "Russia", 144.0),
    ("Europe", "Germany", 84.0),
    ("Europe", "United Kingdom", 70.0),
    ("Europe", "France", 66.0),
];

/// The region of each country of `POPULATION`, for the sunburst.
const REGIONS: [&str; 18] = [
    "South Asia",
    "East Asia",
    "Southeast Asia",
    "South Asia",
    "South Asia",
    "East Asia",
    "Southeast Asia",
    "West Africa",
    "East Africa",
    "North Africa",
    "Central Africa",
    "North America",
    "South America",
    "North America",
    "Eastern Europe",
    "Western Europe",
    "Western Europe",
    "Western Europe",
];

/// Website visitors through the steps to a purchase.
/// The survey's answers, and their colors: a fade from dark blue (every
/// day) to light blue (never), brightest first in dark mode. Both ramps were
/// checked for even steps and contrast against the background.
const ANSWER_ORDER: [&str; 5] = ["Every day", "Most days", "Some days", "Rarely", "Never"];
const SURVEY_LIGHT: [u32; 5] = [0x172f73, 0x1d4ed8, 0x3b7ef0, 0x5f9cf2, 0x86b6ef];
const SURVEY_DARK: [u32; 5] = [0xdbeafe, 0x93c5fd, 0x60a5fa, 0x3b82f6, 0x1d4ed8];

const FUNNEL: [(&str, f32); 5] = [
    ("Visited the site", 12_400.0),
    ("Viewed a product", 7_350.0),
    ("Added to cart", 3_120.0),
    ("Started checkout", 1_840.0),
    ("Purchased", 1_150.0),
];

/// A profit and loss statement, in thousands; `true` marks the totals.
const PROFIT_AND_LOSS: [(&str, f32, bool); 9] = [
    ("Revenue", 420.0, false),
    ("Cost of sales", -185.0, false),
    ("Gross profit", 0.0, true),
    ("Marketing", -48.0, false),
    ("R&D", -62.0, false),
    ("Admin", -31.0, false),
    ("Operating profit", 0.0, true),
    ("Tax", -22.0, false),
    ("Net profit", 0.0, true),
];

/// The regions of the matrix sample.
const SALES_REGIONS: [&str; 6] = [
    "N. America",
    "Europe",
    "Asia Pacific",
    "Latin America",
    "Middle East",
    "Africa",
];

/// Sales per product and region in millions of dollars (made up), in the
/// order of `SALES_REGIONS`; NaN where a product isn't sold.
const SALES: [(&str, [f32; 6]); 8] = [
    ("Phones", [610.0, 540.0, 890.0, 210.0, 160.0, 120.0]),
    ("Laptops", [420.0, 360.0, 510.0, 95.0, 70.0, 38.0]),
    ("Accessories", [240.0, 210.0, 300.0, 80.0, 55.0, 45.0]),
    ("Headphones", [210.0, 190.0, 260.0, 60.0, 45.0, 30.0]),
    ("Tablets", [180.0, 150.0, 220.0, 40.0, 35.0, 18.0]),
    ("Smartwatches", [160.0, 120.0, 180.0, 35.0, 40.0, f32::NAN]),
    ("Monitors", [150.0, 140.0, 190.0, 30.0, 25.0, 12.0]),
    ("Cameras", [90.0, 85.0, 140.0, 15.0, f32::NAN, f32::NAN]),
];

/// Life expectancy at birth in years, in 2000 and 2023 (rounded estimates).
const LIFE_EXPECTANCY: [(&str, f32, f32); 8] = [
    ("Japan", 81.1, 84.7),
    ("Norway", 78.7, 83.3),
    ("China", 71.4, 78.6),
    ("United States", 76.6, 78.4),
    ("Brazil", 70.1, 75.8),
    ("India", 62.7, 72.0),
    ("South Africa", 56.0, 65.0),
    ("Nigeria", 46.3, 54.5),
];

/// Samples shown as tabs of one sidebar entry: the entry's title, and each
/// sample's id and tab title. The first sample is the one the entry opens.
const TAB_GROUPS: &[(&str, &[(&str, &str)])] = &[
    (
        "Segmented ring charts",
        &[
            ("segmented-ring-classes", "By category"),
            ("segmented-ring-scale", "On a scale"),
        ],
    ),
    (
        "Tile grid charts",
        &[
            ("tile-grid-scale", "On a scale"),
            ("tile-grid-classes", "By category"),
        ],
    ),
];

/// The tab group of the sample `id`, if it is in one.
fn tab_group(id: &str) -> Option<&'static (&'static str, &'static [(&'static str, &'static str)])> {
    TAB_GROUPS
        .iter()
        .find(|(_, tabs)| tabs.iter().any(|(tab, _)| *tab == id))
}

struct Sample {
    id: &'static str,
    category: &'static str,
    title: &'static str,
    description: &'static str,
    shape: Shape,
    actions: &'static [&'static str],
}

const fn sample(
    id: &'static str,
    category: &'static str,
    title: &'static str,
    description: &'static str,
    shape: Shape,
    actions: &'static [&'static str],
) -> Sample {
    Sample {
        id,
        category,
        title,
        description,
        shape,
        actions,
    }
}

const MONTHLY: Shape = Shape::Months {
    datasets: 2,
    min: -100.0,
    max: 100.0,
};

const SAMPLES: &[Sample] = &[
    sample(
        "bar-vertical",
        "Bar charts",
        "Vertical bar chart",
        "Grouped bars with a shared value axis. Hover a month to compare the datasets.",
        MONTHLY,
        DATA_ACTIONS,
    ),
    sample(
        "bar-horizontal",
        "Bar charts",
        "Horizontal bar chart",
        "HorizontalBarChart: the categories run down the left side. The legend is on the right, or above the chart on narrow screens.",
        MONTHLY,
        DATA_ACTIONS,
    ),
    sample(
        "bar-stacked",
        "Bar charts",
        "Stacked bar chart",
        "stacked: true. Positive and negative values stack separately.",
        Shape::Months {
            datasets: 3,
            min: -100.0,
            max: 100.0,
        },
        DATA_ACTIONS,
    ),
    sample(
        "bar-border-radius",
        "Bar charts",
        "Bar chart border radius",
        "bar-radius and bar-border-width round the bars and give them a solid outline.",
        MONTHLY,
        DATA_ACTIONS,
    ),
    sample(
        "line",
        "Line charts",
        "Line chart",
        "Smooth lines with point markers (tension: 0.4).",
        MONTHLY,
        DATA_ACTIONS,
    ),
    sample(
        "line-interpolation",
        "Line charts",
        "Interpolation modes",
        "The same values drawn with tension 0 (straight segments) and 0.4 (smooth curves).",
        MONTHLY,
        &["Randomize"],
    ),
    sample(
        "line-stepped",
        "Line charts",
        "Stepped line chart",
        "stepped: true draws the values as steps.",
        Shape::Months {
            datasets: 1,
            min: -100.0,
            max: 100.0,
        },
        &["Randomize", "Steps on", "Steps off"],
    ),
    sample(
        "line-points",
        "Line charts",
        "Line chart without points",
        "show-points: false. Hovering still marks the values of every line.",
        MONTHLY,
        DATA_ACTIONS,
    ),
    sample(
        "bubble",
        "Other charts",
        "Bubble chart",
        "Points with a radius in pixels. Scroll to zoom.",
        Shape::Bubbles,
        DATA_ACTIONS,
    ),
    sample(
        "combo-bar-line",
        "Other charts",
        "Combo bar and line",
        "A bar chart with one dataset drawn as a line (series-type: line).",
        Shape::Months {
            datasets: 3,
            min: -100.0,
            max: 100.0,
        },
        DATA_ACTIONS,
    ),
    sample(
        "doughnut",
        "Other charts",
        "Doughnut chart",
        "Hovered slices move outwards. Click a legend entry to hide a slice.",
        Shape::Slices,
        DATA_ACTIONS,
    ),
    sample(
        "pie",
        "Other charts",
        "Pie chart",
        "Hovered slices move outwards. Click a legend entry to hide a slice.",
        Shape::Slices,
        DATA_ACTIONS,
    ),
    sample(
        "polar-area",
        "Other charts",
        "Polar area chart",
        "Equal angles; the radius shows the value.",
        Shape::Slices,
        DATA_ACTIONS,
    ),
    sample(
        "radial-bar",
        "Other charts",
        "Radial bar charts",
        "RadialBarChart: one ring per bar, filled in proportion to its value, with the labels in the opening. Daily goals against a fixed maximum of 100%, and survey answers against the largest share. Randomize moves the bars to new values.",
        Shape::RadialBar,
        &["Randomize"],
    ),
    sample(
        "radar",
        "Other charts",
        "Radar chart",
        "One spoke per label. Hover a spoke to compare the datasets.",
        Shape::Skills,
        DATA_ACTIONS,
    ),
    sample(
        "scatter",
        "Other charts",
        "Scatter chart",
        "Numeric x and y axes. Hover finds the nearest point; scroll to zoom.",
        Shape::Points,
        DATA_ACTIONS,
    ),
    sample(
        "stacked-bar-line",
        "Other charts",
        "Stacked bar and line",
        "Stacked bars with a line on top. Lines and bars stack separately.",
        Shape::Months {
            datasets: 3,
            min: 0.0,
            max: 100.0,
        },
        DATA_ACTIONS,
    ),
    sample(
        "area-line",
        "Area charts",
        "Line chart with fill",
        "fill: true fills the area under a line.",
        MONTHLY,
        DATA_ACTIONS,
    ),
    sample(
        "area-stacked",
        "Area charts",
        "Stacked area chart",
        "Stacked lines with fill: each area fills down to the one below.",
        Shape::Months {
            datasets: 3,
            min: 0.0,
            max: 100.0,
        },
        DATA_ACTIONS,
    ),
    sample(
        "area-radar",
        "Area charts",
        "Radar chart with fill",
        "Filled radar polygons.",
        Shape::Skills,
        DATA_ACTIONS,
    ),
    sample(
        "legend-position",
        "Legend",
        "Legend position",
        "legend-position places the legend on any side of the chart.",
        MONTHLY,
        &[
            "Position: top",
            "Position: right",
            "Position: bottom",
            "Position: left",
        ],
    ),
    sample(
        "axes-format",
        "Axes",
        "Titles, formats and data labels",
        "x-title, y-title, value-prefix and value-decimals, with show-values writing each value on its bar. Click the chart and use the arrow keys.",
        Shape::Months {
            datasets: 2,
            min: 1000.0,
            max: 9000.0,
        },
        DATA_ACTIONS,
    ),
    sample(
        "axes-fixed",
        "Axes",
        "Fixed range",
        "fixed-range with min-value and max-value: the axis stays put when the data changes.",
        MONTHLY,
        DATA_ACTIONS,
    ),
    sample(
        "axes-log",
        "Axes",
        "Logarithmic axis",
        "logarithmic: true. Values from 1 to 10,000 on a log scale.",
        Shape::Exponential,
        &["Randomize"],
    ),
    sample(
        "axes-two",
        "Axes",
        "Two value axes",
        "right-axis puts a dataset on a second value axis, with its own y2-title and y2-value-suffix. Its ticks line up with the left axis' grid.",
        Shape::Months {
            datasets: 2,
            min: 0.0,
            max: 1.0,
        },
        &["Randomize"],
    ),
    sample(
        "survey",
        "Bar charts",
        "100% stacked bars",
        "stacked-percent: each row adds up to 100%, with the shares written in the bars. Ordered answers get one hue, from dark blue (every day) to light blue (never).",
        Shape::Survey,
        &["Randomize"],
    ),
    sample(
        "time-hourly",
        "Time series",
        "Hourly time series",
        "TimeSeriesChart: x values are seconds after time-origin. Two weeks of hourly values; scroll to zoom into hours.",
        Shape::TimeSeries {
            count: 24 * 14,
            step: 3600.0,
        },
        &["Randomize"],
    ),
    sample(
        "time-week",
        "Time series",
        "One week, every 15 minutes",
        "A week of electricity use, Monday to Sunday: the axis shows days, and zooming in shows hours and minutes.",
        Shape::TimeSeries {
            count: 7 * 96,
            step: 900.0,
        },
        &["Week", "Day", "6 hours", "1 hour", "Randomize"],
    ),
    sample(
        "time-daily",
        "Time series",
        "Daily time series",
        "A year of daily values; the axis shows months, and zooming in shows days.",
        Shape::TimeSeries {
            count: 365,
            step: 86_400.0,
        },
        &["Randomize"],
    ),
    sample(
        "candlestick",
        "Time series",
        "Candlestick chart",
        "CandlestickChart: half a year of daily prices and volumes of a made-up stock, with a 20-day moving average and the last price. Weekends and holidays are skipped; Linear time shows them as gaps. Scroll to zoom; on a narrow screen, candles merge into longer periods.",
        Shape::Candles,
        &["Candles", "OHLC", "Skip gaps", "Linear time", "Randomize"],
    ),
    sample(
        "live",
        "Time series",
        "Live data",
        "Three sensors stream new values into ring buffers (StreamModel in the gallery's source), keeping the last minute. Hover still works while it streams.",
        Shape::Live,
        LIVE_ACTIONS,
    ),
    sample(
        "heatmap",
        "Heatmaps",
        "Heatmap",
        "HeatmapChart: website visits by weekday, in two-hour blocks, with the count in each cell. Darker cells have higher values.",
        Shape::Matrix,
        &["Randomize"],
    ),
    sample(
        "heatmap-diverging",
        "Heatmaps",
        "Diverging heatmap",
        "A correlation matrix: diverging around 0, with a fixed range of -1 to 1 and values in the cells.",
        Shape::Correlation,
        &["Randomize"],
    ),
    sample(
        "matrix",
        "Heatmaps",
        "Matrix",
        "MatrixChart: sales by product and region as circles, their area proportional to the value, colored by growth on last year: blue for growth, red for decline. Totals at the edges; a dash where a product isn't sold (show-empty). Randomize changes the numbers.",
        Shape::Sales,
        &["Randomize"],
    ),
    sample(
        "calendar",
        "Heatmaps",
        "Calendar heatmap",
        "CalendarHeatmap: a year of daily values, like GitHub's contribution graph. It follows the theme; pick other colors with Colors.",
        Shape::Calendar,
        &["Randomize"],
    ),
    sample(
        "segmented-ring-classes",
        "Heatmaps",
        "Segmented rings by category",
        "SegmentedRingChart by category: each value of the matrix is a category index (0, 1, 2) into classes, and the categories make the legend. One ring per row and one segment per column, so each chart takes its size from its data: runs every half hour for a week (7 × 48), a year of uptime with a ring per month of 28 to 31 days, three habits over 30 days, and one ring of pipeline steps. Randomize gives new data, and the runs a new size.",
        Shape::SegmentedRing,
        &["Randomize"],
    ),
    sample(
        "segmented-ring-scale",
        "Heatmaps",
        "Segmented rings on a scale",
        "SegmentedRingChart with values on a color scale, as in a heatmap. One ring per row and one segment per column, so each chart takes its size from its data: website visits by weekday and hour (7 × 24), ten years of temperatures on a diverging scale (10 × 12), CPU load of 8 cores over an hour (8 × 60), and steps per day as a single ring of 31 days. Randomize gives new data.",
        Shape::SegmentedScale,
        &["Randomize"],
    ),
    sample(
        "tile-grid-scale",
        "Heatmaps",
        "Tile grids on a scale",
        "TileGridChart with values on a color scale, as in a heatmap: a matrix as rows of rounded squares, one per value, taking its data as a SegmentedRingChart does and its size from the matrix. Practice hours over a quarter that began a month ago (7 × 13, empty weeks as the track), contributions over half a year (7 × 26), the load of 8 servers each half hour of a day (8 × 48), and ten years of temperatures on a diverging scale (10 × 12). Randomize gives new data.",
        Shape::TileScale,
        &["Randomize"],
    ),
    sample(
        "tile-grid-classes",
        "Heatmaps",
        "Tile grids by category",
        "TileGridChart by category: each value of the matrix is a category index into classes, and the categories make the legend; -1 or NaN is an empty tile. The status of six services by day (6 × 30), test suites over the last 20 builds (12 × 20), room bookings in half hours (5 × 20), and seats sold in a theater whose rows grow longer towards the back. Randomize gives new data.",
        Shape::TileClasses,
        &["Randomize"],
    ),
    sample(
        "treemap",
        "Treemaps and sunbursts",
        "Treemap",
        "TreemapChart: areas proportional to the values, grouped by continent. Click a legend entry to hide a continent.",
        Shape::Treemap,
        &["Randomize"],
    ),
    sample(
        "sunburst",
        "Treemaps and sunbursts",
        "Sunburst",
        "SunburstChart: continents, regions and countries as rings. Click a continent or region to zoom in, and the center to zoom out.",
        Shape::Sunburst,
        &["Randomize"],
    ),
    sample(
        "funnel",
        "Business charts",
        "Funnel",
        "FunnelChart: one curved funnel fading down from the theme color, with each stage's share of the first and conversion badges.",
        Shape::Funnel,
        &["Randomize"],
    ),
    sample(
        "waterfall",
        "Business charts",
        "Waterfall",
        "WaterfallChart: increases, decreases and totals of a profit and loss statement.",
        Shape::Waterfall,
        &["Randomize"],
    ),
    sample(
        "dumbbell",
        "Business charts",
        "Dumbbell",
        "DumbbellChart: two values per category, here life expectancy in 2000 and 2023.",
        Shape::Dumbbell,
        &["Randomize"],
    ),
    sample(
        "gauge",
        "Business charts",
        "Gauges",
        "GaugeChart: a filled arc with rounded ends, the same with a ring of bands, and a needle with ticks over the bands.",
        Shape::Gauge,
        &["Randomize"],
    ),
    sample(
        "bullet",
        "Business charts",
        "Bullet charts",
        "BulletChart: a KPI panel with an axis per row, columns on one axis, and rows without a target. Bands are shades of gray; bars take the theme's colors, and rows below target its decrease color.",
        Shape::Bullet,
        &["Randomize"],
    ),
    sample(
        "gantt",
        "Business charts",
        "Gantt",
        "GanttChart: a release plan in four groups, with progress written after each bar, milestones and a line at today. Click a task to edit it. Scroll to zoom, drag to pan.",
        Shape::Gantt,
        &["Reset"],
    ),
    sample(
        "pie-labels",
        "Other charts",
        "Pie chart with data labels",
        "show-percentages writes each slice's share on it.",
        Shape::Slices,
        DATA_ACTIONS,
    ),
    sample(
        "zoom",
        "Advanced",
        "Zoom and pan",
        "zoom-enabled: true. Scroll to zoom around the mouse, drag to pan, double-click to reset.",
        Shape::Series { count: 500 },
        &["Randomize", "Reset zoom"],
    ),
    sample(
        "decimation",
        "Advanced",
        "Data decimation",
        "100,000 points per dataset. decimate: true draws one span per pixel column; zoom in to see the details.",
        Shape::Series { count: 100_000 },
        &["Decimation on", "Decimation off", "Randomize"],
    ),
    sample(
        "languages",
        "Advanced",
        "Languages",
        "ChartTheme.language: numbers, percentages, month names and the charts' own texts in 14 languages. The chart's title and dataset names are translated by the app.",
        Shape::Months {
            datasets: 2,
            min: 0.0,
            max: 1.0,
        },
        &["Randomize"],
    ),
];

/// The random data's seed, so the samples start the same every time.
const SEED: u64 = 0x2545_f491_4f6c_dd1d;

/// Small xorshift generator, so the example needs no extra dependencies.
struct Rng(u64);

impl Rng {
    fn next(&mut self) -> f32 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        (self.0 >> 40) as f32 / (1u64 << 24) as f32
    }

    fn range(&mut self, min: f32, max: f32) -> f32 {
        (min + self.next() * (max - min)).round()
    }
}

fn strings<'a>(items: impl IntoIterator<Item = &'a str>) -> ModelRc<SharedString> {
    ModelRc::new(VecModel::from(
        items
            .into_iter()
            .map(SharedString::from)
            .collect::<Vec<_>>(),
    ))
}

fn floats(values: Vec<f32>) -> ModelRc<f32> {
    ModelRc::new(VecModel::from(values))
}

/// The data of the sample on screen, and how to change it.
struct State {
    ui: slint::Weak<Gallery>,
    rng: Rng,
    sample: &'static Sample,
    labels: Rc<VecModel<SharedString>>,
    datasets: Rc<VecModel<ChartDataset>>,
    slices: Rc<VecModel<ChartSlice>>,
    /// The second radial bar chart's bars.
    channels: Rc<VecModel<ChartSlice>>,
    /// Heatmap rows, and heatmap or calendar values.
    row_labels: Rc<VecModel<SharedString>>,
    grid: Rc<VecModel<f32>>,
    /// The matrix sample's growth per cell, which colors it.
    growth: Rc<VecModel<f32>>,
    tree: Rc<VecModel<ChartTreemapItem>>,
    sun: Rc<VecModel<ChartSunburstItem>>,
    steps: Rc<VecModel<ChartWaterfallStep>>,
    candles: Rc<VecModel<ChartCandle>>,
    gantt: Rc<VecModel<ChartGanttTask>>,
    /// Whether Randomize was pressed, for samples that start with real data.
    randomized: bool,
    live: Live,
}

impl State {
    fn values(&mut self, count: usize) -> Vec<f32> {
        let (min, max) = match self.sample.shape {
            Shape::Months { min, max, .. } => (min, max),
            _ => (10.0, 100.0),
        };
        (0..count).map(|_| self.rng.range(min, max)).collect()
    }

    fn walk(&mut self, count: usize, offset: f32) -> Vec<f32> {
        let mut v = offset;
        (0..count)
            .map(|_| {
                v += (self.rng.next() - 0.5) * 8.0 + (offset - v) * 0.01;
                v
            })
            .collect()
    }

    fn points(&mut self, count: usize, bubbles: bool) -> Vec<ChartXY> {
        (0..count)
            .map(|_| ChartXY {
                x: self.rng.range(-100.0, 100.0),
                y: self.rng.range(-100.0, 100.0),
                r: if bubbles {
                    self.rng.range(4.0, 20.0)
                } else {
                    0.0
                },
            })
            .collect()
    }

    /// Plausible temperatures every `step` seconds, starting at midnight in
    /// mid October: a yearly and a daily cycle around a city's mean, plus
    /// weather that drifts a few degrees and returns.
    fn temperatures(&mut self, count: usize, step: f32, city: usize) -> Vec<f32> {
        use std::f32::consts::TAU;
        // Oslo, then Bergen (milder winters, cooler summers), then others.
        let (mean, yearly) = [(6.5, 10.0), (8.0, 6.5)]
            .get(city)
            .copied()
            .unwrap_or((7.0, 8.0));
        let mut weather = 0.0f32;
        (0..count)
            .map(|i| {
                let seconds = i as f32 * step;
                let day = seconds / 86_400.0;
                // Warmest in mid July (day 196 of the year), coldest in mid
                // January; the samples start in mid October (about day 290).
                let season = yearly * (TAU * (day + 290.0 - 196.0) / 365.0).cos();
                // Warmest in the afternoon.
                let daily = if step < 86_400.0 {
                    -3.0 * (TAU * (day.fract() - 0.15)).cos()
                } else {
                    0.0
                };
                weather = weather * 0.97
                    + (self.rng.next() - 0.5) * if step < 86_400.0 { 0.6 } else { 2.5 };
                ((mean + season + daily + weather) * 10.0).round() / 10.0
            })
            .collect()
    }

    /// Electricity use in kW every `step` seconds, starting on a Monday at
    /// midnight. An office (`building` 0) is busy on weekdays from 8 to 17;
    /// a home (1) peaks in the morning and the evening, later at weekends.
    fn power(&mut self, count: usize, step: f32, building: usize) -> Vec<f32> {
        let bump = |hour: f32, at: f32, width: f32| (-((hour - at) / width).powi(2)).exp();
        (0..count)
            .map(|i| {
                let seconds = i as f32 * step;
                let day = (seconds / 86_400.0) as usize;
                let hour = seconds % 86_400.0 / 3600.0;
                let weekend = day >= 5;
                let noise = (self.rng.next() - 0.5) * 2.0;
                let kw = if building == 0 {
                    let open = !weekend && (8.0..17.0).contains(&hour);
                    // Servers and ventilation run all the time; a dip at lunch.
                    6.0 + if open {
                        28.0 - 6.0 * bump(hour, 12.0, 0.6)
                    } else {
                        0.0
                    } + noise * 0.6
                } else {
                    let morning = if weekend { 9.5 } else { 7.0 };
                    1.5 + 4.0 * bump(hour, morning, 1.0)
                        + 6.0 * bump(hour, 18.5, 1.6)
                        + if weekend {
                            2.5 * bump(hour, 13.0, 2.5)
                        } else {
                            0.0
                        }
                        + noise * 0.4
                };
                (kw.max(0.0) * 10.0).round() / 10.0
            })
            .collect()
    }

    /// Half a year of trading days of a made-up stock, from Monday 6 April
    /// 2026: a random walk with some drift, gaps at the open, a range around
    /// each day's move, and more shares traded on bigger moves. No trading
    /// at weekends and on the US market holidays. Empty for the other
    /// samples.
    fn stock(&mut self) {
        // Memorial Day, Juneteenth, Independence Day (observed), Labor Day.
        const HOLIDAYS: [usize; 4] = [49, 74, 88, 154];
        let mut candles = Vec::new();
        if self.sample.shape == Shape::Candles {
            let mut close = 120.0f32;
            for day in 0..183 {
                if day % 7 >= 5 || HOLIDAYS.contains(&day) {
                    continue;
                }
                let open = close * (1.0 + (self.rng.next() - 0.5) * 0.012);
                close = open * (1.0 + (self.rng.next() - 0.48) * 0.045);
                let reach = |rng: &mut Rng| close.max(open) * rng.next() * 0.015;
                let high = close.max(open) + reach(&mut self.rng);
                let low = close.min(open) - reach(&mut self.rng);
                let cents = |v: f32| (v * 100.0).round() / 100.0;
                let range = (high - low) / open;
                let volume = 2.0e6 * (0.6 + self.rng.next() * 0.5 + range * 40.0);
                candles.push(ChartCandle {
                    x: day as f32 * 86_400.0,
                    open: cents(open),
                    high: cents(high),
                    low: cents(low),
                    close: cents(close),
                    volume: (volume / 100.0).round() * 100.0,
                });
            }
        }
        self.candles.set_vec(candles);
    }

    /// The dataset at `index` of the current sample, with its style.
    fn dataset(&mut self, index: usize) -> ChartDataset {
        let mut ds = ChartDataset {
            label: format!("Dataset {}", index + 1).into(),
            tension: 0.4,
            ..Default::default()
        };
        match self.sample.shape {
            Shape::Months { .. } | Shape::Skills => {
                ds.values = floats(self.values(self.labels.row_count()));
            }
            Shape::Points => ds.points = ModelRc::new(VecModel::from(self.points(30, false))),
            Shape::Bubbles => ds.points = ModelRc::new(VecModel::from(self.points(12, true))),
            Shape::Series { count } => {
                ds.values = floats(self.walk(count, 40.0 * index as f32));
                ds.tension = 0.0;
            }
            Shape::Exponential => {
                let growth = 1.0 + index as f32;
                let values = (0..self.labels.row_count())
                    .map(|i| {
                        (10f32.powf(i as f32 * 0.6 / growth + self.rng.next() * 0.4))
                            .round()
                            .max(1.0)
                    })
                    .collect();
                ds.values = floats(values);
            }
            Shape::TimeSeries { count, step } if self.sample.id == "time-week" => {
                let points: Vec<ChartXY> = self
                    .power(count, step, index)
                    .into_iter()
                    .enumerate()
                    .map(|(i, y)| ChartXY {
                        x: i as f32 * step,
                        y,
                        r: 0.0,
                    })
                    .collect();
                ds.points = ModelRc::new(VecModel::from(points));
                ds.fill = true;
                ds.label = (if index == 0 { "Office" } else { "Home" }).into();
            }
            Shape::TimeSeries { count, step } => {
                let points: Vec<ChartXY> = self
                    .temperatures(count, step, index)
                    .into_iter()
                    .enumerate()
                    .map(|(i, y)| ChartXY {
                        x: i as f32 * step,
                        y,
                        r: 0.0,
                    })
                    .collect();
                ds.points = ModelRc::new(VecModel::from(points));
                ds.tension = 0.3;
                ds.label = (if index == 0 { "Oslo" } else { "Bergen" }).into();
            }
            Shape::Survey => {
                ds.color = self.survey_color(index);
                // Made-up shares per department, varied a little by Randomize.
                const SHARES: [[f32; 5]; 6] = [
                    [24.0, 30.0, 28.0, 12.0, 6.0],
                    [18.0, 27.0, 31.0, 15.0, 9.0],
                    [5.0, 12.0, 34.0, 28.0, 21.0],
                    [10.0, 21.0, 35.0, 22.0, 12.0],
                    [8.0, 14.0, 23.0, 25.0, 30.0],
                    [12.0, 19.0, 33.0, 23.0, 13.0],
                ];
                ds.label = ANSWER_ORDER[index % 5].into();
                let values = SHARES
                    .iter()
                    .map(|row| (row[index % 5] * (0.8 + 0.4 * self.rng.next())).round())
                    .collect();
                ds.values = floats(values);
            }
            Shape::Dumbbell => {
                ds.label = (if index == 0 { "2000" } else { "2023" }).into();
                let values = LIFE_EXPECTANCY
                    .iter()
                    .map(|&(_, before, after)| {
                        let v = if index == 0 { before } else { after };
                        if self.randomized {
                            (v + (self.rng.next() - 0.5) * 4.0).round()
                        } else {
                            v
                        }
                    })
                    .collect();
                ds.values = floats(values);
            }
            _ => {}
        }
        match self.sample.id {
            "line-interpolation" => {
                ds.label = (if index == 0 {
                    "Straight (tension 0)"
                } else {
                    "Smooth (tension 0.4)"
                })
                .into();
                ds.tension = if index == 0 { 0.0 } else { 0.4 };
            }
            "line-stepped" => ds.stepped = true,
            "area-line" => ds.fill = index == 0,
            "area-stacked" | "area-radar" => ds.fill = true,
            "combo-bar-line" | "stacked-bar-line" if index == 0 => {
                ds.label = "Line".into();
                ds.series_type = ChartSeriesType::Line;
            }
            // Made-up website numbers: visitors as bars, in thousands, and
            // the conversion rate in percent as a line on the right axis.
            "languages" => {
                let months = self.labels.row_count();
                let values = (0..months)
                    .map(|_| {
                        if index == 0 {
                            self.rng.range(8_000.0, 25_000.0).round()
                        } else {
                            self.rng.range(15.0, 45.0) / 10.0
                        }
                    })
                    .collect();
                ds.values = floats(values);
                let (_, visitors, rate) = LANGUAGE_TEXTS[self.language()];
                if index == 0 {
                    ds.label = visitors.into();
                } else {
                    ds.label = rate.into();
                    ds.series_type = ChartSeriesType::Line;
                    ds.right_axis = true;
                }
            }
            // Made-up monthly weather: temperature as a line on the left
            // axis, rainfall as bars on the right one.
            "axes-two" => {
                let months = self.labels.row_count();
                let values = (0..months)
                    .map(|i| {
                        if index == 0 {
                            let season = ((i as f32 - 3.5) / 12.0 * std::f32::consts::TAU).sin();
                            ((7.0 + 9.0 * season + (self.rng.next() - 0.5) * 3.0) * 10.0).round()
                                / 10.0
                        } else {
                            self.rng.range(40.0, 140.0).round()
                        }
                    })
                    .collect();
                ds.values = floats(values);
                if index == 0 {
                    ds.label = "Temperature".into();
                    ds.series_type = ChartSeriesType::Line;
                    ds.tension = 0.4;
                } else {
                    ds.label = "Rainfall".into();
                    ds.right_axis = true;
                }
            }
            _ => {}
        }
        ds
    }

    fn slice(&mut self, index: usize) -> ChartSlice {
        ChartSlice {
            label: SLICE_NAMES[index % SLICE_NAMES.len()].into(),
            value: self.rng.range(5.0, 100.0),
            ..Default::default()
        }
    }

    fn survey_color(&self, index: usize) -> slint::Color {
        let dark = self.ui.upgrade().is_some_and(|ui| ui.get_dark_mode());
        let rgb = (if dark { SURVEY_DARK } else { SURVEY_LIGHT })[index % 5];
        slint::Color::from_rgb_u8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8)
    }

    /// The survey's colors have light and dark mode shades.
    fn recolor_survey(&mut self) {
        if self.sample.shape == Shape::Survey {
            self.update_datasets(|state, ds| {
                let index = ANSWER_ORDER
                    .iter()
                    .position(|a| ds.label == *a)
                    .unwrap_or(0);
                ds.color = state.survey_color(index);
            });
        }
    }

    /// Fills the heatmap or calendar values of the current sample.
    /// The segmented ring samples: four matrices of different sizes, one per
    /// chart, with their column and row labels and the text in the middle;
    /// colored by category or on a scale. Randomize gives new data, and the runs
    /// a new size.
    fn ring_data(&mut self, randomize: bool) {
        let Some(ui) = self.ui.upgrade() else {
            return;
        };
        let charts = if self.sample.shape == Shape::TileScale {
            [
                self.tile_practice(),
                self.tile_contributions(),
                self.tile_load(),
                self.ring_temperature(),
            ]
        } else if self.sample.shape == Shape::TileClasses {
            [
                self.tile_status(),
                self.tile_tests(),
                self.tile_rooms(),
                self.tile_seats(),
            ]
        } else if self.sample.shape == Shape::SegmentedScale {
            [
                self.ring_visits(),
                self.ring_temperature(),
                self.ring_cpu(),
                self.ring_steps(),
            ]
        } else {
            [
                self.ring_runs(randomize),
                self.ring_uptime(),
                self.ring_habits(),
                self.ring_pipeline(),
            ]
        };
        let strings = |items: Vec<String>| -> ModelRc<SharedString> {
            ModelRc::new(VecModel::from(
                items
                    .into_iter()
                    .map(SharedString::from)
                    .collect::<Vec<_>>(),
            ))
        };
        let mut values = Vec::new();
        let mut x_labels = Vec::new();
        let mut y_labels = Vec::new();
        let mut totals = Vec::new();
        for chart in charts {
            values.push(ModelRc::new(VecModel::from(
                chart.values.into_iter().map(floats).collect::<Vec<_>>(),
            )));
            x_labels.push(strings(chart.x_labels));
            y_labels.push(strings(chart.y_labels));
            totals.push(SharedString::from(chart.total));
        }
        ui.set_matrix_values(ModelRc::new(VecModel::from(values)));
        ui.set_matrix_x_labels(ModelRc::new(VecModel::from(x_labels)));
        ui.set_matrix_y_labels(ModelRc::new(VecModel::from(y_labels)));
        ui.set_matrix_totals(ModelRc::new(VecModel::from(totals)));
        self.ring_colors();
    }

    /// The categories' colors of the charts that pick their own: the
    /// segmented rings' runs, uptime and pipeline, and the tile grids'
    /// service status and tests, and the practice tile grid's scale.
    /// "Theme colors" leaves them unset, so the library uses the theme's
    /// (the practice grid takes the theme's first color); "Custom colors"
    /// sets them.
    fn ring_colors(&self) {
        let Some(ui) = self.ui.upgrade() else {
            return;
        };
        let classes = if ui.get_ring_colors() == 0 {
            [[slint::Color::default(); 3]; 5]
        } else {
            [
                [0xc6f432, 0xf0904a, 0xe0636b].map(rgb),
                [0x2fb67c, 0xf2b33d, 0xe0636b].map(rgb),
                [0x2fb67c, 0x3d8bf2, 0xe0636b].map(rgb),
                [0x2fb67c, 0xf2b33d, 0xe0636b].map(rgb),
                [0x2fb67c, 0xf2b33d, 0xe0636b].map(rgb),
            ]
        };
        ui.set_tile_color(if ui.get_ring_colors() == 0 {
            let colors = ui.global::<ChartTheme>().get_colors();
            colors.row_data(0).unwrap_or_default()
        } else {
            rgb(0xe8916a)
        });
        ui.set_ring_class_colors(ModelRc::new(VecModel::from(
            classes
                .iter()
                .map(|c| ModelRc::new(VecModel::from(c.to_vec())))
                .collect::<Vec<_>>(),
        )));
    }

    /// Runs every half hour for a week, by category: 0 on its own, 1 needed
    /// you, 2 failed. Today, the inner ring, has only run up to the time of
    /// day. Randomized, from 3 to 7 days of runs every 15 minutes to every 2
    /// hours.
    fn ring_runs(&mut self, randomize: bool) -> RingSample {
        let (days, per_day) = if randomize {
            let days = (3 + (self.rng.next() * 5.0) as usize).min(7);
            (days, [12, 24, 48, 96][(self.rng.next() * 4.0) as usize % 4])
        } else {
            (7, 48)
        };
        let now = (per_day as f32 * (0.45 + self.rng.next() * 0.4)) as usize;
        let mut runs = 0;
        let values = (0..days)
            .map(|day| {
                (0..per_day)
                    .map(|slot| {
                        if day == days - 1 && slot >= now || self.rng.next() < 0.03 {
                            return f32::NAN;
                        }
                        runs += 1;
                        let r = self.rng.next();
                        if r < 0.03 {
                            2.0
                        } else if r < 0.13 {
                            1.0
                        } else {
                            0.0
                        }
                    })
                    .collect()
            })
            .collect();
        let minutes = 24 * 60 / per_day;
        RingSample {
            values,
            x_labels: (0..per_day)
                .map(|slot| format!("{:02}:{:02}", slot * minutes / 60, slot * minutes % 60))
                .collect(),
            y_labels: WEEKDAYS[7 - days..].iter().map(|d| d.to_string()).collect(),
            total: runs.to_string(),
        }
    }

    /// Website visits by weekday and hour, on a scale: busy in the working
    /// day, quieter at the weekend.
    fn ring_visits(&mut self) -> RingSample {
        let mut total = 0.0;
        let values = (0..7)
            .map(|day| {
                let weekend = if day >= 5 { 0.55 } else { 1.0 };
                (0..24)
                    .map(|hour| {
                        let h = hour as f32;
                        let day_curve = (-(h - 13.0).powi(2) / 18.0).exp();
                        let evening = 0.5 * (-(h - 20.0).powi(2) / 6.0).exp();
                        let v = (40.0
                            + 900.0
                                * weekend
                                * (day_curve + evening)
                                * (0.8 + 0.4 * self.rng.next()))
                        .round();
                        total += v;
                        v
                    })
                    .collect()
            })
            .collect();
        RingSample {
            values,
            x_labels: (0..24).map(|h| h.to_string()).collect(),
            y_labels: WEEKDAYS.iter().map(|d| d.to_string()).collect(),
            total: format!("{:.1}k", total / 1000.0),
        }
    }

    /// A year of a service's days, one ring per month: rows as long as the
    /// months, so the rings are ragged. 0 up, 1 degraded, 2 down.
    fn ring_uptime(&mut self) -> RingSample {
        const LENGTHS: [usize; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        let mut bad = 0.0;
        let values: Vec<Vec<f32>> = LENGTHS
            .iter()
            .map(|&days| {
                (0..days)
                    .map(|_| {
                        let r = self.rng.next();
                        if r < 0.012 {
                            bad += 1.0;
                            2.0
                        } else if r < 0.05 {
                            bad += 0.25;
                            1.0
                        } else {
                            0.0
                        }
                    })
                    .collect()
            })
            .collect();
        RingSample {
            values,
            x_labels: (1..=31).map(|d| d.to_string()).collect(),
            y_labels: SHORT_MONTHS.iter().map(|m| m.to_string()).collect(),
            total: format!("{:.1}%", 100.0 - bad / 365.0 * 100.0),
        }
    }

    /// Ten years of monthly temperatures against the normal, in degrees,
    /// on a diverging scale: warming over the years.
    fn ring_temperature(&mut self) -> RingSample {
        let values: Vec<Vec<f32>> = (0..10)
            .map(|year| {
                (0..12)
                    .map(|_| {
                        let v = -0.4 + year as f32 * 0.14 + (self.rng.next() - 0.5) * 1.4;
                        (v * 10.0).round() / 10.0
                    })
                    .collect()
            })
            .collect();
        let last: f32 = values[9].iter().sum::<f32>() / 12.0;
        RingSample {
            values,
            x_labels: SHORT_MONTHS.iter().map(|m| m.to_string()).collect(),
            y_labels: (2016..2026).map(|y| y.to_string()).collect(),
            total: format!("{last:+.1}°"),
        }
    }

    /// Hours of practice each day of a quarter, a column per week: begun
    /// four weeks ago, so the first weeks are empty, with a few days in the
    /// week before.
    fn tile_practice(&mut self) -> RingSample {
        let values = (0..7)
            .map(|day| {
                (0..13)
                    .map(|week| match week {
                        0..=7 => f32::NAN,
                        8 if matches!(day, 1 | 3 | 4) => {
                            0.5 + (self.rng.next() * 2.0).round() * 0.5
                        }
                        8 => f32::NAN,
                        _ => 1.0 + (self.rng.next() * 6.0).round() * 0.5,
                    })
                    .collect()
            })
            .collect();
        RingSample {
            values,
            x_labels: (1..=13).map(|w| format!("Week {w}")).collect(),
            y_labels: WEEKDAYS.iter().map(|d| d.to_string()).collect(),
            total: String::new(),
        }
    }

    /// Contributions each day over half a year, a column per week; quieter
    /// at the weekend, with some days off.
    fn tile_contributions(&mut self) -> RingSample {
        let values = (0..7)
            .map(|day| {
                (0..26)
                    .map(|_| {
                        let r = self.rng.next();
                        if r < if day >= 5 { 0.6 } else { 0.2 } {
                            0.0
                        } else {
                            (1.0 + self.rng.next() * 11.0).round()
                        }
                    })
                    .collect()
            })
            .collect();
        RingSample {
            values,
            x_labels: (1..=26).map(|w| format!("Week {w}")).collect(),
            y_labels: WEEKDAYS.iter().map(|d| d.to_string()).collect(),
            total: String::new(),
        }
    }

    /// The load of 8 servers each half hour of a day, in percent: busy in
    /// the working day, with a nightly batch on the first two.
    fn tile_load(&mut self) -> RingSample {
        let values = (0..8)
            .map(|server| {
                (0..48)
                    .map(|slot| {
                        let h = slot as f32 / 2.0;
                        let day = 70.0 * (-(h - 14.0).powi(2) / 16.0).exp();
                        let batch = if server < 2 {
                            60.0 * (-(h - 3.0).powi(2) / 2.0).exp()
                        } else {
                            0.0
                        };
                        (5.0 + day + batch + self.rng.next() * 15.0)
                            .min(100.0)
                            .round()
                    })
                    .collect()
            })
            .collect();
        RingSample {
            values,
            x_labels: (0..48)
                .map(|s| format!("{:02}:{:02}", s / 2, s % 2 * 30))
                .collect(),
            y_labels: (1..=8).map(|n| format!("Server {n}")).collect(),
            total: String::new(),
        }
    }

    /// Twelve test suites over the last 20 builds: 0 passed, 1 flaky,
    /// 2 failed; a suite added later has no results for the first builds.
    fn tile_tests(&mut self) -> RingSample {
        const SUITES: [&str; 12] = [
            "Unit",
            "Layout",
            "Axes",
            "Legend",
            "Tooltips",
            "Zoom",
            "Keyboard",
            "Themes",
            "Locales",
            "Screenshots",
            "Fuzz",
            "Wasm",
        ];
        let values = (0..SUITES.len())
            .map(|suite| {
                (0..20)
                    .map(|build| {
                        if suite == 11 && build < 6 {
                            return f32::NAN;
                        }
                        let r = self.rng.next();
                        if r < 0.04 {
                            2.0
                        } else if r < 0.12 {
                            1.0
                        } else {
                            0.0
                        }
                    })
                    .collect()
            })
            .collect();
        RingSample {
            values,
            x_labels: (181..=200).map(|b| format!("#{b}")).collect(),
            y_labels: SUITES.map(String::from).to_vec(),
            total: String::new(),
        }
    }

    /// Five rooms booked in half hours from 08:00 to 18:00: 0 booked,
    /// 1 tentative, -1 free; meetings are an hour or two.
    fn tile_rooms(&mut self) -> RingSample {
        let values = (0..5)
            .map(|_| {
                let mut row = vec![-1.0f32; 20];
                let mut slot = (self.rng.next() * 3.0) as usize;
                while slot < 20 {
                    let length = 2 + (self.rng.next() * 3.0) as usize;
                    let class = if self.rng.next() < 0.2 { 1.0 } else { 0.0 };
                    for cell in row.iter_mut().skip(slot).take(length) {
                        *cell = class;
                    }
                    slot += length + (self.rng.next() * 4.0) as usize;
                }
                row
            })
            .collect();
        RingSample {
            values,
            x_labels: (0..20)
                .map(|s| format!("{:02}:{:02}", 8 + s / 2, s % 2 * 30))
                .collect(),
            y_labels: ["Fjord", "Glacier", "Aurora", "Harbor", "Summit"]
                .map(String::from)
                .to_vec(),
            total: String::new(),
        }
    }

    /// Six services by day over 30 days: 0 up, 1 degraded, 2 down.
    fn tile_status(&mut self) -> RingSample {
        let values = (0..6)
            .map(|_| {
                (0..30)
                    .map(|_| {
                        let r = self.rng.next();
                        if r < 0.03 {
                            2.0
                        } else if r < 0.1 {
                            1.0
                        } else {
                            0.0
                        }
                    })
                    .collect()
            })
            .collect();
        RingSample {
            values,
            x_labels: (1..=30).map(|d| d.to_string()).collect(),
            y_labels: ["API", "Web", "Search", "Payments", "Email", "Storage"]
                .map(String::from)
                .to_vec(),
            total: String::new(),
        }
    }

    /// Seats in a theater, a row of tiles per row of seats, the rows longer
    /// towards the back: 0 sold, 1 reserved, -1 free.
    fn tile_seats(&mut self) -> RingSample {
        const LENGTHS: [usize; 10] = [10, 12, 14, 14, 16, 16, 18, 18, 18, 18];
        let values = LENGTHS
            .iter()
            .enumerate()
            .map(|(row, &seats)| {
                // The middle rows sell first.
                let demand = 0.85 - (row as f32 - 4.5).abs() * 0.08;
                (0..seats)
                    .map(|_| {
                        let r = self.rng.next();
                        if r < demand {
                            0.0
                        } else if r < demand + 0.08 {
                            1.0
                        } else {
                            -1.0
                        }
                    })
                    .collect()
            })
            .collect();
        RingSample {
            values,
            x_labels: (1..=18).map(|n| n.to_string()).collect(),
            y_labels: ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K"]
                .map(String::from)
                .to_vec(),
            total: String::new(),
        }
    }

    /// The CPU load of 8 cores, in percent, each minute of an hour: busy
    /// spells shared by the cores, with one core often busier.
    fn ring_cpu(&mut self) -> RingSample {
        let spells: Vec<f32> = (0..60)
            .map(|minute| {
                let m = minute as f32;
                55.0 * (-(m - 18.0).powi(2) / 30.0).exp()
                    + 70.0 * (-(m - 44.0).powi(2) / 20.0).exp()
            })
            .collect();
        let mut sum = 0.0;
        let values = (0..8)
            .map(|core| {
                let extra = if core == 0 { 20.0 } else { 0.0 };
                spells
                    .iter()
                    .map(|&spell| {
                        let v = (4.0 + spell + extra + self.rng.next() * 12.0)
                            .min(100.0)
                            .round();
                        sum += v;
                        v
                    })
                    .collect()
            })
            .collect();
        RingSample {
            values,
            x_labels: (0..60).map(|m| format!(":{m:02}")).collect(),
            y_labels: (0..8).map(|c| format!("Core {c}")).collect(),
            total: format!("{:.0}%", sum / 480.0),
        }
    }

    /// Steps each day of a month, as one ring of 31 days.
    fn ring_steps(&mut self) -> RingSample {
        let values: Vec<f32> = (0..31)
            .map(|day| {
                let weekend = matches!(day % 7, 5 | 6);
                let base = if weekend { 4000.0 } else { 7500.0 };
                (base + self.rng.next() * 7000.0).round()
            })
            .collect();
        let average = values.iter().sum::<f32>() / 31.0;
        RingSample {
            values: vec![values],
            x_labels: (1..=31).map(|d| format!("Oct {d}")).collect(),
            y_labels: vec!["Steps".into()],
            total: format!("{:.1}k", average / 1000.0),
        }
    }

    /// Three habits over 30 days: 0 done, 1 skipped; the last days are
    /// still to come. The middle shows the share done so far.
    fn ring_habits(&mut self) -> RingSample {
        let today = 22;
        let values: Vec<Vec<f32>> = (0..3)
            .map(|_| {
                (0..30)
                    .map(|day| {
                        if day >= today {
                            f32::NAN
                        } else if self.rng.next() < 0.18 {
                            1.0
                        } else {
                            0.0
                        }
                    })
                    .collect()
            })
            .collect();
        // The share of the habits done so far, the days to come left out.
        let done = values.iter().flatten().filter(|&&v| v == 0.0).count();
        let share = done as f32 / (3 * today) as f32 * 100.0;
        RingSample {
            values,
            x_labels: (1..=30).map(|d| format!("Day {d}")).collect(),
            y_labels: ["Exercise", "Reading", "Meditation"]
                .map(String::from)
                .to_vec(),
            total: format!("{share:.0}%"),
        }
    }

    /// A release pipeline: one ring of 20 steps. 0 passed, 1 running,
    /// 2 failed; the steps after the running one are still to come.
    fn ring_pipeline(&mut self) -> RingSample {
        const STEPS: [&str; 20] = [
            "Checkout",
            "Cache",
            "Format",
            "Lint",
            "Build",
            "Unit tests",
            "Docs",
            "Integration",
            "Fuzz",
            "Screenshots",
            "Package",
            "Sign",
            "Upload",
            "Staging",
            "Smoke tests",
            "Approve",
            "Canary",
            "Rollout",
            "Verify",
            "Notify",
        ];
        let running = 8 + (self.rng.next() * 9.0) as usize;
        let values = vec![
            (0..STEPS.len())
                .map(|i| match i {
                    _ if i < running && self.rng.next() < 0.1 => 2.0,
                    _ if i < running => 0.0,
                    _ if i == running => 1.0,
                    _ => f32::NAN,
                })
                .collect(),
        ];
        RingSample {
            values,
            x_labels: STEPS.map(String::from).to_vec(),
            y_labels: vec!["Release 0.4".into()],
            total: format!("{running}/{}", STEPS.len()),
        }
    }

    fn grid_values(&mut self) {
        let values: Vec<f32> = match self.sample.shape {
            // Two-hour blocks, so the counts fit in the cells.
            Shape::Matrix => (0..7 * 12)
                .map(|i| {
                    let (day, hour) = (i / 12, (i % 12 * 2) as f32 + 1.0);
                    // Busy on weekday afternoons, quiet at night.
                    let daytime = (-((hour - 14.0) / 5.0).powi(2)).exp();
                    let weekday = if day < 5 { 1.0 } else { 0.45 };
                    (200.0 * daytime * weekday + self.rng.next() * 30.0).round()
                })
                .collect(),
            Shape::Correlation => {
                let n = 6;
                let mut m = vec![0.0; n * n];
                for r in 0..n {
                    for c in r..n {
                        let v = if r == c {
                            1.0
                        } else {
                            ((self.rng.next() * 2.0 - 1.0) * 100.0).round() / 100.0
                        };
                        m[r * n + c] = v;
                        m[c * n + r] = v;
                    }
                }
                m
            }
            Shape::Sales => {
                // The table at first; then each figure a little off it.
                let randomize = self.randomized;
                let mut growth = Vec::new();
                let sales = SALES
                    .iter()
                    .flat_map(|(_, row)| row.iter().enumerate())
                    .map(|(region, &v)| {
                        // Faster growth in the smaller markets.
                        let trend = [2.0, -1.0, 6.0, 9.0, 11.0, 14.0][region];
                        let change = (trend + (self.rng.next() - 0.45) * 30.0).round();
                        growth.push(if v.is_nan() { f32::NAN } else { change });
                        if randomize {
                            (v * (0.55 + self.rng.next() * 0.9)).round()
                        } else {
                            v
                        }
                    })
                    .collect();
                self.growth.set_vec(growth);
                sales
            }
            Shape::Calendar => (0..365)
                .map(|i| {
                    // Fewer contributions on weekends, and some idle days.
                    let weekend = i % 7 == 0 || i % 7 == 6;
                    if self.rng.next() < if weekend { 0.6 } else { 0.25 } {
                        0.0
                    } else {
                        (self.rng.next().powi(2) * 20.0).round() + 1.0
                    }
                })
                .collect(),
            _ => Vec::new(),
        };
        self.grid.set_vec(values);
    }

    /// The treemap's items: the population table, randomized after the first
    /// time.
    fn tree_items(&mut self, randomize: bool) {
        let items: Vec<ChartTreemapItem> = POPULATION
            .iter()
            .map(|&(group, label, value)| ChartTreemapItem {
                label: label.into(),
                group: group.into(),
                value: if randomize {
                    (value * (0.5 + self.rng.next())).round()
                } else {
                    value
                },
                ..Default::default()
            })
            .collect();
        self.tree.set_vec(if self.sample.shape == Shape::Treemap {
            items
        } else {
            Vec::new()
        });
    }

    /// The data of the sunburst, funnel, waterfall and gauge samples,
    /// randomized after the first time.
    fn business_data(&mut self, randomize: bool) {
        // `v`, changed by up to `by` (a share) when randomizing.
        let vary = |rng: &mut Rng, v: f32, by: f32| {
            if randomize {
                (v * (1.0 - by + 2.0 * by * rng.next())).round()
            } else {
                v
            }
        };
        let mut sun = Vec::new();
        if self.sample.shape == Shape::Sunburst {
            // Continents, then their regions, then the countries.
            let index = |items: &Vec<ChartSunburstItem>, label: &str, parent: i32| {
                items
                    .iter()
                    .position(|i| i.label == label && i.parent == parent)
                    .map(|p| p as i32)
            };
            for (i, &(continent, country, value)) in POPULATION.iter().enumerate() {
                let c = index(&sun, continent, -1).unwrap_or_else(|| {
                    sun.push(ChartSunburstItem {
                        label: continent.into(),
                        parent: -1,
                        ..Default::default()
                    });
                    sun.len() as i32 - 1
                });
                let r = index(&sun, REGIONS[i], c).unwrap_or_else(|| {
                    sun.push(ChartSunburstItem {
                        label: REGIONS[i].into(),
                        parent: c,
                        ..Default::default()
                    });
                    sun.len() as i32 - 1
                });
                sun.push(ChartSunburstItem {
                    label: country.into(),
                    parent: r,
                    value: vary(&mut self.rng, value, 0.5),
                    ..Default::default()
                });
            }
        }
        self.sun.set_vec(sun);
        if self.sample.shape == Shape::Funnel {
            // Each stage keeps a share of the one before.
            let mut previous = 0.0;
            let stages: Vec<ChartSlice> = FUNNEL
                .iter()
                .enumerate()
                .map(|(i, &(label, value))| {
                    let value = if randomize && i > 0 {
                        (previous * (0.35 + 0.5 * self.rng.next())).round()
                    } else {
                        value
                    };
                    previous = value;
                    ChartSlice {
                        label: label.into(),
                        value,
                        ..Default::default()
                    }
                })
                .collect();
            self.slices.set_vec(stages);
        }
        let steps = if self.sample.shape == Shape::Waterfall {
            PROFIT_AND_LOSS
                .iter()
                .map(|&(label, value, total)| ChartWaterfallStep {
                    label: label.into(),
                    value: vary(&mut self.rng, value, 0.3),
                    total,
                })
                .collect()
        } else {
            Vec::new()
        };
        self.steps.set_vec(steps);
        if let Some(ui) = self.ui.upgrade() {
            ui.set_gauge_value(if randomize {
                self.rng.range(5.0, 98.0)
            } else {
                72.0
            });
            // The bullet charts: a KPI panel, sales by region in percent of
            // target, and website visits.
            const BULLET: [f32; 15] = [
                270.0, 22.5, 320.0, 1650.0, 4.5, 104.0, 87.0, 72.0, 95.0, 128.0, 48.0, 36.0, 14.0,
                9.0, 27.0,
            ];
            let values: Vec<f32> = BULLET
                .iter()
                .enumerate()
                .map(|(i, &v)| {
                    if !randomize {
                        v
                    } else if i == 4 {
                        // Satisfaction, out of 5.
                        (v * (0.7 + 0.4 * self.rng.next()) * 10.0).round().min(50.0) / 10.0
                    } else {
                        vary(&mut self.rng, v, 0.3)
                    }
                })
                .collect();
            ui.set_bullet_values(ModelRc::new(VecModel::from(values)));
        }
    }

    /// The interpolation sample compares two ways of drawing the same values:
    /// give every dataset the first one's values.
    fn share_interpolation_values(&mut self) {
        if self.sample.id != "line-interpolation" {
            return;
        }
        let Some(first) = self.datasets.row_data(0) else {
            return;
        };
        for row in 1..self.datasets.row_count() {
            if let Some(mut ds) = self.datasets.row_data(row) {
                ds.values = first.values.clone();
                self.datasets.set_row_data(row, ds);
            }
        }
    }

    /// The 12 month names in the chart language, or English.
    fn month_names(&self) -> Vec<SharedString> {
        let months = self
            .ui
            .upgrade()
            .map(|ui| ui.global::<ChartTheme>().get_locale().months);
        match months {
            Some(m) if m.row_count() == 12 => m.iter().collect(),
            _ => MONTHS.iter().map(|&m| m.into()).collect(),
        }
    }

    /// The 7 weekday names in the chart language, Monday first, or English.
    fn weekday_names(&self) -> Vec<SharedString> {
        let weekdays = self
            .ui
            .upgrade()
            .map(|ui| ui.global::<ChartTheme>().get_locale().weekdays);
        match weekdays {
            Some(w) if w.row_count() == 7 => w.iter().collect(),
            _ => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
                .map(SharedString::from)
                .to_vec(),
        }
    }

    /// The index into `LANGUAGES` of the chart language: the picker's for
    /// the "languages" sample, English for the others.
    fn language(&self) -> usize {
        match self.ui.upgrade() {
            Some(ui) if self.sample.id == "languages" => {
                (ui.get_language().max(0) as usize).min(LANGUAGES.len() - 1)
            }
            _ => 0,
        }
    }

    /// Sets the chart language, and the "languages" sample's titles in it.
    fn set_chart_language(&self) {
        let language = self.language();
        if let Some(ui) = self.ui.upgrade() {
            ui.global::<ChartTheme>().set_language(LANGUAGES[language]);
            let (title, visitors, rate) = LANGUAGE_TEXTS[language];
            ui.set_language_title(title.into());
            ui.set_language_y_title(visitors.into());
            ui.set_language_y2_title(rate.into());
        }
    }

    /// Sets the chart language, and puts the month and weekday labels and
    /// the "languages" sample's texts in it.
    fn relabel(&mut self) {
        self.set_chart_language();
        let language = self.language();
        if self.sample.id == "languages" {
            let (_, visitors, rate) = LANGUAGE_TEXTS[language];
            for (row, label) in [(0, visitors), (1, rate)] {
                if let Some(mut ds) = self.datasets.row_data(row) {
                    ds.label = label.into();
                    self.datasets.set_row_data(row, ds);
                }
            }
        }
        match self.sample.shape {
            Shape::Months { .. } | Shape::Exponential => {
                let months = self.month_names();
                for i in 0..self.labels.row_count() {
                    self.labels.set_row_data(i, months[i % 12].clone());
                }
            }
            Shape::Matrix => self.row_labels.set_vec(self.weekday_names()),
            _ => {}
        }
    }

    /// Builds the data of `sample` and shows it.
    fn select(&mut self, sample: &'static Sample) {
        self.sample = sample;
        self.randomized = false;
        self.set_chart_language();
        if let Some(ui) = self.ui.upgrade() {
            ui.set_view_start(0.0);
            ui.set_view_end(1.0);
        }
        let row_labels: Vec<SharedString> = match sample.shape {
            Shape::Matrix => self.weekday_names(),
            Shape::Correlation => ["Price", "Size", "Age", "Rooms", "Floor", "Garden"]
                .map(SharedString::from)
                .to_vec(),
            Shape::Sales => SALES.iter().map(|(p, _)| SharedString::from(*p)).collect(),
            _ => Vec::new(),
        };
        self.row_labels.set_vec(row_labels);
        let labels: Vec<SharedString> = match sample.shape {
            Shape::Matrix => (0..12).map(|h| format!("{:02}", h * 2).into()).collect(),
            Shape::Correlation => ["Price", "Size", "Age", "Rooms", "Floor", "Garden"]
                .map(SharedString::from)
                .to_vec(),
            Shape::Sales => SALES_REGIONS.map(SharedString::from).to_vec(),
            Shape::Survey => [
                "Engineering",
                "Design",
                "Sales",
                "Marketing",
                "Support",
                "All staff",
            ]
            .map(SharedString::from)
            .to_vec(),
            // A full year for the "languages" sample, to show every month name.
            Shape::Months { .. } if sample.id == "languages" => self.month_names(),
            Shape::Months { .. } | Shape::Exponential => {
                self.month_names().into_iter().take(7).collect()
            }
            Shape::Skills => SKILLS.iter().map(|&s| s.into()).collect(),
            Shape::Dumbbell => LIFE_EXPECTANCY.iter().map(|c| c.0.into()).collect(),
            Shape::Series { count } => (0..count).map(|i| i.to_string().into()).collect(),
            _ => Vec::new(),
        };
        self.labels.set_vec(labels);
        let count = match sample.shape {
            Shape::Months { datasets, .. } => datasets,
            Shape::Survey => 5,
            Shape::Points
            | Shape::Bubbles
            | Shape::Series { .. }
            | Shape::Exponential
            | Shape::TimeSeries { .. }
            | Shape::Skills
            | Shape::Dumbbell => 2,
            _ => 0,
        };
        self.stock();
        let rows: Vec<ChartDataset> = (0..count).map(|i| self.dataset(i)).collect();
        self.datasets.set_vec(rows);
        self.share_interpolation_values();
        let bars = |items: &[(&str, f32)]| -> Vec<ChartSlice> {
            items
                .iter()
                .map(|&(label, value)| ChartSlice {
                    label: label.into(),
                    value,
                    ..Default::default()
                })
                .collect()
        };
        let slices: Vec<ChartSlice> = match sample.shape {
            Shape::Slices => (0..5).map(|i| self.slice(i)).collect(),
            Shape::RadialBar => bars(&GOALS),
            _ => Vec::new(),
        };
        self.slices.set_vec(slices);
        self.channels.set_vec(match sample.shape {
            Shape::RadialBar => bars(&CHANNELS),
            _ => Vec::new(),
        });
        if matches!(
            sample.shape,
            Shape::SegmentedRing | Shape::SegmentedScale | Shape::TileScale | Shape::TileClasses
        ) {
            self.ring_data(false);
        }
        self.grid_values();
        self.tree_items(false);
        self.business_data(false);

        // The release plan as it was, without the task editor's changes.
        self.gantt.set_vec(if sample.shape == Shape::Gantt {
            let day = 86400.0;
            RELEASE_PLAN
                .iter()
                .map(|&(label, group, start, end, progress)| ChartGanttTask {
                    label: label.into(),
                    group: group.into(),
                    start: start * day,
                    end: end * day,
                    progress,
                    ..Default::default()
                })
                .collect()
        } else {
            Vec::new()
        });

        let Some(ui) = self.ui.upgrade() else { return };
        ui.set_editing_task(-1);
        ui.set_sample(sample.id.into());
        let group = tab_group(sample.id);
        ui.set_sidebar_sample(group.map_or(sample.id, |(_, tabs)| tabs[0].0).into());
        ui.set_tabs(ModelRc::new(VecModel::from(
            group
                .map(|(_, tabs)| {
                    tabs.iter()
                        .map(|&(id, title)| SampleEntry {
                            id: id.into(),
                            title: title.into(),
                            header: false,
                        })
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default(),
        )));
        // A tab group's page is named after the group.
        ui.set_sample_title(
            tab_group(sample.id)
                .map_or(sample.title, |(title, _)| title)
                .into(),
        );
        ui.set_description(sample.description.into());
        ui.set_actions(strings(sample.actions.iter().copied()));
        ui.set_legend_position(ChartLegendPosition::Top);
        ui.set_decimate(true);
        ui.set_ohlc(false);
        ui.set_skip_gaps(true);
        ui.set_status("".into());
        if sample.shape == Shape::Live {
            self.live.paused = false;
            self.live_reset();
            self.show_live_stats(None);
        }
    }

    /// A sensor's next value: noise around a slow wave, different per sensor.
    fn sensor(&mut self, sensor: usize, time: f32) -> f32 {
        let wave = (time / (8.0 + 5.0 * sensor as f32)).sin() * 12.0;
        let target = 20.0 + 25.0 * sensor as f32 + wave;
        let last = self.live.last[sensor];
        let next = last + (target - last) * 0.1 + (self.rng.next() - 0.5) * 1.5;
        self.live.last[sensor] = next;
        next
    }

    /// Fills the live sample with the last minute of values at its rate.
    fn live_reset(&mut self) {
        let rate = self.live.rate;
        let capacity = (LIVE_SECONDS * rate) as usize;
        self.live.time = 0.0;
        self.live.last = [20.0, 45.0, 70.0];
        let mut models = Vec::new();
        let mut rows = Vec::new();
        for sensor in 0..3 {
            let points: Vec<ChartXY> = (0..capacity)
                .map(|i| {
                    let x = i as f32 / rate as f32;
                    ChartXY {
                        x,
                        y: self.sensor(sensor, x),
                        r: 0.0,
                    }
                })
                .collect();
            let model = Rc::new(StreamModel::new(capacity, points));
            rows.push(ChartDataset {
                label: format!("Sensor {}", ["A", "B", "C"][sensor]).into(),
                points: model.clone().into(),
                ..Default::default()
            });
            models.push(model);
        }
        self.live.time = (capacity.max(1) - 1) as f32 / rate as f32;
        self.live.models = models;
        self.live.updates = 0;
        self.live.since = now();
        self.datasets.set_vec(rows);
    }

    /// Appends one value per sensor, and every half second shows the
    /// measured update rate.
    fn live_tick(&mut self) {
        let rate = self.live.rate as f32;
        self.live.time += 1.0 / rate;
        let time = self.live.time;
        for sensor in 0..self.live.models.len() {
            let y = self.sensor(sensor, time);
            self.live.models[sensor].push(ChartXY { x: time, y, r: 0.0 });
        }
        self.live.updates += 1;
        let elapsed = now() - self.live.since;
        if elapsed >= 0.5 {
            let measured = self.live.updates as f64 / elapsed;
            self.live.updates = 0;
            self.live.since = now();
            self.show_live_stats(Some(measured));
        }
    }

    /// The point count, update rate and layout time under the chart.
    fn show_live_stats(&mut self, measured: Option<f64>) {
        let Some(ui) = self.ui.upgrade() else { return };
        // A clicked point's readout stays for three seconds.
        let status = ui.get_status();
        if status.contains("-clicked: ") {
            match &self.live.clicked {
                Some((text, since)) if *text == status => {
                    if now() - since < 3.0 {
                        return;
                    }
                }
                _ => {
                    self.live.clicked = Some((status, now()));
                    return;
                }
            }
        }
        let points = self
            .live
            .models
            .iter()
            .map(|m| m.row_count())
            .sum::<usize>();
        let rate = match measured {
            _ if self.live.paused => "paused".to_string(),
            Some(r) => format!("{r:.0} of {} updates/s", self.live.rate),
            None => format!("{} updates/s", self.live.rate),
        };
        // The browser's standard library has no clock, so layouts aren't timed.
        let layout = if cfg!(target_arch = "wasm32") {
            String::new()
        } else {
            format!(
                " · layout {:.1} ms",
                slintplot::profile::last_layout_time().as_secs_f64() * 1000.0
            )
        };
        ui.set_status(
            format!(
                "{} points · {rate}{layout}",
                slintplot::ticks::format_value(points as f64)
            )
            .into(),
        );
    }

    fn live_action(&mut self, name: &str) {
        match name {
            "Pause / resume" => self.live.paused = !self.live.paused,
            _ => {
                if let Some(rate) = name.split(' ').next().and_then(|r| r.parse().ok()) {
                    self.live.rate = rate;
                    self.live.paused = false;
                    self.live_reset();
                }
            }
        }
        self.show_live_stats(None);
    }

    /// Applies `f` to every dataset.
    fn update_datasets(&mut self, mut f: impl FnMut(&mut Self, &mut ChartDataset)) {
        for row in 0..self.datasets.row_count() {
            let Some(mut ds) = self.datasets.row_data(row) else {
                continue;
            };
            f(self, &mut ds);
            self.datasets.set_row_data(row, ds);
        }
    }

    fn action(&mut self, index: usize) {
        let Some(&name) = self.sample.actions.get(index) else {
            return;
        };
        let Some(ui) = self.ui.upgrade() else { return };
        ui.set_status("".into());
        if self.sample.shape == Shape::Live {
            self.live_action(name);
            return;
        }
        let slices = self.sample.shape == Shape::Slices;
        let points = matches!(self.sample.shape, Shape::Points | Shape::Bubbles);
        // The one-week sample: zoom to a span starting on Wednesday, to see
        // how the time axis labels narrow ranges.
        let span = (7 * 96 - 1) as f32 * 900.0;
        let wednesday = 2.0 * 86_400.0;
        let window = match name {
            "Week" => Some((0.0, span)),
            "Day" => Some((wednesday, wednesday + 86_400.0)),
            "6 hours" => Some((wednesday + 6.0 * 3600.0, wednesday + 12.0 * 3600.0)),
            "1 hour" => Some((wednesday + 8.0 * 3600.0, wednesday + 9.0 * 3600.0)),
            _ => None,
        };
        if let Some((start, end)) = window {
            ui.set_view_start(start / span);
            ui.set_view_end(end / span);
            return;
        }
        match name {
            "Candles" | "OHLC" => ui.set_ohlc(name == "OHLC"),
            "Skip gaps" | "Linear time" => ui.set_skip_gaps(name == "Skip gaps"),
            "Randomize" if self.sample.shape == Shape::Candles => self.stock(),
            "Randomize" if slices => {
                for row in 0..self.slices.row_count() {
                    let Some(mut s) = self.slices.row_data(row) else {
                        continue;
                    };
                    s.value = self.rng.range(5.0, 100.0);
                    self.slices.set_row_data(row, s);
                }
            }
            "Randomize" if self.sample.shape == Shape::Treemap => self.tree_items(true),
            // New values in place, so that the bars move to them.
            "Randomize" if self.sample.shape == Shape::RadialBar => {
                for row in 0..self.slices.row_count() {
                    if let Some(mut s) = self.slices.row_data(row) {
                        s.value = self.rng.range(15.0, 100.0);
                        self.slices.set_row_data(row, s);
                    }
                }
                for row in 0..self.channels.row_count() {
                    if let Some(mut s) = self.channels.row_data(row) {
                        s.value = self.rng.range(2.0, 40.0);
                        self.channels.set_row_data(row, s);
                    }
                }
            }
            "Randomize"
                if matches!(
                    self.sample.shape,
                    Shape::SegmentedRing
                        | Shape::SegmentedScale
                        | Shape::TileScale
                        | Shape::TileClasses
                ) =>
            {
                self.ring_data(true)
            }
            "Randomize"
                if matches!(
                    self.sample.shape,
                    Shape::Sunburst
                        | Shape::Funnel
                        | Shape::Waterfall
                        | Shape::Gauge
                        | Shape::Bullet
                ) =>
            {
                self.business_data(true);
            }
            "Randomize"
                if matches!(
                    self.sample.shape,
                    Shape::Matrix | Shape::Correlation | Shape::Sales | Shape::Calendar
                ) =>
            {
                self.randomized = true;
                self.grid_values();
            }
            "Randomize" => {
                self.randomized = true;
                // Keep each dataset's label and visibility; new values only.
                for row in 0..self.datasets.row_count() {
                    let Some(old) = self.datasets.row_data(row) else {
                        continue;
                    };
                    let fresh = self.dataset(row);
                    self.datasets.set_row_data(
                        row,
                        ChartDataset {
                            values: fresh.values,
                            points: fresh.points,
                            ..old
                        },
                    );
                }
                self.share_interpolation_values();
            }
            "Add dataset" if slices => {
                ui.set_status("Pie, doughnut and polar area charts show one set of slices.".into());
            }
            "Add dataset" => {
                let ds = self.dataset(self.datasets.row_count());
                self.datasets.push(ds);
            }
            "Remove dataset" => {
                if self.datasets.row_count() > 0 {
                    self.datasets.remove(self.datasets.row_count() - 1);
                }
            }
            "Add data" if slices => {
                let s = self.slice(self.slices.row_count());
                self.slices.push(s);
            }
            "Add data" if points => {
                let bubbles = self.sample.shape == Shape::Bubbles;
                self.update_datasets(|state, ds| {
                    let mut all: Vec<ChartXY> = ds.points.iter().collect();
                    all.extend(state.points(1, bubbles));
                    ds.points = ModelRc::new(VecModel::from(all));
                });
            }
            "Add data" => {
                let next = self.labels.row_count();
                self.labels.push(self.month_names()[next % 12].clone());
                self.update_datasets(|state, ds| {
                    let mut values: Vec<f32> = ds.values.iter().collect();
                    values.extend(state.values(1));
                    ds.values = floats(values);
                });
            }
            "Remove data" if slices => {
                if self.slices.row_count() > 0 {
                    self.slices.remove(self.slices.row_count() - 1);
                }
            }
            "Remove data" => {
                if !points && self.labels.row_count() > 0 {
                    self.labels.remove(self.labels.row_count() - 1);
                }
                self.update_datasets(|_, ds| {
                    let mut values: Vec<f32> = ds.values.iter().collect();
                    values.pop();
                    ds.values = floats(values);
                    let mut all: Vec<ChartXY> = ds.points.iter().collect();
                    all.pop();
                    ds.points = ModelRc::new(VecModel::from(all));
                });
            }
            "Steps on" | "Steps off" => {
                let on = name == "Steps on";
                self.update_datasets(|_, ds| ds.stepped = on);
            }
            "Position: top" => ui.set_legend_position(ChartLegendPosition::Top),
            "Position: right" => ui.set_legend_position(ChartLegendPosition::Right),
            "Position: bottom" => ui.set_legend_position(ChartLegendPosition::Bottom),
            "Position: left" => ui.set_legend_position(ChartLegendPosition::Left),
            "Decimation on" => ui.set_decimate(true),
            "Decimation off" => {
                ui.set_decimate(false);
                ui.set_status("Without decimation, 100,000-point lines are slow to draw.".into());
            }
            "Reset zoom" | "Reset" => self.select(self.sample),
            _ => {}
        }
    }
}

/// Creates the gallery window with its samples and callbacks.
fn gallery() -> Result<(Gallery, Rc<RefCell<State>>), slint::PlatformError> {
    let ui = Gallery::new()?;
    slintplot::register!(ui);
    // A monospace font for the code panel.
    ui.set_code_font(
        if cfg!(windows) {
            "Consolas"
        } else if cfg!(target_os = "macos") {
            "Menlo"
        } else {
            "DejaVu Sans Mono"
        }
        .into(),
    );

    // The sample list, with a header row per category, in the order the
    // categories first appear.
    let mut categories: Vec<&str> = Vec::new();
    for s in SAMPLES {
        if !categories.contains(&s.category) {
            categories.push(s.category);
        }
    }
    // New charts on top, so that they are easy to find while reviewed.
    categories.sort_by_key(|c| *c != "New");
    let mut entries = Vec::new();
    for category in categories {
        entries.push(SampleEntry {
            id: "".into(),
            title: category.into(),
            header: true,
        });
        for s in SAMPLES.iter().filter(|s| s.category == category) {
            // A tab group is one entry, which opens its first tab.
            let title = match tab_group(s.id) {
                Some((title, tabs)) if tabs[0].0 == s.id => title,
                Some(_) => continue,
                None => s.title,
            };
            entries.push(SampleEntry {
                id: s.id.into(),
                title: (*title).into(),
                header: false,
            });
        }
    }
    ui.set_samples(ModelRc::new(VecModel::from(entries)));

    let state = Rc::new(RefCell::new(State {
        ui: ui.as_weak(),
        rng: Rng(SEED),
        sample: &SAMPLES[0],
        labels: Rc::new(VecModel::default()),
        datasets: Rc::new(VecModel::default()),
        slices: Rc::new(VecModel::default()),
        channels: Rc::new(VecModel::default()),
        row_labels: Rc::new(VecModel::default()),
        grid: Rc::new(VecModel::default()),
        growth: Rc::new(VecModel::default()),
        tree: Rc::new(VecModel::default()),
        sun: Rc::new(VecModel::default()),
        steps: Rc::new(VecModel::default()),
        candles: Rc::new(VecModel::default()),
        gantt: Rc::new(VecModel::default()),
        randomized: false,
        live: Live {
            rate: 30,
            paused: false,
            time: 0.0,
            last: [0.0; 3],
            models: Vec::new(),
            updates: 0,
            since: 0.0,
            clicked: None,
        },
    }));
    {
        let s = state.borrow();
        ui.set_labels(s.labels.clone().into());
        ui.set_datasets(s.datasets.clone().into());
        ui.set_slices(s.slices.clone().into());
        ui.set_channels(s.channels.clone().into());
        ui.set_row_labels(s.row_labels.clone().into());
        ui.set_grid(s.grid.clone().into());
        ui.set_growth(s.growth.clone().into());
        ui.set_tree(s.tree.clone().into());
        ui.set_sun(s.sun.clone().into());
        ui.set_steps(s.steps.clone().into());
        ui.set_candles(s.candles.clone().into());
        ui.set_gantt_tasks(s.gantt.clone().into());
    }
    state.borrow_mut().select(&SAMPLES[0]);

    // The live sample's updates, while it is shown and not paused.
    let timer = Rc::new(slint::Timer::default());
    let timer_rate = Rc::new(Cell::new(0));
    let s = state.clone();
    let (t, r) = (timer.clone(), timer_rate.clone());
    ui.on_select(move |id| {
        if let Some(sample) = SAMPLES.iter().find(|x| x.id == id.as_str()) {
            s.borrow_mut().select(sample);
        }
        run_live_timer(&t, &r, &s);
    });
    let s = state.clone();
    ui.on_action(move |index| {
        s.borrow_mut().action(index.max(0) as usize);
        run_live_timer(&timer, &timer_rate, &s);
    });
    let s = state.clone();
    ui.on_dark_mode_changed(move || {
        let mut s = s.borrow_mut();
        s.recolor_survey();
        s.ring_colors();
    });
    let s = state.clone();
    ui.on_ring_colors_changed(move || s.borrow().ring_colors());
    let s = state.clone();
    ui.on_language_changed(move || s.borrow_mut().relabel());
    let weak = ui.as_weak();
    ui.on_show_code(move || {
        if let Some(ui) = weak.upgrade() {
            open_code(&ui);
        }
    });
    #[cfg(not(target_arch = "wasm32"))]
    ui.on_open_url(|url| open_in_browser(&url));
    Ok((ui, state))
}

/// Runs `timer` at the live sample's update rate while the sample is shown
/// and not paused, and stops it otherwise. `running` is the rate it runs at.
fn run_live_timer(timer: &slint::Timer, running: &Cell<u32>, state: &Rc<RefCell<State>>) {
    let rate = {
        let s = state.borrow();
        if s.sample.shape == Shape::Live && !s.live.paused {
            s.live.rate
        } else {
            0
        }
    };
    if rate == running.get() {
        return;
    }
    running.set(rate);
    if rate == 0 {
        timer.stop();
        return;
    }
    let state = Rc::downgrade(state);
    timer.start(
        slint::TimerMode::Repeated,
        Duration::from_secs_f64(1.0 / rate as f64),
        move || {
            if let Some(state) = state.upgrade() {
                state.borrow_mut().live_tick();
            }
        },
    );
}

#[cfg(not(target_arch = "wasm32"))]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = std::env::args().skip(1);
    // `--docs`: the website's screenshots, rather than every snapshot;
    // `--video`: the frames of the website's animation.
    let mut docs_dir = None;
    let mut video_dir = None;
    let snapshot_dir = match (args.next().as_deref(), args.next()) {
        (Some("--snapshot"), Some(dir)) => Some(std::path::PathBuf::from(dir)),
        (Some("--docs"), Some(dir)) => {
            docs_dir = Some(std::path::PathBuf::from(dir));
            docs_dir.clone()
        }
        (Some("--video"), Some(dir)) => {
            video_dir = Some(std::path::PathBuf::from(dir));
            video_dir.clone()
        }
        (None, _) => None,
        _ => return Err("usage: gallery [--snapshot <dir> | --docs <dir> | --video <dir>]".into()),
    };
    let headless = snapshot_dir.as_ref().map(|_| snapshot::install());
    // macOS: keep the system frame, so the window has the system's buttons
    // and resizing, but make the title bar see-through, so the content
    // reaches the top edge and the buttons sit over the sample list.
    #[cfg(target_os = "macos")]
    if headless.is_none() && !drawn_frame() {
        use slint::winit_030::winit::platform::macos::WindowAttributesExtMacOS;
        slint::BackendSelector::new()
            .with_winit_window_attributes_hook(|attributes| {
                attributes
                    .with_titlebar_transparent(true)
                    .with_fullsize_content_view(true)
                    .with_title_hidden(true)
            })
            .select()?;
    }

    let (ui, state) = gallery()?;
    match (headless, snapshot_dir) {
        (Some(window), Some(dir)) if docs_dir.is_some() => docs(&ui, &state, &window, &dir),
        (Some(window), Some(dir)) if video_dir.is_some() => video(&ui, &state, &window, &dir),
        (Some(window), Some(dir)) => snapshots(&ui, &state, &window, &dir),
        _ => {
            init_window_frame(&ui);
            // Once the app has finished launching, which would reset it.
            slint::Timer::single_shot(Duration::ZERO, dock_icon::set);
            Ok(ui.run()?)
        }
    }
}

/// Opens `url` in the default browser.
#[cfg(not(target_arch = "wasm32"))]
fn open_in_browser(url: &str) {
    use std::process::Command;
    let result = if cfg!(target_os = "macos") {
        Command::new("open").arg(url).spawn()
    } else if cfg!(windows) {
        Command::new("cmd").args(["/C", "start", "", url]).spawn()
    } else {
        Command::new("xdg-open").arg(url).spawn()
    };
    if let Err(error) = result {
        eprintln!("couldn't open {url}: {error}");
    }
}

/// Whether the app draws the window frame: on Windows and Linux, and on
/// macOS with `SLINTPLOT_DRAWN_FRAME` set, to try it there.
#[cfg(not(target_arch = "wasm32"))]
fn drawn_frame() -> bool {
    !cfg!(target_os = "macos") || std::env::var_os("SLINTPLOT_DRAWN_FRAME").is_some()
}

/// Connects the window frame (see ui/window_frame.slint) to the window.
#[cfg(not(target_arch = "wasm32"))]
fn init_window_frame(ui: &Gallery) {
    use slint::winit_030::{WinitWindowAccessor, winit::window::ResizeDirection};
    let frame = ui.global::<WindowFrame>();
    frame.set_drawn(drawn_frame());
    frame.set_mac_titlebar(!drawn_frame());
    let with_ui = |f: fn(&Gallery)| {
        let weak = ui.as_weak();
        move || {
            if let Some(ui) = weak.upgrade() {
                f(&ui)
            }
        }
    };
    frame.on_drag(with_ui(|ui| {
        ui.window().with_winit_window(|w| {
            let _ = w.drag_window();
        });
    }));
    frame.on_close(with_ui(|ui| {
        let _ = ui.window().hide();
    }));
    frame.on_minimize(with_ui(|ui| ui.window().set_minimized(true)));
    frame.on_toggle_maximize(with_ui(|ui| {
        let maximized = !ui.window().is_maximized();
        ui.window().set_maximized(maximized);
        ui.global::<WindowFrame>().set_maximized(maximized);
    }));
    let weak = ui.as_weak();
    frame.on_resize(move |direction| {
        let direction = match direction {
            0 => ResizeDirection::East,
            1 => ResizeDirection::North,
            2 => ResizeDirection::NorthEast,
            3 => ResizeDirection::NorthWest,
            4 => ResizeDirection::South,
            5 => ResizeDirection::SouthEast,
            6 => ResizeDirection::SouthWest,
            _ => ResizeDirection::West,
        };
        if let Some(ui) = weak.upgrade() {
            ui.window().with_winit_window(|w| {
                let _ = w.drag_resize_window(direction);
            });
        }
    });
}

/// In the browser: counts the click with Plausible, as for a link that leaves
/// the site, and opens `url` in a new tab, or in this one if that is blocked.
#[cfg(target_arch = "wasm32")]
fn open_page(url: &str) {
    use js_sys::{Function, Object, Reflect};
    use wasm_bindgen::{JsCast, JsValue};
    let global = js_sys::global();
    let function = |name: &str| {
        Reflect::get(&global, &name.into())
            .ok()
            .and_then(|f| f.dyn_into::<Function>().ok())
    };
    if let Some(plausible) = function("plausible") {
        let props = Object::new();
        let options = Object::new();
        let _ = Reflect::set(&props, &"url".into(), &url.into());
        let _ = Reflect::set(&options, &"props".into(), &props);
        let _ = plausible.call2(&global, &"Outbound Link: Click".into(), &options);
    }
    let opened = function("open")
        .and_then(|open| open.call2(&global, &url.into(), &"_blank".into()).ok())
        .is_some_and(|tab| !tab.is_null() && tab != JsValue::UNDEFINED);
    if !opened {
        if let Ok(location) = Reflect::get(&global, &"location".into()) {
            let _ = Reflect::set(&location, &"href".into(), &url.into());
        }
    }
}

/// In the browser: copies `text` with the page's clipboard API, as Slint's
/// own copy doesn't reach the system clipboard there.
#[cfg(target_arch = "wasm32")]
fn copy_to_clipboard(text: &str) {
    use js_sys::{Function, Reflect};
    use wasm_bindgen::JsCast;
    let get = |object: &wasm_bindgen::JsValue, name: &str| Reflect::get(object, &name.into()).ok();
    let Some(clipboard) = get(&js_sys::global(), "navigator").and_then(|n| get(&n, "clipboard"))
    else {
        return;
    };
    if let Some(write) = get(&clipboard, "writeText").and_then(|f| f.dyn_into::<Function>().ok()) {
        let _ = write.call1(&clipboard, &text.into());
    }
}

/// In the browser: the gallery in the page's `<canvas id="canvas">`.
#[cfg(target_arch = "wasm32")]
fn main() {
    console_error_panic_hook::set_once();
    let (ui, _state) = gallery().expect("the gallery window");
    // The browser has no fonts for Japanese and Chinese.
    ui.set_cjk_fonts(false);
    ui.on_open_url(|url| open_page(url.as_str()));
    ui.on_copy_text(|text| copy_to_clipboard(text.as_str()));
    ui.run().expect("the event loop");
}

/// Renders the website's screenshots that show the gallery into `dir`
/// (docs/screenshots): the whole gallery for the page's larger pictures, and
/// in `charts/`, the samples the page shows without a code example, 1012 by
/// 660 pixels. The other chart pictures are rendered from the page's code
/// examples by `slintplot-docshots`.
#[cfg(not(target_arch = "wasm32"))]
fn docs(
    ui: &Gallery,
    state: &Rc<RefCell<State>>,
    window: &Rc<slint::platform::software_renderer::MinimalSoftwareWindow>,
    dir: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let charts = dir.join("charts");
    std::fs::create_dir_all(&charts)?;
    ui.show()?;
    let shot = |sample: &str, name: &str, dark: bool| -> std::io::Result<()> {
        ui.set_dark_mode(dark);
        // The same data every time.
        state.borrow_mut().rng = Rng(SEED);
        let sample = SAMPLES.iter().find(|s| s.id == sample).unwrap();
        state.borrow_mut().select(sample);
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(1100));
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(400));
        snapshot::save(window, &charts.join(format!("{name}.png")))
    };

    // The charts alone.
    ui.set_chart_only(true);
    snapshot::resize(window, 1012, 660);
    for dark in [false, true] {
        let suffix = if dark { "-dark" } else { "" };
        shot(
            "heatmap-diverging",
            &format!("heatmap-diverging{suffix}"),
            dark,
        )?;
        ui.set_language(2);
        shot("languages", &format!("languages-de{suffix}"), dark)?;
        ui.set_language(0);
    }

    // The whole gallery.
    ui.set_chart_only(false);
    snapshot::resize(window, snapshot::WIDTH, snapshot::HEIGHT);
    for (sample, name, dark) in [
        ("axes-format", "light", false),
        ("axes-format", "light-dark", true),
        ("bar-vertical", "gallery", false),
        ("bar-vertical", "gallery-dark", true),
        ("time-hourly", "dark", true),
    ] {
        ui.set_dark_mode(dark);
        state.borrow_mut().rng = Rng(SEED);
        state
            .borrow_mut()
            .select(SAMPLES.iter().find(|s| s.id == sample).unwrap());
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(1100));
        snapshot::save(window, &dir.join(format!("{name}.png")))?;
    }
    Ok(())
}

/// Renders the frames of the website's animation of the gallery into
/// `dir/light` and `dir/dark`: hovering the bars of the page's first picture,
/// randomizing them, and opening the radial bar and Gantt charts.
#[cfg(not(target_arch = "wasm32"))]
fn video(
    ui: &Gallery,
    state: &Rc<RefCell<State>>,
    window: &Rc<slint::platform::software_renderer::MinimalSoftwareWindow>,
    dir: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error>> {
    use video::Step::*;
    ui.show()?;
    snapshot::resize(window, snapshot::WIDTH, snapshot::HEIGHT);
    let steps = [
        Wait(0.8),
        // Tooltips on the bars.
        Move(529.0, 420.0, 1.0),
        Wait(0.6),
        Move(905.0, 430.0, 1.4),
        Wait(0.6),
        // New values, twice.
        Move(325.0, 769.0, 1.1),
        Wait(0.2),
        Click,
        Wait(1.3),
        Click,
        Wait(1.3),
        // The radial bar chart grows in; a tooltip on a ring.
        Move(69.0, 584.0, 1.1),
        Wait(0.2),
        Click,
        Wait(1.2),
        Move(560.0, 300.0, 0.8),
        Wait(1.0),
        // Down the sample list to the Gantt chart; a tooltip on a task.
        Move(120.0, 500.0, 0.8),
        Scroll(-3000.0, 1.2),
        Wait(0.3),
        Move(60.0, 664.0, 0.6),
        Wait(0.2),
        Click,
        Wait(1.2),
        Move(700.0, 330.0, 0.9),
        Wait(1.2),
        Move(1150.0, 770.0, 1.0),
    ];
    for (dark, name) in [(false, "light"), (true, "dark")] {
        ui.set_dark_mode(dark);
        // The page's first picture, with the same data.
        state.borrow_mut().rng = Rng(SEED);
        let first = SAMPLES.iter().find(|s| s.id == "axes-format").unwrap();
        state.borrow_mut().select(first);
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(1100));
        video::record(window, &dir.join(name), (1150.0, 770.0), &steps, 0.8)?;
        // The sample list back at the top.
        snapshot::scroll(window, 120.0, 400.0, 5000.0);
    }
    Ok(())
}

/// Renders every sample, and a few interactions, to PNG files in `dir`.
#[cfg(not(target_arch = "wasm32"))]
fn snapshots(
    ui: &Gallery,
    state: &Rc<RefCell<State>>,
    window: &Rc<slint::platform::software_renderer::MinimalSoftwareWindow>,
    dir: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error>> {
    std::fs::create_dir_all(dir)?;
    ui.show()?;
    for (dark, suffix) in [(false, ""), (true, "-dark")] {
        ui.set_dark_mode(dark);
        // The same data in both modes.
        state.borrow_mut().rng = Rng(SEED);
        for sample in SAMPLES {
            state.borrow_mut().select(sample);
            snapshot::render(window);
            snapshot::settle(Duration::from_millis(1100));
            snapshot::save(window, &dir.join(format!("{}{suffix}.png", sample.id)))?;
        }
    }
    // A legend at the side, and hover tooltips.
    ui.set_dark_mode(false);
    let legend = SAMPLES.iter().find(|s| s.id == "legend-position").unwrap();
    state.borrow_mut().select(legend);
    ui.set_legend_position(ChartLegendPosition::Left);
    snapshot::render(window);
    snapshot::settle(Duration::from_millis(1100));
    snapshot::save(window, &dir.join("legend-left.png"))?;
    let bars = SAMPLES.iter().find(|s| s.id == "bar-vertical").unwrap();
    state.borrow_mut().select(bars);
    snapshot::render(window);
    snapshot::settle(Duration::from_millis(1100));
    snapshot::hover(window, 640.0, 400.0);
    snapshot::save(window, &dir.join("hover-bar.png"))?;
    // The one-week time series zoomed to narrower and narrower spans.
    let week = SAMPLES.iter().find(|s| s.id == "time-week").unwrap();
    state.borrow_mut().select(week);
    snapshot::render(window);
    snapshot::settle(Duration::from_millis(1100));
    for (action, name) in [(1, "day"), (2, "6h"), (3, "1h")] {
        state.borrow_mut().action(action);
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(300));
        snapshot::save(window, &dir.join(format!("time-week-{name}.png")))?;
    }
    // Keyboard navigation: click a chart to focus it, move the mouse
    // away, then use the arrow keys.
    use slint::platform::Key;
    for (id, (x, y), keys) in [
        (
            "scatter",
            (700.0, 450.0),
            &[Key::RightArrow, Key::RightArrow, Key::DownArrow][..],
        ),
        (
            "radar",
            (760.0, 420.0),
            &[Key::RightArrow, Key::RightArrow][..],
        ),
        (
            "heatmap",
            (700.0, 400.0),
            &[Key::DownArrow, Key::RightArrow, Key::RightArrow][..],
        ),
        (
            "calendar",
            (700.0, 200.0),
            &[Key::RightArrow, Key::RightArrow, Key::DownArrow][..],
        ),
        (
            "treemap",
            (560.0, 300.0),
            &[Key::RightArrow, Key::RightArrow][..],
        ),
        (
            "sunburst",
            (300.0, 650.0),
            &[Key::RightArrow, Key::RightArrow][..],
        ),
        (
            "funnel",
            (300.0, 650.0),
            &[Key::DownArrow, Key::DownArrow][..],
        ),
        ("waterfall", (700.0, 400.0), &[Key::RightArrow][..]),
        ("dumbbell", (700.0, 400.0), &[Key::DownArrow][..]),
        (
            "gantt",
            (700.0, 300.0),
            &[Key::DownArrow, Key::DownArrow][..],
        ),
        ("candlestick", (700.0, 400.0), &[Key::RightArrow][..]),
        ("radial-bar", (660.0, 432.0), &[Key::DownArrow][..]),
        (
            "matrix",
            (700.0, 400.0),
            &[Key::DownArrow, Key::RightArrow][..],
        ),
    ] {
        let sample = SAMPLES.iter().find(|s| s.id == id).unwrap();
        state.borrow_mut().select(sample);
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(1100));
        snapshot::click(window, x, y);
        snapshot::leave(window);
        for &k in keys {
            snapshot::key(window, k);
        }
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(300));
        snapshot::save(window, &dir.join(format!("keys-{id}.png")))?;
    }
    // The treemap: a tooltip, then Asia hidden from the legend.
    let tree = SAMPLES.iter().find(|s| s.id == "treemap").unwrap();
    state.borrow_mut().select(tree);
    snapshot::render(window);
    snapshot::settle(Duration::from_millis(1100));
    snapshot::hover(window, 560.0, 300.0);
    snapshot::save(window, &dir.join("treemap-hover.png"))?;
    snapshot::click(window, 625.0, 126.0);
    snapshot::render(window);
    snapshot::settle(Duration::from_millis(300));
    snapshot::save(window, &dir.join("treemap-hidden.png"))?;
    // The sunburst zoomed into Asia, a gauge band and a waterfall step.
    for (id, (x, y), click, name) in [
        ("sunburst", (850.0, 497.0), true, "sunburst-zoomed"),
        ("gauge", (1010.0, 300.0), false, "gauge-hover"),
        ("waterfall", (670.0, 420.0), false, "waterfall-hover"),
        ("axes-two", (1000.0, 420.0), false, "axes-two-hover"),
        ("candlestick", (700.0, 400.0), false, "candlestick-hover"),
        ("radial-bar", (660.0, 432.0), false, "radial-bar-hover"),
        ("matrix", (640.0, 330.0), false, "matrix-hover"),
    ] {
        let sample = SAMPLES.iter().find(|s| s.id == id).unwrap();
        state.borrow_mut().select(sample);
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(1100));
        if click {
            snapshot::click(window, x, y);
            snapshot::render(window);
            snapshot::settle(Duration::from_millis(300));
        } else {
            snapshot::hover(window, x, y);
        }
        snapshot::save(window, &dir.join(format!("{name}.png")))?;
    }
    let zoom = SAMPLES.iter().find(|s| s.id == "zoom").unwrap();
    state.borrow_mut().select(zoom);
    snapshot::render(window);
    snapshot::settle(Duration::from_millis(1100));
    snapshot::scroll(window, 740.0, 400.0, 800.0);
    snapshot::save(window, &dir.join("zoomed.png"))?;
    // The candlestick sample as OHLC bars, then zoomed in.
    let candles = SAMPLES.iter().find(|s| s.id == "candlestick").unwrap();
    state.borrow_mut().select(candles);
    state.borrow_mut().action(1);
    snapshot::render(window);
    snapshot::settle(Duration::from_millis(1100));
    snapshot::save(window, &dir.join("candlestick-ohlc.png"))?;
    snapshot::scroll(window, 740.0, 400.0, 800.0);
    snapshot::save(window, &dir.join("candlestick-zoomed.png"))?;
    // The calendar in GitHub's green, from its own color picker.
    let calendar = SAMPLES.iter().find(|s| s.id == "calendar").unwrap();
    state.borrow_mut().select(calendar);
    ui.set_calendar_colors(1);
    snapshot::render(window);
    snapshot::settle(Duration::from_millis(1100));
    snapshot::save(window, &dir.join("calendar-github.png"))?;
    ui.set_calendar_colors(0);
    // The live sample after three seconds of updates, run directly since
    // the headless snapshots have no timers.
    let live = SAMPLES.iter().find(|s| s.id == "live").unwrap();
    state.borrow_mut().select(live);
    for _ in 0..90 {
        state.borrow_mut().live_tick();
    }
    snapshot::render(window);
    snapshot::save(window, &dir.join("live-streamed.png"))?;
    // The "languages" sample in other languages, by index into `LANGUAGES`.
    let languages = SAMPLES.iter().find(|s| s.id == "languages").unwrap();
    for (language, name) in [(2, "de"), (7, "nb"), (12, "ja")] {
        ui.set_language(language);
        state.borrow_mut().select(languages);
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(1100));
        snapshot::save(window, &dir.join(format!("languages-{name}.png")))?;
    }
    ui.set_language(0);
    // A click's readout in the footer, and the code panel.
    for (dark, suffix) in [(false, ""), (true, "-dark")] {
        ui.set_dark_mode(dark);
        state.borrow_mut().rng = Rng(SEED);
        let matrix = SAMPLES.iter().find(|s| s.id == "matrix").unwrap();
        state.borrow_mut().select(matrix);
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(1100));
        snapshot::click(window, 640.0, 330.0);
        snapshot::leave(window);
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(300));
        snapshot::save(window, &dir.join(format!("click-status{suffix}.png")))?;
        open_code(ui);
        snapshot::render(window);
        snapshot::settle(Duration::from_millis(300));
        snapshot::save(window, &dir.join(format!("code-panel{suffix}.png")))?;
        ui.set_code_open(false);
    }
    Ok(())
}