rust_widgets 2.9.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! RadarChart — multi-series values plotted on a shared set of dimension axes.
//!
//! # Why this is a control of its own rather than a `ChartWidget` variant
//!
//! `ChartWidget`'s data model is a one-dimensional ordered series (`Vec<f64>`
//! plus a label per point), and every one of its nine styles is a function of
//! `(index, value)`. A radar chart's geometry is a function of `(axis, series)`:
//! the angle comes from **which dimension** a value belongs to, and each series
//! becomes a closed polygon over those dimensions.
//!
//! Those are not the same shape:
//!
//! | | `ChartWidget` | `RadarChart` |
//! |---|---|---|
//! | data | `Vec<Vec<f64>>` — series over one index order | `Vec<Vec<f64>>` — series **over dimensions** |
//! | x position | derived from the point's index | derived from the **dimension's angle** |
//! | a series draws | a line of marks | a **closed polygon** |
//! | axes | one value axis, implied | **one axis per dimension**, labelled |
//!
//! Forcing radar into `ChartWidget` would mean adding a second, incompatible
//! meaning for the same fields — which rule #80's criterion (\"same data model *and*
//! same interaction\") does not permit. Hence a separate `WidgetKind`.
//!
//! # What is shared rather than duplicated
//!
//! The legend, the hover readout and the colour palette follow `ChartWidget`'s
//! conventions (same palette order, same hover-by-nearest-index signal shape), so
//! a caller switching between the two does not have to relearn them.

//! # Reachability
//!
//! Registered in the widget factory as `radar_chart` (aliases `radar`, `spider_chart`),
//! so it is reachable by name from the declarative JSON path (`"radarchart"`), from a
//! CSS selector (`RadarChart`), and through the typed `create_radar_chart` on
//! `ControlBackend`. `WidgetKind::RadarChart` is its own kind rather than a
//! `chart_type` token, because its data model is series-over-dimensions.

use core::fmt::Write as _;

