ruviz 0.6.0

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

mod annotations;
mod primitives;
mod utils;
pub use self::utils::{
    ColorbarTicks, calculate_plot_area, calculate_plot_area_config, calculate_plot_area_dpi,
    compute_colorbar_ticks, format_log_tick_label, format_tick_label, format_tick_labels,
    format_tick_labels_for_scale, generate_minor_ticks, generate_ticks, map_data_to_pixels,
    map_data_to_pixels_scaled, try_map_data_to_pixels_scaled,
};
pub(crate) use self::utils::{
    colorbar_major_label_anchor_center_from_top, colorbar_major_label_top,
    compute_colorbar_layout_metrics,
};

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct ClipMaskKey {
    x_bits: u32,
    y_bits: u32,
    width_bits: u32,
    height_bits: u32,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct MarkerPathKey {
    style: MarkerStyle,
    size_bits: u32,
}

impl MarkerPathKey {
    fn new(style: MarkerStyle, size: f32) -> Self {
        Self {
            style,
            size_bits: size.to_bits(),
        }
    }
}

impl ClipMaskKey {
    fn new((x, y, width, height): (f32, f32, f32, f32)) -> Self {
        Self {
            x_bits: x.to_bits(),
            y_bits: y.to_bits(),
            width_bits: width.to_bits(),
            height_bits: height.to_bits(),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct MarkerSpriteKey {
    style: MarkerStyle,
    size_bits: u32,
    rgba_bits: u32,
    /// `(edge rgba, edge width in device pixels)`, `None` for a bare marker.
    ///
    /// The rim is baked into the sprite, so it has to be part of the identity of
    /// the sprite. Without it an edged batch would have to fall off the sprite
    /// compositor entirely, which is what used to make a marker rim expensive
    /// enough to be worth disabling by default.
    edge_bits: Option<(u32, u32)>,
    phase_x: u8,
    phase_y: u8,
}

/// Entries the process-wide marker sprite cache holds before it starts evicting.
///
/// Sized from [`SkiaRenderer::marker_subpixel_phases`]: one hot marker — a
/// single (style, size, colour, edge) tuple — occupies at most `phases²`
/// entries once a dense scatter has visited every sub-pixel phase, so the limit
/// has to be a multiple of that or a single series would evict the whole cache
/// on every frame. Two hot markers fit.
const GLOBAL_MARKER_SPRITE_CACHE_LIMIT: usize =
    2 * (SkiaRenderer::marker_subpixel_phases() as usize).pow(2);

/// Frame colour for the legacy `draw_legend*` panels (matplotlib `legend.edgecolor`).
const LEGACY_LEGEND_EDGE_COLOR: Color = Color {
    r: 204,
    g: 204,
    b: 204,
    a: 200,
};
/// Frame width for the legacy `draw_legend*` panels, in points.
const LEGACY_LEGEND_EDGE_WIDTH_PT: f32 = 0.8;

static GLOBAL_MARKER_SPRITE_CACHE: OnceLock<Mutex<HashMap<MarkerSpriteKey, Arc<MarkerSprite>>>> =
    OnceLock::new();

fn global_marker_sprite_cache() -> &'static Mutex<HashMap<MarkerSpriteKey, Arc<MarkerSprite>>> {
    GLOBAL_MARKER_SPRITE_CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}

fn insert_global_marker_sprite(
    global_cache: &mut HashMap<MarkerSpriteKey, Arc<MarkerSprite>>,
    key: MarkerSpriteKey,
    sprite: Arc<MarkerSprite>,
) -> Arc<MarkerSprite> {
    if let Some(existing) = global_cache.get(&key).cloned() {
        return existing;
    }

    if global_cache.len() >= GLOBAL_MARKER_SPRITE_CACHE_LIMIT
        && let Some(evicted_key) = global_cache.keys().next().copied()
    {
        global_cache.remove(&evicted_key);
    }

    global_cache.insert(key, Arc::clone(&sprite));
    sprite
}

impl MarkerSpriteKey {
    fn new(
        style: MarkerStyle,
        size: f32,
        color: Color,
        edge: Option<(Color, f32)>,
        phase_x: u8,
        phase_y: u8,
    ) -> Self {
        Self {
            style,
            size_bits: size.to_bits(),
            rgba_bits: u32::from_be_bytes([color.r, color.g, color.b, color.a]),
            edge_bits: edge.map(|(color, width_px)| {
                (
                    u32::from_be_bytes([color.r, color.g, color.b, color.a]),
                    width_px.to_bits(),
                )
            }),
            phase_x,
            phase_y,
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct MarkerSpriteScanline {
    pub start_x: u16,
    pub end_x: u16,
    pub opaque_start_x: u16,
    pub opaque_end_x: u16,
}

#[derive(Clone, Debug)]
pub(crate) struct MarkerSprite {
    pub width: u32,
    pub height: u32,
    pub origin_x: i32,
    pub origin_y: i32,
    pub pixels: Vec<u8>,
    pub scanlines: Option<Arc<[MarkerSpriteScanline]>>,
}

/// Tiny-skia based renderer with cosmic-text for professional typography
pub struct SkiaRenderer {
    width: u32,
    height: u32,
    pixmap: Pixmap,
    paint: Paint<'static>,
    theme: Theme,
    text_renderer: TextRenderer,
    font_config: FontConfig,
    /// How the x tick label row is drawn; see [`XTickLabelPlan`].
    x_tick_label_plan: XTickLabelPlan,
    /// Shared render scale for unit conversion.
    render_scale: RenderScale,
    /// Active text rendering engine.
    text_engine_mode: TextEngineMode,
    clip_mask_cache: HashMap<ClipMaskKey, Arc<Mask>>,
    marker_path_cache: HashMap<MarkerPathKey, Arc<tiny_skia::Path>>,
    marker_sprite_cache: HashMap<MarkerSpriteKey, Arc<MarkerSprite>>,
    render_diagnostics: RenderDiagnostics,
}

impl SkiaRenderer {
    /// Create a new renderer with the given dimensions
    pub fn new(width: u32, height: u32, theme: Theme) -> Result<Self> {
        let font_family = FontFamily::from(theme.font_family.as_str());
        Self::with_font_family(width, height, theme, font_family)
    }

    /// Create a new renderer with specified font family
    pub fn with_font_family(
        width: u32,
        height: u32,
        theme: Theme,
        font_family: FontFamily,
    ) -> Result<Self> {
        let mut pixmap = Pixmap::new(width, height).ok_or(PlottingError::OutOfMemory)?;

        // Fill background
        let bg_color = theme.background.to_tiny_skia_color();
        pixmap.fill(bg_color);

        let paint = Paint::default();

        // Create text renderer with default font configuration
        let text_renderer = TextRenderer::new();
        let font_config = FontConfig::new(font_family, 12.0);

        Ok(Self {
            width,
            height,
            pixmap,
            paint,
            theme,
            text_renderer,
            font_config,
            x_tick_label_plan: XTickLabelPlan::default(),
            render_scale: RenderScale::from_canvas_size(width, height, crate::core::REFERENCE_DPI),
            text_engine_mode: TextEngineMode::Plain,
            clip_mask_cache: HashMap::new(),
            marker_path_cache: HashMap::new(),
            marker_sprite_cache: HashMap::new(),
            render_diagnostics: RenderDiagnostics::default(),
        })
    }

    /// Set the render scale context used for unit conversion.
    pub fn set_render_scale(&mut self, render_scale: RenderScale) {
        self.render_scale = render_scale;
    }

    /// Get the render scale context used for unit conversion.
    pub fn render_scale(&self) -> RenderScale {
        self.render_scale
    }

    /// Set how the x tick label row is drawn.
    ///
    /// The plan is resolved once, against the margin the layout actually
    /// granted, and then held here — so the row that was measured is the row
    /// that is drawn. Left at its default a row is horizontal and complete,
    /// which is what every caller that never measured one wants.
    pub fn set_x_tick_label_plan(&mut self, plan: XTickLabelPlan) {
        self.x_tick_label_plan = plan;
    }

    /// How the x tick label row is drawn.
    pub fn x_tick_label_plan(&self) -> XTickLabelPlan {
        self.x_tick_label_plan
    }

    /// Legacy compatibility shim for callers that still pass `dpi / 100.0`.
    pub fn set_dpi_scale(&mut self, dpi_scale: f32) {
        self.set_render_scale(RenderScale::from_reference_scale(dpi_scale));
    }

    /// Legacy compatibility shim for callers that still expect `dpi / 100.0`.
    pub fn dpi_scale(&self) -> f32 {
        self.render_scale.reference_scale()
    }

    fn points_to_pixels(&self, points: f32) -> f32 {
        self.render_scale.points_to_pixels(points)
    }

    fn logical_pixels_to_pixels(&self, logical_pixels: f32) -> f32 {
        self.render_scale.logical_pixels_to_pixels(logical_pixels)
    }

    /// Convert line style to a DPI-scaled dash pattern.
    ///
    /// Dash definitions are authored in logical pixels at the reference DPI and
    /// converted through the shared render scale so physical dash spacing
    /// remains consistent across output resolutions.
    fn scaled_dash_pattern(&self, style: &LineStyle) -> Option<Vec<f32>> {
        style.to_dash_array().map(|pattern| {
            pattern
                .into_iter()
                .map(|segment| self.logical_pixels_to_pixels(segment))
                .collect()
        })
    }

    /// Set text rendering backend mode.
    pub fn set_text_engine_mode(&mut self, mode: TextEngineMode) {
        self.text_engine_mode = mode;
    }

    /// Get text rendering backend mode.
    pub fn text_engine_mode(&self) -> TextEngineMode {
        self.text_engine_mode
    }

    /// Set the font family used by plain and Typst text rendering.
    pub fn set_font_family<F>(&mut self, family: F)
    where
        F: Into<FontFamily>,
    {
        self.font_config.family = family.into();
    }

    /// Get the configured font family.
    pub fn font_family(&self) -> &FontFamily {
        &self.font_config.family
    }

    pub(crate) fn set_render_mode_diagnostics(&mut self, mode: &'static str) {
        self.render_diagnostics.render_mode = mode;
    }

    pub(crate) fn note_auto_datashader(&mut self) {
        self.render_diagnostics.used_auto_datashader = true;
    }

    pub(crate) fn note_exact_line_canonicalization(&mut self) {
        self.render_diagnostics.used_exact_line_canonicalization = true;
    }

    pub(crate) fn note_raster_line_reduction(&mut self) {
        self.render_diagnostics.used_raster_line_reduction = true;
    }

    pub(crate) fn note_marker_path_cache(&mut self) {
        self.render_diagnostics.used_marker_path_cache = true;
    }

    pub(crate) fn note_marker_sprite_cache(&mut self) {
        self.render_diagnostics.used_marker_sprite_cache = true;
    }

    pub(crate) fn note_marker_sprite_compositor(&mut self) {
        self.render_diagnostics.used_marker_sprite_compositor = true;
    }

    pub(crate) fn note_marker_sprite_fallback(&mut self) {
        self.render_diagnostics.used_marker_sprite_fallback = true;
    }

    pub(crate) fn note_marker_scanline_blit(&mut self) {
        self.render_diagnostics.used_marker_scanline_blit = true;
    }

    pub(crate) fn note_direct_rect_fill(&mut self) {
        self.render_diagnostics.used_direct_rect_fill = true;
    }

    pub(crate) fn note_pixel_aligned_rect_fill(&mut self) {
        self.render_diagnostics.used_pixel_aligned_rect_fill = true;
    }

    pub(crate) fn note_prepared_geometry_cache(&mut self) {
        self.render_diagnostics.used_prepared_geometry_cache = true;
    }

    pub(crate) fn note_rebuilt_prepared_geometry_cache(&mut self) {
        self.render_diagnostics.rebuilt_prepared_geometry_cache = true;
    }

    pub(crate) fn render_diagnostics(&self) -> &RenderDiagnostics {
        &self.render_diagnostics
    }

    pub(crate) fn marker_path(
        &mut self,
        style: MarkerStyle,
        size: f32,
    ) -> Result<Option<Arc<tiny_skia::Path>>> {
        let key = MarkerPathKey::new(style, size);
        if let Some(path) = self.marker_path_cache.get(&key) {
            return Ok(Some(Arc::clone(path)));
        }

        let path = match style {
            MarkerStyle::Circle | MarkerStyle::CircleOpen => {
                let mut builder = PathBuilder::new();
                builder.push_circle(0.0, 0.0, size * 0.5);
                builder.finish()
            }
            MarkerStyle::Triangle | MarkerStyle::TriangleOpen | MarkerStyle::TriangleDown => {
                let radius = size * 0.5;
                let mut builder = PathBuilder::new();
                if style == MarkerStyle::TriangleDown {
                    builder.move_to(0.0, radius);
                    builder.line_to(-radius * 0.866, -radius * 0.5);
                    builder.line_to(radius * 0.866, -radius * 0.5);
                } else {
                    builder.move_to(0.0, -radius);
                    builder.line_to(-radius * 0.866, radius * 0.5);
                    builder.line_to(radius * 0.866, radius * 0.5);
                }
                builder.close();
                builder.finish()
            }
            MarkerStyle::Diamond | MarkerStyle::DiamondOpen => {
                let radius = size * 0.5;
                let mut builder = PathBuilder::new();
                builder.move_to(0.0, -radius);
                builder.line_to(radius, 0.0);
                builder.line_to(0.0, radius);
                builder.line_to(-radius, 0.0);
                builder.close();
                builder.finish()
            }
            _ => None,
        };

        let Some(path) = path else {
            return Ok(None);
        };

        let path = Arc::new(path);
        self.marker_path_cache.insert(key, Arc::clone(&path));
        Ok(Some(path))
    }

    /// Fetch (or build) the cached raster for one marker.
    ///
    /// `edge` is `(colour, width in **device pixels**)` — already scaled by the
    /// caller, exactly like the vector painter takes it — and is baked into the
    /// sprite, so an edged batch keeps the sprite fast path.
    pub(crate) fn marker_sprite(
        &mut self,
        style: MarkerStyle,
        size: f32,
        color: Color,
        edge: Option<(Color, f32)>,
        phase_x: u8,
        phase_y: u8,
    ) -> Result<Arc<MarkerSprite>> {
        let key = MarkerSpriteKey::new(style, size, color, edge, phase_x, phase_y);
        if let Some(sprite) = self.marker_sprite_cache.get(&key) {
            let sprite = Arc::clone(sprite);
            self.note_marker_sprite_cache();
            return Ok(sprite);
        }

        if let Ok(mut global_cache) = global_marker_sprite_cache().lock() {
            if let Some(sprite) = global_cache.get(&key).cloned() {
                self.marker_sprite_cache.insert(key, Arc::clone(&sprite));
                self.note_marker_sprite_cache();
                return Ok(sprite);
            }

            // Hold the global lock across creation to avoid duplicate same-key sprite work.
            // If parallel PNG workloads make unrelated misses contend here, switch to per-key slots.
            let sprite =
                Arc::new(self.create_marker_sprite(style, size, color, edge, phase_x, phase_y)?);
            let sprite = insert_global_marker_sprite(&mut global_cache, key, sprite);
            self.marker_sprite_cache.insert(key, Arc::clone(&sprite));
            self.note_marker_sprite_cache();
            return Ok(sprite);
        }

        let sprite =
            Arc::new(self.create_marker_sprite(style, size, color, edge, phase_x, phase_y)?);
        self.marker_sprite_cache.insert(key, Arc::clone(&sprite));
        self.note_marker_sprite_cache();
        Ok(sprite)
    }

    fn create_marker_sprite(
        &self,
        style: MarkerStyle,
        size: f32,
        color: Color,
        edge: Option<(Color, f32)>,
        phase_x: u8,
        phase_y: u8,
    ) -> Result<MarkerSprite> {
        let (origin, side) = Self::marker_sprite_geometry(style, size, edge);
        let mut sprite_renderer = SkiaRenderer::new(side, side, self.theme.clone())?;
        sprite_renderer.set_render_scale(self.render_scale);
        sprite_renderer.set_text_engine_mode(self.text_engine_mode);
        sprite_renderer.pixmap.fill(tiny_skia::Color::TRANSPARENT);

        let phase_step = 1.0 / Self::marker_subpixel_phases() as f32;
        let center_x = origin as f32 + phase_x as f32 * phase_step;
        let center_y = origin as f32 + phase_y as f32 * phase_step;

        sprite_renderer.draw_marker_styled_with_mask_vector(
            center_x, center_y, size, style, color, edge, None,
        )?;

        Ok(MarkerSprite {
            width: side,
            height: side,
            origin_x: origin,
            origin_y: origin,
            pixels: sprite_renderer.pixmap.data().to_vec(),
            scanlines: Self::marker_scanlines(style, sprite_renderer.pixmap.data(), side, side),
        })
    }

    fn marker_scanlines(
        style: MarkerStyle,
        pixels: &[u8],
        width: u32,
        height: u32,
    ) -> Option<Arc<[MarkerSpriteScanline]>> {
        if !matches!(
            style,
            MarkerStyle::Circle
                | MarkerStyle::Square
                | MarkerStyle::Triangle
                | MarkerStyle::TriangleDown
        ) {
            return None;
        }

        let width = width as usize;
        let height = height as usize;
        let mut scanlines = Vec::with_capacity(height);
        for row in 0..height {
            let row_start = row * width * 4;
            let mut start = None;
            let mut end = None;
            let mut opaque_start = None;
            let mut opaque_end = None;

            for col in 0..width {
                let alpha = pixels[row_start + col * 4 + 3];
                if alpha != 0 {
                    start.get_or_insert(col);
                    end = Some(col + 1);
                }
                if alpha == u8::MAX {
                    opaque_start.get_or_insert(col);
                    opaque_end = Some(col + 1);
                }
            }

            if let (Some(start), Some(end)) = (start, end) {
                scanlines.push(MarkerSpriteScanline {
                    start_x: start as u16,
                    end_x: end as u16,
                    opaque_start_x: opaque_start.unwrap_or(start) as u16,
                    opaque_end_x: opaque_end.unwrap_or(start) as u16,
                });
            } else {
                scanlines.push(MarkerSpriteScanline {
                    start_x: 0,
                    end_x: 0,
                    opaque_start_x: 0,
                    opaque_end_x: 0,
                });
            }
        }

        Some(scanlines.into())
    }

    /// Sub-pixel positions a cached marker sprite is rasterised at, per axis.
    ///
    /// The sprite compositor snaps every marker centre to the nearest phase, so
    /// this is the only place the fast path disagrees with the vector painter:
    /// a marker lands up to `1 / (2 * PHASES)` device pixels off its exact
    /// position, and the anti-aliased boundary pixels shift with it.
    ///
    /// 64 (not 32) because a marker *rim* is a thin high-contrast feature and
    /// therefore samples that error far more harshly than a bare fill does: at
    /// 32 phases an edged batch showed ~10x the boundary noise of the same
    /// batch drawn one marker at a time, with per-channel deltas past 32. At 64
    /// the worst edged delta is the same as the worst edgeless one, i.e. the
    /// rim no longer costs accuracy. Squaring this bounds the per-batch sprite
    /// table and the cache limit below, so it cannot grow without thought.
    pub(crate) const fn marker_subpixel_phases() -> u8 {
        64
    }

    /// Sprite origin and side length for one marker.
    ///
    /// `edge` is `(colour, width in device pixels)`; a rim straddles the shape's
    /// boundary, so half of it lies outside the fill and the sprite has to be
    /// padded for it or the rim would be clipped off at the sprite border.
    pub(crate) fn marker_sprite_geometry(
        style: MarkerStyle,
        size: f32,
        edge: Option<(Color, f32)>,
    ) -> (i32, u32) {
        let radius = size * 0.5;
        let edge_half = edge
            .filter(|_| style.takes_edge())
            .map(|(_, width_px)| width_px * 0.5)
            .unwrap_or(0.0);
        let stroke_half = match style {
            MarkerStyle::SquareOpen => (size * 0.15).max(1.0) * 0.5,
            MarkerStyle::TriangleOpen | MarkerStyle::DiamondOpen => (size * 0.15).max(1.0) * 0.5,
            MarkerStyle::Plus | MarkerStyle::Cross => (size * 0.25).max(1.0) * 0.5,
            MarkerStyle::Star => (size * 0.22).max(1.0) * 0.5,
            _ => 0.5,
        }
        .max(edge_half);
        let padding = (radius + stroke_half + 3.0).ceil() as i32;
        let origin = padding + 1;
        let side = (origin * 2 + 2).max(4) as u32;
        (origin, side)
    }

    fn vertical_tick_span(
        spine_y: f32,
        tick_size: f32,
        tick_direction: &TickDirection,
        top: bool,
    ) -> (f32, f32) {
        match tick_direction {
            TickDirection::Inside => {
                if top {
                    (spine_y, spine_y + tick_size)
                } else {
                    (spine_y, spine_y - tick_size)
                }
            }
            TickDirection::Outside => {
                if top {
                    (spine_y, spine_y - tick_size)
                } else {
                    (spine_y, spine_y + tick_size)
                }
            }
            TickDirection::InOut => (spine_y - tick_size / 2.0, spine_y + tick_size / 2.0),
        }
    }

    fn horizontal_tick_span(
        spine_x: f32,
        tick_size: f32,
        tick_direction: &TickDirection,
        right: bool,
    ) -> (f32, f32) {
        match tick_direction {
            TickDirection::Inside => {
                if right {
                    (spine_x, spine_x - tick_size)
                } else {
                    (spine_x, spine_x + tick_size)
                }
            }
            TickDirection::Outside => {
                if right {
                    (spine_x, spine_x + tick_size)
                } else {
                    (spine_x, spine_x - tick_size)
                }
            }
            TickDirection::InOut => (spine_x - tick_size / 2.0, spine_x + tick_size / 2.0),
        }
    }

    fn x_label_center(plot_area: &LayoutRect, x_value: f64, x_min: f64, x_max: f64) -> f32 {
        let x_range = x_max - x_min;
        if x_range.abs() < f64::EPSILON {
            plot_area.center_x()
        } else {
            plot_area.left + ((x_value - x_min) as f32 / x_range as f32) * plot_area.width()
        }
    }

    fn x_label_center_scaled(
        plot_area: &LayoutRect,
        x_value: f64,
        x_min: f64,
        x_max: f64,
        scale: &crate::axes::AxisScale,
    ) -> f32 {
        if x_min == x_max
            || (!matches!(scale, crate::axes::AxisScale::Log)
                && (x_max - x_min).abs() < f64::EPSILON)
        {
            plot_area.center_x()
        } else {
            let normalized = scale.normalized_position(x_value, x_min, x_max);
            plot_area.left + normalized as f32 * plot_area.width()
        }
    }

    fn y_label_center_scaled(
        plot_area: &LayoutRect,
        y_value: f64,
        y_min: f64,
        y_max: f64,
        scale: &crate::axes::AxisScale,
    ) -> f32 {
        if y_min == y_max
            || (!matches!(scale, crate::axes::AxisScale::Log)
                && (y_max - y_min).abs() < f64::EPSILON)
        {
            plot_area.center_y()
        } else {
            let normalized = scale.normalized_position(y_value, y_min, y_max);
            plot_area.bottom - normalized as f32 * plot_area.height()
        }
    }

    /// Draw axis lines and ticks
    pub fn draw_axes(
        &mut self,
        plot_area: Rect,
        x_ticks: &[f32],
        y_ticks: &[f32],
        tick_direction: &TickDirection,
        tick_sides: &TickSides,
        color: Color,
    ) -> Result<()> {
        // Axis metrics are authored in logical pixels and resolved via RenderScale.
        let axis_width = self.logical_pixels_to_pixels(1.5);
        let tick_size = self.logical_pixels_to_pixels(5.0);
        let tick_width = self.logical_pixels_to_pixels(1.0);

        // Draw the full plot frame. Tick side selection only controls tick marks.
        self.draw_line(
            plot_area.left(),
            plot_area.bottom(),
            plot_area.right(),
            plot_area.bottom(),
            color,
            axis_width,
            LineStyle::Solid,
        )?;

        self.draw_line(
            plot_area.left(),
            plot_area.top(),
            plot_area.left(),
            plot_area.bottom(),
            color,
            axis_width,
            LineStyle::Solid,
        )?;

        self.draw_line(
            plot_area.left(),
            plot_area.top(),
            plot_area.right(),
            plot_area.top(),
            color,
            axis_width,
            LineStyle::Solid,
        )?;

        self.draw_line(
            plot_area.right(),
            plot_area.top(),
            plot_area.right(),
            plot_area.bottom(),
            color,
            axis_width,
            LineStyle::Solid,
        )?;

        // Draw tick marks
        for &x in x_ticks {
            if x >= plot_area.left() && x <= plot_area.right() {
                if tick_sides.bottom {
                    let (tick_start, tick_end) = Self::vertical_tick_span(
                        plot_area.bottom(),
                        tick_size,
                        tick_direction,
                        false,
                    );
                    self.draw_line(
                        x,
                        tick_start,
                        x,
                        tick_end,
                        color,
                        tick_width,
                        LineStyle::Solid,
                    )?;
                }
                if tick_sides.top {
                    let (tick_start, tick_end) =
                        Self::vertical_tick_span(plot_area.top(), tick_size, tick_direction, true);
                    self.draw_line(
                        x,
                        tick_start,
                        x,
                        tick_end,
                        color,
                        tick_width,
                        LineStyle::Solid,
                    )?;
                }
            }
        }

        for &y in y_ticks {
            if y >= plot_area.top() && y <= plot_area.bottom() {
                if tick_sides.left {
                    let (tick_start, tick_end) = Self::horizontal_tick_span(
                        plot_area.left(),
                        tick_size,
                        tick_direction,
                        false,
                    );
                    self.draw_line(
                        tick_start,
                        y,
                        tick_end,
                        y,
                        color,
                        tick_width,
                        LineStyle::Solid,
                    )?;
                }
                if tick_sides.right {
                    let (tick_start, tick_end) = Self::horizontal_tick_span(
                        plot_area.right(),
                        tick_size,
                        tick_direction,
                        true,
                    );
                    self.draw_line(
                        tick_start,
                        y,
                        tick_end,
                        y,
                        color,
                        tick_width,
                        LineStyle::Solid,
                    )?;
                }
            }
        }

        Ok(())
    }

    /// Draw axis lines with major and minor tick marks.
    pub fn draw_axes_with_minor_ticks(
        &mut self,
        plot_area: Rect,
        x_major_ticks: &[f32],
        y_major_ticks: &[f32],
        x_minor_ticks: &[f32],
        y_minor_ticks: &[f32],
        tick_direction: &TickDirection,
        tick_sides: &TickSides,
        color: Color,
    ) -> Result<()> {
        let axis_width = self.logical_pixels_to_pixels(1.5);
        let major_tick_size = self.logical_pixels_to_pixels(5.0);
        let minor_tick_size = self.logical_pixels_to_pixels(3.0);
        let major_tick_width = self.logical_pixels_to_pixels(1.0);
        let minor_tick_width = self.logical_pixels_to_pixels(0.8);

        self.draw_axes_with_minor_ticks_styled(
            plot_area,
            x_major_ticks,
            y_major_ticks,
            x_minor_ticks,
            y_minor_ticks,
            tick_direction,
            tick_sides,
            &SpineConfig::default(),
            color,
            axis_width,
            major_tick_size,
            minor_tick_size,
            major_tick_width,
            minor_tick_width,
        )
    }

    /// Draw axis lines with caller-supplied axis and tick metrics in pixels.
    pub fn draw_axes_with_minor_ticks_styled(
        &mut self,
        plot_area: Rect,
        x_major_ticks: &[f32],
        y_major_ticks: &[f32],
        x_minor_ticks: &[f32],
        y_minor_ticks: &[f32],
        tick_direction: &TickDirection,
        tick_sides: &TickSides,
        spines: &SpineConfig,
        color: Color,
        axis_width: f32,
        major_tick_size: f32,
        minor_tick_size: f32,
        major_tick_width: f32,
        minor_tick_width: f32,
    ) -> Result<()> {
        fn snap_stroke_coord(coord: f32, width: f32) -> f32 {
            if !coord.is_finite() || !width.is_finite() {
                return coord;
            }
            let rounded_width = width.round().max(1.0) as i32;
            let offset = if rounded_width % 2 == 0 { 0.0 } else { 0.5 };
            (coord - offset).round() + offset
        }

        fn snap_endpoint(coord: f32) -> f32 {
            if coord.is_finite() {
                coord.round()
            } else {
                coord
            }
        }

        let spine_offset = self.render_scale.points_to_pixels(spines.offset.max(0.0));
        let plot_left = snap_endpoint(plot_area.left());
        let plot_right = snap_endpoint(plot_area.right());
        let plot_top = snap_endpoint(plot_area.top());
        let plot_bottom = snap_endpoint(plot_area.bottom());
        let bottom_spine_y = snap_stroke_coord(plot_area.bottom() + spine_offset, axis_width);
        let top_spine_y = snap_stroke_coord(plot_area.top() - spine_offset, axis_width);
        let left_spine_x = snap_stroke_coord(plot_area.left() - spine_offset, axis_width);
        let right_spine_x = snap_stroke_coord(plot_area.right() + spine_offset, axis_width);

        if spines.bottom {
            self.draw_line(
                plot_left,
                bottom_spine_y,
                plot_right,
                bottom_spine_y,
                color,
                axis_width,
                LineStyle::Solid,
            )?;
        }

        if spines.left {
            self.draw_line(
                left_spine_x,
                plot_top,
                left_spine_x,
                plot_bottom,
                color,
                axis_width,
                LineStyle::Solid,
            )?;
        }

        if spines.top {
            self.draw_line(
                plot_left,
                top_spine_y,
                plot_right,
                top_spine_y,
                color,
                axis_width,
                LineStyle::Solid,
            )?;
        }

        if spines.right {
            self.draw_line(
                right_spine_x,
                plot_top,
                right_spine_x,
                plot_bottom,
                color,
                axis_width,
                LineStyle::Solid,
            )?;
        }

        for (tick_size, tick_width, ticks) in [
            (major_tick_size, major_tick_width, x_major_ticks),
            (minor_tick_size, minor_tick_width, x_minor_ticks),
        ] {
            for &x in ticks {
                if x >= plot_area.left() && x <= plot_area.right() {
                    let x = snap_stroke_coord(x, tick_width);
                    if tick_sides.bottom && spines.bottom {
                        let (tick_start, tick_end) = Self::vertical_tick_span(
                            bottom_spine_y,
                            tick_size,
                            tick_direction,
                            false,
                        );
                        self.draw_line(
                            x,
                            tick_start,
                            x,
                            tick_end,
                            color,
                            tick_width,
                            LineStyle::Solid,
                        )?;
                    }
                    if tick_sides.top && spines.top {
                        let (tick_start, tick_end) =
                            Self::vertical_tick_span(top_spine_y, tick_size, tick_direction, true);
                        self.draw_line(
                            x,
                            tick_start,
                            x,
                            tick_end,
                            color,
                            tick_width,
                            LineStyle::Solid,
                        )?;
                    }
                }
            }
        }

        for (tick_size, tick_width, ticks) in [
            (major_tick_size, major_tick_width, y_major_ticks),
            (minor_tick_size, minor_tick_width, y_minor_ticks),
        ] {
            for &y in ticks {
                if y >= plot_area.top() && y <= plot_area.bottom() {
                    let y = snap_stroke_coord(y, tick_width);
                    if tick_sides.left && spines.left {
                        let (tick_start, tick_end) = Self::horizontal_tick_span(
                            left_spine_x,
                            tick_size,
                            tick_direction,
                            false,
                        );
                        self.draw_line(
                            tick_start,
                            y,
                            tick_end,
                            y,
                            color,
                            tick_width,
                            LineStyle::Solid,
                        )?;
                    }
                    if tick_sides.right && spines.right {
                        let (tick_start, tick_end) = Self::horizontal_tick_span(
                            right_spine_x,
                            tick_size,
                            tick_direction,
                            true,
                        );
                        self.draw_line(
                            tick_start,
                            y,
                            tick_end,
                            y,
                            color,
                            tick_width,
                            LineStyle::Solid,
                        )?;
                    }
                }
            }
        }

        Ok(())
    }

    /// Draw axis lines and ticks with advanced configuration
    pub fn draw_axes_with_config(
        &mut self,
        plot_area: Rect,
        x_major_ticks: &[f32],
        y_major_ticks: &[f32],
        x_minor_ticks: &[f32],
        y_minor_ticks: &[f32],
        tick_direction: &TickDirection,
        tick_sides: &TickSides,
        color: Color,
        dpi_scale: f32,
    ) -> Result<()> {
        let render_scale = RenderScale::from_reference_scale(dpi_scale);
        let axis_width = render_scale.logical_pixels_to_pixels(1.5);
        let major_tick_size = render_scale.logical_pixels_to_pixels(8.0);
        let minor_tick_size = render_scale.logical_pixels_to_pixels(4.0);
        let major_tick_width = render_scale.logical_pixels_to_pixels(1.5);
        let minor_tick_width = render_scale.logical_pixels_to_pixels(1.0);

        // Draw the full plot frame. Tick side selection only controls tick marks.
        self.draw_line(
            plot_area.left(),
            plot_area.bottom(),
            plot_area.right(),
            plot_area.bottom(),
            color,
            axis_width,
            LineStyle::Solid,
        )?;

        self.draw_line(
            plot_area.left(),
            plot_area.top(),
            plot_area.left(),
            plot_area.bottom(),
            color,
            axis_width,
            LineStyle::Solid,
        )?;

        self.draw_line(
            plot_area.left(),
            plot_area.top(),
            plot_area.right(),
            plot_area.top(),
            color,
            axis_width,
            LineStyle::Solid,
        )?;

        self.draw_line(
            plot_area.right(),
            plot_area.top(),
            plot_area.right(),
            plot_area.bottom(),
            color,
            axis_width,
            LineStyle::Solid,
        )?;

        for &x in x_major_ticks {
            if x >= plot_area.left() && x <= plot_area.right() {
                if tick_sides.bottom {
                    let (tick_start, tick_end) = Self::vertical_tick_span(
                        plot_area.bottom(),
                        major_tick_size,
                        tick_direction,
                        false,
                    );
                    self.draw_line(
                        x,
                        tick_start,
                        x,
                        tick_end,
                        color,
                        major_tick_width,
                        LineStyle::Solid,
                    )?;
                }
                if tick_sides.top {
                    let (tick_start, tick_end) = Self::vertical_tick_span(
                        plot_area.top(),
                        major_tick_size,
                        tick_direction,
                        true,
                    );
                    self.draw_line(
                        x,
                        tick_start,
                        x,
                        tick_end,
                        color,
                        major_tick_width,
                        LineStyle::Solid,
                    )?;
                }
            }
        }

        for &x in x_minor_ticks {
            if x >= plot_area.left() && x <= plot_area.right() {
                if tick_sides.bottom {
                    let (tick_start, tick_end) = Self::vertical_tick_span(
                        plot_area.bottom(),
                        minor_tick_size,
                        tick_direction,
                        false,
                    );
                    self.draw_line(
                        x,
                        tick_start,
                        x,
                        tick_end,
                        color,
                        minor_tick_width,
                        LineStyle::Solid,
                    )?;
                }
                if tick_sides.top {
                    let (tick_start, tick_end) = Self::vertical_tick_span(
                        plot_area.top(),
                        minor_tick_size,
                        tick_direction,
                        true,
                    );
                    self.draw_line(
                        x,
                        tick_start,
                        x,
                        tick_end,
                        color,
                        minor_tick_width,
                        LineStyle::Solid,
                    )?;
                }
            }
        }

        for &y in y_major_ticks {
            if y >= plot_area.top() && y <= plot_area.bottom() {
                if tick_sides.left {
                    let (tick_start, tick_end) = Self::horizontal_tick_span(
                        plot_area.left(),
                        major_tick_size,
                        tick_direction,
                        false,
                    );
                    self.draw_line(
                        tick_start,
                        y,
                        tick_end,
                        y,
                        color,
                        major_tick_width,
                        LineStyle::Solid,
                    )?;
                }
                if tick_sides.right {
                    let (tick_start, tick_end) = Self::horizontal_tick_span(
                        plot_area.right(),
                        major_tick_size,
                        tick_direction,
                        true,
                    );
                    self.draw_line(
                        tick_start,
                        y,
                        tick_end,
                        y,
                        color,
                        major_tick_width,
                        LineStyle::Solid,
                    )?;
                }
            }
        }

        for &y in y_minor_ticks {
            if y >= plot_area.top() && y <= plot_area.bottom() {
                if tick_sides.left {
                    let (tick_start, tick_end) = Self::horizontal_tick_span(
                        plot_area.left(),
                        minor_tick_size,
                        tick_direction,
                        false,
                    );
                    self.draw_line(
                        tick_start,
                        y,
                        tick_end,
                        y,
                        color,
                        minor_tick_width,
                        LineStyle::Solid,
                    )?;
                }
                if tick_sides.right {
                    let (tick_start, tick_end) = Self::horizontal_tick_span(
                        plot_area.right(),
                        minor_tick_size,
                        tick_direction,
                        true,
                    );
                    self.draw_line(
                        tick_start,
                        y,
                        tick_end,
                        y,
                        color,
                        minor_tick_width,
                        LineStyle::Solid,
                    )?;
                }
            }
        }

        Ok(())
    }

    /// Draw a DataShader aggregated image
    pub fn draw_datashader_image(
        &mut self,
        image: &crate::data::DataShaderImage,
        plot_area: Rect,
    ) -> Result<()> {
        // Create a pixmap from the DataShader image data
        let mut datashader_pixmap = Pixmap::new(image.width as u32, image.height as u32)
            .ok_or(PlottingError::OutOfMemory)?;

        // Copy the RGBA data from DataShader
        if image.pixels.len() != (image.width * image.height * 4) {
            return Err(PlottingError::RenderError(
                "Invalid DataShader image pixel data".to_string(),
            ));
        }

        let tint = self.theme.foreground;

        // Convert the density mask to tiny-skia's native tinted premultiplied
        // format. `Pixmap::data_mut` is premultiplied **RGBA**, not BGRA: this
        // used to write B, G, R, A and so swapped red and blue. It went
        // unnoticed because every theme's `foreground` is black, white or grey,
        // where the swap is invisible.
        let pixmap_data = datashader_pixmap.data_mut();
        for (i, chunk) in image.pixels.chunks_exact(4).enumerate() {
            let a = chunk[3];

            let alpha_f = a as f32 / 255.0;
            let premult_r = (tint.r as f32 * alpha_f).round() as u8;
            let premult_g = (tint.g as f32 * alpha_f).round() as u8;
            let premult_b = (tint.b as f32 * alpha_f).round() as u8;

            pixmap_data[i * 4] = premult_r;
            pixmap_data[i * 4 + 1] = premult_g;
            pixmap_data[i * 4 + 2] = premult_b;
            pixmap_data[i * 4 + 3] = a;
        }

        // Scale and draw the DataShader image onto the plot area
        let transform = Transform::from_scale(
            plot_area.width() / image.width as f32,
            plot_area.height() / image.height as f32,
        )
        .post_translate(plot_area.x(), plot_area.y());

        self.pixmap.draw_pixmap(
            0,
            0,
            datashader_pixmap.as_ref(),
            &PixmapPaint::default(),
            transform,
            None,
        );

        Ok(())
    }

    /// Draw text at the specified position using cosmic-text (professional quality).
    /// `y` is interpreted as the top of the text rendering area.
    pub fn draw_text(&mut self, text: &str, x: f32, y: f32, size: f32, color: Color) -> Result<()> {
        // Bucket 1 of the geometry policy in `primitives.rs`, and the exact
        // twin of `SvgRenderer::draw_text`: a label the axes cannot place is
        // skipped, not raised. Without this the glyph run is laid out at `NaN`
        // and every glyph quantises to 0 on the way to the pixmap, blitting the
        // label into the top-left corner where it reads as real content.
        if !Self::all_finite(&[x, y, size]) {
            return Ok(());
        }
        match self.text_engine_mode {
            TextEngineMode::Plain => {
                let config = FontConfig::new(self.font_config.family.clone(), size);
                self.text_renderer
                    .render_text(&mut self.pixmap, text, x, y, &config, color)
            }
            #[cfg(feature = "typst-math")]
            TextEngineMode::Typst => {
                let size_pt = self.typst_size_pt(size);
                let rendered = typst_text::render_raster_with_font_family(
                    text,
                    size_pt,
                    color,
                    0.0,
                    &self.font_config.family,
                    "Skia text rendering",
                )?;
                let (draw_x, draw_y) = typst_text::anchored_top_left(
                    x,
                    y,
                    rendered.width,
                    rendered.height,
                    TypstTextAnchor::TopLeft,
                );
                self.draw_typst_raster(&rendered, draw_x, draw_y);
                Ok(())
            }
        }
    }

    /// Draw text rotated 90 degrees counterclockwise using cosmic-text
    pub fn draw_text_rotated(
        &mut self,
        text: &str,
        x: f32,
        y: f32,
        size: f32,
        color: Color,
    ) -> Result<()> {
        // See `draw_text`: an unplaceable label is skipped, not raised.
        if !Self::all_finite(&[x, y, size]) {
            return Ok(());
        }
        match self.text_engine_mode {
            TextEngineMode::Plain => {
                let config = FontConfig::new(self.font_config.family.clone(), size);
                self.text_renderer
                    .render_text_rotated(&mut self.pixmap, text, x, y, &config, color)
            }
            #[cfg(feature = "typst-math")]
            TextEngineMode::Typst => {
                let size_pt = self.typst_size_pt(size);
                let rendered = typst_text::render_raster_with_font_family(
                    text,
                    size_pt,
                    color,
                    -90.0,
                    &self.font_config.family,
                    "Skia rotated text rendering",
                )?;
                let (draw_x, draw_y) = typst_text::anchored_top_left(
                    x,
                    y,
                    rendered.width,
                    rendered.height,
                    TypstTextAnchor::Center,
                );
                self.draw_typst_raster(&rendered, draw_x, draw_y);
                Ok(())
            }
        }
    }

    /// Draw text centered horizontally at the given position.
    /// `y` is interpreted as the top of the text rendering area.
    pub fn draw_text_centered(
        &mut self,
        text: &str,
        center_x: f32,
        y: f32,
        size: f32,
        color: Color,
    ) -> Result<()> {
        self.draw_text_centered_with_weight(text, center_x, y, size, color, FontWeight::Normal)
    }

    pub(crate) fn draw_text_centered_with_weight(
        &mut self,
        text: &str,
        center_x: f32,
        y: f32,
        size: f32,
        color: Color,
        weight: FontWeight,
    ) -> Result<()> {
        // See `draw_text`: an unplaceable label is skipped, not raised.
        if !Self::all_finite(&[center_x, y, size]) {
            return Ok(());
        }
        match self.text_engine_mode {
            TextEngineMode::Plain => {
                let config = FontConfig::new(self.font_config.family.clone(), size).weight(weight);
                self.text_renderer.render_text_centered(
                    &mut self.pixmap,
                    text,
                    center_x,
                    y,
                    &config,
                    color,
                )
            }
            #[cfg(feature = "typst-math")]
            TextEngineMode::Typst => {
                let size_pt = self.typst_size_pt(size);
                let multiline_text = typst_text::with_explicit_line_breaks(text);
                let weighted_text = typst_text::with_font_weight(&multiline_text, weight);
                let aligned_text = typst_text::with_horizontal_alignment(
                    &weighted_text,
                    crate::core::TextAlign::Center,
                );
                let rendered = typst_text::render_raster_with_font_family(
                    &aligned_text,
                    size_pt,
                    color,
                    0.0,
                    &self.font_config.family,
                    "Skia centered text rendering",
                )?;
                let (draw_x, draw_y) = typst_text::anchored_top_left(
                    center_x,
                    y,
                    rendered.width,
                    rendered.height,
                    TypstTextAnchor::TopCenter,
                );
                self.draw_typst_raster(&rendered, draw_x, draw_y);
                Ok(())
            }
        }
    }

    /// Measure text dimensions
    pub fn measure_text(&self, text: &str, size: f32) -> Result<(f32, f32)> {
        self.measure_text_with_weight(text, size, FontWeight::Normal)
    }

    pub(crate) fn measure_text_with_weight(
        &self,
        text: &str,
        size: f32,
        weight: FontWeight,
    ) -> Result<(f32, f32)> {
        match self.text_engine_mode {
            TextEngineMode::Plain => {
                let config = FontConfig::new(self.font_config.family.clone(), size).weight(weight);
                self.text_renderer.measure_text(text, &config)
            }
            #[cfg(feature = "typst-math")]
            TextEngineMode::Typst => {
                let size_pt = self.typst_size_pt(size);
                let multiline_text = typst_text::with_explicit_line_breaks(text);
                let weighted_text = typst_text::with_font_weight(&multiline_text, weight);
                let aligned_text = typst_text::with_horizontal_alignment(
                    &weighted_text,
                    crate::core::TextAlign::Center,
                );
                typst_text::measure_text_with_font_family(
                    &aligned_text,
                    size_pt,
                    self.theme.foreground,
                    0.0,
                    TypstBackendKind::Raster,
                    &self.font_config.family,
                    "Skia text measurement",
                )
            }
        }
    }

    pub(crate) fn measure_text_ink_center_from_top(&self, text: &str, size: f32) -> Result<f32> {
        match self.text_engine_mode {
            TextEngineMode::Plain => {
                let config = FontConfig::new(self.font_config.family.clone(), size);
                self.text_renderer
                    .measure_text_ink_center_from_top(text, &config)
            }
            #[cfg(feature = "typst-math")]
            TextEngineMode::Typst => Ok(self.measure_text(text, size)?.1 / 2.0),
        }
    }

    pub(crate) fn measure_label_text(&self, text: &str, size: f32) -> Result<(f32, f32)> {
        let label_snippet = self.generated_label(text);
        self.measure_text(&label_snippet, size)
    }

    fn generated_label<'a>(&self, text: &'a str) -> Cow<'a, str> {
        #[cfg(feature = "typst-math")]
        if self.text_engine_mode.uses_typst() {
            return Cow::Owned(typst_text::literal_text_snippet(text));
        }

        Cow::Borrowed(text)
    }

    /// Draw border around plot area
    pub fn draw_plot_border(
        &mut self,
        plot_area: Rect,
        color: Color,
        dpi_scale: f32,
    ) -> Result<()> {
        // Matches the full-frame axis width used by draw_axes/draw_axes_with_config.
        let border_width =
            RenderScale::from_reference_scale(dpi_scale).logical_pixels_to_pixels(1.5);

        // Create border paint
        let mut paint = tiny_skia::Paint::default();
        paint.set_color_rgba8(color.r, color.g, color.b, color.a);
        paint.anti_alias = true;

        // Create stroke
        let stroke = tiny_skia::Stroke {
            width: border_width,
            ..tiny_skia::Stroke::default()
        };

        // Draw rectangle border around plot area
        let path = tiny_skia::PathBuilder::from_rect(plot_area);
        self.pixmap.stroke_path(
            &path,
            &paint,
            &stroke,
            tiny_skia::Transform::identity(),
            None,
        );

        Ok(())
    }

    /// Draw title using spacing configuration
    ///
    /// The title is positioned near the top of the canvas with minimal padding.
    pub fn draw_title(
        &mut self,
        title: &str,
        _plot_area: Rect,
        color: Color,
        title_size: f32,
        dpi: f32,
        _spacing: &SpacingConfig,
    ) -> Result<()> {
        // Center title horizontally over the entire canvas width
        let canvas_center_x = self.width() as f32 / 2.0;

        // Position title near top of canvas with small top padding
        // Text baseline is at title_y, so top of text is roughly at title_y - title_size * 0.8
        let top_padding = RenderScale::new(dpi).logical_pixels_to_pixels(8.0);
        let title_y = top_padding + title_size;

        self.draw_text_centered(title, canvas_center_x, title_y, title_size, color)
    }

    /// Draw title at a computed position from LayoutCalculator
    ///
    /// This is the preferred method for content-driven layout.
    pub fn draw_title_at(&mut self, pos: &TextPosition, text: &str, color: Color) -> Result<()> {
        self.draw_title_at_with_weight(pos, text, color, FontWeight::Normal)
    }

    pub(crate) fn draw_title_at_with_weight(
        &mut self,
        pos: &TextPosition,
        text: &str,
        color: Color,
        weight: FontWeight,
    ) -> Result<()> {
        self.draw_text_centered_with_weight(text, pos.x, pos.y, pos.size, color, weight)
    }

    /// Draw X-axis label at a computed position from LayoutCalculator
    ///
    /// This is the preferred method for content-driven layout.
    pub fn draw_xlabel_at(&mut self, pos: &TextPosition, text: &str, color: Color) -> Result<()> {
        self.draw_text_centered(text, pos.x, pos.y, pos.size, color)
    }

    /// Draw Y-axis label at a computed position from LayoutCalculator
    ///
    /// The text is rotated 90° counterclockwise for vertical display.
    pub fn draw_ylabel_at(&mut self, pos: &TextPosition, text: &str, color: Color) -> Result<()> {
        self.draw_text_rotated(text, pos.x, pos.y, pos.size, color)
    }

    /// Draw axis tick labels and border using layout positions
    ///
    /// Uses the computed positions from LayoutCalculator for precise placement.
    /// Draw axis tick labels and border on a linear axis pair.
    ///
    /// Thin wrapper over `draw_axis_labels_at_scaled` with linear
    /// scales — it exists only so callers that genuinely have no scale to hand
    /// keep working. It is deliberately not a second implementation.
    #[allow(clippy::too_many_arguments)]
    pub fn draw_axis_labels_at(
        &mut self,
        plot_area: &LayoutRect,
        x_min: f64,
        x_max: f64,
        y_min: f64,
        y_max: f64,
        x_ticks: &[f64],
        y_ticks: &[f64],
        xtick_baseline_y: f32,
        ytick_right_x: f32,
        tick_size: f32,
        color: Color,
        dpi: f32,
        show_tick_labels: bool,
        draw_border: bool,
    ) -> Result<()> {
        self.draw_axis_labels_at_scaled(
            plot_area,
            x_min,
            x_max,
            y_min,
            y_max,
            x_ticks,
            y_ticks,
            xtick_baseline_y,
            ytick_right_x,
            tick_size,
            color,
            dpi,
            show_tick_labels,
            draw_border,
            &crate::axes::AxisScale::Linear,
            &crate::axes::AxisScale::Linear,
        )
    }

    /// Draw the y-axis tick labels.
    ///
    /// This is the single implementation shared by the numeric and both
    /// categorical axis-label paths. It takes the scale by value rather than
    /// defaulting to linear so that a caller physically cannot draw y ticks
    /// without saying which scale they belong to — that omission is exactly how
    /// the categorical paths ended up labelling a log axis "1000" while the
    /// numeric path drew "10³".
    fn draw_y_tick_labels(
        &mut self,
        plot_area: &LayoutRect,
        y_ticks: &[f64],
        y_min: f64,
        y_max: f64,
        y_scale: &crate::axes::AxisScale,
        ytick_right_x: f32,
        tick_size: f32,
        color: Color,
    ) -> Result<()> {
        let y_labels = format_tick_labels_for_scale(y_ticks, y_scale);

        for (tick_value, label_text) in y_ticks.iter().zip(y_labels.iter()) {
            let y_pixel =
                Self::y_label_center_scaled(plot_area, *tick_value, y_min, y_max, y_scale);

            let label_snippet = self.generated_label(label_text);
            let (text_width, text_height) = self.measure_text(&label_snippet, tick_size)?;
            let label_x = (ytick_right_x - text_width).max(0.0);
            let centered_y = y_pixel - text_height / 2.0;
            self.draw_text(&label_snippet, label_x, centered_y, tick_size, color)?;
        }

        Ok(())
    }

    /// Draw axis tick labels and border using scale-aware layout positions.
    pub(crate) fn draw_axis_labels_at_scaled(
        &mut self,
        plot_area: &LayoutRect,
        x_min: f64,
        x_max: f64,
        y_min: f64,
        y_max: f64,
        x_ticks: &[f64],
        y_ticks: &[f64],
        xtick_baseline_y: f32,
        ytick_right_x: f32,
        tick_size: f32,
        color: Color,
        dpi: f32,
        show_tick_labels: bool,
        draw_border: bool,
        x_scale: &crate::axes::AxisScale,
        y_scale: &crate::axes::AxisScale,
    ) -> Result<()> {
        let render_scale = RenderScale::new(dpi);

        let skia_plot_area = Rect::from_ltrb(
            plot_area.left,
            plot_area.top,
            plot_area.right,
            plot_area.bottom,
        )
        .ok_or(PlottingError::InvalidData {
            message: "Invalid plot area dimensions".to_string(),
            position: None,
        })?;

        if show_tick_labels {
            let x_labels = format_tick_labels_for_scale(x_ticks, x_scale);
            for (tick_value, label_text) in x_ticks.iter().zip(x_labels.iter()) {
                let x_pixel =
                    Self::x_label_center_scaled(plot_area, *tick_value, x_min, x_max, x_scale);

                let label_snippet = self.generated_label(label_text);
                let (text_width, _) = self.measure_text(&label_snippet, tick_size)?;
                let label_x = (x_pixel - text_width / 2.0)
                    .max(0.0)
                    .min(self.width() as f32 - text_width);
                self.draw_text(&label_snippet, label_x, xtick_baseline_y, tick_size, color)?;
            }

            self.draw_y_tick_labels(
                plot_area,
                y_ticks,
                y_min,
                y_max,
                y_scale,
                ytick_right_x,
                tick_size,
                color,
            )?;
        }

        if draw_border {
            self.draw_plot_border(skia_plot_area, color, render_scale.reference_scale())?;
        }

        Ok(())
    }

    /// Pixel centre of every categorical slot, in axis order.
    ///
    /// One formula for the measurement, the raster row and the SVG row: a label
    /// measured at one x and drawn at another is the collision this row exists
    /// to avoid, dressed up as a rounding difference.
    pub fn categorical_label_centers(
        plot_area: &LayoutRect,
        x_positions: &[f64],
        x_min: f64,
        x_max: f64,
    ) -> Vec<f32> {
        x_positions
            .iter()
            .map(|&x_position| Self::x_label_center(plot_area, x_position, x_min, x_max))
            .collect()
    }

    /// Measure an x tick label row: how much room it needs, and how far apart
    /// its labels have to be spaced to stop overlapping.
    ///
    /// Labels are measured as the text engine will lay them out, and an empty
    /// label measures nothing — an unnamed slot holds its place on the axis
    /// without writing under it.
    pub fn measure_x_tick_row(
        &self,
        labels: &[String],
        centers: &[f32],
        size: f32,
        bounds: XTickRowBounds,
    ) -> Result<XTickRowMetrics> {
        let mut widths = Vec::with_capacity(labels.len());
        let mut heights = Vec::with_capacity(labels.len());
        let mut horizontal_extent = 0.0_f32;
        let mut max_label_width = 0.0_f32;

        for label in labels {
            if label.is_empty() {
                widths.push(0.0);
                heights.push(0.0);
                continue;
            }
            let (width, height) = self.measure_label_text(label, size)?;
            widths.push(width);
            heights.push(height);
            horizontal_extent = horizontal_extent.max(height);
            max_label_width = max_label_width.max(width);
        }

        let gap = size * X_TICK_LABEL_GAP_EM;
        // One gutter for the whole row: the same clearance a label keeps from
        // its neighbour it also keeps from the figure edge.
        let bounds = bounds.inset(gap);
        Ok(XTickRowMetrics {
            horizontal_extent,
            max_label_width,
            horizontal_stride: clearing_stride(centers, &widths, gap, bounds),
            // Turned a quarter turn, a label is only as wide as it is tall, so
            // its neighbours are cleared by its height rather than its width.
            rotated_stride: clearing_stride(centers, &heights, gap, bounds),
            bounds,
        })
    }

    /// Draw axis tick labels with a categorical x axis.
    ///
    /// Every categorical plot type — bar, box plot, violin, boxen — reaches this
    /// one drawer, with the slot centres from `CategoryAxis::harvest`. A
    /// bar chart's slots happen to be `0..n-1`; there used to be a second copy of
    /// this function that assumed that and could not express anything else, which
    /// is why a violin needed its own.
    ///
    /// A slot whose series carries no category name has an empty label and draws
    /// nothing — it still holds its place on the axis.
    ///
    /// The label row follows [`SkiaRenderer::x_tick_label_plan`], so ten region
    /// names turn a quarter turn instead of overlapping into one illegible run.
    ///
    /// # Arguments
    /// * `plot_area` - The computed plot area
    /// * `categories` - Category labels to draw, in axis order
    /// * `x_positions` - Slot centre for each category, in data space
    /// * `x_min` - Minimum x value (data space)
    /// * `x_max` - Maximum x value (data space)
    /// * `y_min`, `y_max` - Y data range
    /// * `y_ticks` - Y-axis tick values
    /// * Other arguments for positioning and styling
    #[allow(clippy::too_many_arguments)]
    pub fn draw_axis_labels_at_categorical(
        &mut self,
        plot_area: &LayoutRect,
        categories: &[String],
        x_positions: &[f64],
        x_min: f64,
        x_max: f64,
        y_min: f64,
        y_max: f64,
        y_ticks: &[f64],
        xtick_baseline_y: f32,
        ytick_right_x: f32,
        tick_size: f32,
        color: Color,
        dpi: f32,
        show_tick_labels: bool,
        draw_border: bool,
        y_scale: &crate::axes::AxisScale,
    ) -> Result<()> {
        let render_scale = RenderScale::new(dpi);

        // Convert LayoutRect to tiny_skia Rect for border drawing
        let skia_plot_area = Rect::from_ltrb(
            plot_area.left,
            plot_area.top,
            plot_area.right,
            plot_area.bottom,
        )
        .ok_or(PlottingError::InvalidData {
            message: "Invalid plot area dimensions".to_string(),
            position: None,
        })?;

        if show_tick_labels {
            let centers = Self::categorical_label_centers(plot_area, x_positions, x_min, x_max);
            let plan = self.x_tick_label_plan;
            draw_x_tick_label_row(
                self,
                categories,
                &centers,
                xtick_baseline_y,
                tick_size,
                color,
                plan,
            )?;

            self.draw_y_tick_labels(
                plot_area,
                y_ticks,
                y_min,
                y_max,
                y_scale,
                ytick_right_x,
                tick_size,
                color,
            )?;
        }

        if draw_border {
            self.draw_plot_border(skia_plot_area, color, render_scale.reference_scale())?;
        }

        Ok(())
    }

    /// Draw title with DPI scale (legacy compatibility)
    ///
    /// This method uses a hardcoded offset for backward compatibility.
    /// Prefer `draw_title` with `SpacingConfig` for new code.
    pub fn draw_title_legacy(
        &mut self,
        title: &str,
        plot_area: Rect,
        color: Color,
        title_size: f32,
        dpi_scale: f32,
    ) -> Result<()> {
        let title_offset =
            RenderScale::from_reference_scale(dpi_scale).logical_pixels_to_pixels(30.0);
        let canvas_center_x = self.width() as f32 / 2.0;
        let title_y = (plot_area.top() - title_offset).max(title_size + 5.0);
        self.draw_text_centered(title, canvas_center_x, title_y, title_size, color)
    }

    /// Draw legend
    pub fn draw_legend(&mut self, legend_items: &[(String, Color)], plot_area: Rect) -> Result<()> {
        if legend_items.is_empty() {
            return Ok(());
        }

        let legend_size = 12.0;
        let legend_spacing = 20.0;
        let legend_x = plot_area.right() - 150.0;
        let mut legend_y = plot_area.top() + 30.0;

        // Draw legend background (simple rectangle)
        let legend_bg = Rect::from_xywh(
            legend_x - 10.0,
            legend_y - 15.0,
            140.0,
            legend_items.len() as f32 * legend_spacing + 10.0,
        )
        .ok_or(PlottingError::InvalidData {
            message: "Invalid legend dimensions".to_string(),
            position: None,
        })?;

        // Frame the panel explicitly: the fill primitive no longer adds a border.
        self.draw_rectangle_styled(
            legend_bg.left(),
            legend_bg.top(),
            legend_bg.width(),
            legend_bg.height(),
            Some(Color::from_rgba(255, 255, 255, 200)),
            Some((LEGACY_LEGEND_EDGE_COLOR, LEGACY_LEGEND_EDGE_WIDTH_PT)),
        )?;

        // Draw legend items
        for (label, color) in legend_items {
            // Draw color square
            let color_rect = Rect::from_xywh(legend_x, legend_y - 8.0, 12.0, 12.0).ok_or(
                PlottingError::InvalidData {
                    message: "Invalid legend item dimensions".to_string(),
                    position: None,
                },
            )?;
            // Fill is exactly the series colour; the neutral edge is what keeps
            // a white/near-white key visible on the near-white panel.
            self.draw_rectangle_styled(
                color_rect.left(),
                color_rect.top(),
                color_rect.width(),
                color_rect.height(),
                Some(*color),
                Some((
                    legacy_legend_swatch_edge(*color),
                    LEGACY_LEGEND_SWATCH_EDGE_WIDTH_PT,
                )),
            )?;

            // Draw label text
            self.draw_text(
                label,
                legend_x + 20.0,
                legend_y,
                legend_size,
                Color::from_rgba(0, 0, 0, 255),
            )?;

            legend_y += legend_spacing;
        }

        Ok(())
    }

    /// Draw legend with configurable position.
    ///
    /// Accepts a [`LegendPosition`](crate::core::LegendPosition) or the
    /// deprecated [`Position`](crate::core::Position), which converts losslessly.
    pub fn draw_legend_positioned(
        &mut self,
        legend_items: &[(String, Color)],
        plot_area: Rect,
        position: impl Into<crate::core::LegendPosition>,
    ) -> Result<()> {
        let position = position.into();
        if legend_items.is_empty() {
            return Ok(());
        }

        let legend_size = 12.0;
        let legend_spacing = 20.0;
        let legend_width = 140.0;
        let legend_height = legend_items.len() as f32 * legend_spacing + 10.0;

        // Calculate legend position based on position enum
        let center_x = plot_area.left() + plot_area.width() / 2.0;
        let center_y = plot_area.top() + plot_area.height() / 2.0;

        use crate::core::LegendPosition as LP;
        let (legend_x, legend_y) = match position {
            // `Best` defaults to upper-right in this legacy helper; full best
            // positioning lives in `draw_legend_full`. The `Outside*` variants
            // have no margin to expand into here, so they fall back to the
            // nearest inside placement.
            LP::Best | LP::UpperRight | LP::Right | LP::OutsideRight | LP::OutsideUpper => (
                plot_area.right() - legend_width - 10.0,
                plot_area.top() + 10.0,
            ),
            LP::UpperLeft | LP::OutsideLeft => (plot_area.left() + 10.0, plot_area.top() + 10.0),
            LP::UpperCenter => (center_x - legend_width / 2.0, plot_area.top() + 10.0),
            LP::CenterLeft => (plot_area.left() + 10.0, center_y - legend_height / 2.0),
            LP::Center => (
                center_x - legend_width / 2.0,
                center_y - legend_height / 2.0,
            ),
            LP::CenterRight => (
                plot_area.right() - legend_width - 10.0,
                center_y - legend_height / 2.0,
            ),
            LP::LowerLeft => (
                plot_area.left() + 10.0,
                plot_area.bottom() - legend_height - 10.0,
            ),
            LP::LowerCenter | LP::OutsideLower => (
                center_x - legend_width / 2.0,
                plot_area.bottom() - legend_height - 10.0,
            ),
            LP::LowerRight => (
                plot_area.right() - legend_width - 10.0,
                plot_area.bottom() - legend_height - 10.0,
            ),
            // `Custom` is a fraction of the plot area with Y growing upward,
            // matching `Legend::calculate_position`.
            LP::Custom { x, y, .. } => (
                plot_area.left() + x * plot_area.width(),
                plot_area.top() + (1.0 - y) * plot_area.height(),
            ),
        };

        // Draw legend background (simple rectangle)
        let legend_bg =
            Rect::from_xywh(legend_x - 10.0, legend_y - 5.0, legend_width, legend_height).ok_or(
                PlottingError::InvalidData {
                    message: "Invalid legend dimensions".to_string(),
                    position: None,
                },
            )?;

        // Frame the panel explicitly: the fill primitive no longer adds a border.
        self.draw_rectangle_styled(
            legend_bg.left(),
            legend_bg.top(),
            legend_bg.width(),
            legend_bg.height(),
            Some(Color::from_rgba(255, 255, 255, 200)),
            Some((LEGACY_LEGEND_EDGE_COLOR, LEGACY_LEGEND_EDGE_WIDTH_PT)),
        )?;

        // Draw legend items
        let mut item_y = legend_y + 10.0;
        for (label, color) in legend_items {
            // Draw color square
            let color_rect = Rect::from_xywh(legend_x, item_y - 8.0, 12.0, 12.0).ok_or(
                PlottingError::InvalidData {
                    message: "Invalid legend item dimensions".to_string(),
                    position: None,
                },
            )?;
            // Fill is exactly the series colour; the neutral edge is what keeps
            // a white/near-white key visible on the near-white panel.
            self.draw_rectangle_styled(
                color_rect.left(),
                color_rect.top(),
                color_rect.width(),
                color_rect.height(),
                Some(*color),
                Some((
                    legacy_legend_swatch_edge(*color),
                    LEGACY_LEGEND_SWATCH_EDGE_WIDTH_PT,
                )),
            )?;

            // Draw label text
            self.draw_text(
                label,
                legend_x + 20.0,
                item_y,
                legend_size,
                Color::from_rgba(0, 0, 0, 255),
            )?;

            item_y += legend_spacing;
        }

        Ok(())
    }

    // =========================================================================
    // New Legend System with proper handle rendering
    // =========================================================================

    /// Draw a line handle in the legend (for line series)
    ///
    /// Draws a horizontal line segment with the specified style, color, and width.
    fn draw_legend_line_handle(
        &mut self,
        x: f32,
        y: f32,
        length: f32,
        color: Color,
        style: &LineStyle,
        width: f32,
    ) -> Result<()> {
        // Draw horizontal line at vertical center
        self.draw_line(x, y, x + length, y, color, width, style.clone())
    }

    /// Draw a scatter/marker handle in the legend
    ///
    /// Draws a single marker symbol centered in the handle area.
    /// Draw a marker handle in the legend
    ///
    /// The fill is always exactly `color`. `edge` is the rim the plotted
    /// markers carry, as `(colour, width_in_points)`; `draw_marker_styled`
    /// scales the width, so the key matches the plot at any DPI.
    fn draw_legend_scatter_handle(
        &mut self,
        x: f32,
        y: f32,
        length: f32,
        color: Color,
        marker: &MarkerStyle,
        size: f32,
        edge: Option<(Color, f32)>,
    ) -> Result<()> {
        // Draw marker at center of handle area
        let center_x = x + length / 2.0;
        self.draw_marker_styled(center_x, y, size, *marker, color, edge)
    }

    /// Draw a bar handle in the legend
    ///
    /// Draws a filled rectangle to represent bar/histogram series.
    ///
    /// The fill is always exactly `color` — a legend key has to reproduce the
    /// series colour. `edge` is the stroke the corresponding patch is drawn
    /// with, as `(colour, width_in_points)`; the width goes through the render
    /// scale so the key matches the plot at any DPI. `None` draws a flat patch.
    fn draw_legend_bar_handle(
        &mut self,
        x: f32,
        y: f32,
        length: f32,
        height: f32,
        color: Color,
        edge: Option<(Color, f32)>,
    ) -> Result<()> {
        // Draw filled rectangle centered vertically
        let rect_y = y - height / 2.0;
        self.draw_rectangle_styled(x, rect_y, length, height, Some(color), edge)
    }

    /// Draw a line+marker handle in the legend
    ///
    /// Draws a line segment with a marker symbol at the center.
    fn draw_legend_line_marker_handle(
        &mut self,
        x: f32,
        y: f32,
        length: f32,
        color: Color,
        line_style: &LineStyle,
        line_width: f32,
        marker: &MarkerStyle,
        marker_size: f32,
        marker_edge: Option<(Color, f32)>,
    ) -> Result<()> {
        // Draw line first
        self.draw_legend_line_handle(x, y, length, color, line_style, line_width)?;
        // Draw marker on top at center
        self.draw_legend_scatter_handle(x, y, length, color, marker, marker_size, marker_edge)
    }

    /// Draw a legend handle based on the item type
    fn draw_legend_handle(
        &mut self,
        item: &LegendItem,
        x: f32,
        y: f32,
        spacing: &LegendSpacingPixels,
    ) -> Result<()> {
        let handle_length = spacing.handle_length;
        let handle_height = spacing.handle_height;
        // First draw the base type
        match &item.item_type {
            LegendItemType::Line { style, width } => {
                let scaled_width = self.points_to_pixels(*width);
                self.draw_legend_line_handle(x, y, handle_length, item.color, style, scaled_width)?;
            }
            LegendItemType::Scatter { marker, size, edge } => {
                let scaled_size = self.points_to_pixels(*size);
                self.draw_legend_scatter_handle(
                    x,
                    y,
                    handle_length,
                    item.color,
                    marker,
                    scaled_size,
                    *edge,
                )?;
            }
            LegendItemType::LineMarker {
                line_style,
                line_width,
                marker,
                marker_size,
                marker_edge,
            } => {
                let scaled_line_width = self.points_to_pixels(*line_width);
                let scaled_marker_size = self.points_to_pixels(*marker_size);
                self.draw_legend_line_marker_handle(
                    x,
                    y,
                    handle_length,
                    item.color,
                    line_style,
                    scaled_line_width,
                    marker,
                    scaled_marker_size,
                    *marker_edge,
                )?;
            }
            LegendItemType::Bar { edge } | LegendItemType::Histogram { edge } => {
                let edge = *edge;
                self.draw_legend_bar_handle(x, y, handle_length, handle_height, item.color, edge)?;
            }
            LegendItemType::Area { edge_color } => {
                // Draw filled rectangle with optional edge
                self.draw_legend_bar_handle(x, y, handle_length, handle_height, item.color, None)?;
                if let Some(edge) = edge_color {
                    // Draw edge around the rectangle
                    let rect_y = y - handle_height / 2.0;
                    let scaled_edge_width = self.logical_pixels_to_pixels(1.0);
                    self.draw_rectangle_outline(
                        x,
                        rect_y,
                        handle_length,
                        handle_height,
                        *edge,
                        scaled_edge_width,
                    )?;
                }
            }
            LegendItemType::ErrorBar => {
                // ErrorBar type: Draw vertical error bar with marker (matplotlib-style)
                let center_x = x + handle_length / 2.0;
                let error_height = handle_height * 0.8;
                let half_error = error_height / 2.0;
                let cap_width = handle_height * 0.5;
                let half_cap = cap_width / 2.0;
                let error_line_width = self.logical_pixels_to_pixels(1.5);

                // Vertical error bar line
                self.draw_line(
                    center_x,
                    y - half_error,
                    center_x,
                    y + half_error,
                    item.color,
                    error_line_width,
                    LineStyle::Solid,
                )?;
                // Top cap (horizontal)
                self.draw_line(
                    center_x - half_cap,
                    y - half_error,
                    center_x + half_cap,
                    y - half_error,
                    item.color,
                    error_line_width,
                    LineStyle::Solid,
                )?;
                // Bottom cap (horizontal)
                self.draw_line(
                    center_x - half_cap,
                    y + half_error,
                    center_x + half_cap,
                    y + half_error,
                    item.color,
                    error_line_width,
                    LineStyle::Solid,
                )?;
                // Draw marker in center (handle_height is already in pixels, scale marker proportionally)
                let marker_size = handle_height * 0.4;
                self.draw_marker(center_x, y, marker_size, MarkerStyle::Circle, item.color)?;
            }
        }

        // If the series has attached error bars (not ErrorBar type), overlay error bar indicator
        if item.has_error_bars && !matches!(item.item_type, LegendItemType::ErrorBar) {
            let center_x = x + handle_length / 2.0;
            let error_height = handle_height * 0.7; // Slightly smaller for overlay
            let half_error = error_height / 2.0;
            let cap_width = handle_height * 0.4;
            let half_cap = cap_width / 2.0;
            let overlay_line_width = self.logical_pixels_to_pixels(1.0);

            // Vertical error bar line
            self.draw_line(
                center_x,
                y - half_error,
                center_x,
                y + half_error,
                item.color,
                overlay_line_width,
                LineStyle::Solid,
            )?;
            // Top cap (horizontal)
            self.draw_line(
                center_x - half_cap,
                y - half_error,
                center_x + half_cap,
                y - half_error,
                item.color,
                overlay_line_width,
                LineStyle::Solid,
            )?;
            // Bottom cap (horizontal)
            self.draw_line(
                center_x - half_cap,
                y + half_error,
                center_x + half_cap,
                y + half_error,
                item.color,
                overlay_line_width,
                LineStyle::Solid,
            )?;
        }

        Ok(())
    }

    /// Draw rectangle outline (stroke only, no fill)
    fn draw_rectangle_outline(
        &mut self,
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        color: Color,
        line_width: f32,
    ) -> Result<()> {
        // Draw 4 lines forming a rectangle
        let x2 = x + width;
        let y2 = y + height;
        self.draw_line(x, y, x2, y, color, line_width, LineStyle::Solid)?;
        self.draw_line(x2, y, x2, y2, color, line_width, LineStyle::Solid)?;
        self.draw_line(x2, y2, x, y2, color, line_width, LineStyle::Solid)?;
        self.draw_line(x, y2, x, y, color, line_width, LineStyle::Solid)
    }

    /// Draw rounded rectangle outline (stroke only, no fill)
    fn draw_rounded_rectangle_outline(
        &mut self,
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        corner_radius: f32,
        color: Color,
        line_width: f32,
    ) -> Result<()> {
        // Clamp radius to half of the smaller dimension
        let max_radius = (width.min(height) / 2.0).max(0.0);
        let radius = corner_radius.min(max_radius);

        // If radius is effectively zero, use regular rectangle outline
        if radius < 0.1 {
            return self.draw_rectangle_outline(x, y, width, height, color, line_width);
        }

        // Build rounded rectangle path
        let mut pb = PathBuilder::new();

        pb.move_to(x + radius, y);
        pb.line_to(x + width - radius, y);
        pb.quad_to(x + width, y, x + width, y + radius);
        pb.line_to(x + width, y + height - radius);
        pb.quad_to(x + width, y + height, x + width - radius, y + height);
        pb.line_to(x + radius, y + height);
        pb.quad_to(x, y + height, x, y + height - radius);
        pb.line_to(x, y + radius);
        pb.quad_to(x, y, x + radius, y);
        pb.close();

        let path = pb.finish().ok_or(PlottingError::RenderError(
            "Failed to create rounded rectangle outline path".to_string(),
        ))?;

        let mut paint = Paint::default();
        paint.set_color(color.to_tiny_skia_color());
        paint.anti_alias = true;

        let stroke = Stroke {
            width: line_width,
            line_cap: LineCap::Round,
            line_join: LineJoin::Round,
            ..Stroke::default()
        };

        self.pixmap
            .stroke_path(&path, &paint, &stroke, Transform::identity(), None);

        Ok(())
    }

    /// Draw legend frame with background and optional border
    /// Paint a legend frame: shadow, face and edge, from one [`LegendStyle`].
    ///
    /// `pub(crate)` so the 3D overlay paints its legend box with this exact
    /// code rather than a themed look-alike of it. `style` must already be in
    /// device pixels (see `Legend::scaled_for_render`).
    pub(crate) fn draw_legend_frame(
        &mut self,
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        style: &LegendStyle,
    ) -> Result<()> {
        if !style.visible {
            return Ok(());
        }

        let radius = style.effective_corner_radius();

        // Draw shadow if enabled
        if style.shadow {
            let (shadow_dx, shadow_dy) = style.shadow_offset;
            if radius > 0.0 {
                self.draw_rounded_rectangle(
                    x + shadow_dx,
                    y + shadow_dy,
                    width,
                    height,
                    radius,
                    style.shadow_color,
                    true,
                )?;
            } else {
                // Flat fill: a shadow must never gain an outline of its own.
                self.draw_rectangle(
                    x + shadow_dx,
                    y + shadow_dy,
                    width,
                    height,
                    style.shadow_color,
                    true,
                )?;
            }
        }

        // Draw background with alpha applied. Flat fill in both branches: the
        // frame border is drawn below from `style.edge_color`/`border_width`,
        // which is also what the rounded branch has always done.
        let face_color = style.effective_face_color();
        if radius > 0.0 {
            self.draw_rounded_rectangle(x, y, width, height, radius, face_color, true)?;
        } else {
            self.draw_rectangle(x, y, width, height, face_color, true)?;
        }

        // Draw border if specified
        if let Some(edge_color) = style.edge_color {
            if radius > 0.0 {
                self.draw_rounded_rectangle_outline(
                    x,
                    y,
                    width,
                    height,
                    radius,
                    edge_color,
                    style.border_width,
                )?;
            } else {
                self.draw_rectangle_outline(x, y, width, height, edge_color, style.border_width)?;
            }
        }

        Ok(())
    }

    /// Size and place the legend through the one shared layout.
    ///
    /// `legend` must already be scaled for this renderer. The measurement
    /// callback is this backend's own, which is how a Typst-shaped label and a
    /// cosmic-text one stay honestly different without duplicating the layout.
    fn legend_layout(
        &self,
        items: &[LegendItem],
        legend: &Legend,
        plot_area: (f32, f32, f32, f32),
        placement: LegendPlacement<'_>,
    ) -> Result<LegendLayout> {
        layout_legend(items, legend, plot_area, placement, |text| {
            Ok(self.measure_label_text(text, legend.font_size)?.0)
        })
    }

    /// The room this legend needs, measured exactly as it will be drawn.
    ///
    /// The figure-level margin reservation calls this; it shares
    /// [`layout_legend`] with [`SkiaRenderer::draw_legend_full`], so an outside
    /// legend can no longer be reserved at one width and drawn at another.
    ///
    /// `legend` is in points and is scaled for this renderer internally.
    pub(crate) fn measure_legend(
        &self,
        items: &[LegendItem],
        legend: &Legend,
    ) -> Result<(f32, f32)> {
        let legend = legend.scaled_for_render(self.render_scale);
        measure_legend_size(items, &legend, |text| {
            Ok(self.measure_label_text(text, legend.font_size)?.0)
        })
    }

    /// Draw legend with full LegendItem support
    ///
    /// This is the new legend drawing method that properly renders different
    /// series types with their correct visual handles.
    ///
    /// `occupancy` is only consulted for
    /// [`LegendPosition::Best`](crate::core::LegendPosition::Best); `None`
    /// means "no idea where the data is", which degrades to `UpperRight`.
    pub fn draw_legend_full(
        &mut self,
        items: &[LegendItem],
        legend: &Legend,
        plot_area: Rect,
        occupancy: Option<&LegendOccupancy>,
    ) -> Result<()> {
        self.draw_legend_full_resolved(items, legend, plot_area, occupancy, None)
    }

    pub(crate) fn draw_legend_full_resolved(
        &mut self,
        items: &[LegendItem],
        legend: &Legend,
        plot_area: Rect,
        occupancy: Option<&LegendOccupancy>,
        resolved_rect: Option<(f32, f32, f32, f32)>,
    ) -> Result<()> {
        if items.is_empty() || !legend.enabled {
            return Ok(());
        }

        let legend = legend.scaled_for_render(self.render_scale);
        let bounds = (
            plot_area.left(),
            plot_area.top(),
            plot_area.right(),
            plot_area.bottom(),
        );
        let placement = LegendPlacement {
            reserved: resolved_rect,
            occupancy,
        };
        let layout = self.legend_layout(items, &legend, bounds, placement)?;

        self.draw_legend_frame(
            layout.x,
            layout.y,
            layout.width,
            layout.height,
            &legend.style,
        )?;

        if let (Some(title_layout), Some(title)) = (layout.title, legend.title.as_deref()) {
            self.draw_text_centered(
                title,
                title_layout.center_x,
                title_layout.top_y,
                layout.font_size,
                legend.text_color,
            )?;
        }

        for entry in &layout.entries {
            let item = &items[entry.item_index];
            self.draw_legend_handle(item, entry.handle_x, entry.handle_center_y, &layout.spacing)?;
            self.draw_text(
                &item.label,
                entry.label_x,
                entry.label_top_y,
                layout.font_size,
                legend.text_color,
            )?;
        }

        Ok(())
    }

    /// Draw a colorbar for heatmaps
    ///
    /// Draws a vertical gradient bar showing the color mapping from vmin to vmax,
    /// with tick marks and optional label.
    ///
    /// # Arguments
    ///
    /// * `colormap` - The color map to sample from
    /// * `vmin` - Minimum value in the data range
    /// * `vmax` - Maximum value in the data range
    /// * `x` - X position of colorbar (left edge)
    /// * `y` - Y position of colorbar (top edge)
    /// * `width` - Width of the colorbar
    /// * `height` - Height of the colorbar
    /// * `value_scale` - Scale used to normalize values along the colorbar
    /// * `label` - Optional label to display (rotated 90°)
    /// * `foreground_color` - Color for ticks, text, and border
    /// * `tick_font_size` - Font size for tick labels (in points)
    /// * `label_font_size` - Font size for colorbar label (in points, optional)
    /// * `show_log_subticks` - Whether to draw unlabeled logarithmic subticks
    pub fn draw_colorbar(
        &mut self,
        colormap: &crate::render::ColorMap,
        vmin: f64,
        vmax: f64,
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        value_scale: &crate::axes::AxisScale,
        label: Option<&str>,
        foreground_color: Color,
        tick_font_size: f32,
        label_font_size: Option<f32>,
        show_log_subticks: bool,
    ) -> Result<()> {
        crate::render::colorbar::draw_colorbar(
            self,
            &crate::render::colorbar::ColorbarSpec {
                colormap,
                vmin,
                vmax,
                x,
                y,
                width,
                height,
                value_scale,
                label,
                foreground_color,
                tick_font_size,
                label_font_size,
                show_log_subticks,
            },
        )
    }

    /// Consume the renderer and convert to an `Image`.
    ///
    /// Tiny-skia's native premultiplied buffer is normalized to [`Image`]'s
    /// canonical straight-alpha representation.
    pub fn into_image(self) -> Image {
        Image::from_premultiplied_rgba(self.width, self.height, self.pixmap.data().to_vec())
    }

    /// Consume the renderer and convert to an `Image` with straight-alpha
    /// (demultiplied) RGBA pixels.
    ///
    /// Use this when the buffer will be composed by straight-alpha blenders
    /// (e.g. the interactive overlay compositor) rather than tiny-skia.
    pub fn into_image_demultiplied(self) -> Image {
        Image::from_straight_rgba(self.width, self.height, self.pixmap.take_demultiplied())
    }

    /// Save the current pixmap as a PNG with straight-alpha RGBA encoding.
    pub fn save_png<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        crate::export::write_bytes_atomic(path, &self.encode_png_bytes()?)
    }

    /// Encode the current pixmap as PNG bytes with straight-alpha RGBA encoding.
    pub fn encode_png_bytes(&self) -> Result<Vec<u8>> {
        let image = Image::from_straight_rgba(
            self.width,
            self.height,
            self.pixmap.clone().take_demultiplied(),
        );
        crate::export::encode_rgba_png(&image)
    }

    /// Export as SVG (simplified - tiny-skia doesn't directly support SVG export)
    pub fn export_svg<P: AsRef<Path>>(&self, path: P, width: u32, height: u32) -> Result<()> {
        // For now, create a basic SVG placeholder
        // In a real implementation, we'd need to track draw commands and convert to SVG
        let svg_content = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<svg width="{}" height="{}" xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%" fill="{}"/>
  <text x="50%" y="50%" text-anchor="middle" font-family="Arial" font-size="16">
    Ruviz Plot ({} x {})
  </text>
</svg>"#,
            width, height, self.theme.background, width, height
        );

        crate::export::write_bytes_atomic(path, svg_content.as_bytes())
    }

    /// Get the width of the renderer
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Get the height of the renderer  
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Draw a subplot image at the specified position.
    ///
    /// Alias for [`Self::draw_image_layer`]. Prefer `draw_image_layer`, which
    /// borrows instead of consuming.
    pub fn draw_subplot(
        &mut self,
        subplot_image: crate::core::plot::Image,
        x: u32,
        y: u32,
    ) -> Result<()> {
        self.draw_image_layer(&subplot_image, x, y)
    }

    /// Compose an RGBA image onto the canvas.
    ///
    /// This is the only way an [`Image`] is put on
    /// the canvas — [`Self::draw_subplot`] is a thin alias — so the 2D subplot
    /// compositor and the 3D overlay compositor cannot drift apart.
    ///
    /// It used to go through `encode_png` + `decode_png`, which cost a full
    /// deflate *and* inflate of the whole canvas for every composited frame
    /// (~11 MB per 1920x1440 3D orbit frame) purely to change alpha
    /// representation. The canonical straight-alpha input is premultiplied
    /// directly here.
    pub fn draw_image_layer(
        &mut self,
        image: &crate::core::plot::Image,
        x: u32,
        y: u32,
    ) -> Result<()> {
        let expected = (image.width as usize)
            .saturating_mul(image.height as usize)
            .saturating_mul(4);
        if image.pixels.len() != expected {
            return Err(PlottingError::RenderError(
                "image layer pixel buffer does not match its dimensions".to_string(),
            ));
        }

        let premultiplied = image.pixels_in_alpha_mode(crate::core::plot::AlphaMode::Premultiplied);

        let size = tiny_skia::IntSize::from_wh(image.width, image.height)
            .ok_or(PlottingError::OutOfMemory)?;
        let layer =
            Pixmap::from_vec(premultiplied.into_owned(), size).ok_or(PlottingError::OutOfMemory)?;
        self.pixmap.draw_pixmap(
            x as i32,
            y as i32,
            layer.as_ref(),
            &tiny_skia::PixmapPaint::default(),
            tiny_skia::Transform::identity(),
            None,
        );

        Ok(())
    }
}

/// Gutter kept between two neighbouring x tick labels, in ems of their size.
const X_TICK_LABEL_GAP_EM: f32 = 0.35;

/// How the x tick label row is oriented.
///
/// Ten region names under one axis run into each other at any font size a
/// figure would actually use, so the row has to be able to turn — and it turns
/// as a *row*: every label horizontal or every label rotated, never the mix a
/// per-label rule would produce.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum XTickRotation {
    /// Horizontal while the labels fit, a quarter turn when they stop fitting,
    /// and every k-th label when even a rotated row does not fit the margin.
    #[default]
    Auto,
    /// Always horizontal; colliding labels are thinned to every k-th.
    Horizontal,
    /// Always a quarter turn counter-clockwise.
    Vertical,
}

/// The horizontal range one x tick label row's ink may occupy, in pixels.
///
/// The first and last labels of a categorical axis are centred on slots that
/// sit close to the plot area's edges, so a label wider than the outer margin
/// runs off the canvas — a 35-character category name under the first bar of a
/// 400 px figure is not an edge case. A label that would fall outside is slid
/// back inside instead of being cut off.
///
/// The same range is applied when the row is *measured*, which is the point of
/// having a type for it: [`label_left`](Self::label_left) is the one formula
/// `clearing_stride` and `draw_x_tick_label_row` both ask, so sliding an
/// end label inwards can never create the overlap the stride was chosen to
/// avoid.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct XTickRowBounds {
    /// Leftmost pixel the row's ink may touch.
    pub left: f32,
    /// One past the rightmost pixel the row's ink may touch.
    pub right: f32,
}

