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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Chart widget.
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::style::{MotionSlot, PropertyDriver};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::metrics::{effective_font, role_font};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
use std::borrow::Cow;
use std::cell::RefCell;
use std::fmt::Write as _;
/// The chart styles [`ChartWidget`] can switch between at runtime.
///
/// # Scope, and why this is not the same enum as the other `ChartType`s
///
/// This is the **control layer**'s set: one widget that can render any of these
/// styles, so a `match` over it stays exhaustive in this widget. Two same-named
/// enums exist elsewhere and are deliberately kept separate (principle #49):
///
/// * [`crate::widget::display_widgets::mini_chart::ChartType`] — `MiniChart`'s
/// two styles (`Line`, `Bar`), since a mini chart has no pie or scatter form;
/// * `crate::widget::chart_widgets::types::ChartType` — the drawing engine's
/// set, which adds `Area`.
///
/// # Why these variants are one control rather than six (rule #80)
///
/// Every variant below reads the same `series: Vec<Vec<f64>>` plus the same
/// `labels`, and every one shares the same interaction (`hovered_index`,
/// `data_point_clicked`, `data_point_hovered`). Only the drawing geometry differs.
/// Six controls would repeat the axes, the labels, the hover hit-test and the
/// signal plumbing six times — which is the duplication rule #80 exists to
/// prevent.
///
/// The multi-value variants (`Candlestick`, `BoxPlot`) read their extra numbers
/// from consecutive entries of one series rather than from a second axis. That is
/// what `set_series` makes explicit: the grouping is a documented contract of the
/// variant, not an accident of how the vector happened to be filled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ChartType {
/// Vertical bars, one per data point; the default.
#[default]
Bar,
/// Polyline connecting the data points in order.
Line,
/// Filled area between the polyline and the baseline.
Area,
/// Pie/donut wedges whose angles are proportional to each point's share of
/// the total; negative or zero-sum data draws nothing.
Pie,
/// Unconnected markers, one per data point.
Scatter,
/// Floating bars from each point to the running total, showing how each
/// increment contributes to a cumulative value.
Waterfall,
/// Progressively narrowing bars against a shared left edge, one per stage.
///
/// Reads the first `series` entry; further entries are ignored, because a
/// funnel is one measure per stage by definition.
Funnel,
/// Open/high/low/close bars, read as **four consecutive values per bar**:
/// `[open, high, low, close, open, high, low, close, …]`.
///
/// A trailing partial group is ignored rather than padded, so a caller cannot
/// get a bar drawn from an invented value.
Candlestick,
/// Five-number summaries, read as **five consecutive values per box**:
/// `[min, q1, median, q3, max, …]`.
///
/// Trailing partial groups are ignored, as for `Candlestick`.
BoxPlot,
}
impl ChartType {
/// The factory spelling of this variant, matching `CHART_PROPERTIES`.
pub fn as_str(self) -> &'static str {
match self {
ChartType::Bar => "bar",
ChartType::Line => "line",
ChartType::Area => "area",
ChartType::Pie => "pie",
ChartType::Scatter => "scatter",
ChartType::Waterfall => "waterfall",
ChartType::Funnel => "funnel",
ChartType::Candlestick => "candlestick",
ChartType::BoxPlot => "box_plot",
}
}
/// Parses a factory spelling into a variant.
pub fn from_name(name: &str) -> Option<Self> {
Some(match name {
"bar" => ChartType::Bar,
"line" => ChartType::Line,
"area" => ChartType::Area,
"pie" => ChartType::Pie,
"scatter" => ChartType::Scatter,
"waterfall" => ChartType::Waterfall,
"funnel" => ChartType::Funnel,
"candlestick" => ChartType::Candlestick,
"box_plot" => ChartType::BoxPlot,
_ => return None,
})
}
/// How many consecutive values in a series one drawn mark consumes.
///
/// One for the single-value styles, four for `Candlestick`, five for
/// `BoxPlot`. Exposed so a caller can size its data and so the drawing code and
/// the documentation cannot disagree about the grouping.
pub fn values_per_point(self) -> usize {
match self {
ChartType::Candlestick => 4,
ChartType::BoxPlot => 5,
_ => 1,
}
}
}
/// Chart widget for data visualization.
pub struct ChartWidget {
base: BaseWidget,
chart_type: ChartType,
/// The drawn series.
///
/// Always the storage; `data()` is series zero. Kept as a vector-of-vectors
/// rather than a `Vec<f64>` plus an optional second vector so that "one
/// series" and "many series" are the same code path — the previous
/// `Vec<f64>`-only model could not express the multi-value variants above
/// without a grouping convention embedded in the drawing code.
series: Vec<Vec<f64>>,
labels: Vec<String>,
hovered_index: Option<usize>,
/// How far the marks have grown from the baseline: `0.0` flat, `1.0` at their values.
///
/// # Why this is a 0..=1 fraction and not a value
///
/// [`PropertyDriver`] interpolates between `0.0` and `1.0` and **clamps its target**, so a
/// driver aimed at a datum would silently sit at `1.0` for every bar whose value is below one --
/// a chart that looks right for small integers and wrong for everything else, with no error.
/// The driver therefore carries the *progress* and each mark maps it onto its own span (see
/// [`Self::grown_from_baseline`]), which is also what makes one driver able to animate marks
/// with different heights, signs and magnitudes at once.
///
/// It rests at `1.0`: a chart is shown at its values the moment it is built, so it must not
/// animate a seeded series into place on first paint.
reveal: PropertyDriver,
/// Whether the legend strip is drawn.
show_legend: bool,
/// Whether the hover read-out is painted.
show_tooltip: bool,
/// Names shown in the legend; shorter or longer than the series list is tolerated.
series_names: Vec<String>,
/// Reused polyline buffer for the line and area renderers.
///
/// Both styles rebuilt a `Vec<Point>` per series per frame. The point set is a pure function
/// of the data and the plot geometry, so the previous frame's allocation is refilled instead.
plot_points: Vec<Point>,
/// Reused closed-polygon buffer for the area fill.
polygon_points: Vec<Point>,
/// Bumped whenever `series` is replaced, so derived geometry can be keyed on it.
data_generation: u64,
/// Cached pie wedges aligned with the slice index, keyed by the panel and the data generation.
///
/// The painter consumes an owned point list, so a per-frame buffer cannot simply be reused;
/// the wedges are kept as commands and replayed by reference instead. They depend only on the
/// data and the panel rectangle, which is what the key records.
pie_wedges: Option<(Rect, u64, Vec<Option<crate::render::RenderCommand>>)>,
/// A horizontal zoom window over the category axis, or `None` for the full axis.
zoom_x: Option<(f64, f64)>,
/// A vertical zoom window over the value axis, or `None` for the full range.
zoom_y: Option<(f64, f64)>,
/// Per-series visibility, aligned with `series`. A series past this list is visible.
series_visible: Vec<bool>,
/// Bumped when a series' visibility changes, so the cached value range can key on it.
visibility_generation: u64,
/// The value range, keyed by the data and visibility generations.
plot_range_cache: RefCell<Option<(u64, u64, (f64, f64))>>,
/// Bumped when the label list changes, which the hover read-out depends on.
label_generation: u64,
/// Bumped when the legend names change.
names_generation: u64,
/// Legend rows' labels and measured widths, with the key they were built for.
legend_rows: Vec<(String, u32)>,
legend_key: Option<(u64, usize, u32)>,
/// The hover read-out text and its measured size, with the key it was built for.
readout_cache: Option<(usize, u64, String, u32, u32)>,
/// The legend cell rectangles on the last frame, for hit-testing.
legend_hits: Vec<(Rect, usize)>,
/// The legend row under the pointer.
hovered_legend: Option<usize>,
/// Whether the host paints the hover read-out with its own tooltip control.
hover_readout_external: bool,
/// Emitted when a data point is clicked.
pub data_point_clicked: Signal1<usize>,
/// Emitted when pointer hover enters a data point bucket.
pub data_point_hovered: Signal1<usize>,
/// Emitted with the index hover is *leaving*.
///
/// Carries the index that stopped being hovered rather than the one entered, so a
/// subscriber can keep its own highlight in step without remembering the previous index
/// itself. The sibling charts carry the same signal under their own naming
/// (`bar_unhovered` on `candlestick_chart`); `ChartWidget` published only the enter half,
/// so a hover highlight could be turned on and never off.
pub data_point_unhovered: Signal1<usize>,
/// Emitted with the new normalized zoom window, or `None` when the full axis is restored.
pub zoom_changed: Signal1<Option<(f64, f64)>>,
/// Emitted with the visible `[start, end)` category range after every zoom change.
pub viewport_changed: Signal1<(usize, usize)>,
/// Emitted when the legend hides or shows a series, carrying `(series index, visible)`.
pub series_toggled: Signal1<(usize, bool)>,
/// Emitted with the new vertical zoom window, or `None` when it was restored.
pub zoom_y_changed: Signal1<Option<(f64, f64)>>,
}
impl ChartWidget {
/// Creates a new chart widget.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::Chart, geometry, "ChartWidget"),
chart_type: ChartType::default(),
series: Vec::new(),
labels: Vec::new(),
hovered_index: None,
// At rest grown: a chart is shown at its values the moment it is built.
reveal: PropertyDriver::at(1.0, MotionSlot::Normal),
show_legend: false,
show_tooltip: false,
series_names: Vec::new(),
plot_points: Vec::new(),
polygon_points: Vec::new(),
data_generation: 0,
pie_wedges: None,
zoom_x: None,
zoom_y: None,
series_visible: Vec::new(),
visibility_generation: 0,
plot_range_cache: RefCell::new(None),
label_generation: 0,
names_generation: 0,
legend_rows: Vec::new(),
legend_key: None,
readout_cache: None,
legend_hits: Vec::new(),
hovered_legend: None,
hover_readout_external: false,
data_point_clicked: Signal1::new(),
data_point_hovered: Signal1::new(),
data_point_unhovered: Signal1::new(),
zoom_changed: Signal1::new(),
viewport_changed: Signal1::new(),
series_toggled: Signal1::new(),
zoom_y_changed: Signal1::new(),
}
}
/// Returns the chart type.
pub fn chart_type(&self) -> ChartType {
self.chart_type
}
/// Returns the first series' values.
///
/// The single-series spelling of [`Self::series`], kept because it was the
/// whole API before multi-series existed and every non-multi-series style
/// still has exactly one.
pub fn data(&self) -> &[f64] {
self.series.first().map_or(&[], |series| series.as_slice())
}
/// Returns every series.
pub fn series(&self) -> &[Vec<f64>] {
&self.series
}
/// Returns the chart data labels.
pub fn labels(&self) -> &[String] {
&self.labels
}
/// Returns the index of the hovered data point, if any.
///
/// This is the accessor the module doc promises when it says every variant "shares the
/// same interaction (`hovered_index`, ...)": the field was written by `handle_event` and
/// read by nothing, so the hover state existed only as a local comparison and a caller had
/// no way to observe it. The sibling charts (`candlestick_chart`, `volume_chart`,
/// `indicator_chart`, `quote_board`, `order_book`) all expose this.
pub fn hovered_index(&self) -> Option<usize> {
self.hovered_index
}
/// The data value at the hovered index, if the index still names a point.
pub fn hovered_value(&self) -> Option<f64> {
let index = self.hovered_index?;
self.data().get(index).copied()
}
/// Sets the chart type.
pub fn set_chart_type(&mut self, chart_type: ChartType) {
if self.chart_type == chart_type {
return;
}
self.chart_type = chart_type;
self.base.request_redraw();
}
/// Sets the chart data as a single series.
pub fn set_data(&mut self, data: Vec<f64>) {
self.series = if data.is_empty() { Vec::new() } else { vec![data] };
self.series_visible = vec![true; self.series.len()];
self.visibility_generation = self.visibility_generation.wrapping_add(1);
self.data_generation = self.data_generation.wrapping_add(1);
self.restart_reveal();
self.revalidate_hover();
self.base.request_redraw();
}
/// Sets the chart data as multiple series.
///
/// Series zero is what [`Self::data`] reports, so the two setters agree about
/// which values are "the data". An empty input clears the chart, matching
/// `set_data`.
pub fn set_series(&mut self, series: Vec<Vec<f64>>) {
self.series = series;
self.series_visible = vec![true; self.series.len()];
self.visibility_generation = self.visibility_generation.wrapping_add(1);
self.data_generation = self.data_generation.wrapping_add(1);
self.restart_reveal();
self.revalidate_hover();
self.base.request_redraw();
}
/// Sets the chart data labels.
pub fn set_labels(&mut self, labels: Vec<String>) {
self.labels = labels;
self.label_generation = self.label_generation.wrapping_add(1);
self.base.request_redraw();
}
/// Sets the names shown in the legend, one per series.
pub fn set_series_names(&mut self, names: Vec<String>) {
if self.series_names == names {
return;
}
self.series_names = names;
self.names_generation = self.names_generation.wrapping_add(1);
self.base.request_redraw();
}
/// Returns the legend names.
pub fn series_names(&self) -> &[String] {
&self.series_names
}
/// Shows or hides the legend.
pub fn set_show_legend(&mut self, show: bool) {
if self.show_legend == show {
return;
}
self.show_legend = show;
self.base.request_redraw();
}
/// Returns whether the legend is shown.
pub fn show_legend(&self) -> bool {
self.show_legend
}
/// Enables the hover read-out.
pub fn set_show_tooltip(&mut self, show: bool) {
if self.show_tooltip == show {
return;
}
self.show_tooltip = show;
self.base.request_redraw();
}
/// Returns whether the hover read-out is enabled.
pub fn show_tooltip(&self) -> bool {
self.show_tooltip
}
/// The zoom window over the category axis, or `None` when the full axis is shown.
pub fn zoom_range(&self) -> Option<(f64, f64)> {
self.zoom_x
}
/// Sets a zoom window over the category axis.
///
/// The window is expressed in **category indices** (`0.0..=data.len()`), matching what
/// the wheel gesture writes, and is clamped to the data's extent. Every `x`-sequenced
/// renderer draws only the visible range, so the property is a real viewport rather than
/// a stored value nothing reads.
pub fn set_zoom_range(&mut self, range: Option<(f64, f64)>) {
let total = point_count_for(self.chart_type, self.data().len()) as f64;
let range = range.map(|(low, high)| {
let (low, high) = if low <= high { (low, high) } else { (high, low) };
(low.clamp(0.0, total.max(1.0)), high.clamp(0.0, total.max(1.0)))
});
// A degenerate window is the full axis; keeping it would draw nothing.
let range = range.filter(|(low, high)| high - low > f64::EPSILON);
if self.zoom_x == range {
return;
}
self.zoom_x = range;
let (start, end) = self.zoom_bounds();
self.zoom_changed.emit(range);
self.viewport_changed.emit((start, end));
self.base.request_redraw();
}
/// Restores both axes to their full ranges.
pub fn reset_zoom(&mut self) {
self.set_zoom_range(None);
self.set_zoom_y(None);
}
/// The vertical zoom window, or `None` when the full value range is shown.
pub fn zoom_y(&self) -> Option<(f64, f64)> {
self.zoom_y
}
/// Sets a vertical zoom window over the value axis.
///
/// A reversed window is ordered, and a degenerate one is treated as "no window": either would
/// otherwise map every mark to one pixel column.
pub fn set_zoom_y(&mut self, range: Option<(f64, f64)>) {
let range = range.map(|(low, high)| if low <= high { (low, high) } else { (high, low) });
let range = range.filter(|(low, high)| (high - low).abs() > f64::EPSILON);
if self.zoom_y == range {
return;
}
self.zoom_y = range;
self.zoom_y_changed.emit(range);
self.base.request_redraw();
}
/// Whether the series at `index` is painted.
pub fn is_series_visible(&self, index: usize) -> bool {
self.series_visible.get(index).copied().unwrap_or(true)
}
/// Hides or shows the series at `index`, re-deriving the value range when it changes.
pub fn set_series_visible(&mut self, index: usize, visible: bool) -> bool {
if index >= self.series.len() {
return false;
}
if self.series_visible.len() < self.series.len() {
self.series_visible.resize(self.series.len(), true);
}
if self.series_visible[index] == visible {
return true;
}
self.series_visible[index] = visible;
self.visibility_generation = self.visibility_generation.wrapping_add(1);
self.series_toggled.emit((index, visible));
self.base.request_redraw();
true
}
/// Whether the host, rather than this control, paints the hover read-out.
pub fn hover_readout_external(&self) -> bool {
self.hover_readout_external
}
/// Hands the hover read-out to a companion such as
/// [`ChartTooltip`](crate::widget::companions::ChartTooltip).
///
/// The inline bubble is the default because a chart without a host is still readable; this
/// switch turns it off so a host that owns one tooltip for several controls has a single
/// presentation instead of two that cannot agree.
pub fn set_hover_readout_external(&mut self, external: bool) {
if self.hover_readout_external == external {
return;
}
self.hover_readout_external = external;
self.base.request_redraw();
}
/// The hovered bucket's anchor and suggested tooltip content, for an external read-out.
///
/// Returns `None` when nothing is hovered. The anchor is the pointer bucket's centre in the
/// plot area, so a companion bubble appears beside the datum rather than at a fixed corner.
pub fn hover_anchor(
&self,
) -> Option<(Point, crate::compat::Vec<crate::widget::companions::TooltipLine>)> {
use crate::widget::companions::TooltipLine;
let index = self.hovered_index?;
let value = self.hovered_value()?;
let rect = self.geometry();
// The anchor is a bucket centre, so the label row's height only has to be representative;
// the row is reserved from the same constant the axis uses.
let label_row = rect.height.min(12) as i32;
let plot = PlotArea::of(rect, label_row);
let points = point_count_for(self.chart_type, self.data().len()).max(1);
let (start, end) = self.zoom_bounds();
let visible = end.saturating_sub(start).max(1);
let offset = index.saturating_sub(start).min(visible - 1);
let slot = (plot.right - plot.left).max(1) / visible as i32;
let x = plot.left + offset as i32 * slot + slot / 2;
let _ = points;
let (min, max) = self.plot_range();
let y = plot.y_for(value, min, max);
let mut lines = crate::compat::Vec::new();
if let Some(label) = self.labels.get(index) {
lines.push(TooltipLine::colored(
format!("{label}: {}", format_axis_value(value)),
Self::series_color(0),
));
} else {
lines.push(TooltipLine::colored(format_axis_value(value), Self::series_color(0)));
}
Some((Point::new(x, y), lines))
}
/// The visible `[start, end)` category range.
fn zoom_bounds(&self) -> (usize, usize) {
let total = point_count_for(self.chart_type, self.data().len());
if total == 0 {
return (0, 0);
}
match self.zoom_x {
Some((low, high)) => {
let start = low.floor().clamp(0.0, (total - 1) as f64) as usize;
let end = high.ceil().clamp((start + 1) as f64, total as f64) as usize;
(start, end)
}
None => (0, total),
}
}
/// Drops a hover index that the new data no longer has a point for.
///
/// Replacing a 40-point series with a 5-point one left `hovered_index` naming index 30 —
/// an index the chart cannot render and `data_point_hovered` will never emit again. The
/// sibling charts re-validate on `set_series` for the same reason; `ChartWidget` did not.
fn revalidate_hover(&mut self) {
let points = self.data().len();
if self.hovered_index.is_some_and(|index| index >= points) {
self.hovered_index = None;
self.data_point_unhovered.emit(0);
}
}
/// Maps a pointer position to the index of the point under it.
///
/// The bucket is computed from `data().len()`, so the hit area follows the
/// marks the `x`-sequenced styles actually draw.
fn data_index_at(&self, pos: Point) -> Option<usize> {
let point_count = point_count_for(self.chart_type, self.data().len());
if point_count == 0 {
return None;
}
let rect = self.base.geometry();
if !rect.contains_point(pos) || rect.width == 0 {
return None;
}
let (start, end) = self.zoom_bounds();
let visible = end.saturating_sub(start).max(1);
let local_x = (pos.x - rect.x).max(0) as u32;
let width = rect.width.max(1);
let mut idx = start + ((local_x as u64) * (visible as u64) / (width as u64)) as usize;
if idx >= end {
idx = end.saturating_sub(1);
}
Some(idx)
}
/// Restarts the value reveal, for a newly supplied series.
///
/// Both data setters call this, so a caller that replaces the whole series and one that replaces
/// a single series animate identically -- the two-places-to-remember defect this crate keeps
/// recording. `jump_to` rather than `set_target`, so a second replacement restarts from flat
/// instead of continuing from wherever the first reveal had reached.
fn restart_reveal(&mut self) {
self.reveal.jump_to(0.0);
self.reveal.set_target(1.0);
}
/// How far the marks have grown from the baseline: `0.0` flat, `1.0` at their values.
///
/// The value the draw measures with. It is `1.0` except in the frames right after a data set.
pub fn reveal_progress(&self) -> f32 {
self.reveal.value()
}
/// Maps the reveal onto one mark's own span: `baseline` at progress 0 and `value` at 1.
///
/// # Why the mapping is here and not in the driver
///
/// [`PropertyDriver`] carries a `0.0..=1.0` *fraction* and clamps its target. One driver drives
/// every mark on the chart, and those marks have different values, different signs and different
/// magnitudes -- so the driver cannot carry any of them. Each mark asks this question instead:
/// "given how far along the whole reveal is, where is *my* top edge?".
///
/// `baseline` is the value each mark starts from, which is the axis minimum for a bar (a bar
/// grows up the axis) -- a mark that started from zero on an axis spanning `-50..50` would grow
/// *downward* through the axis and cross every other mark on the way.
fn grown_from_baseline(&self, value: f64, baseline: f64) -> f64 {
grow_value(value, baseline, self.reveal.value() as f64)
}
/// The `(x, y)` extremes across every series, for the styles that share one
/// value axis.
///
/// Computed over all series rather than only series zero, so a multi-series
/// line chart does not clip the taller series out of the plot area.
fn value_range(&self) -> Option<(f64, f64)> {
let mut min = f64::INFINITY;
let mut max = f64::NEG_INFINITY;
for (index, series) in self.series.iter().enumerate() {
if !self.is_series_visible(index) {
continue;
}
for value in series {
if value.is_finite() {
min = min.min(*value);
max = max.max(*value);
}
}
}
if !min.is_finite() || !max.is_finite() {
return None;
}
Some((min, max))
}
/// Maps a value to a y coordinate under the active vertical window.
///
/// A window clamps the mark to the plot edge: the alternative is drawing it outside its own
/// panel, which reads as a rendering fault rather than as "this value is off the window".
fn project_y(&self, area: &PlotArea, value: f64, range: (f64, f64)) -> i32 {
project_value_y(self.zoom_y, area, value, range)
}
}
/// Maps `value` to a y coordinate under an optional vertical window.
///
/// A free function rather than a method because the line and area renderers fill a buffer that
/// borrows the widget mutably while they map each vertex.
fn project_value_y(
zoom: Option<(f64, f64)>,
area: &PlotArea,
value: f64,
(min, max): (f64, f64),
) -> i32 {
match zoom {
Some((low, high)) => {
let span = (high - low).max(f64::EPSILON);
let ratio = ((value - low) / span).clamp(0.0, 1.0);
area.baseline_y - (ratio * area.height_range()).round() as i32
}
None => area.y_for(value, min, max),
}
}
/// Maps `value` from `baseline` (at progress 0) to itself (at progress 1).
///
/// The identity path is exact: a settled chart is untouched to the last bit, so the resting
/// snapshot and every value assertion are exactly what they were before the reveal existed.
fn grow_value(value: f64, baseline: f64, progress: f64) -> f64 {
if progress >= 1.0 {
value
} else {
baseline + (value - baseline) * progress
}
}
/// How many drawn points a series of `len` values produces under `chart_type`.
///
/// For the grouped styles this is the number of *complete* groups, so a trailing
/// partial group is neither drawn nor hoverable — there is no mark for it.
fn point_count_for(chart_type: ChartType, len: usize) -> usize {
let per_point = chart_type.values_per_point();
if per_point <= 1 {
len
} else {
len / per_point
}
}
impl Widget for ChartWidget {
fn base(&self) -> &BaseWidget {
&self.base
}
fn set_state_theme_hook(&mut self) {
crate::style::reapply_active_theme_state(self);
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> crate::core::Size {
crate::core::Size::new(
crate::widget::metrics::dimensions::CHART_DEFAULT_WIDTH,
crate::widget::metrics::dimensions::CHART_DEFAULT_HEIGHT,
)
}
/// Advances the value reveal by `delta_ms`; `true` while the marks are still growing.
fn tick(&mut self, delta_ms: u32) -> bool {
self.reveal.tick(delta_ms)
}
fn is_animating(&self) -> bool {
self.reveal.is_moving()
}
impl_draw_bridge!();
impl_widget_property_hooks!();
/// Resolves a published event name to the control's own signal.
///
/// # Why this is explicit
///
/// `connect_event` validates a name against the capability table and registers a hub slot; only
/// `event_signal_dyn` joins that name to the signal the control actually **emits**. Without an
/// arm a published name is valid and inert, which is the silent failure
/// `tools/check_event_signal_dyn.sh` exists to make impossible: the arm set is compared against
/// the capability's published names, so the two cannot drift.
fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
use crate::signal::EventSignalRef;
match name {
"data_point_clicked" => {
Some(EventSignalRef::mapped("data_point_clicked", &self.data_point_clicked, |v| {
CapabilityValue::UInt(*v as u64)
}))
}
"data_point_hovered" => {
Some(EventSignalRef::mapped("data_point_hovered", &self.data_point_hovered, |v| {
CapabilityValue::UInt(*v as u64)
}))
}
"data_point_unhovered" => Some(EventSignalRef::mapped(
"data_point_unhovered",
&self.data_point_unhovered,
|v| CapabilityValue::UInt(*v as u64),
)),
"zoom_changed" => {
Some(EventSignalRef::mapped("zoom_changed", &self.zoom_changed, |v| match v {
Some((low, high)) => CapabilityValue::Tuple(crate::compat::Vec::from([
CapabilityValue::Float(*low),
CapabilityValue::Float(*high),
])),
None => CapabilityValue::Null,
}))
}
"viewport_changed" => {
Some(EventSignalRef::mapped("viewport_changed", &self.viewport_changed, |v| {
CapabilityValue::Tuple(crate::compat::Vec::from([
CapabilityValue::UInt(v.0 as u64),
CapabilityValue::UInt(v.1 as u64),
]))
}))
}
"series_toggled" => {
Some(EventSignalRef::mapped("series_toggled", &self.series_toggled, |v| {
CapabilityValue::Tuple(crate::compat::Vec::from([
CapabilityValue::UInt(v.0 as u64),
CapabilityValue::Bool(v.1),
]))
}))
}
"zoom_y_changed" => {
Some(EventSignalRef::mapped("zoom_y_changed", &self.zoom_y_changed, |v| match v {
Some((low, high)) => CapabilityValue::Tuple(crate::compat::Vec::from([
CapabilityValue::Float(*low),
CapabilityValue::Float(*high),
])),
None => CapabilityValue::Null,
}))
}
_ => None,
}
}
}
/// `ChartWidget`'s property contract, published under the `Chart` kind.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch.
///
/// `WidgetKind::Chart` is the kind the capability layer pairs with `GanttWidget`,
/// so `task_count` / `selected_id` / `viewport_*` / `zoom_level` belong to that
/// control. `chart_capability` publishes no properties for this control, so this
/// contract inherits the shared four and owns nothing beyond them.
impl WidgetProperties for ChartWidget {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"chart_type" => {
Ok(CapabilityValue::String(chart_type_to_str(self.chart_type()).to_string()))
}
"point_count" => Ok(CapabilityValue::UInt(point_count_for(
self.chart_type,
self.data().len(),
) as u64)),
"label_count" => Ok(CapabilityValue::UInt(self.labels().len() as u64)),
"series_count" => Ok(CapabilityValue::UInt(self.series().len() as u64)),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"chart_type" => {
self.set_chart_type(expect_chart_type(value)?);
Ok(())
}
// Both counts are derived from the series the caller supplied through
// `set_data` / `set_series` / `set_labels`.
"point_count" | "label_count" | "series_count" => {
Err(CapabilityAccessError::ReadOnlyProperty)
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of![
"chart_type",
"point_count",
"label_count",
"series_count",
BASE_PROPERTY_NAMES
]
}
}
/// Publishes `ChartType` as the shared lower-case token.
fn chart_type_to_str(chart_type: ChartType) -> &'static str {
chart_type.as_str()
}
/// Parses the shared lower-case token back, rejecting anything else.
fn expect_chart_type(value: CapabilityValue) -> Result<ChartType, CapabilityAccessError> {
match value {
CapabilityValue::String(token) => {
ChartType::from_name(&token).ok_or(CapabilityAccessError::TypeMismatch)
}
_ => Err(CapabilityAccessError::TypeMismatch),
}
}
impl Draw for ChartWidget {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.base.geometry();
// The legend's measured labels are rebuilt before the style borrow is taken, because the
// refresh needs the widget mutably and resolving the style borrows it.
if self.show_legend && self.series.len() > 1 {
self.refresh_legend(context);
}
// The plot panel is a surface, so it resolves like every other control's: the
// caller's style first, then the theme's resolved style for this control, then a
// literal. It used to be a fixed `rgb(255,255,255)` for the fill and `rgb(200,200,200)`
// for the border, which made a dark-appearance chart a white slab — and, worse,
// `draw_truncated_label` *did* read the theme, so on the dark appearance it painted the
// dark theme's ink onto that white slab: `rgb(163,163,163)` on white, 2.52:1. The panel
// and its chrome now come from one derivation, so they cannot disagree.
let style = self.base.style();
let (surface, ink) = Self::panel_colors_with(Some(style));
let label_row_height = self.category_label_line_height(context);
let plot = PlotArea::of(rect, label_row_height);
let border = style
.border_color
.or_else(|| {
crate::style::resolved_theme_style_shared("chart").and_then(|t| t.border_color)
})
.unwrap_or_else(|| surface.blend(&ink, 0.2));
// Draw chart background
context.face_with_gradient(
rect,
surface,
self.style().background_gradient.as_ref(),
self.style().surface.unwrap_or_default(),
self.style().border_radius.unwrap_or(0),
Color::BLACK,
);
// Draw border to make chart area visible
crate::widget::draw::stroke_surface_border(
context,
rect,
self.style().border_radius.unwrap_or(0),
border,
1,
);
if self.series.is_empty() {
// Empty state: axis chrome plus a message, centred on the panel.
//
// The control used to paint only its own rectangle and return, leaving a bare
// slab — no axes, no gridline, nothing that says "this is a chart with no data"
// rather than "this is a rectangle". Drawing the frame it will use once data
// arrives is what makes the two states read as the same control, and it is what
// every charting toolkit does: the axes belong to the chart, not to a series.
self.draw_value_axis(context, &plot, ink, surface, (0.0, 1.0));
let font = role_font(style, 12.0);
let line = context.text_line(rect, &font);
context.draw_text_fitted_cow(
line,
"No data",
&font,
ink.legible_on(surface, 4.5).with_alpha(160),
HorizontalAlignment::Center,
);
return;
}
// A vertical window clips the marks to the plot area; a mark clamped to the window's edge
// is already at the boundary, so nothing that fitted changes a pixel.
if self.zoom_y.is_some() {
context.push_clip(
plot.left,
plot.top_y,
(plot.right - plot.left).max(1) as u32,
(plot.baseline_y - plot.top_y).max(1) as u32,
);
}
match self.chart_type {
// The multi-series styles iterate every series, so a second series is
// drawn beside the first rather than being ignored. The single-series
// callers pass `0` and stop.
ChartType::Bar => {
// The range is scanned once per frame and shared by the axis and every series;
// each renderer used to walk all series to derive it again.
let range = self.plot_range();
let axis_range = self.zoom_y.unwrap_or(range);
self.draw_value_axis(context, &plot, ink, surface, axis_range);
for index in 0..self.series.len() {
if !self.is_series_visible(index) {
continue;
}
self.draw_bar_chart(context, rect, &plot, index, range);
}
}
ChartType::Line => {
let range = self.plot_range();
for index in 0..self.series.len() {
if !self.is_series_visible(index) {
continue;
}
self.draw_line_chart(context, rect, &plot, index, range);
}
}
ChartType::Area => {
let range = self.plot_range();
for index in 0..self.series.len() {
if !self.is_series_visible(index) {
continue;
}
self.draw_area_chart(context, rect, &plot, index, range);
}
}
ChartType::Scatter => {
let range = self.plot_range();
for index in 0..self.series.len() {
if !self.is_series_visible(index) {
continue;
}
self.draw_scatter_chart(context, rect, &plot, index, range);
}
}
ChartType::Pie => {
if self.is_series_visible(0) {
self.draw_pie_chart(context, rect);
}
}
ChartType::Waterfall => {
if self.is_series_visible(0) {
self.draw_waterfall_chart(context, rect, &plot);
}
}
ChartType::Funnel => {
if self.is_series_visible(0) {
self.draw_funnel_chart(context, rect, &plot);
}
}
ChartType::Candlestick => {
if self.is_series_visible(0) {
self.draw_candlestick_chart(context, rect, &plot);
}
}
ChartType::BoxPlot => {
if self.is_series_visible(0) {
self.draw_box_plot_chart(context, rect, &plot);
}
}
}
if self.zoom_y.is_some() {
context.pop_clip();
}
// The renderers above may borrow the chart mutably (the line/area styles refill a shared
// vertex buffer), so the style is re-resolved here rather than held across the match.
let style = self.base.style();
// ── Legend ──
//
// Opt-in, so a chart that never asked for it keeps its previous pixels. Rows are drawn
// top-down from the panel's top-right corner and a swatch carries the series colour, which
// is the only way a multi-series chart identifies which line is which. A row is also the
// toggle for its series: the label widths are measured once per name list, not per frame.
self.legend_hits.clear();
if self.show_legend && self.series.len() > 1 {
let font = effective_font(style);
let line_height = context.measure_text("M", font).height.max(1) as i32 + 4;
let mut y = rect.y + 8;
for index in 0..self.legend_rows.len() {
let (name, text_width) = &self.legend_rows[index];
let swatch_x = rect.x + rect.width as i32 - *text_width as i32 - 26;
if swatch_x < rect.x {
break;
}
let visible = self.series_visible.get(index).copied().unwrap_or(true);
// A hidden series keeps its row, weakened: the row is how it is restored.
let row_ink = if visible {
ink
} else if self.hovered_legend == Some(index) {
ink.with_alpha(150)
} else {
ink.with_alpha(110)
};
context.fill_rect(
Rect::new(swatch_x, y + 2, 10, 10),
if visible {
Self::series_color(index)
} else {
Self::series_color(index).with_alpha(70)
},
);
context.draw_text(
Point::new(swatch_x + 14, y),
name,
font,
row_ink,
HorizontalAlignment::Left,
);
self.legend_hits.push((
Rect::new(swatch_x - 2, y - 2, (*text_width + 22).max(12), line_height as u32),
index,
));
y += line_height;
if y + line_height > rect.y + rect.height as i32 {
break;
}
}
}
// ── Hover read-out ──
//
// The text and its size are cached against the hovered index and the data/label
// generations, so a still frame with the pointer parked on a bucket formats and measures
// nothing.
if self.show_tooltip && !self.hover_readout_external {
if let Some(index) = self.hovered_index {
if let Some(value) = self.hovered_value() {
let generation = self
.data_generation
.wrapping_mul(31)
.wrapping_add(self.label_generation.rotate_left(17));
let font = effective_font(style);
let fresh = matches!(
&self.readout_cache,
Some((cached, cached_generation, _, _, _))
if *cached == index && *cached_generation == generation
);
if !fresh {
let text = match self.labels.get(index) {
Some(label) => format!("{label}: {}", format_axis_value(value)),
None => format_axis_value(value),
};
let metrics = context.measure_text(&text, font);
self.readout_cache =
Some((index, generation, text, metrics.width, metrics.height.max(1)));
}
if let Some((_, _, text, width, height)) = &self.readout_cache {
let width = *width as i32 + 8;
let height = *height as i32 + 6;
let x = (rect.x + 12).min(rect.x + rect.width as i32 - width).max(rect.x);
let y = (rect.y + 8).clamp(rect.y, rect.y + rect.height as i32 - height);
let box_rect = Rect::new(x, y, width.max(1) as u32, height.max(1) as u32);
context.fill_rect(box_rect, surface);
context.draw_rect(box_rect, border);
context.draw_text_line(
box_rect,
text,
font,
ink,
HorizontalAlignment::Center,
);
}
}
}
}
}
}
/// The plot area shared by the `x`-sequenced styles.
///
/// The four margins are named so that every renderer agrees on where the baseline
/// and the top of the plot are; deriving them per-renderer is how the axes drifted
/// apart in the first place.
struct PlotArea {
/// Left edge of the plotting region.
left: i32,
/// Right edge (exclusive in arithmetic, inclusive visually).
right: i32,
/// Bottom edge, where value `min` is drawn.
baseline_y: i32,
/// Top edge, where value `max` is drawn.
top_y: i32,
/// Left edge of the control. The strip between this and [`Self::left`] is the value-axis
/// label column, and naming it here is what lets the axis draw its labels without
/// re-deriving the control's rectangle — the two would otherwise be free to disagree.
outer_left: i32,
}
/// Distance from the plot baseline down to the top of the axis label row.
const LABEL_ROW_TOP: i32 = 12;
/// The margin between the axis label row's bottom edge and the control's own edge: 1 px.
///
/// The row's height is the label's **measured** line box, so without this the label's last pixel
/// lands exactly on the border stroke.
const LABEL_ROW_BOTTOM_GUARD: i32 = 1;
/// Width of the value-axis label column, in pixels.
///
/// Wide enough for a four-character label at the axis font plus the tick gap: `1000`,
/// `-250`, `0.75` all fit. It is a **reservation**, not a measurement, because the column has
/// to be the same width for every tick — a column sized to the widest tick would shift the
/// whole plot area every time the data range crossed a digit boundary, which reads as the
/// chart jumping when a value updates.
const AXIS_LABEL_COLUMN: i32 = 34;
impl PlotArea {
/// Derives the plot area from the control's rectangle and the axis label row height.
///
/// # Why the label height is a parameter and not a constant
///
/// The bottom margin must cover the category-label row, whose height is the **measured** line
/// box of the font the labels are actually drawn in. That was a fixed `10` while the drawn font
/// is the style's effective font (`14 pt` by default), so the reservation was four pixels short
/// and the `A B C D` glyphs descended past the control's bottom edge — the P5 census caught it
/// as a `chart` path escaping the box at `y = 120.66` in a 120 px box. Deriving the margin from
/// the same font the labels use is what keeps the reservation and the ink in agreement, at any
/// text scale (principle #50).
fn of(rect: Rect, label_row_height: i32) -> Self {
const PADDING: i32 = 8;
let label_row_height = label_row_height.max(1);
let bottom_margin = LABEL_ROW_TOP + label_row_height + LABEL_ROW_BOTTOM_GUARD;
// The left margin is the value-axis label column, not just the panel padding: the axis
// draws its tick values in this strip, so the plot region has to start after them. It
// was `PADDING` alone, which left no room for a label and is why the axis could not be
// drawn at all before it was widened.
let left = rect.x.saturating_add(AXIS_LABEL_COLUMN);
let right = rect.x.saturating_add(rect.width as i32).saturating_sub(PADDING);
let baseline_y = rect.y.saturating_add(rect.height as i32).saturating_sub(bottom_margin);
let top_y = rect.y.saturating_add(PADDING);
Self { left, right, baseline_y, top_y, outer_left: rect.x }
}
/// Left edge of the strip the value-axis labels are drawn in.
fn axis_margin_left(&self) -> i32 {
self.outer_left + 2
}
/// The height available to a mark, never zero (a zero height draws nothing and
/// also divides by zero in the ratio, so the floor is load-bearing).
fn height_range(&self) -> f64 {
(self.baseline_y.saturating_sub(self.top_y)).max(1) as f64
}
/// Maps `value` to a y coordinate, given the series' extremes.
///
/// Uses `min` as well as `max` so a series with negative values or a narrow
/// range around a large offset is drawn at its true scale rather than being
/// pinned to the baseline.
fn y_for(&self, value: f64, min: f64, max: f64) -> i32 {
let span = max - min;
if !span.is_finite() || span <= 0.0 {
return self.baseline_y;
}
let ratio = (value - min) / span;
self.baseline_y - (ratio * self.height_range()) as i32
}
/// The x coordinate of point `index` out of `count`, spread across the area.
fn x_for(&self, index: usize, count: usize, inset: i32) -> i32 {
if count <= 1 {
return self.left + (self.right - self.left) / 2;
}
let span = (self.right - self.left).saturating_sub(inset * 2).max(1);
self.left + inset + (index as i32 * span) / (count as i32 - 1).max(1)
}
}
/// Formats one value-axis tick label.
///
/// Rounding is deliberate rather than `{:?}`-style: a tick is a *reading*, and the extra
/// precision of the underlying `f64` is noise on a 10 px label (`0.30000000000000004`).
/// Integers print without a decimal point, which is the common case for this control's data,
/// and fractional ticks keep one decimal — enough to tell two adjacent ticks apart, and short
/// enough to fit [`AXIS_LABEL_COLUMN`].
fn format_axis_value(value: f64) -> String {
if !value.is_finite() {
return "—".to_string();
}
if (value - value.round()).abs() < 1e-9 {
format!("{}", value.round() as i64)
} else {
format!("{value:.1}")
}
}
/// Round tick values covering `min..=max`.
///
/// The step is a nice number (1, 2, 2.5 or 5 times a power of ten) chosen so about `target`
/// intervals fit the range, which is the rule every chart axis uses. The first tick is the
/// smallest multiple of the step at or above `min`, so the labels keep their short decimal
/// spellings instead of inheriting the raw range's floating-point noise.
fn nice_ticks(min: f64, max: f64, target: usize) -> Vec<f64> {
if !min.is_finite() || !max.is_finite() || max <= min {
return Vec::new();
}
let raw = (max - min) / target.max(1) as f64;
let magnitude = 10f64.powf(raw.log10().floor());
let normalized = raw / magnitude;
let step = if normalized <= 1.0 {
1.0
} else if normalized <= 2.0 {
2.0
} else if normalized <= 2.5 {
2.5
} else if normalized <= 5.0 {
5.0
} else {
10.0
} * magnitude;
let first = (min / step).ceil() * step;
let mut values = Vec::new();
let mut value = first;
while value <= max + step * 1e-9 {
values.push(value);
value += step;
if values.len() > 64 {
break;
}
}
values
}
/// Converts an HSL colour to RGB.
///
/// Used only to extend the series palette past its declared six colours: a hue rotation keeps
/// a seventh series distinguishable, where cycling the palette would repeat the first colour.
fn hsl_to_rgb(hue_degrees: f32, saturation: f32, lightness: f32) -> Color {
let h = (hue_degrees.rem_euclid(360.0)) / 60.0;
let c = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
let (r1, g1, b1) = match h as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = lightness - c / 2.0;
let channel = |value: f32| ((value + m) * 255.0).round().clamp(0.0, 255.0) as u8;
Color { r: channel(r1), g: channel(g1), b: channel(b1), a: 255 }
}
/// Draws a label under `x`, truncated to a fixed budget so a long label cannot
/// run into its neighbour. The truncation marker is part of the visible text, so
/// it is counted in the budget rather than appended past it.
///
/// `right_bound` is the widget's own right edge: the label is centred on its tick, so a
/// tick near the edge would otherwise start inside and finish outside. Clamping the origin
/// is what keeps the axis row inside the control at any width.
fn draw_truncated_label(
context: &mut RenderContext,
x: i32,
baseline_y: i32,
label: &str,
right_bound: i32,
font: &Font,
) {
const BUDGET: usize = 6;
if label.is_empty() {
return;
}
// The budget follows the room the label actually has rather than a fixed six characters:
// the old constant cut `Category` to `Categ..` even in a wide slot, and a CJK label of six
// glyphs is twice as wide as six Latin ones. The measured `M` advance is the ruler both the
// painter and this budget share.
let char_width = context.measure_text("M", font).width.max(1) as i32;
let available = (right_bound - x - 4).max(char_width * 4);
let budget = ((available / char_width) as usize).clamp(4, 32).max(BUDGET.min(6));
let text = if label.chars().count() > budget {
let kept: String = label.chars().take(budget.saturating_sub(2)).collect();
Cow::Owned(format!("{kept}.."))
} else {
Cow::Borrowed(label)
};
let width = context.measure_text(&text, font).width as i32;
let origin_x = (x - width / 2).min(right_bound - width).max(0);
// Axis chrome, derived from the **panel the label is painted on**. The literal `80,80,80`
// is a light chart's label colour and rendered at 1.8:1 on the dark appearance — the
// category names were effectively invisible while the chart itself looked correct.
//
// This used to read `theme.colors.background`, which is the *window* colour, while the
// panel was a hardcoded white: on the dark appearance the label therefore used the dark
// theme's ink on a white slab. Both now come from `ChartWidget::panel_colors`, so the
// label cannot disagree with the panel it sits on.
let (surface, ink) = ChartWidget::panel_colors();
context.draw_text(
crate::core::Point { x: origin_x, y: baseline_y + LABEL_ROW_TOP },
&text,
font,
ink.legible_on(surface, 4.5).with_alpha(191),
HorizontalAlignment::Left,
);
}
impl ChartWidget {
/// The plot panel's surface and its ink, resolved the same way for every renderer.
///
/// The caller's style wins, then the theme's resolved style for `chart`, then a literal.
/// Factored out because the panel fill and the axis labels are painted in two different
/// functions: when each derived its own colour they drifted, and on the dark appearance
/// the labels used the theme's ink while the panel stayed hardcoded white.
///
/// `style` is the caller's override for this widget, when the caller is the paint path
/// that has one; the axis labels pass `None` and take the theme's own answer, because
/// they are reading a panel the caller already decided the colour of.
pub(crate) fn panel_colors_with(
style: Option<&crate::style::WidgetStyle>,
) -> (crate::core::Color, crate::core::Color) {
let theme = crate::style::resolved_theme_style_shared("chart");
let surface = style
.and_then(|s| s.background_color)
.or_else(|| theme.as_ref().and_then(|t| t.background_color))
.unwrap_or(crate::core::Color::rgb(255, 255, 255));
let ink = style
.and_then(|s| s.text_color)
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or_else(|| surface.contrast_color());
(surface, ink)
}
/// The plot panel's surface and ink when no caller override is in hand.
pub(crate) fn panel_colors() -> (crate::core::Color, crate::core::Color) {
Self::panel_colors_with(None)
}
/// The palette every renderer draws from.
///
/// Shared rather than repeated so a bar and the line beside it cannot be
/// different colours for the same series.
const PALETTE: [crate::core::Color; 6] = [
crate::core::Color::rgb(66, 133, 244),
crate::core::Color::rgb(219, 68, 55),
crate::core::Color::rgb(244, 180, 0),
crate::core::Color::rgb(15, 157, 88),
crate::core::Color::rgb(171, 71, 188),
crate::core::Color::rgb(0, 172, 193),
];
/// The colour of series `index`, cycling through [`Self::PALETTE`].
fn series_color(index: usize) -> crate::core::Color {
if index < Self::PALETTE.len() {
return Self::PALETTE[index];
}
// Past the palette, derive the colour from a golden-angle rotation of the hue circle:
// adjacent series stay distinguishable instead of repeating the first six colours.
let hue = ((index - Self::PALETTE.len()) as f32 * 137.508) % 360.0;
hsl_to_rgb(hue, 0.62, 0.50)
}
/// The value range the shared-axis styles plot against.
///
/// Falls back to `(0, 1)` when the series is empty or entirely non-finite, so
/// the callers never divide by a zero span. Bars and areas need a zero
/// baseline to be readable, so the minimum is clamped to zero when every value
/// is non-negative — otherwise a series of `[98, 99, 100]` would be drawn with
/// its smallest bar at the baseline and look like zero.
///
/// The answer depends only on the data and which series are visible, so it is cached on those
/// two generations. It used to rescan every series on every frame, and a hidden series now
/// leaves the range (so hiding a tall outlier actually rescales the chart).
fn plot_range(&self) -> (f64, f64) {
if let Some((data, visibility, range)) = *self.plot_range_cache.borrow() {
if data == self.data_generation && visibility == self.visibility_generation {
return range;
}
}
let range = match self.value_range() {
Some((min, max)) => {
if min >= 0.0 {
(0.0, if max > 0.0 { max } else { 1.0 })
} else {
(min, max)
}
}
None => (0.0, 1.0),
};
*self.plot_range_cache.borrow_mut() =
Some((self.data_generation, self.visibility_generation, range));
range
}
/// Draws the **value axis**: a tick column down the left of the plot area with four
/// rounded value labels, plus the gridlines they belong to.
///
/// # Why this exists
///
/// This control published a `y_axis_label` property and its module documentation described
/// a y axis, but `draw` had no left margin and no value labels at all: the highest bar
/// simply reached `rect.y + PADDING`, with nothing on screen saying what value that was.
/// A chart with no measurable scale is a picture, not a chart — every other toolkit (the
/// shared design-system table, `fl_chart`'s `leftTitles`, SwiftUI's default `AxisMarks`) draws one by
/// default. The axis is chrome, so it reads the same `ink`/`surface` pair the panel and the
/// category labels use and cannot disagree with them about the appearance.
///
/// # Tick values
///
/// Four evenly spaced steps include both extremes, so the top label is exactly the value
/// the tallest mark reaches and the bottom one is the axis minimum. They come from the same
/// [`Self::plot_range`] the marks are mapped through, which is what keeps a label and the
/// bar it labels on the same scale.
fn draw_value_axis(
&self,
context: &mut RenderContext,
area: &PlotArea,
ink: Color,
surface: Color,
(min, max): (f64, f64),
) {
const TICKS: i32 = 4;
let axis_ink = ink.legible_on(surface, 4.5).with_alpha(190);
let grid_ink = surface.blend(&axis_ink, 0.18);
let font = role_font(self.style(), 10.0);
let label_height = context.measure_text("M", &font).height.max(1) as i32;
// Ticks land on round numbers rather than on equal fractions of the range: a label of
// `0.30000000000000004` is a value no reader asked for. `nice_ticks` answers the values
// and the count it chose, so a narrow range does not produce four labels that all round
// to the same text.
let ticks = nice_ticks(min, max, TICKS as usize);
for value in ticks {
if value < min - f64::EPSILON || value > max + f64::EPSILON {
continue;
}
let y = area.y_for(value, min, max);
// The axis line and its ticks are one hairline; the gridline runs from the axis to
// the right edge of the plot so a bar can be read against it.
context.draw_line(Point::new(area.left, y), Point::new(area.right, y), grid_ink);
// The label sits in the margin the plot area reserved, vertically centred on its
// tick. `text_line` is given a band one **measured** line tall around the tick's own
// row so a tick at the top or bottom of the axis keeps its label inside the panel.
let band = Rect {
x: area.axis_margin_left(),
y: y - label_height / 2,
width: (area.left - area.axis_margin_left()).max(0) as u32,
height: label_height as u32,
};
let line = context.text_line(band, &font);
context.draw_text_fitted_cow(
line,
&format_axis_value(value),
&font,
axis_ink,
HorizontalAlignment::Right,
);
}
}
/// The height of the category-label row, measured from the font the labels are drawn in.
///
/// The category labels use the style's effective font (see `draw_truncated_label`), so the
/// reservation the plot area makes for their row has to be measured from that same font rather
/// than assumed. A fixed reservation that disagrees with the drawn font is what let the `A B C
/// D` glyphs descend past the control's bottom edge (the P5 census `chart` escape).
fn category_label_line_height(&self, context: &mut RenderContext) -> i32 {
let font = effective_font(self.style());
context.measure_text("M", font).height.max(1) as i32
}
/// Rebuilds the legend rows' labels and widths when the names or the font changed.
///
/// The rows used to be formatted and measured once per row per frame. They depend on the
/// series names, the series count and the font, so those form the key.
fn refresh_legend(&mut self, context: &mut RenderContext) {
let font = effective_font(self.base.style());
let key = (self.names_generation, self.series.len(), font.size().to_bits());
if self.legend_key == Some(key) {
return;
}
let mut rows = Vec::with_capacity(self.series.len());
let mut fallback = String::new();
for index in 0..self.series.len() {
let name = match self.series_names.get(index) {
Some(name) => name.clone(),
None => {
fallback.clear();
let _ = write!(fallback, "Series {}", index + 1);
fallback.clone()
}
};
let width = context.measure_text(&name, font).width;
rows.push((name, width));
}
self.legend_rows = rows;
self.legend_key = Some(key);
}
/// Draws vertical bars for series `series_index`.
///
/// When the widget holds several series they are drawn side by side within
/// each point's slot, which is the grouped-bar reading; with one series the
/// slot arithmetic reduces to the full slot width.
fn draw_bar_chart(
&self,
context: &mut RenderContext,
rect: Rect,
area: &PlotArea,
series_index: usize,
(min, max): (f64, f64),
) {
let data = match self.series.get(series_index) {
Some(data) if !data.is_empty() => data,
_ => return,
};
let (start, end) = self.zoom_bounds();
let visible_count = end.saturating_sub(start).max(1);
let series_total = self.series.len().max(1);
let slot = (area.right - area.left).max(1) / visible_count as i32;
let bar_width = (slot / series_total as i32).max(1);
let gap = if series_total > 1 { 1 } else { 2 };
for (offset, &val) in data[start..end].iter().enumerate() {
let i = start + offset;
let slot_x = area.left + (offset as i32) * slot;
let x = slot_x + (series_index as i32) * bar_width;
// The bar grows from the **baseline** toward its value, which is the one
// interpolation a value chart can express: the axis does not move, only the mark
// climbs it. `grown_from_baseline` maps the 0..=1 progress onto this bar's own
// `min..val` span, so the driver never has to know the data range -- it clamps to
// 0..=1, and handing it a raw value would have it snap to 0.0 for every bar below 1.
let val = self.grown_from_baseline(val, min);
let top = self.project_y(area, val, (min, max));
let color = Self::series_color(series_index);
context.fill_rect(
Rect {
x,
y: top,
width: bar_width.saturating_sub(gap).max(1) as u32,
height: area.baseline_y.saturating_sub(top).max(1) as u32,
},
color,
);
// Only the first series labels the axis: repeating the same labels once
// per series draws them on top of each other.
if series_index == 0 {
if let Some(label) = self.labels.get(i) {
let label_x = slot_x + slot / 2;
draw_truncated_label(
context,
label_x,
area.baseline_y,
label,
rect.x + rect.width as i32,
effective_font(self.style()),
);
}
}
}
}
/// Draws a polyline for series `series_index`.
fn draw_line_chart(
&mut self,
context: &mut RenderContext,
rect: Rect,
area: &PlotArea,
series_index: usize,
(min, max): (f64, f64),
) {
let point_count = match self.series.get(series_index) {
Some(data) if data.len() >= 2 => data.len(),
_ => return,
};
let color = Self::series_color(series_index);
let progress = self.reveal.value() as f64;
let zoom = self.zoom_y;
let (start, end) = self.zoom_bounds();
let visible_count = end.saturating_sub(start).max(1);
{
// The data borrow and the buffer borrow are disjoint fields, so the polyline is
// refilled in place rather than collected into a fresh `Vec`.
let Some(data) = self.series.get(series_index) else {
return;
};
let points = &mut self.plot_points;
points.clear();
points.extend(data[start..end].iter().enumerate().map(|(offset, &val)| Point {
x: area.x_for(offset, visible_count, 0),
// Same reveal as the bars: every vertex climbs from the **axis minimum**, so a
// line grows out of the baseline instead of sliding in from wherever the series
// happened to start.
y: project_value_y(zoom, area, grow_value(val, min, progress), (min, max)),
}));
}
let _ = point_count;
for pair in self.plot_points.windows(2) {
context.draw_line_stroke(pair[0], pair[1], color, 2);
}
for (offset, point) in self.plot_points.iter().enumerate() {
let i = start + offset;
context.fill_circle(*point, 3, color);
if series_index == 0 {
if let Some(label) = self.labels.get(i) {
draw_truncated_label(
context,
point.x,
area.baseline_y,
label,
rect.x + rect.width as i32,
effective_font(self.style()),
);
}
}
}
}
/// Draws a filled area between the polyline and the baseline.
///
/// # Why this is a variant rather than a second widget
///
/// The drawing engine already had an `AreaChart`, but the control layer never
/// exposed it — so the style existed and could not be asked for. It shares the
/// line chart's data model and hit-test exactly, which is the condition rule
/// #80 sets for extending rather than adding.
fn draw_area_chart(
&mut self,
context: &mut RenderContext,
rect: Rect,
area: &PlotArea,
series_index: usize,
(min, max): (f64, f64),
) {
let point_count = match self.series.get(series_index) {
Some(data) if data.len() >= 2 => data.len(),
_ => return,
};
let color = Self::series_color(series_index);
let progress = self.reveal.value() as f64;
let zoom = self.zoom_y;
let (start, end) = self.zoom_bounds();
let visible_count = end.saturating_sub(start).max(1);
{
let Some(data) = self.series.get(series_index) else {
return;
};
let points = &mut self.plot_points;
points.clear();
points.extend(data[start..end].iter().enumerate().map(|(offset, &val)| Point {
x: area.x_for(offset, visible_count, 0),
// Same reveal as the line: the fill tracks the polyline, so the two share the
// mapping rather than each computing its own height.
y: project_value_y(zoom, area, grow_value(val, min, progress), (min, max)),
}));
}
let _ = point_count;
// Fill as one closed polygon: the area under a piecewise-linear curve is a polygon, so
// one filled path replaces a one-pixel column per x. The polygon is built in the reused
// buffer instead of cloning the vertex list first.
let baseline_y = area.baseline_y;
{
let (plot, polygon) = (&self.plot_points, &mut self.polygon_points);
polygon.clear();
polygon.extend_from_slice(plot);
polygon.extend(plot.iter().rev().map(|point| Point::new(point.x, baseline_y)));
}
// The command shares a snapshot of the polygon (G-02), so `polygon_points` stays the
// reusable buffer the next frame refills.
let command = crate::render::RenderCommand::DrawPath {
points: self.polygon_points.as_slice().into(),
closed: true,
color,
filled: true,
width: 0,
};
context.execute_command_ref(&command);
for pair in self.plot_points.windows(2) {
context.draw_line_stroke(pair[0], pair[1], color, 2);
}
if series_index == 0 {
for (offset, point) in self.plot_points.iter().enumerate() {
let i = start + offset;
if let Some(label) = self.labels.get(i) {
draw_truncated_label(
context,
point.x,
area.baseline_y,
label,
rect.x + rect.width as i32,
effective_font(self.style()),
);
}
}
}
}
/// Draws floating bars from each point to the running total.
///
/// Each bar spans `previous_total` to `previous_total + value`, so a negative
/// increment draws downward from the running total — which is what makes a
/// waterfall readable rather than a set of bars at the wrong heights.
fn draw_waterfall_chart(&self, context: &mut RenderContext, rect: Rect, area: &PlotArea) {
let data = match self.series.first() {
Some(data) if !data.is_empty() => data,
_ => return,
};
let mut cumulative = 0.0f64;
let totals: Vec<(f64, f64)> = data
.iter()
.map(|&value| {
let from = cumulative;
cumulative += value;
(from, cumulative)
})
.collect();
// The range covers the running totals, which can exceed any single value.
let mut min = 0.0f64;
let mut max = 0.0f64;
for (from, to) in &totals {
min = min.min(*from).min(*to);
max = max.max(*from).max(*to);
}
let span = max - min;
if !span.is_finite() || span <= 0.0 {
return;
}
let (start, end) = self.zoom_bounds();
let visible_count = end.saturating_sub(start).max(1);
let slot = (area.right - area.left).max(1) / visible_count as i32;
let bar_width = slot.saturating_sub(2).max(1);
for (offset, &(from, to)) in totals[start..end].iter().enumerate() {
let i = start + offset;
let x = area.left + (offset as i32) * slot;
let y_from = self.project_y(area, from, (min, max));
let y_to = self.project_y(area, to, (min, max));
let top = y_from.min(y_to);
let height = (y_from - y_to).unsigned_abs().max(1);
// A rise and a fall get different colours, so the sign of each
// increment is visible without reading the numbers.
let color = if to >= from { Self::series_color(3) } else { Self::series_color(1) };
context.fill_rect(Rect { x, y: top, width: bar_width as u32, height }, color);
// A connector from this bar's top to the next bar's start, so the
// running total is traceable across the chart.
if i + 1 < end {
let connector_y = y_to;
context.draw_line_stroke(
Point { x: x + bar_width, y: connector_y },
Point { x: area.left + ((offset + 1) as i32) * slot, y: connector_y },
crate::core::Color::rgb(150, 150, 150),
1,
);
}
if let Some(label) = self.labels.get(i) {
draw_truncated_label(
context,
x + bar_width / 2,
area.baseline_y,
label,
rect.x + rect.width as i32,
effective_font(self.style()),
);
}
}
}
/// Draws progressively narrowing bars against a shared left edge.
///
/// The width is proportional to the value's share of the largest value, so the
/// silhouette narrows exactly when the numbers fall.
fn draw_funnel_chart(&self, context: &mut RenderContext, rect: Rect, area: &PlotArea) {
let data = match self.series.first() {
Some(data) if !data.is_empty() => data,
_ => return,
};
let max = data.iter().copied().fold(f64::NEG_INFINITY, f64::max);
if !max.is_finite() || max <= 0.0 {
return;
}
let (start, end) = self.zoom_bounds();
let visible_count = end.saturating_sub(start).max(1);
let available_height = area.baseline_y.saturating_sub(area.top_y).max(1);
let stage_height = (available_height / visible_count as i32).max(1);
let available_width = (area.right - area.left).max(1);
for (offset, &value) in data[start..end].iter().enumerate() {
let i = start + offset;
let ratio = (value / max).clamp(0.0, 1.0);
let width = ((ratio * available_width as f64).round() as i32).max(1);
let y = area.top_y + (offset as i32) * stage_height;
// Centred, so the narrowing reads as a funnel rather than a left-aligned
// bar chart.
let x = area.left + (available_width - width) / 2;
context.fill_rect(
Rect {
x,
y,
width: width as u32,
height: stage_height.saturating_sub(2).max(1) as u32,
},
Self::series_color(i),
);
if let Some(label) = self.labels.get(i) {
// The label sits at the stage's left edge, which for a narrow stage
// is inside the bar; centred text would be unreadable there.
draw_truncated_label(
context,
x + 2,
y + stage_height - 4,
label,
rect.x + rect.width as i32,
effective_font(self.style()),
);
}
}
}
/// Draws open/high/low/close bars.
///
/// Reads four consecutive values per mark: the body spans open→close and the
/// wick spans low→high. A rising bar is drawn in the "up" colour and a falling
/// one in the "down" colour, which is the convention that makes a candlestick
/// readable at a glance. A trailing group with fewer than four values is
/// ignored, because there is no bar to draw from it.
fn draw_candlestick_chart(&self, context: &mut RenderContext, rect: Rect, area: &PlotArea) {
const VALUES_PER_BAR: usize = 4;
let data = match self.series.first() {
Some(data) => data,
_ => return,
};
let bar_count = data.len() / VALUES_PER_BAR;
if bar_count == 0 {
return;
}
let mut min = f64::INFINITY;
let mut max = f64::NEG_INFINITY;
for bar in data.as_chunks::<VALUES_PER_BAR>().0.iter().take(bar_count) {
for value in bar {
if value.is_finite() {
min = min.min(*value);
max = max.max(*value);
}
}
}
if !min.is_finite() || !max.is_finite() || max <= min {
return;
}
let (start, end) = self.zoom_bounds();
let visible_count = end.saturating_sub(start).max(1);
let slot = (area.right - area.left).max(1) / visible_count as i32;
let body_width = slot.saturating_sub(2).max(3);
let wick_x_offset = body_width / 2;
for (offset, bar) in data
.as_chunks::<VALUES_PER_BAR>()
.0
.iter()
.take(bar_count)
.skip(start)
.take(end.saturating_sub(start))
.enumerate()
{
let (open, high, low, close) = (bar[0], bar[1], bar[2], bar[3]);
let x = area.left + (offset as i32) * slot;
let y_open = self.project_y(area, open, (min, max));
let y_close = self.project_y(area, close, (min, max));
let y_high = self.project_y(area, high, (min, max));
let y_low = self.project_y(area, low, (min, max));
let rising = close >= open;
let color = if rising { Self::series_color(3) } else { Self::series_color(1) };
// Wick: the high/low extremes, drawn first so the body covers its middle.
let wick_x = x + wick_x_offset;
context.draw_line_stroke(
Point { x: wick_x, y: y_high },
Point { x: wick_x, y: y_low },
color,
1,
);
let body_top = y_open.min(y_close);
context.fill_rect(
Rect {
x,
y: body_top,
width: body_width as u32,
// A doji (open == close) has no height; one pixel keeps it visible.
height: (y_open - y_close).unsigned_abs().max(1),
},
color,
);
}
// One label per bar, placed under every fourth value's slot.
for offset in 0..end.saturating_sub(start) {
let i = start + offset;
if let Some(label) = self.labels.get(i) {
let x = area.left + (offset as i32) * slot + slot / 2;
draw_truncated_label(
context,
x,
area.baseline_y,
label,
rect.x + rect.width as i32,
effective_font(self.style()),
);
}
}
}
/// Draws five-number summary boxes.
///
/// Reads five consecutive values per box — `min`, `q1`, `median`, `q3`, `max` —
/// draws the box between `q1` and `q3`, the median line through it, and the
/// whiskers out to `min` and `max`. A trailing partial group is ignored.
fn draw_box_plot_chart(&self, context: &mut RenderContext, rect: Rect, area: &PlotArea) {
const VALUES_PER_BOX: usize = 5;
// The median reads as a line *through* the box, so it is painted in the panel's own
// surface. It used to be a literal white, which is the light panel colour: on the
// default appearance the most-read statistic of a box plot was white on white.
let (surface, _) = Self::panel_colors_with(Some(self.style()));
let data = match self.series.first() {
Some(data) => data,
_ => return,
};
let box_count = data.len() / VALUES_PER_BOX;
if box_count == 0 {
return;
}
let mut min = f64::INFINITY;
let mut max = f64::NEG_INFINITY;
for group in data.as_chunks::<VALUES_PER_BOX>().0.iter().take(box_count) {
for value in group {
if value.is_finite() {
min = min.min(*value);
max = max.max(*value);
}
}
}
if !min.is_finite() || !max.is_finite() || max <= min {
return;
}
let (start, end) = self.zoom_bounds();
let visible_count = end.saturating_sub(start).max(1);
let slot = (area.right - area.left).max(1) / visible_count as i32;
let box_width = slot.saturating_sub(4).max(4);
let center_offset = box_width / 2;
let color = Self::series_color(0);
for (offset, group) in data
.as_chunks::<VALUES_PER_BOX>()
.0
.iter()
.take(box_count)
.skip(start)
.take(end.saturating_sub(start))
.enumerate()
{
let i = start + offset;
let (low, q1, median, q3, high) = (group[0], group[1], group[2], group[3], group[4]);
let x = area.left + (offset as i32) * slot + 2;
let cx = x + center_offset;
let y_low = self.project_y(area, low, (min, max));
let y_high = self.project_y(area, high, (min, max));
let y_q1 = self.project_y(area, q1, (min, max));
let y_q3 = self.project_y(area, q3, (min, max));
// Whiskers first, so the box covers their inner ends.
context.draw_line_stroke(
Point { x: cx, y: y_high },
Point { x: cx, y: y_low },
color,
1,
);
let box_top = y_q1.min(y_q3);
context.fill_rect(
Rect {
x,
y: box_top,
width: box_width as u32,
height: (y_q1 - y_q3).unsigned_abs().max(1),
},
color,
);
// Median: drawn in the background colour so it reads as a line *through*
// the box rather than another filled band.
let y_median = self.project_y(area, median, (min, max));
context.fill_rect(Rect { x, y: y_median, width: box_width as u32, height: 2 }, surface);
if let Some(label) = self.labels.get(i) {
draw_truncated_label(
context,
cx,
area.baseline_y,
label,
rect.x + rect.width as i32,
effective_font(self.style()),
);
}
}
}
fn draw_pie_chart(&mut self, context: &mut RenderContext, rect: Rect) {
let data_len = match self.series.first() {
Some(data) if !data.is_empty() => data.len(),
_ => return,
};
// Pie labels sit on the chart panel, so their ink comes from the same derivation as
// the panel. The literal `rgb(60,60,60)` was a light-appearance ink: on the dark
// panel it measured below the 4.5:1 floor, so every slice label disappeared.
let (_, ink) = Self::panel_colors_with(Some(self.style()));
let label_font = role_font(self.style(), 9.0);
// Only finite, positive values contribute. `filter(|v| **v > 0.0)` let `+Inf` into the total
// (and `NaN` is not `> 0.0`, so it was excluded from the sum but *not* from the per-slice
// loop below, where `val / total` on a `NaN` produced a NaN angle and a degenerate wedge).
// Filtering `is_finite()` here and at the loop keeps the two consistent.
let total: f64 = self
.series
.first()
.map_or(0.0, |data| data.iter().copied().filter(|v| v.is_finite() && *v > 0.0).sum());
if !total.is_finite() || total <= 0.0 {
return;
}
let cx = rect.x + rect.width as i32 / 2;
let cy = rect.y + rect.height as i32 / 2;
let radius = (rect.width.min(rect.height) as i32 / 2).saturating_sub(10).max(10);
// The wedge geometry is a pure function of the data and the panel rectangle. The painter
// consumes an owned point list, so the wedges are cached as commands and replayed by
// reference; only a data change or a resize rebuilds them.
let fresh = matches!(
&self.pie_wedges,
Some((cached_rect, generation, commands))
if *cached_rect == rect
&& *generation == self.data_generation
&& commands.len() == data_len
);
if !fresh {
let mut commands: Vec<Option<crate::render::RenderCommand>> =
Vec::with_capacity(data_len);
let mut start_angle = -std::f64::consts::FRAC_PI_2;
if let Some(data) = self.series.first() {
for (i, &val) in data.iter().enumerate() {
// A non-finite or non-positive wedge has no angle; skipping it keeps the
// angle sum equal to the sum of the positive values the total was taken over.
if !val.is_finite() || val <= 0.0 {
commands.push(None);
continue;
}
let slice_angle = 2.0 * std::f64::consts::PI * (val / total);
// A filled wedge: one closed path per sector instead of a fan of radial
// strokes. The stroke version left a pie that looked like spokes; a polygon
// is the shape the form actually draws.
let segments =
((radius as f64 * slice_angle * 0.5).ceil() as i32).clamp(3, 180);
let mut wedge = Vec::with_capacity(segments as usize + 2);
wedge.push(Point { x: cx, y: cy });
for step in 0..=segments {
let t = start_angle + slice_angle * (step as f64 / segments as f64);
wedge.push(Point {
x: cx + (radius as f64 * t.cos()) as i32,
y: cy + (radius as f64 * t.sin()) as i32,
});
}
commands.push(Some(crate::render::RenderCommand::DrawPath {
points: wedge.into(),
closed: true,
color: Self::series_color(i),
filled: true,
width: 0,
}));
start_angle += slice_angle;
}
}
self.pie_wedges = Some((rect, self.data_generation, commands));
}
let mut start_angle = -std::f64::consts::FRAC_PI_2;
// One buffer for every label: `format!` built a fresh `String` per slice per frame.
let mut text = crate::compat::String::new();
let Some(data) = self.series.first() else {
return;
};
for (i, &val) in data.iter().enumerate() {
// A non-finite or non-positive wedge has no angle; skipping it keeps the
// angle sum equal to the sum of the positive values the total was taken over.
if !val.is_finite() || val <= 0.0 {
continue;
}
let slice_angle = 2.0 * std::f64::consts::PI * (val / total);
let mid_angle = start_angle + slice_angle / 2.0;
let end_angle = start_angle + slice_angle;
if let Some(Some(wedge)) =
self.pie_wedges.as_ref().and_then(|(_, _, commands)| commands.get(i))
{
context.execute_command_ref(wedge);
}
if let Some(label) = self.labels.get(i) {
let label_radius = radius.saturating_add(14) as f64;
let lx = cx + (label_radius * mid_angle.cos()) as i32;
let ly = cy + (label_radius * mid_angle.sin()) as i32;
let pct = val / total * 100.0;
text.clear();
if pct >= 1.0 {
let _ =
core::fmt::Write::write_fmt(&mut text, format_args!("{label}:{pct:.0}%"));
} else {
let _ =
core::fmt::Write::write_fmt(&mut text, format_args!("{label}:{pct:.1}%"));
}
// Anchor the label's *box* on the midpoint and clamp that box to the
// control. The old origin was the anchor with no bound, so the bottom slice
// of a 120 px chart painted its label below the control.
let metrics = context.measure_text(&text, &label_font);
let label_w = metrics.width as i32;
let label_h = metrics.height as i32;
let max_x = (rect.x + rect.width as i32 - label_w).max(rect.x);
let max_y = (rect.y + rect.height as i32 - label_h).max(rect.y);
let x = (lx - label_w / 2).clamp(rect.x, max_x);
let y = (ly - label_h / 2).clamp(rect.y, max_y);
context.draw_text(
Point { x, y },
&text,
&label_font,
ink,
HorizontalAlignment::Left,
);
}
start_angle = end_angle;
}
}
/// Draws unconnected markers for series `series_index`.
fn draw_scatter_chart(
&self,
context: &mut RenderContext,
rect: Rect,
area: &PlotArea,
series_index: usize,
(min, max): (f64, f64),
) {
let data = match self.series.get(series_index) {
Some(data) if !data.is_empty() => data,
_ => return,
};
let color = Self::series_color(series_index);
let (start, end) = self.zoom_bounds();
let visible_count = end.saturating_sub(start).max(1);
let slot = (area.right - area.left).max(1) / visible_count as i32;
for (offset, &val) in data[start..end].iter().enumerate() {
let i = start + offset;
// Scatter uses the slot centre, since unconnected markers have no
// line to sit on.
let x = area.left + (offset as i32) * slot + slot / 2;
let y = self.project_y(area, val, (min, max));
context.fill_circle(Point { x, y }, 3, color);
if series_index == 0 {
if let Some(label) = self.labels.get(i) {
draw_truncated_label(
context,
x,
area.baseline_y,
label,
rect.x + rect.width as i32,
effective_font(self.style()),
);
}
}
}
}
}
impl EventHandler for ChartWidget {
fn handle_event(&mut self, event: &Event) {
self.base.handle_event(event);
if !self.base.is_enabled() {
return;
}
match event {
Event::MouseMove { pos } => {
// The legend rows are controls: hovering one highlights it, and a press toggles its
// series below.
let legend = self
.legend_hits
.iter()
.find(|(cell, _)| cell.contains_point(*pos))
.map(|(_, index)| *index);
if legend != self.hovered_legend {
self.hovered_legend = legend;
self.base.request_redraw();
}
// Entering a *different* bucket must also leave the previous one, or a
// subscriber that highlights on `data_point_hovered` accumulates highlights.
let next = self.data_index_at(*pos);
if next != self.hovered_index {
if let Some(previous) = self.hovered_index {
self.data_point_unhovered.emit(previous);
}
if let Some(index) = next {
self.hovered_index = Some(index);
self.data_point_hovered.emit(index);
} else {
// Moved off the plot area: no bucket is under the pointer.
self.hovered_index = None;
}
self.base.request_redraw();
}
}
Event::MouseLeave { .. } => {
// Without this arm `hovered_index` was only ever set, never cleared — the
// chart kept reporting a hover after the pointer left, and the stale index
// survived a `set_series` that shrank the data. Every sibling chart clears
// on leave; this one now does too.
if let Some(previous) = self.hovered_index.take() {
self.data_point_unhovered.emit(previous);
self.base.request_redraw();
}
}
Event::MousePress { pos, button, .. } if *button == 1 => {
self.base.set_mouse_pressed(true);
// A legend row toggles its series, which is how a multi-series chart is focused
// without editing the data.
if let Some((_, index)) =
self.legend_hits.iter().find(|(cell, _)| cell.contains_point(*pos)).copied()
{
let visible = self.is_series_visible(index);
let _ = self.set_series_visible(index, !visible);
return;
}
if let Some(index) = self.data_index_at(*pos) {
self.base.clicked.emit();
self.data_point_clicked.emit(index);
}
}
Event::MouseRelease { pos: _, button } if *button == 1 => {
self.base.set_mouse_pressed(false);
}
Event::Wheel { delta, modifiers, .. } => {
let pressed = crate::shortcut::Modifiers::from_event_bits(*modifiers);
if pressed.contains(crate::shortcut::Modifiers::ALT) {
// The modifier turns the same gesture into a vertical zoom, so the two axes
// share one input rather than inventing a second control.
if delta.y == 0 {
return;
}
let (low, high) = self.zoom_y.unwrap_or_else(|| self.plot_range());
let anchor = self
.hovered_value()
.map_or((low + high) / 2.0, |value| value.clamp(low, high));
let factor = if delta.y > 0 { 1.25 } else { 0.8 };
let new_low = anchor - (anchor - low) * factor;
let new_high = anchor + (high - anchor) * factor;
self.set_zoom_y(Some((new_low, new_high)));
return;
}
// Zoom the category axis around the pointer's bucket. A plot with one point has
// no axis to zoom.
let points = point_count_for(self.chart_type, self.data().len()) as f64;
if points < 2.0 || delta.y == 0 {
return;
}
let (low, high) = self.zoom_x.unwrap_or((0.0, points));
let span = (high - low).max(f64::EPSILON);
let anchor = self
.hovered_index
.map_or((low + high) / 2.0, |index| low + span * (index as f64 / points));
let factor = if delta.y > 0 { 1.25 } else { 0.8 };
let new_low = (anchor - (anchor - low) * factor).max(0.0);
let new_high = (anchor + (high - anchor) * factor).min(points);
if new_high - new_low > 0.5 {
self.set_zoom_range(Some((new_low, new_high)));
}
}
_ => { /* Other events are not relevant */ }
}
}
}
// ---------------------------------------------------------------------------
// COMP-H01 ChartCrosshair
// ---------------------------------------------------------------------------
/// A pair of axis-aligned reference lines drawn at a chart's hovered datum.
///
/// The chart publishes `data_point_hovered` / `data_point_unhovered` and this control consumes
/// them: a host calls [`Self::show_at`] on entry and [`Self::hide`] on exit. It deliberately does
/// not own the chart — one crosshair can serve several charts, and a chart that reached into an
/// overlay would be a second hit-testing path for the same datum.
///
/// # Why the position is absolute
///
/// The overlay is given the chart's rectangle, so its position is in the same coordinates the
/// chart reported. That is what lets one control serve a chart mounted anywhere without the host
/// converting coordinates twice.
pub struct ChartCrosshair {
base: BaseWidget,
position: Option<Point>,
snap_to_data_point: bool,
show_x: bool,
show_y: bool,
follow_pointer: bool,
/// Emitted with the anchor when the crosshair moves.
pub position_changed: Signal1<Point>,
}
impl ChartCrosshair {
/// Creates a hidden crosshair with both reference lines enabled.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::ChartTooltip, geometry, "ChartCrosshair"),
position: None,
snap_to_data_point: true,
show_x: true,
show_y: true,
follow_pointer: true,
position_changed: Signal1::new(),
}
}
/// The anchor, or `None` when the crosshair is hidden.
pub fn position(&self) -> Option<Point> {
self.position
}
/// Moves the anchor, or hides the crosshair with `None`.
pub fn set_position(&mut self, position: Option<Point>) {
if self.position == position {
return;
}
self.position = position;
if let Some(position) = position {
self.position_changed.emit(position);
}
self.base.request_redraw();
}
/// Shows the crosshair at `point`.
pub fn show_at(&mut self, point: Point) {
self.set_position(Some(point));
}
/// Hides the crosshair without discarding its settings.
pub fn hide(&mut self) {
self.set_position(None);
}
/// Whether the crosshair is visible.
pub fn is_visible(&self) -> bool {
self.position.is_some()
}
/// Whether the anchor is snapped to a datum's column.
pub fn snap_to_data_point(&self) -> bool {
self.snap_to_data_point
}
/// Enables or disables datum snapping.
///
/// A host that supplies an already-snapped anchor (the chart's own bucket centre) is unaffected;
/// the flag is for a host that drives the overlay from raw pointer motion.
pub fn set_snap_to_data_point(&mut self, snap: bool) {
self.snap_to_data_point = snap;
}
/// Which reference lines are painted, as `(x, y)`.
pub fn show_axes(&self) -> (bool, bool) {
(self.show_x, self.show_y)
}
/// Enables or disables each reference line independently.
pub fn set_show_axes(&mut self, show_x: bool, show_y: bool) {
if self.show_x == show_x && self.show_y == show_y {
return;
}
self.show_x = show_x;
self.show_y = show_y;
self.base.request_redraw();
}
/// Whether the anchor follows pointer motion between hovers.
pub fn follow_pointer(&self) -> bool {
self.follow_pointer
}
/// Enables or disables pointer following.
pub fn set_follow_pointer(&mut self, follow_pointer: bool) {
self.follow_pointer = follow_pointer;
}
}
impl Widget for ChartCrosshair {
fn base(&self) -> &BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn set_state_theme_hook(&mut self) {
crate::style::reapply_active_theme_state(self);
}
fn size_hint(&self) -> crate::core::Size {
crate::core::Size::new(240, 160)
}
impl_draw_bridge!();
impl_widget_property_hooks!();
}
impl EventHandler for ChartCrosshair {
fn handle_event(&mut self, event: &Event) {
self.base.handle_event(event);
match event {
Event::MouseMove { pos } | Event::PointerMove { pos, .. } => {
if self.follow_pointer && self.position.is_some() {
self.set_position(Some(*pos));
}
}
Event::MouseLeave { .. } => {
if self.follow_pointer {
self.hide();
}
}
Event::KeyPress { key: 27, .. } => self.hide(),
_ => {}
}
}
}
impl Draw for ChartCrosshair {
fn draw(&mut self, context: &mut RenderContext) {
let Some(position) = self.position else {
return;
};
let rect = self.geometry();
if !rect.contains_point(position) {
return;
}
// The lines take the theme's outline colour, which is the role a gridline/driver line
// already uses; a crosshair is chrome over data, not a datum of its own.
let color = crate::style::theme_manager()
.current_theme()
.map(|active| active.colors.outline_variant)
.unwrap_or_else(|| Color::BLACK.with_alpha(120));
if self.show_x {
context.draw_line(
Point::new(position.x, rect.y),
Point::new(position.x, rect.y + rect.height as i32),
color,
);
}
if self.show_y {
context.draw_line(
Point::new(rect.x, position.y),
Point::new(rect.x + rect.width as i32, position.y),
color,
);
}
}
}
impl WidgetProperties for ChartCrosshair {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
// `Null` is the published spelling of "hidden": a point a designer can express, rather
// than a separate visibility flag that could disagree with it.
"position" => Ok(match self.position {
Some(point) => CapabilityValue::Tuple(crate::compat::Vec::from([
CapabilityValue::Int(i64::from(point.x)),
CapabilityValue::Int(i64::from(point.y)),
])),
None => CapabilityValue::Null,
}),
"snap_to_data_point" => Ok(CapabilityValue::Bool(self.snap_to_data_point)),
"show_x" => Ok(CapabilityValue::Bool(self.show_x)),
"show_y" => Ok(CapabilityValue::Bool(self.show_y)),
"follow_pointer" => Ok(CapabilityValue::Bool(self.follow_pointer)),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"position" => {
let position = match value {
CapabilityValue::Null => None,
CapabilityValue::Tuple(items) if items.len() == 2 => {
let mut items = items.into_iter();
let x = match items.next() {
Some(CapabilityValue::Int(x)) => x as i32,
_ => return Err(CapabilityAccessError::TypeMismatch),
};
let y = match items.next() {
Some(CapabilityValue::Int(y)) => y as i32,
_ => return Err(CapabilityAccessError::TypeMismatch),
};
Some(Point::new(x, y))
}
_ => return Err(CapabilityAccessError::TypeMismatch),
};
self.set_position(position);
Ok(())
}
"snap_to_data_point" => {
let snap = match value {
CapabilityValue::Bool(snap) => snap,
_ => return Err(CapabilityAccessError::TypeMismatch),
};
self.set_snap_to_data_point(snap);
Ok(())
}
"show_x" | "show_y" => {
let CapabilityValue::Bool(flag) = value else {
return Err(CapabilityAccessError::TypeMismatch);
};
if name == "show_x" {
self.set_show_axes(flag, self.show_y);
} else {
self.set_show_axes(self.show_x, flag);
}
Ok(())
}
"follow_pointer" => {
let CapabilityValue::Bool(follow) = value else {
return Err(CapabilityAccessError::TypeMismatch);
};
self.set_follow_pointer(follow);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of![
"position",
"snap_to_data_point",
"show_x",
"show_y",
"follow_pointer",
BASE_PROPERTY_NAMES
]
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
#[test]
fn chart_mouse_interaction_emits_data_index_signals() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 100));
chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);
let clicked = Arc::new(Mutex::new(Vec::<usize>::new()));
let hovered = Arc::new(Mutex::new(Vec::<usize>::new()));
let clicked_sink = clicked.clone();
chart.data_point_clicked.connect(move |index| {
if let Ok(mut guard) = clicked_sink.lock() {
guard.push(*index);
}
});
let hovered_sink = hovered.clone();
chart.data_point_hovered.connect(move |index| {
if let Ok(mut guard) = hovered_sink.lock() {
guard.push(*index);
}
});
chart.handle_event(&Event::mouse_move(120, 50));
chart.handle_event(&Event::mouse_press(120, 50, 1));
let clicked_values = clicked.lock().expect("clicked lock poisoned").clone();
let hovered_values = hovered.lock().expect("hovered lock poisoned").clone();
assert_eq!(hovered_values, vec![2]);
assert_eq!(clicked_values, vec![2]);
}
/// Renders the chart into a software frame and returns the pixels.
fn render(chart: &mut ChartWidget, width: u32, height: u32) -> Vec<u8> {
use crate::core::{Color, Size};
use crate::render::{PaintBackend, SoftwarePaintBackend};
let mut backend = SoftwarePaintBackend::new(Size::new(width, height), 1.0);
backend.begin_frame(Color::WHITE);
let mut context = RenderContext::new(&mut backend);
chart.draw(&mut context);
backend.end_frame();
backend.frame_rgba().to_vec()
}
/// Counts pixels that are neither the white background nor the grey border.
///
/// A renderer that silently draws nothing leaves the frame at background, so
/// this is the discriminating measure for "the new variant actually painted".
fn painted_pixels(rgba: &[u8]) -> usize {
rgba.as_chunks::<4>()
.0
.iter()
.filter(|px| {
let (r, g, b) = (px[0], px[1], px[2]);
// Skip pure white (background) and the grey border family.
!((r == 255 && g == 255 && b == 255) || (r == 200 && g == 200 && b == 200))
})
.count()
}
// ── Multi-series data model (C-1) ───────────────────────────────────────
/// `zoom_x` is a real viewport: hit testing and the published signals follow it.
#[test]
fn the_zoom_window_is_consumed_by_hit_testing() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 100));
chart.set_data((0..10).map(|value| value as f64).collect());
let viewports = Arc::new(Mutex::new(Vec::<(usize, usize)>::new()));
let sink = Arc::clone(&viewports);
chart.viewport_changed.connect(move |range| sink.lock().unwrap().push(*range));
chart.set_zoom_range(Some((5.0, 10.0)));
assert_eq!(chart.zoom_range(), Some((5.0, 10.0)));
assert_eq!(*viewports.lock().unwrap(), vec![(5, 10)]);
assert_eq!(chart.data_index_at(Point::new(0, 50)), Some(5));
assert_eq!(chart.data_index_at(Point::new(199, 50)), Some(9));
chart.reset_zoom();
assert_eq!(*viewports.lock().unwrap(), vec![(5, 10), (0, 10)]);
}
#[test]
fn chart_set_data_populates_series_zero() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 100));
chart.set_data(vec![1.0, 2.0, 3.0]);
assert_eq!(chart.data(), &[1.0, 2.0, 3.0]);
assert_eq!(chart.series().len(), 1);
assert_eq!(chart.get("series_count").unwrap(), CapabilityValue::UInt(1));
}
#[test]
fn chart_set_data_empty_clears_series() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 100));
chart.set_data(vec![1.0]);
chart.set_data(Vec::new());
// An empty input must not leave a phantom series of length zero, which
// would make `series_count` report 1 for a chart with nothing in it.
assert!(chart.series().is_empty());
assert_eq!(chart.get("series_count").unwrap(), CapabilityValue::UInt(0));
}
#[test]
fn chart_set_series_keeps_every_series_and_agrees_with_data() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 100));
chart.set_series(vec![vec![1.0, 2.0], vec![3.0, 4.0, 5.0]]);
assert_eq!(chart.series().len(), 2);
assert_eq!(chart.data(), &[1.0, 2.0], "data() reports series zero");
assert_eq!(chart.get("series_count").unwrap(), CapabilityValue::UInt(2));
}
// ── C-2: the new variants ───────────────────────────────────────────────
#[test]
fn chart_every_variant_paints_something() {
for variant in [
ChartType::Bar,
ChartType::Line,
ChartType::Area,
ChartType::Pie,
ChartType::Scatter,
ChartType::Waterfall,
ChartType::Funnel,
ChartType::Candlestick,
ChartType::BoxPlot,
] {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
chart.set_chart_type(variant);
// Enough values for every variant, including the four- and five-value
// groupings.
chart.set_data(vec![
10.0, 30.0, 20.0, 40.0, 25.0, 35.0, 15.0, 45.0, 30.0, 50.0, 40.0, 60.0, 45.0, 55.0,
50.0, 70.0, 60.0, 80.0, 65.0, 75.0,
]);
let rgba = render(&mut chart, 200, 120);
assert!(
painted_pixels(&rgba) > 0,
"{variant:?} painted nothing; a variant that cannot draw is a name without a control"
);
}
}
#[test]
fn chart_grouped_variants_ignore_trailing_partial_group() {
// Seven values: one complete candlestick (4) plus three stragglers, and
// one complete box (5) plus two stragglers.
let mut candle = ChartWidget::new(Rect::new(0, 0, 200, 120));
candle.set_chart_type(ChartType::Candlestick);
candle.set_data(vec![10.0, 30.0, 5.0, 20.0, 99.0, 99.0, 99.0]);
assert_eq!(
candle.get("point_count").unwrap(),
CapabilityValue::UInt(1),
"three trailing values do not make a second candlestick"
);
let mut boxes = ChartWidget::new(Rect::new(0, 0, 200, 120));
boxes.set_chart_type(ChartType::BoxPlot);
boxes.set_data(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
assert_eq!(
boxes.get("point_count").unwrap(),
CapabilityValue::UInt(1),
"one trailing value does not make a second box"
);
}
#[test]
fn chart_values_per_point_matches_the_documented_grouping() {
assert_eq!(ChartType::Candlestick.values_per_point(), 4);
assert_eq!(ChartType::BoxPlot.values_per_point(), 5);
for variant in [
ChartType::Bar,
ChartType::Line,
ChartType::Area,
ChartType::Pie,
ChartType::Scatter,
ChartType::Waterfall,
ChartType::Funnel,
] {
assert_eq!(variant.values_per_point(), 1);
}
}
#[test]
fn chart_hover_index_follows_the_grouping() {
// With two candlesticks in a 200px wide chart, a pointer at x=150 is in the
// second bucket, not the fourth value's bucket.
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
chart.set_chart_type(ChartType::Candlestick);
chart.set_data(vec![10.0, 30.0, 5.0, 20.0, 15.0, 40.0, 10.0, 35.0]);
let hovered = Arc::new(Mutex::new(Vec::<usize>::new()));
let sink = hovered.clone();
chart.data_point_hovered.connect(move |index| {
if let Ok(mut guard) = sink.lock() {
guard.push(*index);
}
});
chart.handle_event(&Event::mouse_move(150, 50));
assert_eq!(
*hovered.lock().expect("hover lock poisoned"),
vec![1],
"the hit bucket counts bars, not raw values"
);
}
// ── C-5: the tokens round-trip (rule #82) ───────────────────────────────
#[test]
fn chart_type_token_round_trips_for_every_variant() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
for variant in [
ChartType::Bar,
ChartType::Line,
ChartType::Area,
ChartType::Pie,
ChartType::Scatter,
ChartType::Waterfall,
ChartType::Funnel,
ChartType::Candlestick,
ChartType::BoxPlot,
] {
chart
.set("chart_type", CapabilityValue::String(variant.as_str().to_string()))
.expect("every published token must be writable");
assert_eq!(chart.chart_type(), variant);
assert_eq!(
chart.get("chart_type").unwrap(),
CapabilityValue::String(variant.as_str().to_string())
);
// `from_name` and `as_str` must agree, or a token could be published
// that the parser rejects.
assert_eq!(ChartType::from_name(variant.as_str()), Some(variant));
}
assert!(chart
.set("chart_type", CapabilityValue::String("candlestick_chart".to_string()))
.is_err());
}
#[test]
fn chart_series_count_is_read_only() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
assert_eq!(
chart.set("series_count", CapabilityValue::UInt(5)),
Err(CapabilityAccessError::ReadOnlyProperty)
);
}
#[test]
fn chart_renders_negative_values_below_the_baseline() {
// A series crossing zero must use a range that includes it, or the negative
// bars would be drawn at a positive height.
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
chart.set_chart_type(ChartType::Bar);
chart.set_data(vec![-10.0, 20.0, -5.0]);
let rgba = render(&mut chart, 200, 120);
assert!(painted_pixels(&rgba) > 0);
assert_eq!(chart.chart_type(), ChartType::Bar);
}
/// Counts pixels drawn in the **first series' colour**, which is the data ink and nothing else.
///
/// [`painted_pixels`] answers "did the control draw at all", and it counts the panel fill -- so
/// it saturates at the panel's own area and cannot see a mark change height. A test about a mark's
/// size has to count the mark, which means naming its colour: the series palette is the one part
/// of this control that is deliberately data rather than chrome.
fn series_pixels(rgba: &[u8], series: usize) -> usize {
let color = ChartWidget::series_color(series);
rgba.as_chunks::<4>()
.0
.iter()
.filter(|px| px[0] == color.r && px[1] == color.g && px[2] == color.b)
.count()
}
/// Setting data makes the marks **grow** from the baseline rather than appearing at their
/// heights between two frames.
///
/// # The defect this pins
///
/// Every style drew its marks at their final positions on the first frame after a `set_data`,
/// so a chart whose values changed looked identical to one whose values had always been there --
/// the reader had no way to tell an update from a repaint. The assertions are in three parts,
/// because a driver nothing reads is not an animation: the progress must take an interior value,
/// the *painted* frame must differ at that moment, and the pixels must be **shorter** (a chart
/// that merely redrew at a different moment would satisfy "differs").
///
/// The height comparison is the half that cannot be faked: with the reveal at `1.0` the mapping
/// is the identity, so a settled chart paints exactly what it always did, and every pixel
/// assertion in this module keeps its previous meaning.
#[test]
fn setting_data_grows_the_marks_from_the_baseline() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
chart.set_chart_type(ChartType::Bar);
chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);
assert!(chart.is_animating(), "freshly set data owes frames");
assert!(chart.tick(20), "still growing after one step");
let mid = chart.reveal_progress();
assert!(mid > 0.0 && mid < 1.0, "it passes through an interior value (got {mid})");
let mid_pixels = series_pixels(&render(&mut chart, 200, 120), 0);
while chart.tick(1000) {}
assert_eq!(chart.reveal_progress(), 1.0, "and settles fully grown");
assert!(!chart.is_animating(), "owing no further frames");
let settled_pixels = series_pixels(&render(&mut chart, 200, 120), 0);
assert!(
mid_pixels > 0 && mid_pixels < settled_pixels,
"a half-grown chart must paint fewer pixels than a settled one: \
mid={mid_pixels} settled={settled_pixels}"
);
// A second set restarts the growth rather than continuing from the settled end.
chart.set_data(vec![5.0, 5.0, 5.0, 5.0]);
assert!(
chart.reveal_progress() < 1.0,
"replacing the data restarts the reveal: {}",
chart.reveal_progress()
);
}
/// Hover is observable through the accessor the module doc promises.
///
/// `hovered_index` was written by `handle_event` and read by nothing, and had no
/// accessor at all — so the "shared interaction (`hovered_index`, ...)" the module doc
/// describes was not reachable by a caller.
#[test]
fn chart_hovered_index_is_observable() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);
assert_eq!(chart.hovered_index(), None, "nothing is hovered initially");
chart.handle_event(&Event::mouse_move(120, 50));
assert_eq!(chart.hovered_index(), Some(2));
assert_eq!(chart.hovered_value(), Some(30.0));
}
/// Leaving the chart clears the hover, and says which point was left.
///
/// There was no `MouseLeave` arm, so `hovered_index` was only ever set: the chart kept
/// reporting a hover after the pointer left, and a highlight driven by
/// `data_point_hovered` could be turned on but never off. The accessor reports the index
/// that stopped being hovered, matching the sibling charts' `*_unhovered` signals.
#[test]
fn chart_mouse_leave_clears_hover_and_reports_it() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);
let unhovered = Arc::new(Mutex::new(Vec::<usize>::new()));
let sink = unhovered.clone();
chart.data_point_unhovered.connect(move |index| {
if let Ok(mut guard) = sink.lock() {
guard.push(*index);
}
});
chart.handle_event(&Event::mouse_move(120, 50));
assert_eq!(chart.hovered_index(), Some(2));
chart.handle_event(&Event::mouse_leave(120, 50));
assert_eq!(chart.hovered_index(), None, "leave must clear the hover");
assert_eq!(
unhovered.lock().expect("lock poisoned").clone(),
vec![2],
"leave must report the point it left"
);
// A second leave with nothing hovered must not emit again.
chart.handle_event(&Event::mouse_leave(120, 50));
assert_eq!(unhovered.lock().expect("lock poisoned").len(), 1);
}
/// Moving between buckets leaves the previous one before entering the next.
#[test]
fn chart_moving_between_buckets_unhovers_the_previous() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
chart.set_data(vec![10.0, 20.0, 30.0, 40.0]);
let events = Arc::new(Mutex::new(Vec::<String>::new()));
let hover_sink = events.clone();
chart.data_point_hovered.connect(move |index| {
if let Ok(mut guard) = hover_sink.lock() {
guard.push(format!("enter {index}"));
}
});
let unhover_sink = events.clone();
chart.data_point_unhovered.connect(move |index| {
if let Ok(mut guard) = unhover_sink.lock() {
guard.push(format!("leave {index}"));
}
});
chart.handle_event(&Event::mouse_move(30, 50));
chart.handle_event(&Event::mouse_move(120, 50));
assert_eq!(
events.lock().expect("lock poisoned").clone(),
vec!["enter 0".to_string(), "leave 0".to_string(), "enter 2".to_string()],
"a bucket change must leave the old bucket before entering the new one"
);
}
/// Replacing the data drops a hover that no longer names a point.
///
/// The sibling charts re-validate on `set_series`. `ChartWidget` kept a stale index, so
/// `hovered_index()` reported a point the chart cannot draw and `data_point_hovered`
/// would never fire for again.
#[test]
fn chart_replacing_data_drops_a_stale_hover() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
chart.set_data(vec![1.0; 40]);
chart.handle_event(&Event::mouse_move(150, 50));
let index = chart.hovered_index().expect("the pointer is over a point");
assert!(index >= 5, "expected a high index for a 40-point series, got {index}");
// Shrink the series below the hovered index.
chart.set_data(vec![1.0; 5]);
assert_eq!(chart.hovered_index(), None, "the stale index must be dropped");
assert_eq!(chart.hovered_value(), None);
// A hover that *is* still in range survives the replacement.
chart.handle_event(&Event::mouse_move(30, 50));
let in_range = chart.hovered_index().expect("pointer over a point");
assert!(in_range < 5);
chart.set_data(vec![1.0; 8]);
assert_eq!(chart.hovered_index(), Some(in_range), "an in-range hover is kept");
}
/// N-CH-03: a pie chart with `NaN`/`+Inf` slices draws without producing NaN angles.
///
/// `filter(|v| **v > 0.0)` admitted `+Inf` into the total, and the per-slice guard `val <= 0.0`
/// is false for `NaN`, so a `NaN` slice reached `val / total` and produced a NaN angle and a
/// degenerate wedge. Rendering must complete and the output must be parseable.
#[test]
fn pie_chart_with_non_finite_slices_renders_no_nan_angles() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 200, 120));
chart.set_chart_type(ChartType::Pie);
chart.set_data(vec![f64::NAN, 1.0, f64::INFINITY, 2.0, -1.0]);
// Debug builds would have produced `NaN as i32 == 0` coordinates; reaching here is the check.
let svg = crate::widget::svg::render_widget_to_svg(&mut chart, Rect::new(0, 0, 200, 120));
assert!(svg.starts_with("<svg"));
assert!(!svg.contains("NaN"), "no NaN may reach the rendered geometry: {svg}");
assert!(!svg.contains("inf"), "no infinity may reach the rendered geometry");
}
#[test]
fn legend_and_tooltip_are_opt_in_and_paint() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 240, 160));
chart.set_series(vec![vec![1.0, 2.0], vec![3.0, 1.0]]);
chart.set_series_names(vec!["first".to_string(), "second".to_string()]);
let without = crate::widget::svg::render_to_svg(&mut chart);
chart.set_show_legend(true);
let with = crate::widget::svg::render_to_svg(&mut chart);
assert_ne!(without, with, "the legend adds visible text");
chart.set_show_tooltip(true);
chart.handle_event(&Event::MouseMove { pos: Point::new(60, 80) });
assert!(chart.hovered_index().is_some());
}
#[test]
fn the_palette_extends_past_its_declared_six_colours() {
let first = ChartWidget::series_color(6);
assert_ne!(first, ChartWidget::series_color(0));
assert_ne!(first, ChartWidget::series_color(7));
}
#[test]
fn axis_ticks_land_on_round_numbers() {
let ticks = nice_ticks(0.0, 100.0, 4);
assert!(ticks.len() >= 3);
assert!(ticks.iter().all(|value| (value - value.round()).abs() < 1e-9));
let narrow = nice_ticks(0.0, 1.0, 4);
assert!(narrow.windows(2).all(|pair| pair[1] > pair[0]));
}
}
#[cfg(test)]
mod issue_2_8_tests {
use super::*;
use std::sync::{Arc, Mutex};
/// SP-11: hiding a series removes it from the value range and reports the toggle.
#[test]
fn hiding_a_series_rescales_the_range_and_reports_it() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 320, 200));
chart.set_series(vec![vec![1.0, 2.0], vec![3.0, 4.0]]);
assert_eq!(chart.plot_range(), (0.0, 4.0));
let seen = Arc::new(Mutex::new(Vec::<(usize, bool)>::new()));
let sink = seen.clone();
chart.series_toggled.connect_ref(move |event| {
if let Ok(mut guard) = sink.lock() {
guard.push(*event);
}
});
assert!(chart.set_series_visible(1, false));
assert_eq!(chart.plot_range(), (0.0, 2.0));
assert_eq!(
seen.lock().ok().map(|guard| guard.clone()).unwrap_or_default(),
vec![(1, false)]
);
assert!(chart.set_series_visible(1, true));
assert_eq!(chart.plot_range(), (0.0, 4.0));
}
/// SP-12: the vertical window is a real window, not a stored value.
#[test]
fn the_vertical_zoom_window_is_stored_ordered_and_reset() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 320, 200));
chart.set_series(vec![vec![0.0, 10.0, 20.0]]);
chart.set_zoom_y(Some((15.0, 5.0)));
assert_eq!(chart.zoom_y(), Some((5.0, 15.0)));
chart.reset_zoom();
assert_eq!(chart.zoom_y(), None);
assert_eq!(chart.zoom_range(), None);
}
/// COMP-H01: the crosshair hides itself, and its anchor is what it was told.
#[test]
fn the_crosshair_shows_hides_and_reports_its_anchor() {
let mut crosshair = ChartCrosshair::new(Rect::new(0, 0, 200, 120));
assert!(!crosshair.is_visible());
crosshair.show_at(Point::new(20, 40));
assert!(crosshair.is_visible());
assert_eq!(crosshair.position(), Some(Point::new(20, 40)));
crosshair.hide();
assert!(!crosshair.is_visible());
crosshair.set_show_axes(false, true);
assert_eq!(crosshair.show_axes(), (false, true));
}
/// COMP-H03: the hover anchor answers where and what the host should show.
#[test]
fn the_hover_anchor_reports_the_bucket_and_its_text() {
let mut chart = ChartWidget::new(Rect::new(0, 0, 320, 200));
chart.set_series(vec![vec![1.0, 2.0, 3.0]]);
chart.set_labels(vec!["a".to_string(), "b".to_string(), "c".to_string()]);
assert!(chart.hover_anchor().is_none());
chart.hovered_index = Some(1);
let (anchor, lines) = chart.hover_anchor().expect("a hovered bucket has an anchor");
assert!(lines.iter().any(|line| line.text.contains("b: 2")));
assert!(anchor.x > 0);
chart.set_hover_readout_external(true);
assert!(chart.hover_readout_external());
}
}