use crate::core::{deg_to_rad, Color, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::{RenderContext, TEXT_FIT_MARGIN};
use crate::signal::Signal1;
use crate::style::{MotionSlot, PropertyDriver};
use crate::widget::capability::coercion::expect_bool;
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::role_font;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// The angular start of the first axis, in degrees measured clockwise from
/// 12 o'clock.
///
/// North rather than east because a radar chart is read like a compass rose: the
/// first dimension should be the one directly above the centre, and every
/// documented example of the form does it that way.
const FIRST_AXIS_DEGREES: f32 = 0.0;

/// The six series colours, in `ChartWidget`'s order.
///
/// Duplicated as a constant rather than imported because `ChartWidget::PALETTE` is
/// private to that module; the *order* is what matters for consistency, and the
/// comment is what keeps the two from drifting apart unnoticed.
const PALETTE: [Color; 6] = [
    Color::rgb(66, 133, 244),
    Color::rgb(219, 68, 55),
    Color::rgb(244, 180, 0),
    Color::rgb(15, 157, 88),
    Color::rgb(171, 71, 188),
    Color::rgb(0, 172, 193),
];

/// The chart's resolved chrome, so one `style`-then-theme lookup feeds every consumer.
///
/// Five fields because five distinct things are painted; the **series palette is deliberately
/// absent**, because a series colour is data rather than chrome (see [`RadarChart::chrome_colors`]).
#[derive(Debug, Clone, Copy)]
struct RadarChrome {
    /// The plotting surface the polygons are drawn on.
    surface: Color,
    /// The control's own frame.
    border: Color,
    /// The rings and spokes. Weaker than `border`, derived from it.
    grid: Color,
    /// The axis names.
    label: Color,
    /// The "No data" caption.
    placeholder: Color,
    /// The legend's text and the hover read-out's text.
    ///
    /// # Why these are chrome rather than data
    ///
    /// A legend's own words and a hover read-out name what the chart shows; they are not part
    /// of what it plots. They used to be literals (`rgb(70,70,70)` and `rgb(60,60,60)`), which
    /// were the only two places in this control a dark theme still produced dark-on-dark text —
    /// the five colours resolved here simply did not cover them, so the legend and the read-out
    /// bypassed the one derivation every other piece of chrome goes through.
    legend_ink: Color,
    /// The spoke drawn from the centre to the hovered dimension's vertex.
    ///
    /// Chrome, not data: it points at a dimension rather than plotting a value.
    hover_spoke: Color,
}

/// Nudges a text box of `width`×`height` at `(x, y)` back inside `rect`.
///
/// The returned box is the caller's own measured size, moved so it lies within `rect`.
/// A box larger than the control cannot be made to fit by moving, so it is pinned to the
/// control's origin and left for `draw_text_fitted` to fit to the room that remains:
/// the fitting step is the one place that answers "too wide to fit", and duplicating
/// that judgement here would let the two disagree.
fn label_box(x: i32, y: i32, width: i32, height: i32, rect: Rect) -> Rect {
    let max_x = (rect.x + rect.width as i32 - width).max(rect.x);
    let max_y = (rect.y + rect.height as i32 - height).max(rect.y);
    Rect::new(x.clamp(rect.x, max_x), y.clamp(rect.y, max_y), width as u32, height as u32)
}

/// A radar (spider) chart: several series measured against shared dimension axes.
///
/// # Data model
///
/// `axes[i]` names dimension `i`. `series[s][i]` is series `s`'s value on
/// dimension `i`. Every series is plotted against the same axes, so a series
/// shorter than `axes` leaves the trailing dimensions at zero — the honest reading
/// of \"no value supplied\" on a chart where the dimension exists.
pub struct RadarChart {
    base: BaseWidget,
    axes: Vec<String>,
    series: Vec<Vec<f64>>,
    /// Display names, index-aligned with `series`. An empty entry falls back to `Series N`.
    series_names: Vec<String>,
    /// Whether the value rings and the spoke lines are drawn.
    show_grid: bool,
    /// Whether axis names are drawn around the perimeter.
    show_axis_labels: bool,
    /// Whether the legend is drawn.
    show_legend: bool,
    /// The axis index nearest the pointer, or `None` when the pointer is away.
    hovered_axis: Option<usize>,
    /// The `(series, axis)` vertex nearest the pointer.
    hovered_vertex: Option<(usize, usize)>,
    /// Per-series visibility, index-aligned with `series` and short lists treated as visible.
    ///
    /// A hidden series is skipped by the paint and by the hit tests, which is what lets a reader
    /// isolate two overlapping polygons on a crowded chart (SP-55).
    series_visible: Vec<bool>,
    /// Per-axis maximum values. Empty means every axis uses the shared data maximum.
    axis_maxima: Vec<f64>,
    /// The number of concentric value rings.
    ring_count: u32,
    /// Whether polygons grow out from the centre on first paint.
    animate_entry: bool,
    /// The entry animation's progress.
    reveal: PropertyDriver,
    /// Emitted when the pointer's nearest axis changes.
    pub axis_hovered: Signal1<usize>,
    /// Emitted when a series polygon is clicked, carrying the series index.
    pub series_clicked: Signal1<usize>,
    /// Emitted when a `(series, axis)` vertex is hovered or clicked.
    pub vertex_hovered: Signal1<(usize, usize)>,
    /// Emitted when a `(series, axis)` vertex is clicked.
    pub vertex_clicked: Signal1<(usize, usize)>,
    /// Emitted with `(series, visible)` after a series is shown or hidden.
    pub series_visibility_changed: Signal1<(usize, bool)>,
}

impl RadarChart {
    /// Creates a radar chart with no axes and no series.
    ///
    /// Defaults: grid on, axis labels on, legend on.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::RadarChart, geometry, "RadarChart"),
            axes: Vec::new(),
            series: Vec::new(),
            series_names: Vec::new(),
            show_grid: true,
            show_axis_labels: true,
            show_legend: true,
            hovered_axis: None,
            hovered_vertex: None,
            series_visible: Vec::new(),
            axis_maxima: Vec::new(),
            ring_count: 4,
            animate_entry: false,
            reveal: PropertyDriver::at(1.0, MotionSlot::Normal),
            axis_hovered: Signal1::new(),
            series_clicked: Signal1::new(),
            vertex_hovered: Signal1::new(),
            vertex_clicked: Signal1::new(),
            series_visibility_changed: Signal1::new(),
        }
    }

    /// Sets a maximum for each dimension.
    ///
    /// A radar chart compares dimensions with different units (speed, weight, cost), so one
    /// shared maximum flattens every axis whose own range is smaller. An entry of zero or a
    /// non-finite value means "use the shared data maximum" for that axis; a shorter list
    /// leaves the remaining axes shared too.
    pub fn set_axis_maxima(&mut self, maxima: Vec<f64>) {
        if self.axis_maxima == maxima {
            return;
        }
        self.axis_maxima = maxima;
        self.base.request_redraw();
    }

    /// Returns the per-axis maxima as configured.
    pub fn axis_maxima(&self) -> &[f64] {
        &self.axis_maxima
    }

    /// The maximum used to scale `axis`.
    pub fn axis_maximum(&self, axis: usize) -> Option<f64> {
        match self.axis_maxima.get(axis).copied() {
            Some(value) if value.is_finite() && value > 0.0 => Some(value),
            _ => self.data_max(),
        }
    }

    /// Sets the number of concentric value rings (clamped to one through twelve).
    pub fn set_ring_count(&mut self, rings: u32) {
        let rings = rings.clamp(1, 12);
        if self.ring_count == rings {
            return;
        }
        self.ring_count = rings;
        self.base.request_redraw();
    }

    /// Returns the number of concentric value rings.
    pub fn ring_count(&self) -> u32 {
        self.ring_count
    }

    /// Enables the polygon entry animation.
    pub fn set_animate_entry(&mut self, animate: bool) {
        if self.animate_entry == animate {
            return;
        }
        self.animate_entry = animate;
        if animate {
            self.reveal.jump_to(0.0);
            self.reveal.set_target(1.0);
        } else {
            self.reveal.jump_to(1.0);
        }
        self.base.request_redraw();
    }

    /// Returns whether polygons animate in.
    pub fn animate_entry(&self) -> bool {
        self.animate_entry
    }

    /// The `(series, axis)` vertex under the pointer, if any.
    pub fn hovered_vertex(&self) -> Option<(usize, usize)> {
        self.hovered_vertex
    }

    /// The radius scale the polygons are drawn at, in `0.0..=1.0`.
    fn reveal_scale(&self) -> f32 {
        if self.animate_entry {
            self.reveal.value()
        } else {
            1.0
        }
    }

    /// Replaces the dimension axes with `axes`.
    ///
    /// At least three axes are needed for a polygon, so fewer than three is
    /// refused and the previous axes are kept: a two-spoke \"radar\" is a line, and
    /// silently drawing one would look like a rendering fault rather than a
    /// rejected input.
    pub fn set_axes(&mut self, axes: Vec<String>) -> bool {
        if axes.len() < 3 {
            return false;
        }
        self.axes = axes;
        self.hovered_axis = None;
        self.base.request_redraw();
        true
    }

    /// Returns the dimension axis labels.
    pub fn axes(&self) -> &[String] {
        &self.axes
    }

    /// Returns the number of dimension axes.
    pub fn axis_count(&self) -> usize {
        self.axes.len()
    }

    /// Replaces every series.
    pub fn set_series(&mut self, series: Vec<Vec<f64>>) {
        self.series = series;
        // A visibility flag belongs to a *position*, and replacing the list keeps the reader's
        // per-position choices where they still address a series.
        self.series_visible.resize(self.series.len(), true);
        self.base.request_redraw();
    }

    /// Shows or hides series `index`, returning `false` when the index is not a series.
    pub fn set_series_visible(&mut self, index: usize, visible: bool) -> bool {
        if index >= self.series.len() {
            return false;
        }
        if self.series_visible.len() <= index {
            self.series_visible.resize(index + 1, true);
        }
        if self.series_visible[index] == visible {
            return true;
        }
        self.series_visible[index] = visible;
        self.series_visibility_changed.emit((index, visible));
        self.base.request_redraw();
        true
    }

    /// Whether series `index` is painted; an index past the list answers `false`.
    pub fn is_series_visible(&self, index: usize) -> bool {
        if index >= self.series.len() {
            return false;
        }
        self.series_visible.get(index).copied().unwrap_or(true)
    }

    /// Toggles series `index`, as a legend click does.
    pub fn toggle_series_visible(&mut self, index: usize) -> bool {
        let next = !self.is_series_visible(index);
        self.set_series_visible(index, next)
    }

    /// Returns every series.
    pub fn series(&self) -> &[Vec<f64>] {
        &self.series
    }

    /// Returns the number of series.
    pub fn series_count(&self) -> usize {
        self.series.len()
    }

    /// Returns the series display names as configured.
    ///
    /// Entries are index-aligned with the series and may be shorter; a series with no name still
    /// draws, under the `Series N` fallback.
    pub fn series_names(&self) -> &[String] {
        &self.series_names
    }

    /// Replaces the series display names.
    pub fn set_series_names(&mut self, names: Vec<String>) {
        if self.series_names == names {
            return;
        }
        self.series_names = names;
        self.base.request_redraw();
    }

    /// Names one series, returning `false` when the index is not a series.
    ///
    /// # Why a name is a separate row from the values
    ///
    /// The legend and the hover read-out had to call every series `Series N`, because the only thing
    /// the chart knew about a series was its values. A name is the one datum the *reader* needs that
    /// the numbers do not carry.
    pub fn set_series_name(&mut self, index: usize, name: impl Into<String>) -> bool {
        if index >= self.series.len() {
            return false;
        }
        if self.series_names.len() <= index {
            self.series_names.resize(index + 1, String::new());
        }
        self.series_names[index] = name.into();
        self.base.request_redraw();
        true
    }

    /// The display name of series `index`, or `None` when it has none.
    fn series_name(&self, index: usize) -> Option<&str> {
        self.series_names.get(index).map(String::as_str).filter(|name| !name.is_empty())
    }

    /// Adds one series, returning its index.
    pub fn add_series(&mut self, values: Vec<f64>) -> usize {
        let index = self.series.len();
        self.series.push(values);
        self.series_visible.resize(self.series.len(), true);
        self.base.request_redraw();
        index
    }

    /// Returns the value of `series` on `axis`, or `None` when either index is
    /// unset.
    ///
    /// A series shorter than the axis list reports `None` rather than `0.0`, so a
    /// caller can tell \"no value\" from \"a value of zero\".
    pub fn value_at(&self, series: usize, axis: usize) -> Option<f64> {
        self.series.get(series).and_then(|values| values.get(axis)).copied()
    }

    /// Whether the grid rings and spokes are drawn.
    pub fn show_grid(&self) -> bool {
        self.show_grid
    }

    /// Sets whether the grid rings and spokes are drawn.
    pub fn set_show_grid(&mut self, show: bool) {
        if self.show_grid == show {
            return;
        }
        self.show_grid = show;
        self.base.request_redraw();
    }

    /// Whether axis names are drawn.
    pub fn show_axis_labels(&self) -> bool {
        self.show_axis_labels
    }

    /// Sets whether axis names are drawn.
    pub fn set_show_axis_labels(&mut self, show: bool) {
        if self.show_axis_labels == show {
            return;
        }
        self.show_axis_labels = show;
        self.base.request_redraw();
    }

    /// Whether the legend is drawn.
    pub fn show_legend(&self) -> bool {
        self.show_legend
    }

    /// Sets whether the legend is drawn.
    pub fn set_show_legend(&mut self, show: bool) {
        if self.show_legend == show {
            return;
        }
        self.show_legend = show;
        self.base.request_redraw();
    }

    /// The largest value in the data, or `None` when there is none.
    ///
    /// Every series is scaled against the same maximum so the polygons are
    /// comparable; scaling each series against its own maximum would make a series
    /// of small numbers look identical to one of large numbers.
    fn data_max(&self) -> Option<f64> {
        let max = self
            .series
            .iter()
            .flatten()
            .copied()
            .filter(|value| value.is_finite())
            .fold(f64::NEG_INFINITY, f64::max);
        if max.is_finite() && max > 0.0 {
            Some(max)
        } else {
            None
        }
    }

    /// The geometry the plot is drawn within.
    ///
    /// The legend reserves a strip on the right and the axis labels need room
    /// outside the outermost ring, so the radius is derived from the smallest
    /// usable dimension rather than from the raw rectangle.
    fn geometry_center_radius(&self) -> Option<(Point, u32)> {
        let rect = self.base.geometry();
        if rect.width == 0 || rect.height == 0 {
            return None;
        }
        /// Room outside the outermost ring for the axis labels.
        const LABEL_MARGIN: u32 = 44;
        /// Room on the right for the legend.
        const LEGEND_WIDTH: u32 = 96;
        /// Room below for the legend-free bottom margin.
        const BOTTOM_MARGIN: u32 = 8;

        let legend = if self.show_legend && !self.series.is_empty() { LEGEND_WIDTH } else { 0 };
        let usable_w = rect.width.saturating_sub(LABEL_MARGIN * 2 + legend).max(1);
        let usable_h = rect.height.saturating_sub(LABEL_MARGIN + BOTTOM_MARGIN).max(1);
        let radius = usable_w.min(usable_h) / 2;
        if radius < 8 {
            return None;
        }
        let center = Point::new(
            rect.x + LABEL_MARGIN as i32 + radius as i32,
            rect.y + LABEL_MARGIN as i32 + radius as i32,
        );
        Some((center, radius))
    }

    /// The angle of `axis` in radians, measured clockwise from 12 o'clock.
    fn axis_angle(&self, axis: usize) -> f32 {
        let count = self.axis_count().max(1) as f32;
        let step = 360.0 / count;
        // `-90` converts \"0 degrees = 3 o'clock\" to \"0 degrees = 12 o'clock\".
        deg_to_rad(FIRST_AXIS_DEGREES + step * axis as f32 - 90.0)
    }

    /// The point a series reaches on `axis`, given the plot geometry.
    fn vertex(&self, center: Point, radius: u32, angle: f32, value: f64, max: f64) -> Point {
        // Negative values would point backwards past the centre, which a radar
        // chart has no way to show; they are clamped to the centre.
        let ratio = (value / max).clamp(0.0, 1.0) as f32;
        let r = radius as f32 * ratio;
        Point::new(center.x + (r * angle.cos()) as i32, center.y + (r * angle.sin()) as i32)
    }

    /// The axis whose spoke is nearest `pos`, when the pointer is in the plot.
    /// The axis nearest `pos`'s bearing from the centre, or `None` when `pos` is outside the
    /// control.
    ///
    /// # Why the containment test comes first
    ///
    /// This used to reduce the point to an *angle* about the centre and snap that to the nearest
    /// spoke, with no rectangle test at all. An angle is defined for every point in the plane, so a
    /// press anywhere on the window -- in a sibling control, on the window's own chrome, in another
    /// window entirely once the point is translated -- still resolved to *some* axis, and the press
    /// arm then reported a series click for a gesture that never touched the chart. `nearest_series`
    /// below cannot catch it either: it picks the closest of a fixed series set with no distance
    /// threshold, so it always answers `Some`.
    ///
    /// The guard therefore belongs here, at the outermost of the two, and it is the same predicate
    /// every other control in the crate uses (`contains_point_with_touch_expansion`, which adds the
    /// device class's touch-target expansion).
    fn axis_at(&self, pos: Point) -> Option<usize> {
        if !self.base.contains_point_with_touch_expansion(pos) {
            return None;
        }
        let (center, _) = self.geometry_center_radius()?;
        if self.axis_count() == 0 {
            return None;
        }
        let dx = (pos.x - center.x) as f32;
        let dy = (pos.y - center.y) as f32;
        if dx == 0.0 && dy == 0.0 {
            return None;
        }
        // The pointer's own angle, in the same convention the axes use.
        let pointer = dy.atan2(dx).to_degrees() + 90.0;
        let step = 360.0 / self.axis_count() as f32;
        // Snap to the nearest spoke, wrapping at 360.
        let normalized = ((pointer % 360.0) + 360.0) % 360.0;
        let index = ((normalized + step / 2.0) / step).floor() as usize % self.axis_count();
        Some(index)
    }
}