impl XTickRowBounds {
    /// No clamping at all — what a row measured against no particular canvas
    /// gets, and what [`XTickLabelPlan::default`] carries.
    pub const UNBOUNDED: Self = Self {
        left: f32::NEG_INFINITY,
        right: f32::INFINITY,
    };

    /// The full width of a `width` pixel canvas.
    pub fn canvas(width: f32) -> Self {
        Self {
            left: 0.0,
            right: width,
        }
    }

    /// The same range pulled `inset` pixels in from both edges.
    ///
    /// A label flush against the figure edge reads as clipped even when every
    /// glyph is present, so the row keeps the same gutter from the canvas that
    /// it keeps from its neighbours. An unbounded range stays unbounded.
    pub fn inset(&self, inset: f32) -> Self {
        if self.right - self.left <= inset * 2.0 {
            return *self;
        }
        Self {
            left: self.left + inset,
            right: self.right - inset,
        }
    }

    /// Where a label `extent` pixels wide and centred on `center` starts.
    ///
    /// Centred when it fits, slid inwards when it does not, and pinned to the
    /// left edge when it is wider than the whole range — a label too wide for
    /// the canvas has to lose one end, and losing the tail is the readable
    /// choice.
    pub fn label_left(&self, center: f32, extent: f32) -> f32 {
        (center - extent / 2.0)
            .min(self.right - extent)
            .max(self.left)
    }
}

impl Default for XTickRowBounds {
    fn default() -> Self {
        Self::UNBOUNDED
    }
}

/// What one x tick label row measures, before it is decided how to draw it.
///
/// Produced by [`SkiaRenderer::measure_x_tick_row`]; turned into an
/// [`XTickLabelPlan`] by [`XTickRowMetrics::plan`].
#[derive(Clone, Debug, PartialEq)]
pub struct XTickRowMetrics {
    /// Vertical pixels a horizontal row occupies.
    pub horizontal_extent: f32,
    /// The widest label, in pixels — and so the vertical pixels a rotated row
    /// occupies, since a quarter turn trades a label's width for its height.
    pub max_label_width: f32,
    /// Smallest stride at which a horizontal row stops overlapping.
    pub horizontal_stride: usize,
    /// Smallest stride at which a rotated row stops overlapping.
    pub rotated_stride: usize,
    /// The range the strides above were measured against, carried into the
    /// plan so the row that was measured is the row that is drawn.
    pub bounds: XTickRowBounds,
}

impl XTickRowMetrics {
    /// Whether the caller has to find out if a rotated row fits.
    ///
    /// Answering that costs a trial layout, so it is only worth asking when
    /// rotation is on the table at all.
    pub fn wants_rotation(&self, rotation: XTickRotation) -> bool {
        match rotation {
            XTickRotation::Horizontal => false,
            XTickRotation::Vertical => true,
            XTickRotation::Auto => self.horizontal_stride > 1,
        }
    }