impl Widget for RadarChart {
    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) -> Size {
        Size::new(
            crate::widget::metrics::dimensions::RADAR_CHART_DEFAULT_SIZE,
            crate::widget::metrics::dimensions::RADAR_CHART_DEFAULT_SIZE,
        )
    }

    /// Advances the polygon entry animation.
    fn tick(&mut self, delta_ms: u32) -> bool {
        if !self.animate_entry {
            return false;
        }
        let moving = self.reveal.tick(delta_ms);
        if moving {
            self.base.request_redraw();
        }
        moving
    }

    /// Whether the entry animation still owes frames.
    fn is_animating(&self) -> bool {
        self.animate_entry && 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 {
            "series_clicked" => {
                Some(EventSignalRef::mapped("series_clicked", &self.series_clicked, |v| {
                    CapabilityValue::UInt(*v as u64)
                }))
            }
            "axis_hovered" => {
                Some(EventSignalRef::mapped("axis_hovered", &self.axis_hovered, |v| {
                    CapabilityValue::UInt(*v as u64)
                }))
            }
            "vertex_clicked" => {
                Some(EventSignalRef::mapped("vertex_clicked", &self.vertex_clicked, |v| {
                    crate::widget::capability::CapabilityValue::Tuple(crate::compat::Vec::from([
                        crate::widget::capability::CapabilityValue::Int(v.0 as i64),
                        crate::widget::capability::CapabilityValue::Int(v.1 as i64),
                    ]))
                }))
            }
            "vertex_hovered" => {
                Some(EventSignalRef::mapped("vertex_hovered", &self.vertex_hovered, |v| {
                    crate::widget::capability::CapabilityValue::Tuple(crate::compat::Vec::from([
                        crate::widget::capability::CapabilityValue::Int(v.0 as i64),
                        crate::widget::capability::CapabilityValue::Int(v.1 as i64),
                    ]))
                }))
            }
            "series_visibility_changed" => Some(EventSignalRef::mapped(
                "series_visibility_changed",
                &self.series_visibility_changed,
                // `(series index, visible)` — a number and a flag, so the declared shape is `Mixed`.
                |v| {
                    CapabilityValue::Tuple(crate::compat::Vec::from([
                        CapabilityValue::UInt(v.0 as u64),
                        CapabilityValue::Bool(v.1),
                    ]))
                },
            )),
            _ => None,
        }
    }
}

/// `RadarChart`'s property contract.
///
/// The axes and series are lists of strings and numbers, so they are written
/// through `set_axes` / `set_series`; what the property layer reports is the
/// derived counts plus the three display switches, following the same convention
/// `Meter`'s threshold bands and `ScrollArea`'s sticky regions use.
impl WidgetProperties for RadarChart {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "axis_count" => Ok(CapabilityValue::UInt(self.axis_count() as u64)),
            "series_count" => Ok(CapabilityValue::UInt(self.series_count() as u64)),
            "show_grid" => Ok(CapabilityValue::Bool(self.show_grid())),
            "show_axis_labels" => Ok(CapabilityValue::Bool(self.show_axis_labels())),
            "show_legend" => Ok(CapabilityValue::Bool(self.show_legend())),
            "hovered_axis" => Ok(match self.hovered_axis {
                Some(axis) => CapabilityValue::UInt(axis as u64),
                None => CapabilityValue::Null,
            }),
            "series_names" => Ok(CapabilityValue::Tuple(
                self.series_names()
                    .iter()
                    .map(|name| CapabilityValue::String(name.clone()))
                    .collect(),
            )),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "show_grid" => {
                self.set_show_grid(expect_bool(value)?);
                Ok(())
            }
            "show_axis_labels" => {
                self.set_show_axis_labels(expect_bool(value)?);
                Ok(())
            }
            "show_legend" => {
                self.set_show_legend(expect_bool(value)?);
                Ok(())
            }
            "series_names" => {
                let names = crate::widget::capability::coercion::expect_string_list(value)?;
                self.set_series_names(names);
                Ok(())
            }
            // `hovered_axis` is written through the pointer, not through the
            // property layer: a name that could be set to an arbitrary index would
            // claim a hover that is not happening.
            "axis_count" | "series_count" | "hovered_axis" => {
                Err(CapabilityAccessError::ReadOnlyProperty)
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        // Mirrors `RADAR_CHART_PROPERTIES`.
        property_names_of![
            "axis_count",
            "series_count",
            "show_grid",
            "show_axis_labels",
            "show_legend",
            "hovered_axis",
            "series_names",
            BASE_PROPERTY_NAMES
        ]
    }