    /// The plan this row is drawn with.
    ///
    /// `rotated_fits` answers "does a row [`max_label_width`] pixels tall fit
    /// the bottom margin the layout grants?" — the caller asks the layout,
    /// because only the layout knows what the margin config allows. An explicit
    /// [`XTickRotation::Vertical`] is honoured either way: a knob that silently
    /// does nothing is worse than one that costs a little room.
    ///
    /// [`max_label_width`]: Self::max_label_width
    pub fn plan(&self, rotation: XTickRotation, rotated_fits: bool) -> XTickLabelPlan {
        let rotated = match rotation {
            XTickRotation::Horizontal => false,
            XTickRotation::Vertical => true,
            XTickRotation::Auto => self.horizontal_stride > 1 && rotated_fits,
        };
        if rotated {
            XTickLabelPlan {
                rotated: true,
                stride: self.rotated_stride,
                extent: self.max_label_width,
                bounds: self.bounds,
            }
        } else {
            XTickLabelPlan {
                rotated: false,
                stride: self.horizontal_stride,
                extent: self.horizontal_extent,
                bounds: self.bounds,
            }
        }
    }
}

/// The resolved orientation and thinning of one x tick label row.
///
/// [`extent`](Self::extent) is the vertical room the row needs, and it is what
/// the bottom margin has to be reserved from *before* the plot area is
/// computed. Reserve it afterwards and the labels are clipped instead of
/// overlapping, which is not an improvement.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct XTickLabelPlan {
    /// Whether the row is drawn a quarter turn counter-clockwise.
    pub rotated: bool,
    /// Only every `stride`-th label is drawn; `1` draws them all.
    pub stride: usize,
    /// Vertical pixels the row occupies.
    pub extent: f32,
    /// The horizontal range the row's ink is kept inside; see
    /// [`XTickRowBounds`].
    pub bounds: XTickRowBounds,
}

impl Default for XTickLabelPlan {
    /// Every label, horizontal, reserving nothing, clamped to nothing — what a
    /// row that was never measured is entitled to assume.
    fn default() -> Self {
        Self {
            rotated: false,
            stride: 1,
            extent: 0.0,
            bounds: XTickRowBounds::UNBOUNDED,
        }
    }
}

/// Smallest stride at which the drawn labels stop overlapping.
///
/// `extents` is each label's size along the axis: its width for a horizontal
/// row, its height for a rotated one. A label with no extent draws nothing and
/// so collides with nothing.
///
/// `bounds` is where the labels will actually be drawn, not where they would
/// like to be: an end label slid off the canvas edge is measured where it lands.
fn clearing_stride(centers: &[f32], extents: &[f32], gap: f32, bounds: XTickRowBounds) -> usize {
    let count = centers.len().min(extents.len());
    if count <= 1 {
        return 1;
    }
    (1..=count)
        .find(|&stride| stride_clears(centers, extents, gap, stride, bounds))
        .unwrap_or(count)
}

fn stride_clears(
    centers: &[f32],
    extents: &[f32],
    gap: f32,
    stride: usize,
    bounds: XTickRowBounds,
) -> bool {
    let mut previous_right: Option<f32> = None;
    for (&center, &extent) in centers.iter().zip(extents.iter()).step_by(stride) {
        if extent <= 0.0 || !center.is_finite() {
            continue;
        }
        let left = bounds.label_left(center, extent);
        let right = left + extent;
        if let Some(previous) = previous_right {
            if left < previous + gap {
                return false;
            }
            previous_right = Some(previous.max(right));
        } else {
            previous_right = Some(right);
        }
    }
    true
}