    /// Runs one of the commands `radar_chart` publishes.
    ///
    /// `add_series` cannot execute bare: a series is a list of values per axis, and
    /// `add_series` reports the index it appended at, so there is no default the
    /// control could supply without inventing data. The name is valid and the
    /// *argument* is what is missing, which is
    /// [`CapabilityAccessError::OutOfRange`], not `UnknownCommand`. `set_axes` and
    /// `set_series` likewise carry their own payloads.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "add_series" | "set_axes" | "set_series" => Err(CapabilityAccessError::OutOfRange),
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl Draw for RadarChart {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.base.geometry();
        if rect.width == 0 || rect.height == 0 {
            return;
        }
        let chrome = self.chrome_colors();
        context.face_with_gradient(
            rect,
            chrome.surface,
            self.style().background_gradient.as_ref(),
            self.style().surface.unwrap_or_default(),
            self.style().border_radius.unwrap_or(0),
            Color::BLACK,
        );
        crate::widget::draw::stroke_surface_border(
            context,
            rect,
            self.style().border_radius.unwrap_or(0),
            chrome.border,
            1,
        );
        // One font derivation for every piece of text the chart paints this frame.
        let font = role_font(self.style(), 10.0);

        let axis_count = self.axis_count();
        let Some(max) = self.data_max() else {
            self.draw_placeholder(context, rect, &font, &chrome);
            return;
        };
        let Some((center, radius)) = self.geometry_center_radius() else {
            return;
        };
        if axis_count == 0 {
            self.draw_placeholder(context, rect, &font, &chrome);
            return;
        }

        if self.show_grid {
            self.draw_grid(context, center, radius, axis_count, &font, &chrome);
        }
        if self.show_axis_labels {
            self.draw_axis_labels(context, center, radius, axis_count, &font, &chrome);
        }
        // One vertex buffer for every series: each series cleared it, so the paint allocated a
        // fresh vector per series per frame for a fixed number of points.
        let mut vertices: Vec<Point> = Vec::with_capacity(axis_count);
        for series_index in 0..self.series.len() {
            if !self.is_series_visible(series_index) {
                continue;
            }
            self.draw_series(context, center, radius, max, series_index, &mut vertices);
        }
        // The hovered vertex is marked so the pointer's nearest point is visible before a
        // click commits to it.
        if let Some((series, axis)) = self.hovered_vertex {
            if self.is_series_visible(series) {
                if let Some(value) = self.value_at(series, axis) {
                    let axis_max = self.axis_maximum(axis).unwrap_or(max);
                    let point = self.vertex(center, radius, self.axis_angle(axis), value, axis_max);
                    context.fill_circle(point, 3, Self::series_color(series));
                    context.draw_circle_stroke(point, 5, chrome.border, 1);
                }
            }
        }
        if self.show_legend && self.series.len() > 1 {
            self.draw_legend(context, rect, &font, &chrome);
        }
        // The hovered spoke last, so it is legible over every polygon.
        if let Some(axis) = self.hovered_axis {
            self.draw_hover_spoke(context, center, radius, axis, max, &chrome);
        }
    }
}

impl RadarChart {
    /// The chart's **chrome** colours, resolved once: axe surface, border, grid, label ink and the
    /// empty-state caption.
    ///
    /// # Why the chrome moved off literals
    ///
    /// Every one of these was a literal — a `rgb(255,255,255)` surface, a `rgb(200,200,200)` frame,
    /// a `rgb(225,225,225)` grid and two greys for the ink — so the control painted a **white board
    /// with near-black lettering** on every appearance and `audit_appearance.py` counted it among the
    /// Draw files that read no style at all. The **series palette is deliberately not here**: which
    /// colour identifies which axis polygon is the data's identity, and recolouring it by appearance
    /// would misrepresent it (the exemption `tools/control_color_exemptions.txt` records for
    /// `radar_chart`).
    ///
    /// Precedence mirrors every other panel in the crate: an explicit style wins, then the active
    /// theme's roles, then the literal as the last resort for a build with no theme.
    fn chrome_colors(&self) -> RadarChrome {
        let style = self.style();
        // The guard is released before `self.style()` is consumed below — `theme_manager()` is a
        // non-reentrant mutex, so the theme facts are copied out in one scope.
        let themed = {
            let manager = crate::style::theme_manager();
            manager.current_theme().map(|theme| {
                (
                    theme.colors.surface_container,
                    theme.colors.outline_variant,
                    theme.colors.foreground,
                    theme.colors.secondary,
                )
            })
        };
        let (surface, divider, ink, muted) = themed.unwrap_or((
            Color::rgb(255, 255, 255),
            Color::rgb(200, 200, 200),
            Color::rgb(90, 90, 90),
            Color::rgb(180, 180, 180),
        ));

        let surface = style.background_color.unwrap_or(surface);
        let ink = style.text_color.unwrap_or(ink);
        let divider = style.border_color.unwrap_or(divider);
        RadarChrome {
            surface,
            border: divider,
            // The grid is a *derivative* of the axes rather than a second token: it must read as
            // weaker than the frame it sits inside on any appearance.
            grid: surface.blend(&divider, 0.55),
            label: ink,
            placeholder: muted,
            // The legend text sits *on* the control's own surface, so it is the same ink the
            // axis names use — one role, two consumers, and no way for the two to disagree.
            legend_ink: ink,
            // A hover spoke points at a dimension, so it belongs with the axis ink rather than
            // with the series colours; a step toward the surface keeps it visibly weaker than
            // the frame while still follows the appearance.
            hover_spoke: ink.blend(&surface, 0.35),
        }
    }

    /// Draws the "no data" caption.
    fn draw_placeholder(
        &self,
        context: &mut RenderContext,
        rect: Rect,
        font: &crate::core::Font,
        chrome: &RadarChrome,
    ) {
        context.draw_text_fitted_cow(
            rect,
            "No data",
            font,
            chrome.placeholder,
            HorizontalAlignment::Left,
        );
    }

    /// Draws the concentric rings, the spokes and the value scale on the upward axis.
    fn draw_grid(
        &self,
        context: &mut RenderContext,
        center: Point,
        radius: u32,
        axis_count: usize,
        font: &crate::core::Font,
        chrome: &RadarChrome,
    ) {
        let grid = chrome.grid;
        let rings = self.ring_count.max(1);
        // Rings: one per quarter of the radius, so the gauge reading is easy to
        // estimate. Drawn as polylines through the axis angles, which is what makes
        // them polygons rather than circles — a radar chart's rings are the shapes
        // of the plotted polygons themselves.
        for ring in 1..=rings {
            let ring_radius = radius * ring / rings;
            for axis in 0..axis_count {
                let angle = self.axis_angle(axis);
                let next_angle = self.axis_angle((axis + 1) % axis_count);
                let from = Point::new(
                    center.x + (ring_radius as f32 * angle.cos()) as i32,
                    center.y + (ring_radius as f32 * angle.sin()) as i32,
                );
                let to = Point::new(
                    center.x + (ring_radius as f32 * next_angle.cos()) as i32,
                    center.y + (ring_radius as f32 * next_angle.sin()) as i32,
                );
                context.draw_line_stroke(from, to, grid, 1);
            }
        }
        // Spokes: one per axis, from the centre to the outermost ring.
        for axis in 0..axis_count {
            let angle = self.axis_angle(axis);
            let outer = Point::new(
                center.x + (radius as f32 * angle.cos()) as i32,
                center.y + (radius as f32 * angle.sin()) as i32,
            );
            context.draw_line_stroke(center, outer, grid, 1);
        }
        // Ring values along the first spoke (straight up). A ring's radius is a fraction of the
        // axis maximum, so without a number the reader can only guess the magnitude the rings
        // stand for (SP-54). The first axis is used because it is the one drawn upward, which is
        // where a scale is conventionally read.
        let scale_axis = 0usize;
        if let Some(max) = self.axis_maximum(scale_axis) {
            let angle = self.axis_angle(scale_axis);
            let ink = chrome.label.blend(&chrome.surface, 0.25);
            for ring in 1..=rings {
                if ring == rings {
                    // The outermost ring's value is the axis maximum, which the axis label above
                    // it already states; repeating it crowds the corner.
                    continue;
                }
                let ring_radius = radius * ring / rings;
                let value = max * f64::from(ring) / f64::from(rings);
                let text = format_ring_value(value);
                let point = Point::new(
                    center.x + (ring_radius as f32 * angle.cos()) as i32 + 3,
                    center.y + (ring_radius as f32 * angle.sin()) as i32 - 10,
                );
                context.draw_text(point, &text, font, ink, HorizontalAlignment::Left);
            }
        }
    }