/// Draw one x tick label row onto any backend, following `plan`.
///
/// The raster and SVG backends share this body, so a figure cannot be labelled
/// one way as a PNG and another way as an SVG — the SVG twin used not to
/// measure its category labels at all. `top_y` is the top of the row in both
/// orientations.
///
/// The canvas is [`ColorbarCanvas`](crate::render::colorbar::ColorbarCanvas),
/// the crate's one backend-neutral text canvas, named for its first client.
pub(crate) fn draw_x_tick_label_row<C>(
    canvas: &mut C,
    labels: &[String],
    centers: &[f32],
    top_y: f32,
    size: f32,
    color: Color,
    plan: XTickLabelPlan,
) -> Result<()>
where
    C: crate::render::colorbar::ColorbarCanvas + ?Sized,
{
    let stride = plan.stride.max(1);
    // A thinned row writes only every stride-th name, and an unnamed slot holds
    // its place on the axis without writing under it.
    for (label, &center) in labels.iter().zip(centers.iter()).step_by(stride) {
        if label.is_empty() {
            continue;
        }
        let snippet = canvas.colorbar_label_snippet(label);
        let (width, height) = canvas.colorbar_measure_text(&snippet, size)?;
        if plan.rotated {
            // A quarter turn trades the label's width for its height, so the
            // row hangs from `top_y` and takes up only `height` sideways. The
            // rotated primitive centres its block on the x it is given.
            let left = plan.bounds.label_left(center, height);
            canvas.colorbar_text_rotated(
                &snippet,
                left + height / 2.0,
                top_y + width / 2.0,
                size,
                color,
            )?;
        } else {
            canvas.colorbar_text(
                &snippet,
                plan.bounds.label_left(center, width),
                top_y,
                size,
                color,
            )?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests;

/// The raster backend's colorbar primitives.
///
/// The geometry lives in [`crate::render::colorbar::draw_colorbar`]; this only
/// says how each primitive is put on a pixmap.
impl crate::render::colorbar::ColorbarCanvas for SkiaRenderer {
    fn colorbar_points_to_pixels(&self, points: f32) -> f32 {
        self.points_to_pixels(points)
    }

    fn colorbar_logical_pixels_to_pixels(&self, pixels: f32) -> f32 {
        self.logical_pixels_to_pixels(pixels)
    }

    fn colorbar_label_snippet<'a>(&self, text: &'a str) -> std::borrow::Cow<'a, str> {
        self.generated_label(text)
    }

    fn colorbar_measure_text(&self, text: &str, size: f32) -> Result<(f32, f32)> {
        self.measure_text(text, size)
    }

    fn colorbar_measure_ink_center_from_top(&self, text: &str, size: f32) -> Result<f32> {
        self.measure_text_ink_center_from_top(text, size)
    }

    fn colorbar_fill_rect(
        &mut self,
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        color: Color,
    ) -> Result<()> {
        self.draw_solid_rectangle(x, y, width, height, color)
    }

    fn colorbar_stroke_rect(
        &mut self,
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        color: Color,
        stroke_width: f32,
    ) -> Result<()> {
        self.draw_rectangle_outline(x, y, width, height, color, stroke_width)
    }

    fn colorbar_line(
        &mut self,
        x1: f32,
        y1: f32,
        x2: f32,
        y2: f32,
        color: Color,
        stroke_width: f32,
    ) -> Result<()> {
        self.draw_line(x1, y1, x2, y2, color, stroke_width, LineStyle::Solid)
    }

    fn colorbar_text(&mut self, text: &str, x: f32, y: f32, size: f32, color: Color) -> Result<()> {
        self.draw_text(text, x, y, size, color)
    }

    fn colorbar_text_rotated(
        &mut self,
        text: &str,
        x: f32,
        y: f32,
        size: f32,
        color: Color,
    ) -> Result<()> {
        self.draw_text_rotated(text, x, y, size, color)
    }
}

#[cfg(test)]
mod legend_patch_tests {
    use super::*;

    fn pixel_rgba(image: &Image, x: u32, y: u32) -> [u8; 4] {
        let idx = ((y * image.width + x) * 4) as usize;
        [
            image.pixels[idx],
            image.pixels[idx + 1],
            image.pixels[idx + 2],
            image.pixels[idx + 3],
        ]
    }

    /// Any pixel in the box that is clearly darker than the white panel/fill.
    fn has_dark_pixel(image: &Image, x0: u32, y0: u32, x1: u32, y1: u32) -> bool {
        (y0..y1).any(|y| {
            (x0..x1).any(|x| {
                let pixel = pixel_rgba(image, x, y);
                pixel[3] > 0 && pixel[0] < 200 && pixel[1] < 200 && pixel[2] < 200
            })
        })
    }

    fn handle_spacing(length: f32, height: f32) -> LegendSpacingPixels {
        LegendSpacingPixels {
            handle_length: length,
            handle_height: height,
            handle_text_pad: 10.0,
            label_spacing: 7.0,
            border_pad: 6.0,
            border_axes_pad: 10.0,
            column_spacing: 20.0,
        }
    }

    #[test]
    fn legacy_swatch_edge_contrasts_with_the_fill() {
        assert_eq!(
            legacy_legend_swatch_edge(Color::WHITE),
            LEGACY_LEGEND_SWATCH_EDGE_DARK
        );
        assert_eq!(
            legacy_legend_swatch_edge(Color::from_gray(250)),
            LEGACY_LEGEND_SWATCH_EDGE_DARK
        );
        assert_eq!(
            legacy_legend_swatch_edge(Color::BLACK),
            LEGACY_LEGEND_SWATCH_EDGE_LIGHT
        );
        // A transparent fill renders as the near-white panel, so it needs the
        // dark neutral even though its own channels are dark.
        assert_eq!(
            legacy_legend_swatch_edge(Color::from_rgba(0, 0, 0, 0)),
            LEGACY_LEGEND_SWATCH_EDGE_DARK
        );
    }

    #[test]
    fn legacy_legend_white_swatch_keeps_a_visible_contour() {
        let mut renderer = SkiaRenderer::new(400, 200, Theme::default()).unwrap();
        let plot_area = Rect::from_xywh(0.0, 0.0, 400.0, 200.0).unwrap();

        renderer
            .draw_legend(&[("white series".to_string(), Color::WHITE)], plot_area)
            .expect("legacy legend should render");

        let image = renderer.into_image();
        // Swatch occupies (250, 22) .. (262, 34); the stroke straddles the edge.
        // The panel frame (240/380, 15/45) and the label (x >= 270) stay outside.
        assert!(
            has_dark_pixel(&image, 246, 18, 267, 38),
            "a white swatch on the near-white panel must still have a contour"
        );
        // ... while the fill stays exactly the series colour.
        let interior = pixel_rgba(&image, 256, 28);
        assert_eq!(
            [interior[0], interior[1], interior[2]],
            [255, 255, 255],
            "the swatch fill must not be tinted"
        );
    }

    #[test]
    fn bar_and_histogram_handles_stroke_their_edge() {
        for item in [
            LegendItem::bar_with_edge("bars", Color::WHITE, Some((Color::BLACK, 1.5))),
            LegendItem::histogram_with_edge("hist", Color::WHITE, Some((Color::BLACK, 1.5))),
        ] {
            let mut renderer = SkiaRenderer::new(60, 40, Theme::default()).unwrap();
            renderer.pixmap.fill(Color::WHITE.to_tiny_skia_color());
            renderer
                .draw_legend_handle(&item, 10.0, 20.0, &handle_spacing(30.0, 14.0))
                .expect("patch handle should render");

            let image = renderer.into_image();
            assert!(
                has_dark_pixel(&image, 0, 0, 60, 40),
                "{:?} handle must stroke its edge so the key matches the plot",
                item.item_type
            );
            let interior = pixel_rgba(&image, 25, 20);
            assert_eq!(
                [interior[0], interior[1], interior[2]],
                [255, 255, 255],
                "the handle fill must stay exactly the series colour"
            );
        }
    }

    #[test]
    fn bar_handle_without_edge_stays_flat() {
        let mut renderer = SkiaRenderer::new(60, 40, Theme::default()).unwrap();
        renderer.pixmap.fill(Color::WHITE.to_tiny_skia_color());
        renderer
            .draw_legend_handle(
                &LegendItem::bar("bars", Color::WHITE),
                10.0,
                20.0,
                &handle_spacing(30.0, 14.0),
            )
            .expect("patch handle should render");

        let image = renderer.into_image();
        assert!(
            !has_dark_pixel(&image, 0, 0, 60, 40),
            "a patch with no configured edge must not grow an implicit one"
        );
    }

    /// The bug this layout exists to kill.
    ///
    /// The frame used to be sized as `label.len() * font_size * 0.6` — a
    /// **byte** count against a guessed advance. `"WWWWWWWWWW"` is ten bytes of
    /// glyphs each far wider than 0.6 em, so the label ran out of the frame;
    /// `"日本語"` is three glyphs in nine bytes, so the frame was drawn about
    /// three times too wide. Now the frame comes from the same measurement the
    /// renderer draws with, so the label has to fit inside it.
    #[test]
    fn legend_frame_fits_the_measured_label_not_its_byte_count() {
        let renderer = SkiaRenderer::new(400, 300, Theme::default()).unwrap();
        let legend = Legend {
            enabled: true,
            position: crate::core::LegendPosition::UpperLeft,
            ..Default::default()
        };
        let scaled = legend.scaled_for_render(renderer.render_scale());

        for label in ["WWWWWWWWWW", "日本語ラベル", "Ünïcödé", "iiii"] {
            let items = vec![LegendItem::line(label, Color::BLUE, LineStyle::Solid, 1.5)];
            let layout = renderer
                .legend_layout(
                    &items,
                    &scaled,
                    (0.0, 0.0, 400.0, 300.0),
                    LegendPlacement::default(),
                )
                .expect("legend layout");
            let text_width = renderer
                .measure_label_text(label, scaled.font_size)
                .expect("measure")
                .0;
            let entry = layout.entries[0];
            let inner_right = layout.x + layout.width - layout.spacing.border_pad;

            assert!(
                entry.label_x + text_width <= inner_right + 0.01,
                "{label:?} runs past the frame: label ends at {}, frame ends at {inner_right}",
                entry.label_x + text_width
            );
            // The reservation and the drawing are the same call, so the size the
            // figure layout reserves is the size the frame is drawn at.
            assert_eq!(
                layout.size(),
                renderer.measure_legend(&items, &legend).expect("reserve")
            );
        }
    }
}

/// The x tick label row: what it measures, what it decides, and what it draws.
#[cfg(test)]
mod x_tick_label_row_tests {
    use super::*;

    const REGIONS: [&str; 10] = [
        "North America",
        "South America",
        "Western Europe",
        "Eastern Europe",
        "Middle East",
        "North Africa",
        "Sub-Saharan Africa",
        "Central Asia",
        "South East Asia",
        "Australasia",
    ];

    fn renderer() -> SkiaRenderer {
        SkiaRenderer::new(600, 400, Theme::default()).expect("renderer")
    }

    fn labels(names: &[&str]) -> Vec<String> {
        names.iter().map(|name| (*name).to_string()).collect()
    }

    /// Evenly spaced slot centres across `[left, right]`, the way a categorical
    /// axis lays its slots out.
    fn centers(count: usize, left: f32, right: f32) -> Vec<f32> {
        let span = right - left;
        (0..count)
            .map(|index| left + span * (index as f32 + 0.5) / count as f32)
            .collect()
    }

    fn dark_pixels(image: &crate::core::plot::Image) -> Vec<(u32, u32)> {
        let mut found = Vec::new();
        for y in 0..image.height {
            for x in 0..image.width {
                let index = ((y * image.width + x) * 4) as usize;
                if image.pixels[index] < 128 {
                    found.push((x, y));
                }
            }
        }
        found
    }

    /// Ten region names in one 500 px axis cannot be drawn horizontally without
    /// overlapping — the figure this row exists for. Turned a quarter turn they
    /// clear each other completely, because a label's height is a fraction of
    /// its width.
    #[test]
    fn ten_region_names_collide_horizontally_and_clear_when_rotated() {
        let renderer = renderer();
        let names = labels(&REGIONS);
        let metrics = renderer
            .measure_x_tick_row(
                &names,
                &centers(REGIONS.len(), 60.0, 560.0),
                12.0,
                XTickRowBounds::UNBOUNDED,
            )
            .expect("measure");

        assert!(
            metrics.horizontal_stride > 1,
            "ten region names should not fit horizontally, got stride {}",
            metrics.horizontal_stride
        );
        assert_eq!(metrics.rotated_stride, 1, "rotated names clear each other");
        assert!(
            metrics.max_label_width > metrics.horizontal_extent,
            "a rotated row is taller than a horizontal one for these labels"
        );
    }

    /// Short names in the same axis are left alone: no rotation, no thinning,
    /// and the row reserves exactly the height it draws at.
    #[test]
    fn short_names_stay_horizontal_and_complete() {
        let renderer = renderer();
        let names = labels(&["A", "B", "C", "D"]);
        let metrics = renderer
            .measure_x_tick_row(
                &names,
                &centers(4, 60.0, 560.0),
                12.0,
                XTickRowBounds::UNBOUNDED,
            )
            .expect("measure");

        assert_eq!(metrics.horizontal_stride, 1);
        let plan = metrics.plan(XTickRotation::Auto, true);
        assert!(!plan.rotated);
        assert_eq!(plan.stride, 1);
        assert_eq!(plan.extent, metrics.horizontal_extent);
    }

    /// An empty slot label writes nothing, so it cannot collide with anything —
    /// otherwise a nameless slot would thin its named neighbours out.
    #[test]
    fn unnamed_slots_do_not_collide() {
        let renderer = renderer();
        let mut names = labels(&[""; 10]);
        names[0] = "Western Europe".to_string();
        let metrics = renderer
            .measure_x_tick_row(
                &names,
                &centers(10, 60.0, 560.0),
                12.0,
                XTickRowBounds::UNBOUNDED,
            )
            .expect("measure");

        assert_eq!(metrics.horizontal_stride, 1);
    }

    /// The policy in one place: `Auto` rotates only when the margin can hold a
    /// rotated row and falls back to every k-th label when it cannot, while the
    /// explicit settings are honoured either way.
    #[test]
    fn auto_rotates_only_when_the_rotated_row_fits() {
        let renderer = renderer();
        let names = labels(&REGIONS);
        let metrics = renderer
            .measure_x_tick_row(
                &names,
                &centers(REGIONS.len(), 60.0, 560.0),
                12.0,
                XTickRowBounds::UNBOUNDED,
            )
            .expect("measure");

        let rotated = metrics.plan(XTickRotation::Auto, true);
        assert!(rotated.rotated);
        assert_eq!(rotated.stride, metrics.rotated_stride);
        assert_eq!(rotated.extent, metrics.max_label_width);

        let thinned = metrics.plan(XTickRotation::Auto, false);
        assert!(!thinned.rotated);
        assert_eq!(thinned.stride, metrics.horizontal_stride);
        assert!(thinned.stride > 1);
        assert_eq!(thinned.extent, metrics.horizontal_extent);

        assert!(!metrics.plan(XTickRotation::Horizontal, true).rotated);
        assert!(metrics.plan(XTickRotation::Vertical, false).rotated);
        assert!(!metrics.wants_rotation(XTickRotation::Horizontal));
        assert!(metrics.wants_rotation(XTickRotation::Vertical));
    }

    /// The plan is what gets drawn: a stride of two draws half the names, and a
    /// rotated row hangs down from the same baseline instead of spreading
    /// sideways.
    #[test]
    fn the_plan_is_what_the_row_draws() {
        let names = labels(&REGIONS);
        let centers = centers(REGIONS.len(), 60.0, 560.0);

        let ink = |plan: XTickLabelPlan| {
            let mut renderer = renderer();
            draw_x_tick_label_row(
                &mut renderer,
                &names,
                &centers,
                100.0,
                12.0,
                Color::BLACK,
                plan,
            )
            .expect("draw");
            dark_pixels(&renderer.into_image())
        };

        let complete = ink(XTickLabelPlan::default());
        let thinned = ink(XTickLabelPlan {
            stride: 2,
            ..XTickLabelPlan::default()
        });
        assert!(
            thinned.len() * 4 < complete.len() * 3,
            "every second label should be dropped: {} vs {}",
            thinned.len(),
            complete.len()
        );

        let rotated = ink(XTickLabelPlan {
            rotated: true,
            stride: 1,
            ..XTickLabelPlan::default()
        });
        let lowest = |pixels: &[(u32, u32)]| pixels.iter().map(|&(_, y)| y).max().unwrap_or(0);
        assert!(
            lowest(&rotated) > lowest(&complete) + 20,
            "a rotated row hangs below a horizontal one: {} vs {}",
            lowest(&rotated),
            lowest(&complete)
        );
        assert!(
            rotated.iter().all(|&(_, y)| y >= 99),
            "a rotated row hangs from the baseline, it does not rise above it"
        );
    }

    /// The end labels of a categorical axis are centred on slots that sit near
    /// the plot area's edges, so a name wider than the outer margin runs off the
    /// canvas. It is slid back inside instead of being cut in half.
    #[test]
    fn end_labels_are_slid_inside_the_canvas_rather_than_cut() {
        let names = labels(&["A very long first category name indeed", "B", "C"]);
        // A narrow figure's slots: the first centre sits well inside the widest
        // name, which is the whole point.
        let centers = centers(3, 20.0, 320.0);
        let renderer = renderer();
        let bounds = XTickRowBounds::canvas(renderer.width() as f32);
        let metrics = renderer
            .measure_x_tick_row(&names, &centers, 12.0, bounds)
            .expect("measure");
        let plan = metrics.plan(XTickRotation::Horizontal, false);

        let (width, _) = renderer
            .measure_text(&names[0], 12.0)
            .expect("measure first label");
        assert!(
            centers[0] - width / 2.0 < 0.0,
            "the figure under test must have an end label wider than its margin"
        );
        assert_eq!(
            plan.bounds.label_left(centers[0], width),
            plan.bounds.left,
            "an over-hanging first label starts at the row's left gutter, not \
             outside the canvas"
        );
        assert!(
            plan.bounds.left > 0.0 && plan.bounds.right < renderer.width() as f32,
            "the row keeps a gutter from the figure edge"
        );

        let mut renderer = renderer;
        draw_x_tick_label_row(
            &mut renderer,
            &names,
            &centers,
            100.0,
            12.0,
            Color::BLACK,
            plan,
        )
        .expect("draw");
        let image = renderer.into_image();
        let ink = dark_pixels(&image);
        assert!(!ink.is_empty(), "the row should draw something");
        assert!(
            ink.iter().all(|&(x, _)| x < image.width),
            "no label ink may fall outside the canvas"
        );
        assert!(
            ink.iter().any(|&(x, _)| x < 20),
            "the slid label should still sit hard against the left edge"
        );
    }

    /// Sliding an end label inwards moves it towards its neighbour, so the
    /// stride has to be measured where the labels land — otherwise the row that
    /// was measured as clearing is drawn overlapping.
    #[test]
    fn the_stride_is_measured_where_the_labels_land() {
        let renderer = renderer();
        // Two wide names whose first is pushed right by the canvas edge: unclamped
        // they clear each other, clamped they do not.
        let names = labels(&["Sub-Saharan Africa", "Sub-Saharan Africa"]);
        let (width, _) = renderer.measure_text(&names[0], 12.0).expect("measure");
        let gap = 12.0 * X_TICK_LABEL_GAP_EM;
        // Place the first label so that half of it hangs off the canvas, and the
        // second exactly one clearing width to its right.
        let first = width / 4.0;
        let centers = vec![first, first + width + gap + 1.0];

        let unclamped = renderer
            .measure_x_tick_row(&names, &centers, 12.0, XTickRowBounds::UNBOUNDED)
            .expect("measure");
        assert_eq!(
            unclamped.horizontal_stride, 1,
            "where they are asked to be drawn, the two names clear each other"
        );

        let clamped = renderer
            .measure_x_tick_row(&names, &centers, 12.0, XTickRowBounds::canvas(600.0))
            .expect("measure");
        assert_eq!(
            clamped.horizontal_stride, 2,
            "slid inside the canvas the first name runs into the second, so the \
             row has to thin"
        );
    }
}