    /// Draws the axis names just outside the outermost ring.
    fn draw_axis_labels(
        &self,
        context: &mut RenderContext,
        center: Point,
        radius: u32,
        axis_count: usize,
        font: &crate::core::Font,
        chrome: &RadarChrome,
    ) {
        const LABEL_GAP: u32 = 10;
        let rect = self.base.geometry();
        let label_ink = chrome.label;
        let label_radius = radius + LABEL_GAP;
        for axis in 0..axis_count {
            let Some(label) = self.axes.get(axis) else {
                continue;
            };
            let angle = self.axis_angle(axis);
            let anchor_x = center.x + (label_radius as f32 * angle.cos()) as i32;
            let anchor_y = center.y + (label_radius as f32 * angle.sin()) as i32;
            let metrics = context.measure_text(label, font);
            // Centre the text on the anchor horizontally and on the spoke's vertical
            // position, then clamp the *fitted* box into the control.
            //
            // The anchor sits outside the outermost ring, so on the upward-pointing
            // spokes it lands above the control and on the downward ones below it; a
            // label centred there had half its glyph box outside the widget. Fitting the
            // text to the room the clamp leaves is what keeps a long axis name both inside
            // the control and readable, rather than being clipped away by the raster
            // backend and running off the picture in the SVG one.
            let text_x = anchor_x - metrics.width as i32 / 2;
            // Origin is the glyph box's top edge, so centring on the spoke is half the line
            // box; the removed `+ ascent / 2` sat the label half a line low on the anchor.
            let text_y = anchor_y - metrics.height as i32 / 2;
            // The box is the *measured* width **plus both fit margins**. `draw_text_fitted`
            // insets three pixels at each end, so handing it the bare measured width asks it
            // to fit the label into 6 px less than the label needs — which it answers by
            // truncating to `...`. Every axis label on the census canvas was three dots for
            // exactly that reason, which reads as a broken chart rather than a tight one.
            let margin = TEXT_FIT_MARGIN as i32;
            let bounds = label_box(
                text_x - margin,
                text_y,
                metrics.width as i32 + 2 * margin,
                metrics.height as i32,
                rect,
            );
            context.draw_text_fitted_cow(bounds, label, font, label_ink, HorizontalAlignment::Left);
        }
    }

    /// Draws one series as a stroked, filled polygon.
    fn draw_series(
        &self,
        context: &mut RenderContext,
        center: Point,
        radius: u32,
        max: f64,
        series_index: usize,
        vertices: &mut Vec<Point>,
    ) {
        let Some(values) = self.series.get(series_index) else {
            return;
        };
        let axis_count = self.axis_count();
        if axis_count == 0 {
            return;
        }
        let color = Self::series_color(series_index);
        let scale = self.reveal_scale();
        vertices.clear();
        for axis in 0..axis_count {
            let angle = self.axis_angle(axis);
            // A missing dimension reads as zero, which lands on the centre,
            // matching `value_at` returning `None` for it.
            let value = values.get(axis).copied().unwrap_or(0.0);
            let axis_max = self.axis_maximum(axis).unwrap_or(max);
            let scaled_radius = (radius as f32 * scale).max(0.0) as u32;
            vertices.push(self.vertex(center, scaled_radius, angle, value, axis_max));
        }

        // Fill first, then stroke: the render context has no filled-polygon
        // primitive, so the fill is a fan of triangles from the centre — exact for a
        // star-shaped polygon, which a radar polygon always is because every vertex
        // lies on a ray from the centre.
        //
        // One radial line per vertex, then one edge per vertex. The previous loop painted
        // `center→from`, `center→to` and `from→to` for every edge, so each radial line was drawn
        // twice (once as the previous edge's `to`, once as this edge's `from`) — twice the ink for
        // the same fan, and the adjacent-segment overlap made the spokes look darker than the rim.
        // One edge per vertex, drawn once. The previous form painted the same data edge twice —
        // once with `draw_line` and again with `draw_line_stroke` — so every polygon's rim was
        // double ink for a single segment (SP-P61). The radial fan stays: it is what reads as a
        // filled area on a renderer with no filled-polygon primitive.
        for vertex in vertices.iter() {
            context.draw_line(center, *vertex, color);
        }
        for axis in 0..axis_count {
            let from = vertices[axis];
            let to = vertices[(axis + 1) % axis_count];
            context.draw_line_stroke(from, to, color, 2);
        }
        for vertex in vertices.iter() {
            context.fill_circle(*vertex, 2, color);
        }
    }

    /// Draws the series legend down the right edge.
    fn draw_legend(
        &self,
        context: &mut RenderContext,
        rect: Rect,
        font: &crate::core::Font,
        chrome: &RadarChrome,
    ) {
        const SWATCH: u32 = 10;
        const ROW_HEIGHT: i32 = 18;
        // One derivation for the legend's ink, shared with every other piece of chrome.
        let legend_ink = chrome.legend_ink;
        let x = rect.x + rect.width as i32 - 90;
        let mut y = rect.y + 12;
        // One buffer reused across rows: `format!` per series per frame was a fresh
        // allocation for a label that a `write!` renders in place.
        let mut label = String::new();
        for index in 0..self.series.len() {
            // A hidden series' swatch is drawn faded, so the legend states which polygons are off
            // rather than only which ones exist (SP-55).
            let visible = self.is_series_visible(index);
            let swatch = Self::series_color(index);
            context.fill_rect(
                Rect::new(x, y, SWATCH, SWATCH),
                if visible { swatch } else { swatch.with_alpha(50) },
            );
            label.clear();
            match self.series_name(index) {
                Some(name) => label.push_str(name),
                None => {
                    let _ = write!(label, "Series {}", index + 1);
                }
            }
            // The legend strip is fixed at 90 px on the right, so the text is fitted to
            // what remains of it beside the swatch: an unfitted `Series 12` ran past the
            // control's right edge and only the raster backends hid it.
            let text_x = x + SWATCH as i32 + 6;
            let row =
                Rect::new(text_x, y, (rect.x + rect.width as i32 - text_x).max(0) as u32, SWATCH);
            context.draw_text_fitted_cow(
                row,
                label.as_str(),
                font,
                // The legend swatch's ink, taken from the same `chrome_colors()` the rest of
                // the chart's chrome uses. A literal here was the one place a dark theme still
                // produced dark-on-dark text: the five colours `chrome_colors()` resolves
                // (surface, border, grid, label, placeholder) did not include the legend, so
                // this arm bypassed them.
                if visible { legend_ink } else { legend_ink.blend(&chrome.surface, 0.4) },
                HorizontalAlignment::Left,
            );
            y += ROW_HEIGHT;
        }
    }

    /// Draws the hovered axis's spoke emphasised, with its value marked.
    fn draw_hover_spoke(
        &self,
        context: &mut RenderContext,
        center: Point,
        radius: u32,
        axis: usize,
        max: f64,
        chrome: &RadarChrome,
    ) {
        if axis >= self.axis_count() {
            return;
        }
        let angle = self.axis_angle(axis);
        let outer = Point::new(
            center.x + (radius as f32 * angle.cos()) as i32,
            center.y + (radius as f32 * angle.sin()) as i32,
        );
        context.draw_line_stroke(center, outer, chrome.hover_spoke, 1);
        // The read-out for every series on this dimension, which is what makes the
        // hover worth doing on a chart whose polygons overlap.
        let font = role_font(self.style(), 9.0);
        let mut text_y = outer.y + 4;
        // One buffer reused across the read-outs, for the same reason as `draw_legend`.
        let mut label = String::new();
        for series_index in 0..self.series.len() {
            let Some(value) = self.value_at(series_index, axis) else {
                continue;
            };
            let marker = self.vertex(center, radius, angle, value, max);
            context.fill_circle(marker, 4, Self::series_color(series_index));
            label.clear();
            // A named series is identified by its name; an unnamed one keeps the old bare value, so
            // the read-out cannot invent a label the caller did not give it.
            match self.series_name(series_index) {
                Some(name) => {
                    let _ = write!(label, "{name}: {value:.1}");
                }
                None => {
                    let _ = write!(label, "{value:.1}");
                }
            }
            context.draw_text(
                Point { x: outer.x + 4, y: text_y },
                &label,
                &font,
                chrome.legend_ink,
                HorizontalAlignment::Left,
            );
            text_y += 12;
        }
    }

    /// The colour of series `index`, cycling through [`PALETTE`].
    fn series_color(index: usize) -> Color {
        PALETTE[index % PALETTE.len()]
    }
}

impl EventHandler for RadarChart {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MouseMove { pos } => {
                let axis = self.axis_at(*pos);
                if axis != self.hovered_axis {
                    self.hovered_axis = axis;
                    if let Some(axis) = axis {
                        self.axis_hovered.emit(axis);
                    }
                }
                let vertex = self.vertex_at(*pos);
                if vertex != self.hovered_vertex {
                    self.hovered_vertex = vertex;
                    if let Some(vertex) = vertex {
                        self.vertex_hovered.emit(vertex);
                    }
                    self.base.request_redraw();
                } else if axis != self.hovered_axis {
                    self.base.request_redraw();
                }
            }
            Event::MouseLeave { .. } => {
                if self.hovered_axis.take().is_some() || self.hovered_vertex.take().is_some() {
                    self.base.request_redraw();
                }
            }
            Event::MousePress { pos, button, .. } if *button == 1 => {
                self.base.set_mouse_pressed(true);
                // The inline legend is an interactive toggle when it is painted. A press there
                // hides or shows the series it names, which is what lets a reader isolate two
                // overlapping polygons (SP-55).
                if let Some(index) = self.legend_entry_at(*pos) {
                    self.toggle_series_visible(index);
                    self.base.clicked.emit();
                    return;
                }
                if let Some(vertex) = self.vertex_at(*pos) {
                    self.vertex_clicked.emit(vertex);
                }
                if let Some(axis) = self.axis_at(*pos) {
                    // The nearest series polygon is reported, so a click on a
                    // chart tells the caller *which* series was aimed at rather
                    // than only which dimension.
                    if let Some(series) = self.nearest_series(axis, *pos) {
                        self.base.clicked.emit();
                        self.series_clicked.emit(series);
                    }
                }
            }
            Event::MouseRelease { button, .. } if *button == 1 => {
                self.base.set_mouse_pressed(false);
            }
            _ => {}
        }
    }
}

impl RadarChart {
    /// The series whose vertex is nearest `pos` among those crossing `axis`.
    ///
    /// \"Nearest\" is measured by the vertex the series has on the hovered axis, so
    /// the result is the series whose marker the pointer is closest to — which is
    /// what a caller clicking at a chart expects, and is stable regardless of which
    /// side of the spoke they clicked.
    fn nearest_series(&self, axis: usize, pos: Point) -> Option<usize> {
        let (center, radius) = self.geometry_center_radius()?;
        let max = self.data_max()?;
        let angle = self.axis_angle(axis);
        let mut best: Option<(usize, i64)> = None;
        for series_index in 0..self.series.len() {
            if !self.is_series_visible(series_index) {
                continue;
            }
            let value = self.value_at(series_index, axis).unwrap_or(0.0);
            let axis_max = self.axis_maximum(axis).unwrap_or(max);
            let vertex = self.vertex(center, radius, angle, value, axis_max);
            let dx = (vertex.x - pos.x) as i64;
            let dy = (vertex.y - pos.y) as i64;
            // Squared distance, which orders identically to the distance and
            // avoids a square root per series.
            let distance = dx * dx + dy * dy;
            if best.is_none_or(|(_, best_distance)| distance < best_distance) {
                best = Some((series_index, distance));
            }
        }
        best.map(|(index, _)| index)
    }

    /// The vertex nearest `pos`, within a pointer-sized tolerance.
    fn vertex_at(&self, pos: Point) -> Option<(usize, usize)> {
        let (center, radius) = self.geometry_center_radius()?;
        let max = self.data_max()?;
        if !self.base.contains_point_with_touch_expansion(pos) {
            return None;
        }
        let mut best: Option<((usize, usize), i64)> = None;
        for series_index in 0..self.series.len() {
            if !self.is_series_visible(series_index) {
                continue;
            }
            for axis in 0..self.axis_count() {
                let value = self.value_at(series_index, axis).unwrap_or(0.0);
                let axis_max = self.axis_maximum(axis).unwrap_or(max);
                let point = self.vertex(center, radius, self.axis_angle(axis), value, axis_max);
                let dx = i64::from(point.x - pos.x);
                let dy = i64::from(point.y - pos.y);
                let distance = dx * dx + dy * dy;
                if distance <= 14 * 14 && best.is_none_or(|(_, near)| distance < near) {
                    best = Some(((series_index, axis), distance));
                }
            }
        }
        best.map(|(vertex, _)| vertex)
    }

    /// The legend row under `pos`, when the inline legend is painted.
    fn legend_entry_at(&self, pos: Point) -> Option<usize> {
        if !self.show_legend || self.series.len() <= 1 {
            return None;
        }
        let rect = self.geometry();
        let x = rect.x + rect.width as i32 - 90;
        const ROW_HEIGHT: i32 = 18;
        let top = rect.y + 12;
        if pos.x < x || pos.y < top {
            return None;
        }
        let row = (pos.y - top) / ROW_HEIGHT;
        let index = row as usize;
        (index < self.series.len()).then_some(index)
    }
}

/// Formats one ring's value for the grid scale.
///
/// Whole numbers stay whole and fractional values keep one decimal, so a scale from `0` to `1`
/// reads `0.25`/`0.5`/`0.75` while a scale from `0` to `100` reads `25`/`50`/`75`.
fn format_ring_value(value: f64) -> String {
    if !value.is_finite() {
        return String::from("-");
    }
    let magnitude = value.abs();
    if magnitude >= 100.0 || (magnitude - magnitude.round()).abs() < 0.05 {
        format!("{}", magnitude.round() as i64)
    } else {
        format!("{magnitude:.1}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render::{PaintBackend, SoftwarePaintBackend};

    fn chart() -> RadarChart {
        let mut chart = RadarChart::new(Rect::new(0, 0, 320, 320));
        assert!(chart.set_axes(vec![
            "Speed".to_string(),
            "Power".to_string(),
            "Range".to_string(),
            "Comfort".to_string(),
            "Safety".to_string(),
        ]));
        chart.add_series(vec![80.0, 60.0, 90.0, 70.0, 50.0]);
        chart
    }

    /// Renders the chart and returns the RGBA frame.
    fn render(chart: &mut RadarChart, size: Size) -> Vec<u8> {
        let mut backend = SoftwarePaintBackend::new(size, 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 near `target`.
    fn count_near(rgba: &[u8], target: (u8, u8, u8)) -> usize {
        const TOLERANCE: i32 = 24;
        rgba.as_chunks::<4>()
            .0
            .iter()
            .filter(|px| {
                (px[0] as i32 - target.0 as i32).abs() <= TOLERANCE
                    && (px[1] as i32 - target.1 as i32).abs() <= TOLERANCE
                    && (px[2] as i32 - target.2 as i32).abs() <= TOLERANCE
                    && px[3] > 0
            })
            .count()
    }

    /// The chart's plotting surface follows the appearance.
    ///
    /// # The defect this pins
    ///
    /// `draw` filled the whole rectangle with a literal `rgb(255,255,255)` and framed it with a
    /// `rgb(200,200,200)` stroke, so a radar chart painted a **white board** on the dark appearance —
    /// the same shape as `font_preview`'s unthemed panel. The grid and both inks were literals too.
    ///
    /// # What must **not** change
    ///
    /// The series palette stays put: which colour identifies which axis polygon is the data's
    /// identity, and the exemption table records that judgement for this control. The assertion is
    /// therefore about the surface and not about the coloured series at all.
    #[test]
    #[cfg(all(device_profile, feature = "desktop"))]
    fn the_plotting_surface_follows_the_appearance() {
        let _guard = crate::style::theme_test_guard();
        crate::widget::census::install_preset_appearances();
        let rect = Rect::new(0, 0, 240, 200);
        let size = Size::new(240, 200);

        let surface_pixel = |appearance| -> (u8, u8, u8) {
            crate::theme::global_theme_manager().set_appearance(appearance);
            let mut chart = RadarChart::new(rect);
            chart.set_axes(vec!["A".to_string(), "B".to_string(), "C".to_string()]);
            crate::theme::apply_theme_to_widget(&mut chart);
            let frame = render(&mut chart, size);
            // A point that is **only** the surface: past the frame stroke, past the grid rings and
            // away from every label box. The top-left was tried and rejected by measurement — it lands
            // on the frame stroke, and the grid rings reach further in than they look, so a point near
            // the corner read one of those instead and the assertion passed with the surface restored
            // to white. The bottom strip below the outermost ring is clear of all three.
            let width = size.width as usize;
            let x = 6usize;
            let y = size.height as usize - 3;
            let offset = (y * width + x) * 4;
            let px = &frame[offset..offset + 3];
            (px[0], px[1], px[2])
        };

        let dark = surface_pixel(crate::theme::AppearanceMode::Dark);
        let light = surface_pixel(crate::theme::AppearanceMode::Light);
        assert_ne!(
            dark, light,
            "the plotting surface must follow the appearance; both were {dark:?}"
        );
        assert_ne!(
            dark,
            (255, 255, 255),
            "the surface must not be the fixed white the defect used"
        );
    }

    #[test]
    fn radar_chart_creation_defaults() {
        let chart = RadarChart::new(Rect::new(0, 0, 320, 320));
        assert_eq!(chart.kind(), WidgetKind::RadarChart);
        assert_eq!(chart.axis_count(), 0);
        assert_eq!(chart.series_count(), 0);
        assert!(chart.show_grid());
        assert!(chart.show_axis_labels());
        assert!(chart.show_legend());
    }

    #[test]
    fn radar_chart_set_axes_requires_three() {
        let mut chart = RadarChart::new(Rect::new(0, 0, 320, 320));
        // A two-spoke radar is a line, not a polygon.
        assert!(!chart.set_axes(vec!["A".to_string(), "B".to_string()]));
        assert_eq!(chart.axis_count(), 0, "a refused input must not change state");
        assert!(chart.set_axes(vec!["A".to_string(), "B".to_string(), "C".to_string()]));
        assert_eq!(chart.axis_count(), 3);
    }

    #[test]
    fn radar_chart_value_at_distinguishes_missing_from_zero() {
        let mut chart = RadarChart::new(Rect::new(0, 0, 320, 320));
        chart.set_axes(vec!["A".to_string(), "B".to_string(), "C".to_string()]);
        chart.add_series(vec![1.0, 0.0]);
        // A supplied zero.
        assert_eq!(chart.value_at(0, 1), Some(0.0));
        // A dimension the series has no value for.
        assert_eq!(chart.value_at(0, 2), None);
        // An unset series.
        assert_eq!(chart.value_at(9, 0), None);
    }

    #[test]
    fn radar_chart_series_count_and_polygon_pixels() {
        let mut chart = chart();
        assert_eq!(chart.series_count(), 1);
        let rgba = render(&mut chart, Size::new(320, 320));
        // Series zero's colour must be on the canvas, which proves the polygon was
        // actually drawn rather than only stored.
        assert!(count_near(&rgba, (66, 133, 244)) > 0);
    }

    #[test]
    fn radar_chart_multiple_series_use_distinct_colours() {
        let mut chart = chart();
        chart.add_series(vec![50.0, 90.0, 60.0, 85.0, 95.0]);
        assert_eq!(chart.series_count(), 2);
        let rgba = render(&mut chart, Size::new(320, 320));
        assert!(count_near(&rgba, (66, 133, 244)) > 0, "series zero");
        assert!(count_near(&rgba, (219, 68, 55)) > 0, "series one");
    }

    #[test]
    fn radar_chart_empty_draw_does_not_panic() {
        let mut chart = RadarChart::new(Rect::new(0, 0, 320, 320));
        let rgba = render(&mut chart, Size::new(320, 320));
        assert!(!rgba.is_empty());
    }

    #[test]
    fn radar_chart_zero_geometry_does_not_panic() {
        let mut chart = chart();
        let rgba = render(&mut chart, Size::new(4, 4));
        assert!(!rgba.is_empty());
    }

    #[test]
    fn radar_chart_axis_hover_emits_nearest_axis() {
        let mut chart = chart();
        let hovered = std::sync::Arc::new(std::sync::Mutex::new(Vec::<usize>::new()));
        let sink = hovered.clone();
        chart.axis_hovered.connect(move |axis| {
            if let Ok(mut guard) = sink.lock() {
                guard.push(*axis);
            }
        });

        // First axis points straight up from the centre; hovering above the centre
        // must select it.
        let (center, _) = chart.geometry_center_radius().expect("geometry");
        chart.handle_event(&Event::mouse_move(center.x, center.y - 40));
        assert_eq!(*hovered.lock().expect("hover lock poisoned"), vec![0]);
        assert_eq!(chart.get("hovered_axis").unwrap(), CapabilityValue::UInt(0));

        // Leaving clears the hover.
        chart.handle_event(&Event::MouseLeave { pos: Point::new(0, 0) });
        assert_eq!(chart.get("hovered_axis").unwrap(), CapabilityValue::Null);
    }

    #[test]
    fn radar_chart_axis_at_centres_on_the_first_spoke() {
        let chart = chart();
        let (center, _) = chart.geometry_center_radius().expect("geometry");
        // Straight up is axis 0; straight right is axis 1 on a five-axis chart
        // (72 degrees per spoke, so 90 degrees is nearest to spoke 1).
        assert_eq!(chart.axis_at(Point::new(center.x, center.y - 30)), Some(0));
        assert_eq!(chart.axis_at(Point::new(center.x + 30, center.y)), Some(1));
        // The exact centre has no direction and therefore no axis.
        assert_eq!(chart.axis_at(center), None);
    }

    #[test]
    fn radar_chart_click_emits_nearest_series() {
        let mut chart = chart();
        chart.add_series(vec![20.0, 20.0, 20.0, 20.0, 20.0]);
        let clicked = std::sync::Arc::new(std::sync::Mutex::new(Vec::<usize>::new()));
        let sink = clicked.clone();
        chart.series_clicked.connect(move |series| {
            if let Ok(mut guard) = sink.lock() {
                guard.push(*series);
            }
        });

        let (center, radius) = chart.geometry_center_radius().expect("geometry");
        let max = chart.data_max().expect("data");
        // Click exactly on series zero's vertex for axis 0.
        let vertex = chart.vertex(center, radius, chart.axis_angle(0), 80.0, max);
        chart.handle_event(&Event::mouse_press(vertex.x, vertex.y, 1));
        assert_eq!(*clicked.lock().expect("click lock poisoned"), vec![0]);
    }

    /// A press that never touched the chart must not report a series click.
    ///
    /// # Why this is the test the geometry assertion above could not replace
    ///
    /// `axis_at` used to reduce the point to an *angle* about the centre with no rectangle test. An
    /// angle exists for every point in the plane, so a press in a sibling control -- or on the
    /// window chrome -- still resolved to *some* axis, and `nearest_series` then answered `Some`
    /// because it picks the closest of a fixed set with no distance threshold. The vertex test above
    /// cannot see that: it presses *inside*, where both the old and the new code agree.
    ///
    /// The point is chosen well outside on every side, because "outside" was not previously
    /// distinguished from "inside" in any direction: the old guard had no x bound, no y bound and no
    /// radius test.
    #[test]
    fn a_press_outside_the_chart_reports_no_series() {
        let mut chart = chart();
        chart.add_series(vec![20.0, 20.0, 20.0, 20.0, 20.0]);
        let clicks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let sink = clicks.clone();
        chart.series_clicked.connect(move |_| {
            sink.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        });

        let rect = chart.geometry();
        // One point just outside each edge and one far away, so a guard on a single side would not
        // pass this.
        let outside = [
            Point::new(rect.x - 40, rect.y + rect.height as i32 / 2),
            Point::new(rect.x + rect.width as i32 + 40, rect.y + rect.height as i32 / 2),
            Point::new(rect.x + rect.width as i32 / 2, rect.y - 40),
            Point::new(rect.x + rect.width as i32 / 2, rect.y + rect.height as i32 + 40),
            Point::new(5000, 5000),
        ];
        for point in outside {
            assert_eq!(
                chart.axis_at(point),
                None,
                "a point outside the control at {point:?} must resolve to no axis"
            );
            chart.handle_event(&Event::mouse_press(point.x, point.y, 1));
        }
        assert_eq!(
            clicks.load(std::sync::atomic::Ordering::SeqCst),
            0,
            "a press outside the chart emitted a series click"
        );
    }

    #[test]
    fn radar_chart_display_switches_round_trip() {
        let mut chart = chart();
        for name in ["show_grid", "show_axis_labels", "show_legend"] {
            chart.set(name, CapabilityValue::Bool(false)).unwrap();
            assert_eq!(chart.get(name).unwrap(), CapabilityValue::Bool(false));
            chart.set(name, CapabilityValue::Bool(true)).unwrap();
            assert_eq!(chart.get(name).unwrap(), CapabilityValue::Bool(true));
        }
        assert!(chart.set("show_grid", CapabilityValue::UInt(1)).is_err());
    }

    #[test]
    fn radar_chart_derived_properties_are_read_only() {
        let mut chart = chart();
        for name in ["axis_count", "series_count", "hovered_axis"] {
            assert_eq!(
                chart.set(name, CapabilityValue::UInt(1)),
                Err(CapabilityAccessError::ReadOnlyProperty),
                "{name} must be read-only"
            );
        }
        assert_eq!(chart.get("axis_count").unwrap(), CapabilityValue::UInt(5));
        assert_eq!(chart.get("series_count").unwrap(), CapabilityValue::UInt(1));
    }

    #[test]
    fn radar_chart_hidden_grid_removes_grid_pixels() {
        // # Why this asserts on the two frames rather than on a probed colour
        //
        // The first version counted pixels near the literal `(225,225,225)` — the grid's colour when
        // this test was written. The grid is **derived** from the chrome palette now, so that literal
        // names nothing and both counts collapsed to the background (`100149 vs 100149`). Probing the
        // derived colour instead was tried and also wrong (`0 vs 101425`): the strokes are rasterised
        // with coverage, so almost no pixel equals the stroke colour exactly. Both failures are the
        // same lesson — **counting pixels of one colour is a fragile probe for "a set of lines was
        // drawn"**. Comparing the two whole frames states the intent directly: turning the grid off
        // must change the picture, and turning it back on must restore it.
        let size = Size::new(320, 320);
        let mut with_grid = chart();
        with_grid.set_show_axis_labels(false);
        let painted = render(&mut with_grid, size);

        let mut without_grid = chart();
        without_grid.set_show_axis_labels(false);
        without_grid.set_show_grid(false);
        let bare = render(&mut without_grid, size);

        assert_ne!(painted.len(), 0);
        assert_eq!(painted.len(), bare.len(), "both renders cover the same surface");
        let differing = painted
            .as_chunks::<4>()
            .0
            .iter()
            .zip(bare.as_chunks::<4>().0.iter())
            .filter(|(a, b)| a != b)
            .count();
        assert!(
            differing > 0,
            "turning the grid off must change the picture; the two renders were identical"
        );
    }

    #[test]
    fn radar_chart_series_shorter_than_axes_reads_as_zero() {
        let mut chart = RadarChart::new(Rect::new(0, 0, 320, 320));
        chart.set_axes(vec!["A".to_string(), "B".to_string(), "C".to_string()]);
        // Only two of three dimensions supplied.
        chart.add_series(vec![10.0, 20.0]);
        let rgba = render(&mut chart, Size::new(320, 320));
        assert!(!rgba.is_empty());
        assert_eq!(chart.value_at(0, 2), None);
    }

    #[test]
    fn series_names_replace_the_generic_legend_label() {
        let mut chart = chart();
        assert_eq!(chart.series_name(0), None);
        assert!(chart.set_series_name(0, "Current"));
        assert_eq!(chart.series_name(0), Some("Current"));
        assert!(!chart.set_series_name(9, "Missing"), "there is no series 9");

        // The property is the same row, as a list of strings.
        chart
            .set(
                "series_names",
                CapabilityValue::Tuple(vec![CapabilityValue::String("Current".to_string())]),
            )
            .expect("a string list is accepted");
        assert_eq!(chart.get("series_names").unwrap(), {
            CapabilityValue::Tuple(vec![CapabilityValue::String("Current".to_string())])
        });
    }

    /// A recorder that keeps every render command, so the paint's line count is observable.
    struct Recorder {
        commands: Vec<crate::render::RenderCommand>,
        inner: SoftwarePaintBackend,
    }

    impl PaintBackend for Recorder {
        fn begin_frame(&mut self, clear: Color) {
            self.inner.begin_frame(clear);
        }
        fn end_frame(&mut self) {
            self.inner.end_frame();
        }
        fn execute_command(&mut self, command: &crate::render::RenderCommand) {
            self.commands.push(command.clone());
            self.inner.execute_command(command);
        }
        fn size(&self) -> Size {
            self.inner.size()
        }
        fn set_size(&mut self, size: Size) {
            self.inner.set_size(size);
        }
        fn dpi_scale(&self) -> f32 {
            self.inner.dpi_scale()
        }
        fn set_dpi_scale(&mut self, scale: f32) {
            self.inner.set_dpi_scale(scale);
        }
        fn measure_text(&self, text: &str, font: &crate::core::Font) -> crate::render::TextMetrics {
            self.inner.measure_text(text, font)
        }
        fn shape_text(
            &self,
            text: &str,
            font: &crate::core::Font,
        ) -> crate::compat::Rc<crate::render::ShapedText> {
            self.inner.shape_text(text, font)
        }
        fn frame_rgba(&self) -> &[u8] {
            self.inner.frame_rgba()
        }
        fn apply_render_config(&mut self, config: crate::render::SoftwareRenderConfig) {
            self.inner.apply_render_config(config)
        }
    }

    /// SP-36: the fan fill paints one radial line per vertex, not one per edge per endpoint.
    ///
    /// The old loop drew `center→from`, `center→to` and `from→to` for every edge, so each radial
    /// line was emitted twice. With the grid, labels, legend and hover all off, one series of `n`
    /// dimensions must therefore emit exactly `2n` plain lines: `n` radials and `n` edges.
    #[test]
    fn fan_fill_draws_each_radial_once() {
        let mut chart = RadarChart::new(Rect::new(0, 0, 320, 320));
        chart.set_axes(vec!["A".to_string(), "B".to_string(), "C".to_string(), "D".to_string()]);
        chart.add_series(vec![10.0, 20.0, 30.0, 40.0]);
        chart.set_show_grid(false);
        chart.set_show_axis_labels(false);
        chart.set_show_legend(false);

        let mut recorder = Recorder {
            commands: Vec::new(),
            inner: SoftwarePaintBackend::new(Size::new(320, 320), 1.0),
        };
        recorder.begin_frame(Color::WHITE);
        {
            let mut context = RenderContext::new(&mut recorder);
            chart.draw(&mut context);
        }
        recorder.end_frame();

        // The fan is one radial per vertex, and each data edge is stroked **once**. The previous
        // form drew every edge twice (plain and stroked), which is the double ink SP-P61 removed.
        let radials = recorder
            .commands
            .iter()
            .filter(|command| matches!(command, crate::render::RenderCommand::DrawLine { .. }))
            .count();
        let edges = recorder
            .commands
            .iter()
            .filter(|command| {
                matches!(command, crate::render::RenderCommand::DrawLineStroke { .. })
            })
            .count();
        assert_eq!(radials, 4, "4 dimensions must emit one radial each, got {radials}");
        assert_eq!(edges, 4, "each data edge is stroked exactly once, got {edges}");
    }
}