siplot 0.1.0

silx-style scientific plotting for egui, rendered with wgpu
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
//! Interaction math: pure functions mapping pointer input to new data limits.
//!
//! The widget reads egui input, converts it through the *current* on-screen
//! [`Transform`](crate::core::transform::Transform), and applies one of these to
//! produce the next limits. Because everything downstream (the wgpu ortho matrix
//! and the egui chrome) derives from those limits, the image, curve, and axes
//! move together with no extra bookkeeping (`doc/design.md` §4·§8·§11.6).
//!
//! Pointer-mode mapping lives in the widget; this module is just the geometry
//! for pan/zoom/pick math, kept pure so it is unit-testable.

use egui::{Pos2, Rect, Vec2};

use crate::core::marker::{Marker, MarkerConstraint, MarkerKind};
use crate::core::roi::{ManagedRoi, Roi, RoiEdge};
use crate::core::transform::{Scale, Transform};

/// Data limits `(x_min, x_max, y_min, y_max)`.
pub type Limits = (f64, f64, f64, f64);

/// Float32 safe lower bound, mirroring silx `_utils/panzoom.py`
/// `FLOAT32_SAFE_MIN`. Linear-axis limits are kept inside `[FLOAT32_SAFE_MIN,
/// FLOAT32_SAFE_MAX]` so that span subtractions (`max - min`) do not overflow
/// float32 downstream in the shaders.
pub const FLOAT32_SAFE_MIN: f64 = -1e37;
/// Float32 safe upper bound, mirroring silx `FLOAT32_SAFE_MAX`.
pub const FLOAT32_SAFE_MAX: f64 = 1e37;
/// Smallest positive normal float32 (`numpy.finfo(numpy.float32).tiny`),
/// mirroring silx `FLOAT32_MINPOS`. The lower clamp bound on a log axis (where
/// the min must stay strictly positive).
pub const FLOAT32_MINPOS: f64 = 1.1754943508222875e-38;

/// Translate a single axis range by a screen-space drag of `delta_px` pixels
/// across an axis of `extent_px` pixels, mirroring silx `Pan.drag`
/// (`PlotInteraction.py`). For a [`Scale::Log10`] axis the shift is applied in
/// log10 space; for [`Scale::Linear`] it is a plain offset.
///
/// `delta_px` is the pixel delta that should be *subtracted* from the range (the
/// data point under the pointer follows the cursor). Returns the new
/// `(min, max)`; on a log axis with a non-positive `min` or an out-of-range
/// result the original range is kept (silx reverts in those cases).
fn pan_axis(min: f64, max: f64, delta_px: f64, extent_px: f64, scale: Scale) -> (f64, f64) {
    match scale {
        Scale::Log10 if min > 0.0 && max > 0.0 => {
            let log_min = min.log10();
            let log_max = max.log10();
            // Per-pixel log10 delta across the axis (the data-to-pixel mapping is
            // linear in log space), matching silx `dx = log10(xData) - log10(lastX)`.
            let d_log = delta_px * (log_max - log_min) / extent_px;
            let new_min = 10f64.powf(log_min - d_log);
            let new_max = 10f64.powf(log_max - d_log);
            // silx keeps the axis only while both bounds stay in positive float32.
            if new_min < FLOAT32_MINPOS || new_max > FLOAT32_SAFE_MAX {
                (min, max)
            } else {
                (new_min, new_max)
            }
        }
        _ => {
            let offset = delta_px * (max - min) / extent_px;
            let new_min = min - offset;
            let new_max = max - offset;
            if new_min < FLOAT32_SAFE_MIN || new_max > FLOAT32_SAFE_MAX {
                (min, max)
            } else {
                (new_min, new_max)
            }
        }
    }
}

/// Translate `limits` by a screen-space drag delta (pixels) so the data point
/// under the pointer stays under the pointer (the content follows the cursor),
/// mirroring silx `Pan.drag` (`PlotInteraction.py`).
///
/// Screen `+x` is right and `+y` is down; the Y axis is flipped (data `y_max` at
/// the top), so a downward drag increases the data Y limits. `x_scale` /
/// `y_scale` select linear vs. log10 translation per axis.
pub fn pan(limits: Limits, area: Rect, delta_px: Vec2, x_scale: Scale, y_scale: Scale) -> Limits {
    let (x_min, x_max, y_min, y_max) = limits;
    let w = area.width().max(1.0) as f64;
    let h = area.height().max(1.0) as f64;
    // X: a rightward drag (+delta_px.x) shifts the view left.
    let (new_x_min, new_x_max) = pan_axis(x_min, x_max, delta_px.x as f64, w, x_scale);
    // Y is flipped: a downward drag (+delta_px.y) shifts the view up, so the
    // subtracted pixel delta is negated relative to the X convention.
    let (new_y_min, new_y_max) = pan_axis(y_min, y_max, -(delta_px.y as f64), h, y_scale);
    (new_x_min, new_x_max, new_y_min, new_y_max)
}

/// Scale a 1D range about an invariant `center` by `scale`, mirroring silx
/// `scale1DRange` (`_utils/panzoom.py`). `scale < 1` zooms out (widens the
/// span); `scale > 1` zooms in. On a log axis the operation is performed in
/// log10 space and the result is clipped to the positive float32 range; on a
/// linear axis it is clipped to the float32 range. A degenerate (`min == max`)
/// range is returned unchanged.
///
/// Note silx's `scale` is the multiplicative *zoom factor* (`range / scale`),
/// the reciprocal of the per-axis shrink ratio used by [`zoom_about`].
fn scale1d_range(min: f64, max: f64, center: f64, scale: f64, is_log: bool) -> (f64, f64) {
    let (mut min, mut center, mut max) = (min, center, max);
    if is_log {
        // Min and center can be <= 0 when autoscale is off and the axis switched
        // to log; silx substitutes FLOAT32_MINPOS in that case.
        min = if min > 0.0 {
            min.log10()
        } else {
            FLOAT32_MINPOS
        };
        center = if center > 0.0 {
            center.log10()
        } else {
            FLOAT32_MINPOS
        };
        max = if max > 0.0 {
            max.log10()
        } else {
            FLOAT32_MINPOS
        };
    }

    if min == max {
        return (min, max);
    }

    let offset = (center - min) / (max - min);
    let range = (max - min) / scale;
    let mut new_min = center - offset * range;
    let mut new_max = center + (1.0 - offset) * range;

    if is_log {
        new_min = 10f64.powf(new_min).clamp(FLOAT32_MINPOS, FLOAT32_SAFE_MAX);
        new_max = 10f64.powf(new_max).clamp(FLOAT32_MINPOS, FLOAT32_SAFE_MAX);
    } else {
        new_min = new_min.clamp(FLOAT32_SAFE_MIN, FLOAT32_SAFE_MAX);
        new_max = new_max.clamp(FLOAT32_SAFE_MIN, FLOAT32_SAFE_MAX);
    }
    (new_min, new_max)
}

/// Scale `limits` about a fixed data point `(cx, cy)`, mirroring silx
/// `applyZoomToPlot` (`_utils/panzoom.py`). `factor < 1` zooms in (shrinks the
/// span); `factor > 1` zooms out. The point `(cx, cy)` keeps its screen
/// position. `x_scale` / `y_scale` select log10 vs. linear scaling per axis.
///
/// silx `scale1DRange` divides the span by its `scale`, so to shrink the span by
/// `factor` here the silx scale is `1 / factor`.
pub fn zoom_about(
    limits: Limits,
    factor: f64,
    cx: f64,
    cy: f64,
    x_scale: Scale,
    y_scale: Scale,
) -> Limits {
    let (x_min, x_max, y_min, y_max) = limits;
    // silx `scale` is the reciprocal of our span-shrink `factor`.
    let silx_scale = 1.0 / factor;
    let (new_x_min, new_x_max) =
        scale1d_range(x_min, x_max, cx, silx_scale, x_scale == Scale::Log10);
    let (new_y_min, new_y_max) =
        scale1d_range(y_min, y_max, cy, silx_scale, y_scale == Scale::Log10);
    (new_x_min, new_x_max, new_y_min, new_y_max)
}

/// Pan a single axis range by `pan_factor` (a signed proportion of the range),
/// mirroring silx `applyPan` (`_utils/panzoom.py`). This is the arrow-key /
/// programmatic pan path (distinct from the mouse-drag [`pan`]). For a log axis
/// with a positive `min` the offset is applied in log10 space; otherwise it is a
/// linear offset. Out-of-range results are discarded (the original range is
/// kept), matching silx.
pub fn apply_pan(min: f64, max: f64, pan_factor: f64, is_log10: bool) -> (f64, f64) {
    if is_log10 && min > 0.0 {
        // Negative range with log scale can happen via other backends; skip it.
        let log_min = min.log10();
        let log_max = max.log10();
        let log_offset = pan_factor * (log_max - log_min);
        let new_min = 10f64.powf(log_min + log_offset);
        let new_max = 10f64.powf(log_max + log_offset);
        if new_min > 0.0 && new_max.is_finite() {
            (new_min, new_max)
        } else {
            (min, max)
        }
    } else {
        let offset = pan_factor * (max - min);
        let new_min = min + offset;
        let new_max = max + offset;
        if new_min > f64::NEG_INFINITY && new_max < f64::INFINITY {
            (new_min, new_max)
        } else {
            (min, max)
        }
    }
}

/// A pan direction for [`apply_pan`]-based arrow-key panning, mirroring silx
/// `PlotWidget.pan` directions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PanDirection {
    Up,
    Down,
    Left,
    Right,
}

/// Limits covering the data-space box defined by two corners, in any order.
pub fn box_zoom(ax: f64, ay: f64, bx: f64, by: f64) -> Limits {
    (ax.min(bx), ax.max(bx), ay.min(by), ay.max(by))
}

/// Convert an egui wheel delta (`smooth_scroll_delta.y`, pixels) to a zoom
/// factor for [`zoom_about`]. Scrolling up (`> 0`) zooms in (`factor < 1`).
pub fn wheel_zoom_factor(scroll_y: f32) -> f64 {
    // Exponential so repeated notches compose multiplicatively and symmetrically.
    (-(scroll_y as f64) * 0.0015).exp()
}

/// Whether `limits` are non-degenerate (both spans strictly positive). The
/// widget keeps the previous limits when a candidate fails this.
pub fn is_valid(limits: Limits) -> bool {
    let (x_min, x_max, y_min, y_max) = limits;
    x_max > x_min && y_max > y_min
}

/// Clamp one axis range into the float32-safe window and repair degenerate
/// ranges, mirroring silx `_utils/panzoom.checkAxisLimits` (panzoom.py:51-77).
///
/// Both bounds are clamped to `[lower, FLOAT32_SAFE_MAX]`, where `lower` is
/// [`FLOAT32_MINPOS`] on a log axis (`is_log == true`) and [`FLOAT32_SAFE_MIN`]
/// otherwise. If the clamp leaves `max < min` the two are swapped; if it leaves
/// `max == min` the range is expanded the way silx does:
/// - `v == 0` → `(-0.1, 0.1)`
/// - `v < 0`  → `(max(v * 1.1, FLOAT32_SAFE_MIN), v * 0.9)`
/// - `v > 0`  → `(v * 0.9, min(v * 1.1, FLOAT32_SAFE_MAX))`
///
/// A `NaN` bound clamps to `lower` (matching `numpy.clip`'s NaN→bound on the
/// platforms silx targets), so the result is always finite and ordered.
pub fn clamp_axis_limits(min: f64, max: f64, is_log: bool) -> (f64, f64) {
    let lower = if is_log {
        FLOAT32_MINPOS
    } else {
        FLOAT32_SAFE_MIN
    };
    let clip = |v: f64| -> f64 {
        // numpy.clip with a NaN input yields the NaN, but silx's downstream
        // expects a finite ordered range; map NaN to the lower bound so the
        // window is always usable.
        if v.is_nan() {
            lower
        } else {
            v.clamp(lower, FLOAT32_SAFE_MAX)
        }
    };
    let mut vmin = clip(min);
    let mut vmax = clip(max);

    if vmax < vmin {
        std::mem::swap(&mut vmin, &mut vmax);
    } else if vmax == vmin {
        let v = vmin;
        if v == 0.0 {
            vmin = -0.1;
            vmax = 0.1;
        } else if v < 0.0 {
            vmax = v * 0.9;
            vmin = (v * 1.1).max(FLOAT32_SAFE_MIN);
        } else {
            vmax = (v * 1.1).min(FLOAT32_SAFE_MAX);
            vmin = v * 0.9;
        }
    }
    (vmin, vmax)
}

/// Clamp both axes of `limits` into the float32-safe window via
/// [`clamp_axis_limits`], mirroring silx applying `checkAxisLimits` per axis
/// after pan/zoom (`PlotInteraction.py:241-250`, panzoom.py). `x_log` / `y_log`
/// select the log lower bound per axis. Applied after every pan and zoom so an
/// extreme gesture cannot push a bound past the float32-safe range.
pub fn clamp_limits(limits: Limits, x_log: bool, y_log: bool) -> Limits {
    let (x_min, x_max, y_min, y_max) = limits;
    let (nx0, nx1) = clamp_axis_limits(x_min, x_max, x_log);
    let (ny0, ny1) = clamp_axis_limits(y_min, y_max, y_log);
    (nx0, nx1, ny0, ny1)
}

// Draw-mode state machine ####################################################

/// Which shape an interactive draw session produces, mirroring silx's draw-mode
/// state machines (`PlotInteraction.py`): [`SelectRectangle`], [`SelectEllipse`],
/// [`SelectLine`], [`SelectHLine`], [`SelectVLine`], [`SelectPolygon`], and the
/// freehand pencil ([`DrawFreeHand`] / [`SelectFreeLine`]).
///
/// [`SelectRectangle`]: # "PlotInteraction.py:767"
/// [`SelectEllipse`]: # "PlotInteraction.py:681"
/// [`SelectLine`]: # "PlotInteraction.py:809"
/// [`SelectHLine`]: # "PlotInteraction.py:885"
/// [`SelectVLine`]: # "PlotInteraction.py:920"
/// [`SelectPolygon`]: # "PlotInteraction.py:485"
/// [`DrawFreeHand`]: # "PlotInteraction.py:955"
/// [`SelectFreeLine`]: # "PlotInteraction.py:1051"
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DrawMode {
    /// Two-point axis-aligned rectangle drag (silx `SelectRectangle`).
    Rectangle,
    /// Two-point drag producing an ellipse (silx `SelectEllipse`); the press is
    /// the center and the drag end a point on the ellipse.
    Ellipse,
    /// Two-point line segment drag (silx `SelectLine`).
    Line,
    /// One-point horizontal line at a captured Y (silx `SelectHLine`).
    HLine,
    /// One-point vertical line at a captured X (silx `SelectVLine`).
    VLine,
    /// Point-by-point polygon, closed by clicking near the first vertex (silx
    /// `SelectPolygon`).
    Polygon,
    /// Continuous freehand polyline accumulated while dragging (silx
    /// `DrawFreeHand` / `SelectFreeLine`).
    FreeHand,
    /// Single-click point capture (silx `_plotShape = "point"`, used by
    /// `PointROI`/`CrossROI` whose `setFirstShapePoints` takes `points[0]`,
    /// `items/roi.py:89`/`:176`). One press captures the data position and
    /// finishes the draw immediately — no drag/release is needed.
    Point,
}

/// A pointer sample fed to [`DrawState`]: the data-space position plus the
/// pixel-space position. The pixel position is needed for the polygon's
/// snap-to-first-point pixel threshold (silx `SelectPolygon`); the data position
/// is what the produced shape stores.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DrawInput {
    /// Data-space `(x, y)` under the cursor.
    pub data: (f64, f64),
    /// Pixel-space `(x, y)` of the cursor.
    pub pixel: (f32, f32),
}

impl DrawInput {
    /// Build a sample from a cursor pixel and the display [`Transform`],
    /// projecting the pixel to data space (the widget's per-event conversion).
    pub fn from_pixel(transform: &Transform, pixel: Pos2) -> Self {
        Self {
            data: transform.pixel_to_data(pixel),
            pixel: (pixel.x, pixel.y),
        }
    }
}

/// Parameters of a finished draw, mirroring the `points` / `parameters` payload
/// of silx's `prepareDrawingSignal` (`PlotEvents.py:34-55`) per shape type. All
/// coordinates are data-space.
#[derive(Clone, Debug, PartialEq)]
pub enum DrawParams {
    /// Axis-aligned rectangle, as silx `prepareDrawingSignal("rectangle", ...)`
    /// derives it: the lower-left `(x, y)` corner plus `width`/`height`
    /// (`PlotEvents.py:49-53`).
    Rectangle {
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    },
    /// Ellipse from silx `SelectEllipse`: a `center` plus the semi-axes
    /// `(width, height)` from center to the bounding box
    /// (`PlotInteraction.py:688-746`).
    Ellipse {
        center: (f64, f64),
        /// Semi-axis lengths `(a, b)` from center to bounding box.
        semi_axes: (f64, f64),
    },
    /// Line segment between two endpoints (silx `SelectLine`).
    Line { start: (f64, f64), end: (f64, f64) },
    /// Horizontal line at data `y` (silx `SelectHLine` captures the row; the
    /// widget extends it across the plot bounds for display).
    HLine { y: f64 },
    /// Vertical line at data `x` (silx `SelectVLine`).
    VLine { x: f64 },
    /// Closed polygon vertices (silx `SelectPolygon`). silx duplicates the first
    /// vertex as the last on close; this stores the open vertex ring without the
    /// duplicate so each vertex appears once.
    Polygon { vertices: Vec<(f64, f64)> },
    /// Freehand polyline vertices (silx `DrawFreeHand` / `SelectFreeLine`).
    FreeHand { vertices: Vec<(f64, f64)> },
    /// A single captured point (silx `_plotShape = "point"`): the data-space
    /// position of the click.
    Point { x: f64, y: f64 },
}

/// An event emitted by [`DrawState`], mirroring silx's `drawingProgress` /
/// `drawingFinished` signals (`prepareDrawingSignal`, `PlotEvents.py:34-55`).
#[derive(Clone, Debug, PartialEq)]
pub enum DrawEvent {
    /// The in-progress preview shape (silx `"drawingProgress"`). `points` are the
    /// data-space vertices of the current rubber-band, suitable for overlay
    /// drawing. For an ellipse these are the sampled circle-preview vertices.
    InProgress {
        mode: DrawMode,
        points: Vec<(f64, f64)>,
    },
    /// The draw completed (silx `"drawingFinished"`), carrying the resolved
    /// [`DrawParams`].
    Finished { mode: DrawMode, params: DrawParams },
}

/// Default polygon close / first-point snap threshold in pixels, mirroring silx
/// `SelectPolygon.DRAG_THRESHOLD_DIST` (`PlotInteraction.py:488`).
pub const DRAW_CLOSE_THRESHOLD_PX: f32 = 4.0;

/// Number of preview vertices silx samples for the ellipse/circle rubber band
/// (`PlotInteraction.py:729`).
const ELLIPSE_PREVIEW_POINTS: usize = 27;

/// Internal phase of a two-/one-point or polygon/freehand draw, kept private so
/// the only public surface is [`DrawState`]'s event API.
#[derive(Clone, Debug, PartialEq)]
enum Phase {
    /// No active draw.
    Idle,
    /// A two-point draw in progress: `start` captured, dragging to the end.
    TwoPoint { start: DrawInput },
    /// A one-point draw in progress (hline/vline): tracking the current point.
    OnePoint,
    /// A polygon in progress: `first` is the anchor (for the close test) and
    /// `points` is the committed vertex ring whose last entry tracks the cursor.
    /// Each vertex keeps its pixel position so the close / near-previous tests
    /// run in pixel space exactly as silx does.
    Polygon {
        first: DrawInput,
        points: Vec<DrawInput>,
    },
    /// A freehand draw in progress: accumulated data-space vertices.
    FreeHand { points: Vec<(f64, f64)> },
}

/// A pure draw-mode state machine over data-space coordinates, mirroring silx's
/// `Select*` / `DrawFreeHand` interactions (`PlotInteraction.py:485-1110`).
///
/// The widget feeds it pointer press / move / release events (already projected
/// to [`DrawInput`]); it returns an optional [`DrawEvent`] (`InProgress` preview
/// or `Finished` result) without touching any GPU state, so it is fully
/// unit-testable. The current preview vertices are also available via
/// [`DrawState::preview`] for overlay drawing between events.
#[derive(Clone, Debug)]
pub struct DrawState {
    mode: DrawMode,
    phase: Phase,
    close_threshold_px: f32,
}

impl DrawState {
    /// A fresh idle state for `mode`, using the default close threshold.
    pub fn new(mode: DrawMode) -> Self {
        Self {
            mode,
            phase: Phase::Idle,
            close_threshold_px: DRAW_CLOSE_THRESHOLD_PX,
        }
    }

    /// Override the polygon close / first-point snap threshold (pixels).
    pub fn with_close_threshold(mut self, px: f32) -> Self {
        self.close_threshold_px = px;
        self
    }

    /// The polygon close / first-point snap threshold in pixels. Used to size
    /// the on-plot first-point close target (silx `updateFirstPoint`).
    pub fn close_threshold_px(&self) -> f32 {
        self.close_threshold_px
    }

    /// The active draw mode.
    pub fn mode(&self) -> DrawMode {
        self.mode
    }

    /// Whether a draw is currently in progress (a press has started a shape that
    /// has not finished).
    pub fn is_active(&self) -> bool {
        !matches!(self.phase, Phase::Idle)
    }

    /// The current preview vertices (data space) for overlay drawing, or `None`
    /// when idle. Mirrors the rubber-band silx keeps via `setSelectionArea`.
    pub fn preview(&self) -> Option<Vec<(f64, f64)>> {
        match &self.phase {
            Phase::Idle => None,
            Phase::TwoPoint { .. } | Phase::OnePoint => None,
            Phase::Polygon { points, .. } => Some(points.iter().map(|p| p.data).collect()),
            Phase::FreeHand { points } => Some(points.clone()),
        }
    }

    /// Handle a pointer *press* (left-button down). For two-/one-point and
    /// freehand modes this begins the draw; for polygon mode it begins the
    /// polygon on the first press and is a no-op on later presses (vertices are
    /// added on release, mirroring silx `SelectPolygon`).
    pub fn on_press(&mut self, input: DrawInput) -> Option<DrawEvent> {
        match self.mode {
            DrawMode::Rectangle | DrawMode::Ellipse | DrawMode::Line => {
                self.phase = Phase::TwoPoint { start: input };
                None
            }
            DrawMode::HLine | DrawMode::VLine => {
                self.phase = Phase::OnePoint;
                Some(self.one_point_progress(input))
            }
            DrawMode::Polygon => {
                if matches!(self.phase, Phase::Idle) {
                    // First press anchors the polygon (silx enterState seeds
                    // points with [firstPos, firstPos]).
                    self.phase = Phase::Polygon {
                        first: input,
                        points: vec![input, input],
                    };
                    Some(self.polygon_progress())
                } else {
                    None
                }
            }
            DrawMode::FreeHand => {
                // silx SelectFreeLine seeds the first vertex on press (beginDrag).
                self.phase = Phase::FreeHand {
                    points: vec![input.data],
                };
                Some(self.freehand_progress())
            }
            DrawMode::Point => {
                // silx `_plotShape = "point"`: a single click finishes at once.
                // The phase stays Idle (no in-progress preview), so move/release
                // are no-ops and the next press starts a fresh point.
                Some(DrawEvent::Finished {
                    mode: DrawMode::Point,
                    params: DrawParams::Point {
                        x: input.data.0,
                        y: input.data.1,
                    },
                })
            }
        }
    }

    /// Handle a pointer *move*. Emits an `InProgress` preview while a draw is
    /// active, or `None` when idle.
    pub fn on_move(&mut self, input: DrawInput) -> Option<DrawEvent> {
        match self.mode {
            DrawMode::Rectangle | DrawMode::Ellipse | DrawMode::Line => match &self.phase {
                Phase::TwoPoint { start } => Some(self.two_point_progress(*start, input)),
                _ => None,
            },
            DrawMode::HLine | DrawMode::VLine => match self.phase {
                Phase::OnePoint => Some(self.one_point_progress(input)),
                _ => None,
            },
            DrawMode::Polygon => {
                if let Phase::Polygon { first, points } = &mut self.phase {
                    // Snap the tracked last vertex to the first point when the
                    // cursor is within the close threshold (silx onMove,
                    // PlotInteraction.py:593-604).
                    let snapped = if Self::within_threshold(
                        first.pixel,
                        input.pixel,
                        self.close_threshold_px,
                    ) {
                        *first
                    } else {
                        input
                    };
                    if let Some(last) = points.last_mut() {
                        *last = snapped;
                    }
                    Some(self.polygon_progress())
                } else {
                    None
                }
            }
            DrawMode::FreeHand => {
                if let Phase::FreeHand { points } = &mut self.phase {
                    // Accumulate, skipping a repeated identical point (silx
                    // SelectFreeLine._processEvent isNewPoint check).
                    if points.last() != Some(&input.data) {
                        points.push(input.data);
                    }
                    Some(self.freehand_progress())
                } else {
                    None
                }
            }
            // Point finishes on press; a move is a no-op.
            DrawMode::Point => None,
        }
    }

    /// Handle a pointer *release* (left-button up). Two-/one-point and freehand
    /// modes finish here; polygon mode appends a vertex (or closes if released
    /// near the first point with more than two vertices), mirroring silx
    /// `SelectPolygon.onRelease`.
    pub fn on_release(&mut self, input: DrawInput) -> Option<DrawEvent> {
        match self.mode {
            DrawMode::Rectangle | DrawMode::Ellipse | DrawMode::Line => {
                match std::mem::replace(&mut self.phase, Phase::Idle) {
                    Phase::TwoPoint { start } => Some(self.two_point_finished(start, input)),
                    other => {
                        self.phase = other;
                        None
                    }
                }
            }
            DrawMode::HLine | DrawMode::VLine => {
                if matches!(self.phase, Phase::OnePoint) {
                    self.phase = Phase::Idle;
                    Some(self.one_point_finished(input))
                } else {
                    None
                }
            }
            DrawMode::Polygon => self.polygon_on_release(input),
            DrawMode::FreeHand => {
                if let Phase::FreeHand { points } = &mut self.phase {
                    if points.last() != Some(&input.data) {
                        points.push(input.data);
                    }
                    let vertices = std::mem::take(points);
                    self.phase = Phase::Idle;
                    Some(DrawEvent::Finished {
                        mode: DrawMode::FreeHand,
                        params: DrawParams::FreeHand { vertices },
                    })
                } else {
                    None
                }
            }
            // Point finished on press; a release is a no-op.
            DrawMode::Point => None,
        }
    }

    /// Cancel any in-progress draw, returning to idle. Mirrors silx `cancel` /
    /// `cancelSelect` (drops the rubber band without a finished event).
    pub fn cancel(&mut self) {
        self.phase = Phase::Idle;
    }

    // --- internal helpers -------------------------------------------------

    fn within_threshold(a: (f32, f32), b: (f32, f32), threshold: f32) -> bool {
        // silx tests dx <= threshold AND dy <= threshold (axis-wise box, not a
        // radial distance), PlotInteraction.py:560-565.
        (a.0 - b.0).abs() <= threshold && (a.1 - b.1).abs() <= threshold
    }

    fn two_point_progress(&self, start: DrawInput, cur: DrawInput) -> DrawEvent {
        DrawEvent::InProgress {
            mode: self.mode,
            points: self.two_point_preview(start.data, cur.data),
        }
    }

    fn two_point_finished(&self, start: DrawInput, end: DrawInput) -> DrawEvent {
        let params = match self.mode {
            DrawMode::Rectangle => {
                let (sx, sy) = start.data;
                let (ex, ey) = end.data;
                let x = sx.min(ex);
                let y = sy.min(ey);
                DrawParams::Rectangle {
                    x,
                    y,
                    width: sx.max(ex) - x,
                    height: sy.max(ey) - y,
                }
            }
            DrawMode::Ellipse => {
                let semi_axes = ellipse_semi_axes(start.data, end.data);
                DrawParams::Ellipse {
                    center: start.data,
                    semi_axes,
                }
            }
            DrawMode::Line => DrawParams::Line {
                start: start.data,
                end: end.data,
            },
            _ => unreachable!("two_point_finished only for rectangle/ellipse/line"),
        };
        DrawEvent::Finished {
            mode: self.mode,
            params,
        }
    }

    fn two_point_preview(&self, start: (f64, f64), cur: (f64, f64)) -> Vec<(f64, f64)> {
        match self.mode {
            DrawMode::Rectangle => {
                // silx four corners: start, (start.x, cur.y), cur, (cur.x, start.y).
                vec![start, (start.0, cur.1), cur, (cur.0, start.1)]
            }
            DrawMode::Line => vec![start, cur],
            DrawMode::Ellipse => {
                let (a, b) = ellipse_semi_axes(start, cur);
                ellipse_preview(start, a, b)
            }
            _ => unreachable!("two_point_preview only for rectangle/ellipse/line"),
        }
    }

    fn one_point_progress(&self, input: DrawInput) -> DrawEvent {
        DrawEvent::InProgress {
            mode: self.mode,
            // The pure machine has no plot bounds; the preview point is just the
            // captured coordinate. The widget extends it across the data area.
            points: vec![input.data],
        }
    }

    fn one_point_finished(&self, input: DrawInput) -> DrawEvent {
        let params = match self.mode {
            DrawMode::HLine => DrawParams::HLine { y: input.data.1 },
            DrawMode::VLine => DrawParams::VLine { x: input.data.0 },
            _ => unreachable!("one_point_finished only for hline/vline"),
        };
        DrawEvent::Finished {
            mode: self.mode,
            params,
        }
    }

    fn polygon_progress(&self) -> DrawEvent {
        let points = match &self.phase {
            Phase::Polygon { points, .. } => points.iter().map(|p| p.data).collect(),
            _ => Vec::new(),
        };
        DrawEvent::InProgress {
            mode: DrawMode::Polygon,
            points,
        }
    }

    fn polygon_on_release(&mut self, input: DrawInput) -> Option<DrawEvent> {
        let Phase::Polygon { first, points } = &mut self.phase else {
            return None;
        };
        // Close when there is a real polygon (silx requires len > 2, i.e. the
        // seeded pair plus at least one appended vertex) and the release is near
        // the first point (PlotInteraction.py:565).
        let close = points.len() > 2
            && Self::within_threshold(first.pixel, input.pixel, self.close_threshold_px);
        if close {
            return Some(self.close_polygon());
        }

        // Compare the release pixel to the *previous* committed vertex's pixel
        // (points[-2]); append only if it is far enough, else replace the tracked
        // last vertex (silx PlotInteraction.py:581-588).
        let prev = points.get(points.len().wrapping_sub(2)).map(|p| p.pixel);
        let near_prev = prev
            .map(|pp| Self::within_threshold(pp, input.pixel, self.close_threshold_px))
            .unwrap_or(false);
        if let Some(last) = points.last_mut() {
            *last = input;
        }
        if !near_prev {
            points.push(input);
        }
        Some(self.polygon_progress())
    }

    fn close_polygon(&mut self) -> DrawEvent {
        let vertices = match &mut self.phase {
            Phase::Polygon { points, .. } => {
                let mut v: Vec<(f64, f64)> = points.iter().map(|p| p.data).collect();
                // The tracked last vertex is the cursor; drop it so only the
                // committed ring remains (silx sets points[-1] = points[0] then
                // emits; we drop the cursor tail and keep the open ring without a
                // duplicated first vertex).
                v.pop();
                v
            }
            _ => Vec::new(),
        };
        self.phase = Phase::Idle;
        DrawEvent::Finished {
            mode: DrawMode::Polygon,
            params: DrawParams::Polygon { vertices },
        }
    }

    fn freehand_progress(&self) -> DrawEvent {
        let points = match &self.phase {
            Phase::FreeHand { points } => points.clone(),
            _ => Vec::new(),
        };
        DrawEvent::InProgress {
            mode: DrawMode::FreeHand,
            points,
        }
    }
}

/// How a selection / draw-mode area is filled, mirroring silx
/// `setSelectionArea(fill=...)` (`PlotInteraction.py:98-141`): `'hatch'`,
/// `'solid'`, or `'none'`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FillMode {
    /// Diagonal hatch fill (silx `fill="hatch"`), the default for closed
    /// selection areas (rectangle/ellipse/polygon).
    #[default]
    Hatch,
    /// Solid fill (silx `fill="solid"`).
    Solid,
    /// No fill, outline only (silx `fill="none"`), used for the freehand
    /// polyline and the polygon first-point marker.
    None,
}

/// Style of an in-progress selection / draw-mode overlay, mirroring the
/// parameters silx passes to `setSelectionArea` (`PlotInteraction.py:98-141`):
/// a [`FillMode`] and an RGBA color. silx draws the outline dashed
/// (`linestyle="--"`); the widget honors that when painting.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SelectionStyle {
    /// How the area is filled.
    pub fill: FillMode,
    /// The outline / fill color.
    pub color: egui::Color32,
}

impl Default for SelectionStyle {
    fn default() -> Self {
        // silx default selection color is a translucent black; the widget can
        // override per draw session.
        Self {
            fill: FillMode::Hatch,
            color: egui::Color32::from_rgba_unmultiplied(0, 0, 0, 128),
        }
    }
}

impl SelectionStyle {
    /// A style with the given fill and color.
    pub fn new(fill: FillMode, color: egui::Color32) -> Self {
        Self { fill, color }
    }
}

/// Diagonal (45°) hatch line endpoints covering `rect`, spaced `spacing` pixels
/// apart, mirroring the visual of silx's `fill="hatch"`
/// (`PlotInteraction.py:98-141`). Each returned pair `(a, b)` is a line segment
/// (in `rect`'s coordinate space) clipped to the rectangle. Pure so the line
/// layout is unit-testable without a painter. A non-positive `spacing` or
/// degenerate `rect` yields no lines.
pub fn hatch_lines(rect: Rect, spacing: f32) -> Vec<(Pos2, Pos2)> {
    if spacing <= 0.0 || rect.width() <= 0.0 || rect.height() <= 0.0 {
        return Vec::new();
    }
    let mut lines = Vec::new();
    // Lines of slope +1 (going down-right): x - y = c. c ranges so the line
    // crosses the rect. For a line x = y + c, it intersects the rect when
    // c ∈ [left - bottom, right - top].
    let (left, right, top, bottom) = (rect.left(), rect.right(), rect.top(), rect.bottom());
    // Start c at the first multiple of spacing at or below the min, so the
    // pattern is stable regardless of rect offset.
    let c_min = left - bottom;
    let c_max = right - top;
    let mut c = (c_min / spacing).floor() * spacing;
    while c <= c_max {
        // Clip the infinite line x = y + c to the rect, collecting entry/exit.
        let mut pts: Vec<Pos2> = Vec::new();
        // Intersection with the four edges; keep those within the rect.
        // Top edge y = top: x = top + c.
        let xt = top + c;
        if xt >= left && xt <= right {
            pts.push(egui::pos2(xt, top));
        }
        // Bottom edge y = bottom: x = bottom + c.
        let xb = bottom + c;
        if xb >= left && xb <= right {
            pts.push(egui::pos2(xb, bottom));
        }
        // Left edge x = left: y = left - c.
        let yl = left - c;
        if yl >= top && yl <= bottom {
            pts.push(egui::pos2(left, yl));
        }
        // Right edge x = right: y = right - c.
        let yr = right - c;
        if yr >= top && yr <= bottom {
            pts.push(egui::pos2(right, yr));
        }
        if pts.len() >= 2 {
            lines.push((pts[0], pts[1]));
        }
        c += spacing;
    }
    lines
}

/// Semi-axes `(a, b)` of the ellipse centered at `center` passing through
/// `point`, mirroring silx `SelectEllipse._getEllipseSize`
/// (`PlotInteraction.py:688-721`). `a`/`b` are the lengths from the center to
/// the bounding box along X/Y. A degenerate point (zero X or Y offset) returns
/// the raw offsets, matching silx's early return.
pub fn ellipse_semi_axes(center: (f64, f64), point: (f64, f64)) -> (f64, f64) {
    let mut x = (center.0 - point.0).abs();
    let mut y = (center.1 - point.1).abs();
    if x == 0.0 || y == 0.0 {
        return (x, y);
    }
    // The eccentricity of the ellipse defined by a=x, b=y is the one we search.
    let swap = x < y;
    if swap {
        std::mem::swap(&mut x, &mut y);
    }
    let e = (x * x - y * y).sqrt() / x;
    // a^2 = x^2 + y^2 / (1 - e^2); b = a * sqrt(1 - e^2).
    let a = (x * x + y * y / (1.0 - e * e)).sqrt();
    let b = a * (1.0 - e * e).sqrt();
    if swap { (b, a) } else { (a, b) }
}

/// Sampled vertices of the ellipse preview centered at `center` with semi-axes
/// `(a, b)`, mirroring silx's [`ELLIPSE_PREVIEW_POINTS`]-point circle sampling
/// (`PlotInteraction.py:729-734`).
fn ellipse_preview(center: (f64, f64), a: f64, b: f64) -> Vec<(f64, f64)> {
    let n = ELLIPSE_PREVIEW_POINTS;
    (0..n)
        .map(|i| {
            let angle = i as f64 * std::f64::consts::TAU / n as f64;
            (center.0 + angle.cos() * a, center.1 + angle.sin() * b)
        })
        .collect()
}

/// Mouse-cursor shape for a draggable plot handle, mirroring silx's
/// `CURSOR_SIZE_HOR` / `CURSOR_SIZE_VER` / `CURSOR_SIZE_ALL` / `CURSOR_DEFAULT`
/// (`backends/BackendBase.py:44-48`, used by `_setCursorForMarker`,
/// `PlotInteraction.py:1165-1184`). A handle that moves only horizontally shows
/// `SizeHor`, only vertically `SizeVer`, freely in both `SizeAll`; nothing
/// grabbable shows `Default`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CursorShape {
    /// Horizontal resize (silx `CURSOR_SIZE_HOR`, Qt `SizeHorCursor`).
    SizeHor,
    /// Vertical resize (silx `CURSOR_SIZE_VER`, Qt `SizeVerCursor`).
    SizeVer,
    /// Diagonal resize along the ↘↖ axis: top-left ↔ bottom-right corner (Qt
    /// `SizeFDiagCursor`). silx maps all corner handles to `CURSOR_SIZE_ALL`;
    /// siplot uses egui's native diagonal cursor for Rect corners, matching
    /// egui's own window-corner resize affordance.
    SizeNwse,
    /// Diagonal resize along the ↗↙ axis: top-right ↔ bottom-left corner (Qt
    /// `SizeBDiagCursor`); the siplot Rect-corner counterpart of `SizeNwse`.
    SizeNesw,
    /// Move in both axes (silx `CURSOR_SIZE_ALL`, Qt `SizeAllCursor`).
    SizeAll,
    /// The default arrow cursor (silx `CURSOR_DEFAULT`, Qt `ArrowCursor`).
    #[default]
    Default,
}

impl CursorShape {
    /// Map to the egui [`egui::CursorIcon`] the widget sets. `SizeHor` →
    /// `ResizeHorizontal`, `SizeVer` → `ResizeVertical`, `SizeAll` → `Move`,
    /// `Default` → `Default`, matching silx's Qt cursor mapping
    /// (`backends/BackendPygfx.py:2354-2358`).
    pub fn to_egui(self) -> egui::CursorIcon {
        match self {
            CursorShape::SizeHor => egui::CursorIcon::ResizeHorizontal,
            CursorShape::SizeVer => egui::CursorIcon::ResizeVertical,
            CursorShape::SizeNwse => egui::CursorIcon::ResizeNwSe,
            CursorShape::SizeNesw => egui::CursorIcon::ResizeNeSw,
            CursorShape::SizeAll => egui::CursorIcon::Move,
            CursorShape::Default => egui::CursorIcon::Default,
        }
    }
}

/// Cursor shape for a draggable ROI edge handle, mirroring the direction logic
/// of silx `_setCursorForMarker` (`PlotInteraction.py:1165-1184`): a handle that
/// constrains motion to one axis shows that axis's resize cursor; a free
/// (vertex) handle shows the move cursor.
///
/// - [`RoiEdge::Left`] / [`RoiEdge::Right`] move only in X → [`CursorShape::SizeHor`].
/// - [`RoiEdge::Top`] / [`RoiEdge::Bottom`] move only in Y → [`CursorShape::SizeVer`].
/// - [`RoiEdge::TopLeft`] / [`RoiEdge::BottomRight`] resize diagonally along the
///   ↘↖ axis → [`CursorShape::SizeNwse`].
/// - [`RoiEdge::TopRight`] / [`RoiEdge::BottomLeft`] resize diagonally along the
///   ↗↙ axis → [`CursorShape::SizeNesw`].
/// - [`RoiEdge::Vertex`] moves in both axes → [`CursorShape::SizeAll`].
///
/// The corner edges are labeled in *data* space (matching
/// [`Roi::edge_at`](crate::core::roi::Roi::edge_at)), but the diagonal cursor
/// must reflect the *screen* diagonal of the corner. An axis inversion mirrors
/// that data edge's screen position; a horizontal mirror (X inverted) and a
/// vertical mirror (Y inverted) each swap ↘↖ ↔ ↗↙, so the screen diagonal
/// flips iff exactly one axis is inverted (both cancel). `t` supplies the
/// per-axis inversion. The side cursors (`SizeHor`/`SizeVer`) are symmetric and
/// axis-aligned, so inversion never changes them; only the corners flip.
pub fn cursor_for_edge(edge: RoiEdge, t: &Transform) -> CursorShape {
    let flip = t.x.inverted ^ t.y.inverted;
    match edge {
        RoiEdge::Left | RoiEdge::Right => CursorShape::SizeHor,
        RoiEdge::Top | RoiEdge::Bottom => CursorShape::SizeVer,
        RoiEdge::TopLeft | RoiEdge::BottomRight => {
            if flip {
                CursorShape::SizeNesw
            } else {
                CursorShape::SizeNwse
            }
        }
        RoiEdge::TopRight | RoiEdge::BottomLeft => {
            if flip {
                CursorShape::SizeNwse
            } else {
                CursorShape::SizeNesw
            }
        }
        RoiEdge::Vertex(_) => CursorShape::SizeAll,
    }
}

/// Cursor shape for an optional grabbed edge: the edge's shape when `Some`, the
/// default arrow when `None` (nothing grabbable under the cursor). This is the
/// shape the widget passes to egui each hover frame. `t` resolves the corner
/// diagonal against the axis orientation (see [`cursor_for_edge`]).
pub fn cursor_for_grab(edge: Option<RoiEdge>, t: &Transform) -> CursorShape {
    edge.map(|e| cursor_for_edge(e, t)).unwrap_or_default()
}

/// Cursor shape for a draggable marker, reflecting its drag degrees of freedom,
/// mirroring silx's per-marker size cursor (`PlotInteraction.py`
/// `_handleMarkerCursor`, `CURSOR_SIZE_*`):
///
/// - [`MarkerKind::VLine`] moves only in X → [`CursorShape::SizeHor`].
/// - [`MarkerKind::HLine`] moves only in Y → [`CursorShape::SizeVer`].
/// - [`MarkerKind::Point`] with [`MarkerConstraint::None`] moves freely →
///   [`CursorShape::SizeAll`]; with [`MarkerConstraint::Horizontal`] (pins X,
///   leaves Y free) it moves only in Y → [`CursorShape::SizeVer`]; with
///   [`MarkerConstraint::Vertical`] (pins Y, leaves X free) only in X →
///   [`CursorShape::SizeHor`].
///
/// Pure, so the mapping is unit-testable without a `Ui`.
pub fn marker_cursor(marker: &Marker) -> CursorShape {
    match marker.kind {
        MarkerKind::VLine { .. } => CursorShape::SizeHor,
        MarkerKind::HLine { .. } => CursorShape::SizeVer,
        MarkerKind::Point { .. } => match marker.constraint {
            MarkerConstraint::None => CursorShape::SizeAll,
            // Horizontal pins X, leaving Y free: vertical motion only.
            MarkerConstraint::Horizontal => CursorShape::SizeVer,
            // Vertical pins Y, leaving X free: horizontal motion only.
            MarkerConstraint::Vertical => CursorShape::SizeHor,
        },
    }
}

/// Index of the topmost *draggable* marker hit by `cursor` (screen pixels) under
/// `transform`, or `None` when no draggable marker is hit. Iterates in reverse
/// (the last-drawn marker has the highest z, so it wins the pick), skipping any
/// marker whose [`Marker::is_draggable`] is `false` even if the cursor is over
/// it. Pure ([`Marker::pick`] is the per-kind hit-test), so it is unit-testable.
pub fn marker_at(markers: &[Marker], transform: &Transform, cursor: Pos2) -> Option<usize> {
    markers
        .iter()
        .enumerate()
        .rev()
        .find(|(_, m)| m.is_draggable && m.pick(transform, cursor))
        .map(|(i, _)| i)
}

// On-plot ROI creation ########################################################

/// Which of the 11 ROI shapes an on-plot creation interaction produces, mirroring
/// the `RegionOfInterest` subclasses silx arms via
/// `RegionOfInterestManager.start(roiClass)` (`tools/roi.py`). Each kind maps to
/// the draw shape silx's `_plotShape` selects ([`roi_draw_mode`]) and the
/// `setFirstShapePoints` geometry it computes ([`roi_from_draw`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RoiDrawKind {
    /// Axis-aligned rectangle (silx `RectangleROI`).
    Rect,
    /// Horizontal band over a Y range, full X (our `Roi::HRange`).
    HRange,
    /// Vertical band over an X range, full Y (our `Roi::VRange`; silx
    /// `HorizontalRangeROI` spans X with two vertical markers).
    VRange,
    /// Single point (silx `PointROI`).
    Point,
    /// Line segment (silx `LineROI`).
    Line,
    /// Polygon (silx `PolygonROI`).
    Polygon,
    /// Full-span cross-hairs at a point (silx `CrossROI`).
    Cross,
    /// Circle (silx `CircleROI`).
    Circle,
    /// Axis-aligned ellipse (silx `EllipseROI`).
    Ellipse,
    /// Annular sector (silx `ArcROI`).
    Arc,
    /// Rotatable band (silx `BandROI`).
    Band,
}

/// The [`DrawMode`] silx arms for creating `kind`, matching each ROI class's
/// `_plotShape` (`items/roi.py`, `items/_arc_roi.py:253`, `items/_band_roi.py:169`).
///
/// silx uses the 2-point `"line"` drag for `Line`/`Circle`/`Arc`/`Band` and for
/// `HorizontalRangeROI`, computing the final geometry from the two points in
/// `setFirstShapePoints`. `Point`/`Cross` use `"point"` (a single click). `Rect`
/// uses `"rectangle"`. For `Ellipse` this port arms the silx `SelectEllipse`
/// 2-point interaction (press = center, drag = perimeter point) so an
/// axis-aligned ellipse is produced directly; silx's `EllipseROI._plotShape` is
/// `"line"` with an oriented circle default (`items/roi.py:888`/`:953`), which
/// our axis-aligned `Roi::Ellipse` does not model.
pub fn roi_draw_mode(kind: RoiDrawKind) -> DrawMode {
    match kind {
        RoiDrawKind::Rect => DrawMode::Rectangle,
        RoiDrawKind::Ellipse => DrawMode::Ellipse,
        RoiDrawKind::Polygon => DrawMode::Polygon,
        RoiDrawKind::Point | RoiDrawKind::Cross => DrawMode::Point,
        RoiDrawKind::Line
        | RoiDrawKind::Circle
        | RoiDrawKind::HRange
        | RoiDrawKind::VRange
        | RoiDrawKind::Arc
        | RoiDrawKind::Band => DrawMode::Line,
    }
}

/// Build the [`Roi`] from a finished draw's [`DrawParams`], the
/// `setFirstShapePoints` equivalent per ROI class (`items/roi.py`,
/// `items/_arc_roi.py`, `items/_band_roi.py`). Returns `None` for a
/// `(kind, params)` pair that [`roi_draw_mode`] can never produce together
/// (e.g. an `HLine`/`VLine`/`FreeHand` params for any ROI kind), so an
/// unexpected pairing is dropped rather than mis-built.
///
/// Geometry per kind (each silx default cited inline):
/// - `Rect` <- `Rectangle{x,y,w,h}` (silx `_setBound`, `items/roi.py:558`).
/// - `Line` <- `Line` endpoints (silx `setEndPoints`, `items/roi.py:254`).
/// - `Polygon` <- `Polygon` vertices (silx `setPoints`, `items/roi.py:1236`).
/// - `Point`/`Cross` <- `Point` (silx `setPosition(points[0])`,
///   `items/roi.py:89`/`:176`).
/// - `Circle` <- `Line`: `center = start`, `radius = |end - start|`
///   (silx `CircleROI._setRay`, `items/roi.py:782`).
/// - `Ellipse` <- `Ellipse{center, semi_axes}`: `radii = semi_axes` (the silx
///   `SelectEllipse` interaction; see [`roi_draw_mode`]).
/// - `HRange` <- `Line`: `y = (min, max)` of the two endpoint Ys (the band over
///   a Y range; silx `HorizontalRangeROI.setFirstShapePoints` is the X analogue,
///   `items/roi.py:1420`).
/// - `VRange` <- `Line`: `x = (min, max)` of the two endpoint Xs (silx
///   `HorizontalRangeROI.setFirstShapePoints`, `items/roi.py:1420`).
/// - `Arc` <- `Line`: the faithful silx default arc from the 2 diameter points
///   (silx `ArcROI.setFirstShapePoints` + `_createGeometryFromControlPoints`,
///   `items/_arc_roi.py:363`/`:622`); see [`arc_from_two_points`].
/// - `Band` <- `Line`: `begin = start`, `end = end`,
///   `width = 0.1 * |end - begin|` (silx `BandGeometry.create` default width,
///   `items/_band_roi.py:64-66`).
pub fn roi_from_draw(kind: RoiDrawKind, params: &DrawParams) -> Option<Roi> {
    match (kind, params) {
        (
            RoiDrawKind::Rect,
            DrawParams::Rectangle {
                x,
                y,
                width,
                height,
            },
        ) => Some(Roi::Rect {
            x: (*x, x + width),
            y: (*y, y + height),
        }),
        (RoiDrawKind::Line, DrawParams::Line { start, end }) => Some(Roi::Line {
            start: *start,
            end: *end,
        }),
        (RoiDrawKind::Polygon, DrawParams::Polygon { vertices }) => Some(Roi::Polygon {
            vertices: vertices.clone(),
        }),
        (RoiDrawKind::Point, DrawParams::Point { x, y }) => Some(Roi::Point { x: *x, y: *y }),
        (RoiDrawKind::Cross, DrawParams::Point { x, y }) => Some(Roi::Cross { center: (*x, *y) }),
        (RoiDrawKind::Ellipse, DrawParams::Ellipse { center, semi_axes }) => Some(Roi::Ellipse {
            center: *center,
            radii: *semi_axes,
        }),
        // Circle: center = first point, radius = distance to the second
        // (silx CircleROI._setRay, items/roi.py:782).
        (RoiDrawKind::Circle, DrawParams::Line { start, end }) => {
            let r = (end.0 - start.0).hypot(end.1 - start.1);
            Some(Roi::Circle {
                center: *start,
                radius: r,
            })
        }
        // HRange: a Y band, bounded by the two endpoints' Ys (ordered).
        (RoiDrawKind::HRange, DrawParams::Line { start, end }) => Some(Roi::HRange {
            y: (start.1.min(end.1), start.1.max(end.1)),
        }),
        // VRange: an X band, bounded by the two endpoints' Xs (ordered).
        (RoiDrawKind::VRange, DrawParams::Line { start, end }) => Some(Roi::VRange {
            x: (start.0.min(end.0), start.0.max(end.0)),
        }),
        // Arc: the faithful silx default arc from the 2 diameter points.
        (RoiDrawKind::Arc, DrawParams::Line { start, end }) => {
            Some(arc_from_two_points(*start, *end))
        }
        // Band: begin/end from the 2 points, default width = 0.1 * length.
        (RoiDrawKind::Band, DrawParams::Line { start, end }) => {
            let width = 0.1 * (end.0 - start.0).hypot(end.1 - start.1);
            Some(Roi::Band {
                begin: *start,
                end: *end,
                width: width.max(0.0),
            })
        }
        // Any other (kind, params) pair cannot be produced by roi_draw_mode.
        _ => None,
    }
}

/// The faithful silx `ArcROI` default geometry from two diameter points,
/// porting `ArcROI.setFirstShapePoints` + `_createGeometryFromControlPoints`
/// (`items/_arc_roi.py:363-385`, `:622-664`) and the public-geometry mapping in
/// `getGeometry` / `getInnerRadius` / `getOuterRadius` (`:781-874`).
///
/// silx builds a curvature control point `mid` off the `point0 → point1` line,
/// fits the circle through `(point0, mid, point1)`, and derives a `weight`
/// (band thickness) of `0.2 * |point1 - point0|`. The public form our
/// [`Roi::Arc`] stores is `center`, `inner_radius = radius - weight/2`
/// (clamped ≥ 0), `outer_radius = radius + weight/2`, `start_angle`, `end_angle`.
///
/// `defaultCurvature = π/5`, `weightCoef = 0.20`
/// (`items/_arc_roi.py:377-381`). For two coincident points the result is a
/// degenerate zero-radius arc at the point (silx would special-case a closed
/// circle; an on-plot drag never produces coincident diameter points, so this
/// path is only a safe fallback).
pub fn arc_from_two_points(point0: (f64, f64), point1: (f64, f64)) -> Roi {
    // center of the diameter; normal rotated -90 deg (silx: (normal_y, -normal_x)).
    let mid_center = ((point0.0 + point1.0) * 0.5, (point0.1 + point1.1) * 0.5);
    let normal_raw = (point1.0 - mid_center.0, point1.1 - mid_center.1);
    let normal = (normal_raw.1, -normal_raw.0);
    let default_curvature = std::f64::consts::PI / 5.0;
    let weight_coef = 0.20;
    let mid = (
        mid_center.0 - normal.0 * default_curvature,
        mid_center.1 - normal.1 * default_curvature,
    );
    let distance = (point0.0 - point1.0).hypot(point0.1 - point1.1);
    let weight = distance * weight_coef;

    // Degenerate fallback: coincident points -> zero-radius arc at the point.
    if distance == 0.0 {
        return Roi::Arc {
            center: point0,
            inner_radius: 0.0,
            outer_radius: 0.0,
            start_angle: 0.0,
            end_angle: 0.0,
        };
    }

    // Circle through (point0, mid, point1) — silx _circleEquation, ported from
    // the complex-number form (items/_arc_roi.py:986-996).
    let (center, radius) = circle_through(point0, mid, point1);

    // Start/mid/end angles from the fitted center (silx numpy.angle).
    let angle = |p: (f64, f64)| (p.1 - center.1).atan2(p.0 - center.0);
    let start_angle = angle(point0);
    let mid_angle = angle(mid);
    let mut end_angle = angle(point1);

    // Disambiguate sweep direction (silx items/_arc_roi.py:652-660).
    let two_pi = std::f64::consts::TAU;
    let relative_mid = (end_angle - mid_angle + two_pi).rem_euclid(two_pi);
    let relative_end = (end_angle - start_angle + two_pi).rem_euclid(two_pi);
    if relative_mid < relative_end {
        if end_angle < start_angle {
            end_angle += two_pi;
        }
    } else if end_angle > start_angle {
        end_angle -= two_pi;
    }

    let inner_radius = (radius - weight * 0.5).max(0.0);
    let outer_radius = radius + weight * 0.5;
    Roi::Arc {
        center,
        inner_radius,
        outer_radius,
        start_angle,
        end_angle,
    }
}

/// Center and radius of the circle through three points, porting silx
/// `ArcROI._circleEquation` (`items/_arc_roi.py:986-996`). silx uses complex
/// arithmetic:
/// ```text
/// x, y, z = complex(pt1), complex(pt2), complex(pt3)
/// w = (z - x) / (y - x)
/// c = (x - y) * (w - |w|^2) / (2j * w.imag) - x
/// center = (-c.real, -c.imag);  radius = |c + x|
/// ```
/// Ported below with explicit complex multiply/divide. Collinear points yield
/// `w.imag == 0`; the caller (`arc_from_two_points`) never passes collinear
/// triples because `mid` is offset off the `pt1 → pt3` line.
fn circle_through(pt1: (f64, f64), pt2: (f64, f64), pt3: (f64, f64)) -> ((f64, f64), f64) {
    // Complex helpers on (re, im) tuples.
    let sub = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0, a.1 - b.1);
    let mul = |a: (f64, f64), b: (f64, f64)| (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0);
    let div = |a: (f64, f64), b: (f64, f64)| {
        let den = b.0 * b.0 + b.1 * b.1;
        ((a.0 * b.0 + a.1 * b.1) / den, (a.1 * b.0 - a.0 * b.1) / den)
    };
    let (x, y, z) = (pt1, pt2, pt3);
    let w = div(sub(z, x), sub(y, x));
    let w_abs2 = w.0 * w.0 + w.1 * w.1;
    // numerator: (x - y) * (w - |w|^2)
    let num = mul(sub(x, y), (w.0 - w_abs2, w.1));
    // denominator: 2j * w.imag  ==  (0, 2 * w.imag)
    let den = (0.0, 2.0 * w.1);
    let c = sub(div(num, den), x);
    let center = (-c.0, -c.1);
    // radius = |c + x|
    let cx = (c.0 + x.0, c.1 + x.1);
    let radius = (cx.0 * cx.0 + cx.1 * cx.1).sqrt();
    (center, radius)
}

/// How an on-plot drag grabbed an existing ROI for editing, mirroring silx's
/// `HandleBasedROI` interaction: either a specific edge/vertex handle
/// ([`RoiGrab::Edge`], silx `handleDragUpdated`) or the whole-shape body
/// ([`RoiGrab::Translate`], silx `addTranslateHandle` / drag-on-body).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RoiGrab {
    /// A specific draggable edge/vertex handle was grabbed.
    Edge(RoiEdge),
    /// The ROI body (no handle under the cursor, but inside the shape) was
    /// grabbed for a whole-ROI translate.
    Translate,
}

/// Classify what an on-plot primary-drag grabs at `cursor` (screen pixels) over
/// `rois`, mirroring silx's per-ROI hit priority: a handle wins over the body.
/// Iterates topmost-first (last drawn = highest z); for each ROI returns
/// [`RoiGrab::Edge`] when an edge handle is within `grab_px` of the cursor, else
/// [`RoiGrab::Translate`] when the cursor's data position is inside the shape.
/// Returns the `(index, grab)` of the first ROI that matches, or `None`. Pure,
/// so the priority is unit-testable without a `Ui`.
pub fn roi_grab_at(
    rois: &[ManagedRoi],
    transform: &Transform,
    cursor: Pos2,
    grab_px: f32,
) -> Option<(usize, RoiGrab)> {
    let data = transform.pixel_to_data(cursor);
    for (i, managed) in rois.iter().enumerate().rev() {
        let roi = &managed.roi;
        if let Some(edge) = roi.edge_at(transform, cursor, grab_px) {
            return Some((i, RoiGrab::Edge(edge)));
        }
        if roi.contains(data) {
            return Some((i, RoiGrab::Translate));
        }
    }
    None
}

/// Which mouse button a [`PlotPointerEvent`] carries, mirroring silx's
/// `"left" | "middle" | "right"` button strings (`PlotEvents.py:58-71`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MouseButton {
    Left,
    Middle,
    Right,
}

impl MouseButton {
    /// Map an egui [`egui::PointerButton`] to the silx button identity. egui's
    /// extra buttons collapse to the nearest silx button (silx has only three).
    pub fn from_egui(button: egui::PointerButton) -> Self {
        match button {
            egui::PointerButton::Primary => MouseButton::Left,
            egui::PointerButton::Middle => MouseButton::Middle,
            _ => MouseButton::Right,
        }
    }
}

/// A structured pointer event over the plot data area, mirroring silx's
/// `prepareMouseSignal` (`PlotEvents.py:58-71`) and `prepareLimitsChangedSignal`
/// (`PlotEvents.py:176-184`). Each pointer variant carries the button (where a
/// button applies), the data-space position, and the pixel-space position so
/// application code has both without re-projecting.
///
/// This is the structured low-level pointer event produced by [`PlotView`]
/// interaction; it is distinct from the high-level item-lifecycle
/// `PlotEvent` queue owned by `PlotWidget`.
///
/// [`PlotView`]: crate::PlotView
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PlotPointerEvent {
    /// A single click (silx `"mouseClicked"`).
    Clicked {
        button: MouseButton,
        /// Data-space `(x, y)` under the cursor.
        data: (f64, f64),
        /// Pixel-space `(x, y)` of the cursor.
        pixel: (f32, f32),
    },
    /// A double click (silx `"mouseDoubleClicked"`). silx only emits this for
    /// the left button, at the position of the first click.
    DoubleClicked {
        button: MouseButton,
        data: (f64, f64),
        pixel: (f32, f32),
    },
    /// The cursor moved over the data area (silx `"mouseMoved"` hover).
    Moved {
        /// `None` for a bare move (silx leaves the button unset when no button
        /// is held); `Some` when a button is held during the move.
        button: Option<MouseButton>,
        data: (f64, f64),
        pixel: (f32, f32),
    },
    /// The display limits changed (silx `"limitsChanged"`), carrying the new
    /// left-X, left-Y, and (optional) right-Y2 ranges as `(min, max)` tuples.
    LimitsChanged {
        x: (f64, f64),
        y: (f64, f64),
        y2: Option<(f64, f64)>,
    },
}

impl PlotPointerEvent {
    /// Build a [`PlotPointerEvent::Clicked`] from a cursor pixel position and
    /// the display [`Transform`], projecting the pixel to data space (silx
    /// `prepareMouseSignal("mouseClicked", ...)`).
    pub fn clicked(button: MouseButton, transform: &Transform, pixel: Pos2) -> Self {
        PlotPointerEvent::Clicked {
            button,
            data: transform.pixel_to_data(pixel),
            pixel: (pixel.x, pixel.y),
        }
    }

    /// Build a [`PlotPointerEvent::DoubleClicked`] from a cursor pixel position
    /// (silx `prepareMouseSignal("mouseDoubleClicked", ...)`).
    pub fn double_clicked(button: MouseButton, transform: &Transform, pixel: Pos2) -> Self {
        PlotPointerEvent::DoubleClicked {
            button,
            data: transform.pixel_to_data(pixel),
            pixel: (pixel.x, pixel.y),
        }
    }

    /// Build a [`PlotPointerEvent::Moved`] hover event from a cursor pixel
    /// position (silx `prepareMouseSignal("mouseMoved", ...)`). `button` is the
    /// held button, if any.
    pub fn moved(button: Option<MouseButton>, transform: &Transform, pixel: Pos2) -> Self {
        PlotPointerEvent::Moved {
            button,
            data: transform.pixel_to_data(pixel),
            pixel: (pixel.x, pixel.y),
        }
    }

    /// Build a [`PlotPointerEvent::LimitsChanged`] (silx
    /// `prepareLimitsChangedSignal`).
    pub fn limits_changed(x: (f64, f64), y: (f64, f64), y2: Option<(f64, f64)>) -> Self {
        PlotPointerEvent::LimitsChanged { x, y, y2 }
    }
}

/// A picked polyline vertex: its index and data coordinates, plus the pixel
/// distance from the cursor (`doc/design.md` §13 C2).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PointPick {
    pub index: usize,
    pub x: f64,
    pub y: f64,
    pub dist_px: f32,
}

/// Nearest polyline vertex to `cursor` (screen pixels) within `threshold_px`.
/// `points` are data coordinates, projected through `transform` to pixels for
/// the distance test. `None` if no vertex is within the threshold.
pub fn nearest_point(
    points: &[(f64, f64)],
    transform: &Transform,
    cursor: Pos2,
    threshold_px: f32,
) -> Option<PointPick> {
    let mut best: Option<PointPick> = None;
    for (index, &(x, y)) in points.iter().enumerate() {
        let dist_px = transform.data_to_pixel(x, y).distance(cursor);
        if dist_px <= threshold_px && best.is_none_or(|b| dist_px < b.dist_px) {
            best = Some(PointPick {
                index,
                x,
                y,
                dist_px,
            });
        }
    }
    best
}

/// Image pixel `(col, row)` under `cursor` (screen pixels), or `None` if the
/// cursor maps outside the image. `origin` is the data coordinate of pixel
/// `(0, 0)`'s lower-left corner and `scale` is data units per pixel (matching
/// [`crate::ImageData`]); row 0 is at the bottom.
pub fn image_index(
    transform: &Transform,
    origin: (f64, f64),
    scale: (f64, f64),
    dims: (u32, u32),
    cursor: Pos2,
) -> Option<(u32, u32)> {
    if scale.0 <= 0.0 || scale.1 <= 0.0 {
        return None;
    }
    let (x, y) = transform.pixel_to_data(cursor);
    if !x.is_finite() || !y.is_finite() {
        return None;
    }
    let col = ((x - origin.0) / scale.0).floor();
    let row = ((y - origin.1) / scale.1).floor();
    if col < 0.0 || row < 0.0 {
        return None;
    }
    // Saturating f64->u32 cast handles huge values; the bounds check rejects them.
    let (col, row) = (col as u32, row as u32);
    (col < dims.0 && row < dims.1).then_some((col, row))
}

#[cfg(test)]
mod tests {
    use super::*;
    use egui::{pos2, vec2};

    fn area_100() -> Rect {
        Rect::from_min_size(pos2(0.0, 0.0), vec2(100.0, 100.0))
    }

    fn close(a: Limits, b: Limits) -> bool {
        let t = 1e-9;
        (a.0 - b.0).abs() <= t
            && (a.1 - b.1).abs() <= t
            && (a.2 - b.2).abs() <= t
            && (a.3 - b.3).abs() <= t
    }

    #[test]
    fn pan_right_shifts_view_left() {
        // Drag 10px right (10% of width, span 10) -> x limits shift -1.
        let out = pan(
            (0.0, 10.0, 0.0, 10.0),
            area_100(),
            vec2(10.0, 0.0),
            Scale::Linear,
            Scale::Linear,
        );
        assert!(close(out, (-1.0, 9.0, 0.0, 10.0)), "{out:?}");
    }

    #[test]
    fn pan_down_increases_y_limits() {
        // Y is flipped: dragging down raises the data Y window.
        let out = pan(
            (0.0, 10.0, 0.0, 10.0),
            area_100(),
            vec2(0.0, 10.0),
            Scale::Linear,
            Scale::Linear,
        );
        assert!(close(out, (0.0, 10.0, 1.0, 11.0)), "{out:?}");
    }

    #[test]
    fn pan_log_round_trips_in_log_space() {
        // Boundary: a +d drag then a -d drag on a log axis returns to the start.
        let limits = (1.0, 100.0, 1.0, 100.0);
        let area = area_100();
        let forward = pan(limits, area, vec2(20.0, 13.0), Scale::Log10, Scale::Log10);
        let back = pan(
            forward,
            area,
            vec2(-20.0, -13.0),
            Scale::Log10,
            Scale::Log10,
        );
        assert!(close(back, limits), "{back:?}");
        // The intermediate state must have moved (otherwise the round-trip is trivial).
        assert!(!close(forward, limits), "{forward:?}");
    }

    #[test]
    fn pan_log_translates_in_log_space() {
        // A drag of half the width on a log decade [1, 100] shifts both bounds by
        // half a log decade in log10 space (the span is 2 decades over 100px, so
        // 50px == 1 decade).
        let out = pan(
            (1.0, 100.0, 1.0, 100.0),
            area_100(),
            vec2(50.0, 0.0),
            Scale::Log10,
            Scale::Linear,
        );
        // X limits shift left by one decade: 1 -> 0.1, 100 -> 10.
        assert!((out.0 - 0.1).abs() <= 1e-9, "{out:?}");
        assert!((out.1 - 10.0).abs() <= 1e-9, "{out:?}");
        // Y (linear) unchanged.
        assert!(
            (out.2 - 1.0).abs() <= 1e-9 && (out.3 - 100.0).abs() <= 1e-9,
            "{out:?}"
        );
    }

    #[test]
    fn zoom_about_center_halves_span_keeping_center() {
        let out = zoom_about(
            (0.0, 10.0, 0.0, 10.0),
            0.5,
            5.0,
            5.0,
            Scale::Linear,
            Scale::Linear,
        );
        assert!(close(out, (2.5, 7.5, 2.5, 7.5)), "{out:?}");
    }

    #[test]
    fn zoom_about_keeps_anchor_fixed() {
        // The anchor's fractional position within the limits is unchanged.
        let limits = (0.0, 10.0, 0.0, 10.0);
        let (cx, cy) = (8.0, 2.0);
        let out = zoom_about(limits, 0.3, cx, cy, Scale::Linear, Scale::Linear);
        let frac_before = (cx - limits.0) / (limits.1 - limits.0);
        let frac_after = (cx - out.0) / (out.1 - out.0);
        assert!((frac_before - frac_after).abs() <= 1e-9);
        let _ = cy;
    }

    #[test]
    fn zoom_about_log_keeps_anchor_data_coord_fixed() {
        // Boundary: on a log axis the cursor's data coordinate must stay fixed
        // across a zoom (its fractional position in log space is invariant).
        let limits = (1.0, 1000.0, 1.0, 1000.0);
        let (cx, cy) = (10.0, 100.0);
        let out = zoom_about(limits, 0.5, cx, cy, Scale::Log10, Scale::Log10);
        let frac_log =
            |v: f64, lo: f64, hi: f64| (v.log10() - lo.log10()) / (hi.log10() - lo.log10());
        let fx_before = frac_log(cx, limits.0, limits.1);
        let fx_after = frac_log(cx, out.0, out.1);
        assert!(
            (fx_before - fx_after).abs() <= 1e-9,
            "x {fx_before} {fx_after}"
        );
        let fy_before = frac_log(cy, limits.2, limits.3);
        let fy_after = frac_log(cy, out.2, out.3);
        assert!(
            (fy_before - fy_after).abs() <= 1e-9,
            "y {fy_before} {fy_after}"
        );
    }

    #[test]
    fn apply_pan_linear_offsets_by_fraction() {
        // Linear: pan 10% of the [0, 10] span to the right.
        let (lo, hi) = apply_pan(0.0, 10.0, 0.1, false);
        assert!(
            (lo - 1.0).abs() <= 1e-12 && (hi - 11.0).abs() <= 1e-12,
            "{lo} {hi}"
        );
    }

    #[test]
    fn apply_pan_log_round_trips() {
        // Boundary: log pan +f then -f returns to the start in log space.
        let (lo, hi) = apply_pan(1.0, 100.0, 0.25, true);
        let (lo2, hi2) = apply_pan(lo, hi, -0.25, true);
        assert!(
            (lo2 - 1.0).abs() <= 1e-9 && (hi2 - 100.0).abs() <= 1e-9,
            "{lo2} {hi2}"
        );
        // Forward step moved by 0.25 decade: 1 -> 10^0.5, 100 -> 10^2.5.
        assert!((lo - 10f64.powf(0.5)).abs() <= 1e-9, "{lo}");
        assert!((hi - 10f64.powf(2.5)).abs() <= 1e-9, "{hi}");
    }

    #[test]
    fn apply_pan_log_nonpositive_min_falls_back_to_linear() {
        // Boundary: a non-positive min on a log axis takes silx's linear branch.
        let (lo, hi) = apply_pan(-1.0, 10.0, 0.1, true);
        // Linear offset: 0.1 * (10 - -1) = 1.1.
        assert!(
            (lo - 0.1).abs() <= 1e-12 && (hi - 11.1).abs() <= 1e-12,
            "{lo} {hi}"
        );
    }

    #[test]
    fn box_zoom_orders_corners() {
        let out = box_zoom(8.0, 1.0, 2.0, 9.0);
        assert!(close(out, (2.0, 8.0, 1.0, 9.0)), "{out:?}");
    }

    #[test]
    fn wheel_factor_direction_and_neutral() {
        assert!(wheel_zoom_factor(100.0) < 1.0);
        assert!(wheel_zoom_factor(-100.0) > 1.0);
        assert!((wheel_zoom_factor(0.0) - 1.0).abs() <= 1e-12);
    }

    #[test]
    fn validity_rejects_collapsed_or_inverted() {
        assert!(is_valid((0.0, 1.0, 0.0, 1.0)));
        assert!(!is_valid((1.0, 1.0, 0.0, 1.0)));
        assert!(!is_valid((0.0, 1.0, 2.0, 1.0)));
    }

    use crate::core::transform::Transform;

    // 100×100 px area mapping data [0,10]×[0,10]; 1 data unit = 10 px.
    fn pick_transform() -> Transform {
        Transform::new(0.0, 10.0, 0.0, 10.0, area_100())
    }

    fn di(data: (f64, f64), pixel: (f32, f32)) -> DrawInput {
        DrawInput { data, pixel }
    }

    #[test]
    fn rectangle_two_point_bounds() {
        // Drag from (8,1) to (2,9): finished rectangle is the ordered lower-left
        // corner plus width/height (silx prepareDrawingSignal "rectangle").
        let mut s = DrawState::new(DrawMode::Rectangle);
        // A rectangle press starts the draw but emits nothing (silx beginSelect).
        assert!(s.on_press(di((8.0, 1.0), (80.0, 90.0))).is_none());
        assert!(matches!(
            s.on_move(di((2.0, 9.0), (20.0, 10.0))),
            Some(DrawEvent::InProgress {
                mode: DrawMode::Rectangle,
                ..
            })
        ));
        let fin = s
            .on_release(di((2.0, 9.0), (20.0, 10.0)))
            .expect("finished");
        match fin {
            DrawEvent::Finished {
                mode: DrawMode::Rectangle,
                params:
                    DrawParams::Rectangle {
                        x,
                        y,
                        width,
                        height,
                    },
            } => {
                assert_eq!((x, y), (2.0, 1.0));
                assert_eq!((width, height), (6.0, 8.0));
            }
            other => panic!("{other:?}"),
        }
        assert!(!s.is_active());
    }

    #[test]
    fn line_two_point_endpoints() {
        let mut s = DrawState::new(DrawMode::Line);
        s.on_press(di((1.0, 2.0), (10.0, 20.0)));
        let fin = s
            .on_release(di((3.0, 4.0), (30.0, 40.0)))
            .expect("finished");
        assert_eq!(
            fin,
            DrawEvent::Finished {
                mode: DrawMode::Line,
                params: DrawParams::Line {
                    start: (1.0, 2.0),
                    end: (3.0, 4.0),
                },
            }
        );
    }

    #[test]
    fn ellipse_params_from_drag() {
        // Axis-aligned drag (center to a point straight along X): degenerate
        // ellipse returns the raw offsets (silx early return when y offset 0).
        let (a, b) = ellipse_semi_axes((0.0, 0.0), (5.0, 0.0));
        assert_eq!((a, b), (5.0, 0.0));
        // A real off-axis point: the point lies on the resulting ellipse, i.e.
        // x^2/a^2 + y^2/b^2 == 1.
        let center = (1.0, 2.0);
        let point = (4.0, 6.0);
        let (a, b) = ellipse_semi_axes(center, point);
        let dx = point.0 - center.0;
        let dy = point.1 - center.1;
        let on_ellipse = dx * dx / (a * a) + dy * dy / (b * b);
        assert!(
            (on_ellipse - 1.0).abs() <= 1e-9,
            "a={a} b={b} -> {on_ellipse}"
        );
        // The longer semi-axis follows the larger offset: here |dy| (4) > |dx|
        // (3), so the Y semi-axis b is the larger one.
        assert!(b > a, "a={a} b={b}");

        // Through the state machine the finished event carries center + semi-axes.
        let mut s = DrawState::new(DrawMode::Ellipse);
        s.on_press(di(center, (10.0, 20.0)));
        let fin = s.on_release(di(point, (40.0, 60.0))).expect("finished");
        match fin {
            DrawEvent::Finished {
                mode: DrawMode::Ellipse,
                params:
                    DrawParams::Ellipse {
                        center: c,
                        semi_axes,
                    },
            } => {
                assert_eq!(c, center);
                assert!((semi_axes.0 - a).abs() <= 1e-12 && (semi_axes.1 - b).abs() <= 1e-12);
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn ellipse_preview_has_full_ring() {
        // The in-progress preview is a 27-point sampled ring around the center.
        let mut s = DrawState::new(DrawMode::Ellipse);
        s.on_press(di((0.0, 0.0), (0.0, 0.0)));
        let ev = s.on_move(di((4.0, 6.0), (40.0, 60.0))).expect("progress");
        match ev {
            DrawEvent::InProgress { points, .. } => {
                assert_eq!(points.len(), 27);
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn hline_vline_capture_one_coordinate() {
        // HLine captures the data Y of the release.
        let mut s = DrawState::new(DrawMode::HLine);
        assert!(matches!(
            s.on_press(di((3.0, 7.0), (30.0, 70.0))),
            Some(DrawEvent::InProgress { .. })
        ));
        let fin = s
            .on_release(di((9.0, 7.5), (90.0, 75.0)))
            .expect("finished");
        assert_eq!(
            fin,
            DrawEvent::Finished {
                mode: DrawMode::HLine,
                params: DrawParams::HLine { y: 7.5 },
            }
        );
        // VLine captures the data X of the release.
        let mut s = DrawState::new(DrawMode::VLine);
        s.on_press(di((3.0, 7.0), (30.0, 70.0)));
        let fin = s
            .on_release(di((4.2, 1.0), (42.0, 10.0)))
            .expect("finished");
        assert_eq!(
            fin,
            DrawEvent::Finished {
                mode: DrawMode::VLine,
                params: DrawParams::VLine { x: 4.2 },
            }
        );
    }

    #[test]
    fn polygon_accumulates_vertices_and_closes_on_first_point() {
        let mut s = DrawState::new(DrawMode::Polygon).with_close_threshold(4.0);
        // First press anchors the polygon at (0,0)/pixel(0,0).
        s.on_press(di((0.0, 0.0), (0.0, 0.0)));
        // Release far from start -> appends a vertex (now 3 entries: seed pair
        // updated + appended).
        s.on_release(di((10.0, 0.0), (100.0, 0.0)));
        s.on_release(di((10.0, 10.0), (100.0, 100.0)));
        // Move the cursor near the first point (within 4px) -> snaps to first.
        s.on_move(di((0.05, 0.05), (2.0, 3.0)));
        // Release near the first point with >2 points -> closes.
        let fin = s.on_release(di((0.05, 0.05), (2.0, 3.0))).expect("closed");
        match fin {
            DrawEvent::Finished {
                mode: DrawMode::Polygon,
                params: DrawParams::Polygon { vertices },
            } => {
                // Open ring: the three distinct corners, first not duplicated.
                assert_eq!(vertices, vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]);
            }
            other => panic!("{other:?}"),
        }
        assert!(!s.is_active());
    }

    #[test]
    fn polygon_does_not_close_with_two_points() {
        // Boundary: a release near the first point but with only the seed pair
        // (len == 2, no appended vertex) must NOT close (silx len > 2 gate).
        let mut s = DrawState::new(DrawMode::Polygon).with_close_threshold(4.0);
        s.on_press(di((0.0, 0.0), (0.0, 0.0)));
        // Release exactly on the first point: len is still 2, so no close; it is
        // treated as a near-previous replace, not an append.
        let ev = s.on_release(di((0.0, 0.0), (0.0, 0.0))).expect("progress");
        assert!(matches!(ev, DrawEvent::InProgress { .. }));
        assert!(s.is_active());
    }

    #[test]
    fn polygon_replaces_near_previous_vertex() {
        // A release within threshold of the previous committed vertex replaces
        // the tracked last vertex instead of appending (silx 581-588).
        let mut s = DrawState::new(DrawMode::Polygon).with_close_threshold(4.0);
        s.on_press(di((0.0, 0.0), (0.0, 0.0)));
        // First real release far from the seed -> append: the seeded tail is
        // overwritten with (10,0) and a new (10,0) tail is pushed, so the ring is
        // [first, (10,0), (10,0)] (silx's enterState seeds the pair, onRelease
        // appends the cursor tail).
        s.on_release(di((10.0, 0.0), (100.0, 0.0)));
        // Second release within 4px of the previous committed vertex (100,0) ->
        // replace the cursor tail in place, no append.
        s.on_release(di((10.2, 0.1), (102.0, 1.0)));
        let preview = s.preview().expect("active");
        // Ring length unchanged at 3; the tail was replaced, not appended.
        assert_eq!(preview.len(), 3);
        assert_eq!(preview[1], (10.0, 0.0));
        assert_eq!(preview[2], (10.2, 0.1));
    }

    #[test]
    fn freehand_accumulates_and_dedups() {
        let mut s = DrawState::new(DrawMode::FreeHand);
        // Press seeds the first vertex.
        assert!(matches!(
            s.on_press(di((0.0, 0.0), (0.0, 0.0))),
            Some(DrawEvent::InProgress {
                mode: DrawMode::FreeHand,
                ..
            })
        ));
        s.on_move(di((1.0, 1.0), (10.0, 10.0)));
        // Repeated identical point is skipped.
        s.on_move(di((1.0, 1.0), (10.0, 10.0)));
        s.on_move(di((2.0, 0.0), (20.0, 0.0)));
        let fin = s
            .on_release(di((3.0, 1.0), (30.0, 10.0)))
            .expect("finished");
        match fin {
            DrawEvent::Finished {
                mode: DrawMode::FreeHand,
                params: DrawParams::FreeHand { vertices },
            } => {
                assert_eq!(
                    vertices,
                    vec![(0.0, 0.0), (1.0, 1.0), (2.0, 0.0), (3.0, 1.0)]
                );
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn freehand_release_does_not_duplicate_last() {
        // Boundary: releasing at the same point as the last accumulated vertex
        // does not duplicate it (silx isLast append-if-different).
        let mut s = DrawState::new(DrawMode::FreeHand);
        s.on_press(di((0.0, 0.0), (0.0, 0.0)));
        s.on_move(di((1.0, 1.0), (10.0, 10.0)));
        let fin = s
            .on_release(di((1.0, 1.0), (10.0, 10.0)))
            .expect("finished");
        match fin {
            DrawEvent::Finished {
                params: DrawParams::FreeHand { vertices },
                ..
            } => assert_eq!(vertices, vec![(0.0, 0.0), (1.0, 1.0)]),
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn cancel_drops_in_progress_draw() {
        let mut s = DrawState::new(DrawMode::Polygon);
        s.on_press(di((0.0, 0.0), (0.0, 0.0)));
        assert!(s.is_active());
        s.cancel();
        assert!(!s.is_active());
        assert!(s.preview().is_none());
    }

    #[test]
    fn idle_move_and_release_are_noops() {
        // Before any press, move/release emit nothing for two-point modes.
        let mut s = DrawState::new(DrawMode::Rectangle);
        assert!(s.on_move(di((1.0, 1.0), (10.0, 10.0))).is_none());
        assert!(s.on_release(di((1.0, 1.0), (10.0, 10.0))).is_none());
    }

    #[test]
    fn fill_mode_and_style_defaults() {
        assert_eq!(FillMode::default(), FillMode::Hatch);
        let s = SelectionStyle::default();
        assert_eq!(s.fill, FillMode::Hatch);
        let s = SelectionStyle::new(FillMode::Solid, egui::Color32::RED);
        assert_eq!(s.fill, FillMode::Solid);
        assert_eq!(s.color, egui::Color32::RED);
    }

    #[test]
    fn hatch_lines_cover_rect() {
        let rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(40.0, 40.0));
        let lines = hatch_lines(rect, 10.0);
        // Diagonal lines spanning a 40x40 box at 10px spacing produce several
        // segments, each with both endpoints on the rect boundary.
        assert!(!lines.is_empty());
        for (a, b) in &lines {
            assert!(rect.contains(*a) && rect.contains(*b), "{a:?} {b:?}");
            // Slope +1 within tolerance (segment is a 45-degree line).
            let dx = b.x - a.x;
            let dy = b.y - a.y;
            assert!((dx.abs() - dy.abs()).abs() <= 1e-3, "dx={dx} dy={dy}");
        }
    }

    #[test]
    fn hatch_lines_degenerate_inputs_empty() {
        let rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(40.0, 40.0));
        // Non-positive spacing -> no lines.
        assert!(hatch_lines(rect, 0.0).is_empty());
        assert!(hatch_lines(rect, -5.0).is_empty());
        // Degenerate rect -> no lines.
        let zero = Rect::from_min_max(pos2(0.0, 0.0), pos2(0.0, 0.0));
        assert!(hatch_lines(zero, 10.0).is_empty());
    }

    #[test]
    fn cursor_shape_per_edge() {
        // Non-inverted axes: data orientation == screen orientation.
        let t = pick_transform();
        // Horizontal-only edges -> SizeHor.
        assert_eq!(cursor_for_edge(RoiEdge::Left, &t), CursorShape::SizeHor);
        assert_eq!(cursor_for_edge(RoiEdge::Right, &t), CursorShape::SizeHor);
        // Vertical-only edges -> SizeVer.
        assert_eq!(cursor_for_edge(RoiEdge::Top, &t), CursorShape::SizeVer);
        assert_eq!(cursor_for_edge(RoiEdge::Bottom, &t), CursorShape::SizeVer);
        // Diagonal corners: TL/BR share the ↘↖ axis, TR/BL the ↗↙ axis.
        assert_eq!(cursor_for_edge(RoiEdge::TopLeft, &t), CursorShape::SizeNwse);
        assert_eq!(
            cursor_for_edge(RoiEdge::BottomRight, &t),
            CursorShape::SizeNwse
        );
        assert_eq!(
            cursor_for_edge(RoiEdge::TopRight, &t),
            CursorShape::SizeNesw
        );
        assert_eq!(
            cursor_for_edge(RoiEdge::BottomLeft, &t),
            CursorShape::SizeNesw
        );
        // Free vertex -> SizeAll.
        assert_eq!(
            cursor_for_edge(RoiEdge::Vertex(0), &t),
            CursorShape::SizeAll
        );
        assert_eq!(
            cursor_for_edge(RoiEdge::Vertex(7), &t),
            CursorShape::SizeAll
        );
    }

    #[test]
    fn cursor_shape_corner_diagonal_flips_under_single_axis_inversion() {
        // The corner cursor reflects the SCREEN diagonal. On an inverted-Y image
        // plot the data TopLeft corner (x.min, y.max) is drawn at screen
        // bottom-left, whose diagonal is ↗↙ (SizeNesw), not ↘↖ — so the corner
        // cursors swap. Sides stay axis-symmetric. (This was the user-reported
        // "코너 화살표 방향이 90도 틀어짐" under inverted Y.)
        let mut inv_y = pick_transform();
        inv_y.y.inverted = true;
        assert_eq!(
            cursor_for_edge(RoiEdge::TopLeft, &inv_y),
            CursorShape::SizeNesw
        );
        assert_eq!(
            cursor_for_edge(RoiEdge::BottomRight, &inv_y),
            CursorShape::SizeNesw
        );
        assert_eq!(
            cursor_for_edge(RoiEdge::TopRight, &inv_y),
            CursorShape::SizeNwse
        );
        assert_eq!(
            cursor_for_edge(RoiEdge::BottomLeft, &inv_y),
            CursorShape::SizeNwse
        );
        // Sides unaffected by inversion.
        assert_eq!(cursor_for_edge(RoiEdge::Left, &inv_y), CursorShape::SizeHor);
        assert_eq!(cursor_for_edge(RoiEdge::Top, &inv_y), CursorShape::SizeVer);

        // Both axes inverted: the two mirrors cancel, diagonals return to the
        // non-inverted mapping.
        let mut inv_xy = pick_transform();
        inv_xy.x.inverted = true;
        inv_xy.y.inverted = true;
        assert_eq!(
            cursor_for_edge(RoiEdge::TopLeft, &inv_xy),
            CursorShape::SizeNwse
        );
        assert_eq!(
            cursor_for_edge(RoiEdge::TopRight, &inv_xy),
            CursorShape::SizeNesw
        );
    }

    #[test]
    fn cursor_for_grab_defaults_when_nothing_grabbed() {
        let t = pick_transform();
        // None -> Default (nothing under the cursor).
        assert_eq!(cursor_for_grab(None, &t), CursorShape::Default);
        // Some(edge) -> that edge's shape.
        assert_eq!(
            cursor_for_grab(Some(RoiEdge::Left), &t),
            CursorShape::SizeHor
        );
    }

    #[test]
    fn cursor_shape_maps_to_egui_icon() {
        assert_eq!(
            CursorShape::SizeHor.to_egui(),
            egui::CursorIcon::ResizeHorizontal
        );
        assert_eq!(
            CursorShape::SizeVer.to_egui(),
            egui::CursorIcon::ResizeVertical
        );
        assert_eq!(
            CursorShape::SizeNwse.to_egui(),
            egui::CursorIcon::ResizeNwSe
        );
        assert_eq!(
            CursorShape::SizeNesw.to_egui(),
            egui::CursorIcon::ResizeNeSw
        );
        assert_eq!(CursorShape::SizeAll.to_egui(), egui::CursorIcon::Move);
        assert_eq!(CursorShape::Default.to_egui(), egui::CursorIcon::Default);
    }

    #[test]
    fn mouse_button_maps_from_egui() {
        assert_eq!(
            MouseButton::from_egui(egui::PointerButton::Primary),
            MouseButton::Left
        );
        assert_eq!(
            MouseButton::from_egui(egui::PointerButton::Middle),
            MouseButton::Middle
        );
        assert_eq!(
            MouseButton::from_egui(egui::PointerButton::Secondary),
            MouseButton::Right
        );
        // egui's extra buttons collapse to Right (silx has only three buttons).
        assert_eq!(
            MouseButton::from_egui(egui::PointerButton::Extra1),
            MouseButton::Right
        );
    }

    #[test]
    fn pointer_event_maps_pixel_to_data() {
        // 100x100 px over data [0,10]: center pixel (50,50) -> data (5,5).
        let t = pick_transform();
        let ev = PlotPointerEvent::clicked(MouseButton::Left, &t, pos2(50.0, 50.0));
        match ev {
            PlotPointerEvent::Clicked {
                button,
                data,
                pixel,
            } => {
                assert_eq!(button, MouseButton::Left);
                assert!(
                    (data.0 - 5.0).abs() <= 1e-9 && (data.1 - 5.0).abs() <= 1e-9,
                    "{data:?}"
                );
                assert_eq!(pixel, (50.0, 50.0));
            }
            other => panic!("expected Clicked, got {other:?}"),
        }
        // Corner: bottom-left pixel (0,100) -> data (0,0).
        let ev = PlotPointerEvent::double_clicked(MouseButton::Left, &t, pos2(0.0, 100.0));
        match ev {
            PlotPointerEvent::DoubleClicked { data, pixel, .. } => {
                assert!(data.0.abs() <= 1e-9 && data.1.abs() <= 1e-9, "{data:?}");
                assert_eq!(pixel, (0.0, 100.0));
            }
            other => panic!("expected DoubleClicked, got {other:?}"),
        }
    }

    #[test]
    fn pointer_event_moved_carries_optional_button() {
        let t = pick_transform();
        // Bare hover: no held button.
        let ev = PlotPointerEvent::moved(None, &t, pos2(50.0, 50.0));
        assert!(matches!(ev, PlotPointerEvent::Moved { button: None, .. }));
        // Held button during a move.
        let ev = PlotPointerEvent::moved(Some(MouseButton::Left), &t, pos2(50.0, 50.0));
        assert!(matches!(
            ev,
            PlotPointerEvent::Moved {
                button: Some(MouseButton::Left),
                ..
            }
        ));
    }

    #[test]
    fn limits_changed_carries_ranges() {
        let ev = PlotPointerEvent::limits_changed((0.0, 10.0), (1.0, 5.0), Some((2.0, 8.0)));
        assert_eq!(
            ev,
            PlotPointerEvent::LimitsChanged {
                x: (0.0, 10.0),
                y: (1.0, 5.0),
                y2: Some((2.0, 8.0)),
            }
        );
        // No y2 axis -> None.
        let ev = PlotPointerEvent::limits_changed((0.0, 10.0), (1.0, 5.0), None);
        assert!(matches!(
            ev,
            PlotPointerEvent::LimitsChanged { y2: None, .. }
        ));
    }

    #[test]
    fn nearest_point_picks_closest_within_threshold() {
        let t = pick_transform();
        let pts = [(0.0, 0.0), (5.0, 5.0), (10.0, 10.0)];
        // (5,5) -> pixel (50, 50). Cursor a few px away picks index 1.
        let pick = nearest_point(&pts, &t, pos2(52.0, 47.0), 6.0).expect("a pick");
        assert_eq!(pick.index, 1);
        assert_eq!((pick.x, pick.y), (5.0, 5.0));
        // Nothing within threshold -> None.
        assert!(nearest_point(&pts, &t, pos2(52.0, 47.0), 2.0).is_none());
        assert!(nearest_point(&[], &t, pos2(0.0, 0.0), 100.0).is_none());
    }

    #[test]
    fn clamp_axis_leaves_normal_range_untouched() {
        // A normal in-range linear range is returned unchanged.
        assert_eq!(clamp_axis_limits(-3.0, 5.0, false), (-3.0, 5.0));
        // A normal in-range positive log range is returned unchanged.
        assert_eq!(clamp_axis_limits(1.0, 1000.0, true), (1.0, 1000.0));
    }

    #[test]
    fn clamp_axis_clamps_beyond_safe_values() {
        // Boundary: a max beyond FLOAT32_SAFE_MAX clamps to it.
        let (lo, hi) = clamp_axis_limits(0.0, 1e40, false);
        assert_eq!((lo, hi), (0.0, FLOAT32_SAFE_MAX));
        // Boundary: a min below FLOAT32_SAFE_MIN clamps to it (linear).
        let (lo, hi) = clamp_axis_limits(-1e40, 5.0, false);
        assert_eq!((lo, hi), (FLOAT32_SAFE_MIN, 5.0));
        // Boundary: a non-positive min on a log axis clamps up to FLOAT32_MINPOS.
        let (lo, hi) = clamp_axis_limits(-10.0, 1000.0, true);
        assert_eq!((lo, hi), (FLOAT32_MINPOS, 1000.0));
    }

    #[test]
    fn clamp_axis_swaps_inverted_bounds() {
        // Boundary: max < min after clamping is swapped to ordered.
        let (lo, hi) = clamp_axis_limits(5.0, -3.0, false);
        assert_eq!((lo, hi), (-3.0, 5.0));
    }

    #[test]
    fn clamp_axis_expands_equal_bounds() {
        // v == 0 -> (-0.1, 0.1).
        assert_eq!(clamp_axis_limits(0.0, 0.0, false), (-0.1, 0.1));
        // v > 0 -> (v*0.9, v*1.1).
        let (lo, hi) = clamp_axis_limits(10.0, 10.0, false);
        assert!(
            (lo - 9.0).abs() <= 1e-12 && (hi - 11.0).abs() <= 1e-12,
            "{lo},{hi}"
        );
        // v < 0 -> (v*1.1, v*0.9).
        let (lo, hi) = clamp_axis_limits(-10.0, -10.0, false);
        assert!(
            (lo - -11.0).abs() <= 1e-12 && (hi - -9.0).abs() <= 1e-12,
            "{lo},{hi}"
        );
    }

    #[test]
    fn clamp_axis_nan_falls_to_lower_bound() {
        // Boundary: a NaN bound maps to the lower bound, keeping the range finite.
        let (lo, hi) = clamp_axis_limits(f64::NAN, 5.0, false);
        assert!(lo.is_finite() && hi.is_finite());
        assert_eq!((lo, hi), (FLOAT32_SAFE_MIN, 5.0));
        // Both NaN -> both fall to lower, then equal-expansion kicks in.
        let (lo, hi) = clamp_axis_limits(f64::NAN, f64::NAN, true);
        assert!(lo.is_finite() && hi.is_finite() && hi > lo, "{lo},{hi}");
    }

    #[test]
    fn clamp_limits_clamps_both_axes() {
        let out = clamp_limits((-1e40, 1e40, 0.0, 0.0), false, false);
        assert_eq!(out.0, FLOAT32_SAFE_MIN);
        assert_eq!(out.1, FLOAT32_SAFE_MAX);
        // Degenerate y expands.
        assert_eq!((out.2, out.3), (-0.1, 0.1));
    }

    #[test]
    fn image_index_maps_cursor_to_pixel() {
        // 10×10 image, origin (0,0), unit scale, over data [0,10] in a 100px area.
        let t = pick_transform();
        // Data (0,0) is bottom-left -> pixel (0, 100). Pixel (5,95) -> data ~(0.5, 0.5)
        // -> col 0, row 0.
        assert_eq!(
            image_index(&t, (0.0, 0.0), (1.0, 1.0), (10, 10), pos2(5.0, 95.0)),
            Some((0, 0))
        );
        // Center pixel (55, 45) -> data (5.5, 5.5) -> col 5, row 5.
        assert_eq!(
            image_index(&t, (0.0, 0.0), (1.0, 1.0), (10, 10), pos2(55.0, 45.0)),
            Some((5, 5))
        );
        // Outside the data area maps outside the image.
        assert!(image_index(&t, (0.0, 0.0), (1.0, 1.0), (10, 10), pos2(-5.0, 50.0)).is_none());
    }

    #[test]
    fn marker_cursor_reflects_drag_dof() {
        // VLine moves in X only -> SizeHor.
        assert_eq!(marker_cursor(&Marker::vline(3.0)), CursorShape::SizeHor);
        // HLine moves in Y only -> SizeVer.
        assert_eq!(marker_cursor(&Marker::hline(3.0)), CursorShape::SizeVer);
        // Free point moves in both -> SizeAll.
        let p = Marker::point(1.0, 2.0);
        assert_eq!(marker_cursor(&p), CursorShape::SizeAll);
        // Point + Horizontal constraint pins X, leaving Y free -> SizeVer.
        let ph = Marker::point(1.0, 2.0).with_constraint(MarkerConstraint::Horizontal);
        assert_eq!(marker_cursor(&ph), CursorShape::SizeVer);
        // Point + Vertical constraint pins Y, leaving X free -> SizeHor.
        let pv = Marker::point(1.0, 2.0).with_constraint(MarkerConstraint::Vertical);
        assert_eq!(marker_cursor(&pv), CursorShape::SizeHor);
    }

    #[test]
    fn marker_at_returns_topmost_draggable_index() {
        let t = pick_transform();
        // Two draggable points stacked at the same spot (data (5,5) -> pixel
        // (50,50)); the later one (higher z, drawn last) wins.
        let markers = vec![
            Marker::point(5.0, 5.0).with_draggable(true),
            Marker::point(5.0, 5.0).with_draggable(true),
        ];
        assert_eq!(marker_at(&markers, &t, pos2(50.0, 50.0)), Some(1));
    }

    #[test]
    fn marker_at_skips_non_draggable_even_when_hit() {
        let t = pick_transform();
        // The topmost marker is hit but not draggable; it is skipped and the
        // draggable one below it is returned.
        let markers = vec![
            Marker::point(5.0, 5.0).with_draggable(true),
            Marker::point(5.0, 5.0), // is_draggable == false
        ];
        assert_eq!(marker_at(&markers, &t, pos2(50.0, 50.0)), Some(0));
    }

    #[test]
    fn marker_at_none_when_nothing_hit() {
        let t = pick_transform();
        let markers = vec![Marker::point(5.0, 5.0).with_draggable(true)];
        // Cursor far from the marker: no hit.
        assert_eq!(marker_at(&markers, &t, pos2(90.0, 10.0)), None);
        // Empty list: no hit.
        assert_eq!(marker_at(&[], &t, pos2(50.0, 50.0)), None);
    }

    // --- on-plot ROI creation: roi_draw_mode + roi_from_draw + DrawMode::Point ---

    #[test]
    fn roi_draw_mode_per_kind() {
        use DrawMode as D;
        use RoiDrawKind as K;
        assert_eq!(roi_draw_mode(K::Rect), D::Rectangle);
        assert_eq!(roi_draw_mode(K::Ellipse), D::Ellipse);
        assert_eq!(roi_draw_mode(K::Polygon), D::Polygon);
        assert_eq!(roi_draw_mode(K::Point), D::Point);
        assert_eq!(roi_draw_mode(K::Cross), D::Point);
        // The six 2-point "line"-drag kinds.
        assert_eq!(roi_draw_mode(K::Line), D::Line);
        assert_eq!(roi_draw_mode(K::Circle), D::Line);
        assert_eq!(roi_draw_mode(K::HRange), D::Line);
        assert_eq!(roi_draw_mode(K::VRange), D::Line);
        assert_eq!(roi_draw_mode(K::Arc), D::Line);
        assert_eq!(roi_draw_mode(K::Band), D::Line);
    }

    #[test]
    fn draw_mode_point_finishes_on_press() {
        // silx _plotShape "point": a single press finishes immediately with the
        // captured data position; no move/release needed, phase stays idle.
        let mut s = DrawState::new(DrawMode::Point);
        let ev = s.on_press(di((3.5, 7.25), (35.0, 27.5))).expect("finished");
        assert_eq!(
            ev,
            DrawEvent::Finished {
                mode: DrawMode::Point,
                params: DrawParams::Point { x: 3.5, y: 7.25 },
            }
        );
        // Not active afterwards; move/release are no-ops; no preview.
        assert!(!s.is_active());
        assert!(s.on_move(di((9.0, 9.0), (90.0, 90.0))).is_none());
        assert!(s.on_release(di((9.0, 9.0), (90.0, 90.0))).is_none());
        assert!(s.preview().is_none());
    }

    // roi_from_draw: ONE assertion per kind (all 11), exact geometry.

    #[test]
    fn roi_from_draw_rect() {
        let p = DrawParams::Rectangle {
            x: 2.0,
            y: 1.0,
            width: 6.0,
            height: 8.0,
        };
        assert_eq!(
            roi_from_draw(RoiDrawKind::Rect, &p),
            Some(Roi::Rect {
                x: (2.0, 8.0),
                y: (1.0, 9.0),
            })
        );
    }

    #[test]
    fn roi_from_draw_line() {
        let p = DrawParams::Line {
            start: (1.0, 2.0),
            end: (3.0, 4.0),
        };
        assert_eq!(
            roi_from_draw(RoiDrawKind::Line, &p),
            Some(Roi::Line {
                start: (1.0, 2.0),
                end: (3.0, 4.0),
            })
        );
    }

    #[test]
    fn roi_from_draw_polygon() {
        let p = DrawParams::Polygon {
            vertices: vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0)],
        };
        assert_eq!(
            roi_from_draw(RoiDrawKind::Polygon, &p),
            Some(Roi::Polygon {
                vertices: vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0)],
            })
        );
    }

    #[test]
    fn roi_from_draw_point() {
        let p = DrawParams::Point { x: 5.0, y: 6.0 };
        assert_eq!(
            roi_from_draw(RoiDrawKind::Point, &p),
            Some(Roi::Point { x: 5.0, y: 6.0 })
        );
    }

    #[test]
    fn roi_from_draw_cross() {
        // Cross consumes the same Point params, producing a Cross center.
        let p = DrawParams::Point { x: 5.0, y: 6.0 };
        assert_eq!(
            roi_from_draw(RoiDrawKind::Cross, &p),
            Some(Roi::Cross { center: (5.0, 6.0) })
        );
    }

    #[test]
    fn roi_from_draw_ellipse_radii_are_semi_axes() {
        let p = DrawParams::Ellipse {
            center: (1.0, 2.0),
            semi_axes: (4.0, 2.5),
        };
        assert_eq!(
            roi_from_draw(RoiDrawKind::Ellipse, &p),
            Some(Roi::Ellipse {
                center: (1.0, 2.0),
                radii: (4.0, 2.5),
            })
        );
    }

    #[test]
    fn roi_from_draw_circle_radius_is_distance() {
        // silx CircleROI._setRay: center = start, radius = |end - start|.
        let p = DrawParams::Line {
            start: (1.0, 1.0),
            end: (4.0, 5.0), // distance = sqrt(9+16) = 5
        };
        match roi_from_draw(RoiDrawKind::Circle, &p).expect("circle") {
            Roi::Circle { center, radius } => {
                assert_eq!(center, (1.0, 1.0));
                assert!((radius - 5.0).abs() <= 1e-12, "{radius}");
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn roi_from_draw_hrange_orders_ys() {
        // y descending in the drag -> ordered (min, max).
        let p = DrawParams::Line {
            start: (1.0, 7.0),
            end: (9.0, 3.0),
        };
        assert_eq!(
            roi_from_draw(RoiDrawKind::HRange, &p),
            Some(Roi::HRange { y: (3.0, 7.0) })
        );
    }

    #[test]
    fn roi_from_draw_vrange_orders_xs() {
        // x descending in the drag -> ordered (min, max).
        let p = DrawParams::Line {
            start: (8.0, 1.0),
            end: (2.0, 9.0),
        };
        assert_eq!(
            roi_from_draw(RoiDrawKind::VRange, &p),
            Some(Roi::VRange { x: (2.0, 8.0) })
        );
    }

    #[test]
    fn roi_from_draw_band_default_width_is_tenth_of_length() {
        // silx BandGeometry.create default width = 0.1 * |end - begin|.
        let p = DrawParams::Line {
            start: (0.0, 0.0),
            end: (10.0, 0.0), // length 10 -> width 1.0
        };
        match roi_from_draw(RoiDrawKind::Band, &p).expect("band") {
            Roi::Band { begin, end, width } => {
                assert_eq!(begin, (0.0, 0.0));
                assert_eq!(end, (10.0, 0.0));
                assert!((width - 1.0).abs() <= 1e-12, "{width}");
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn roi_from_draw_arc_matches_silx_default() {
        // Faithful silx ArcROI default from diameter points (0,0)->(4,0).
        // Reference values computed by replaying ArcROI.setFirstShapePoints +
        // _createGeometryFromControlPoints + getGeometry (items/_arc_roi.py).
        let p = DrawParams::Line {
            start: (0.0, 0.0),
            end: (4.0, 0.0),
        };
        match roi_from_draw(RoiDrawKind::Arc, &p).expect("arc") {
            Roi::Arc {
                center,
                inner_radius,
                outer_radius,
                start_angle,
                end_angle,
            } => {
                assert!((center.0 - 2.0).abs() <= 1e-9, "cx={}", center.0);
                assert!(
                    (center.1 - (-0.9632309002009949)).abs() <= 1e-9,
                    "cy={}",
                    center.1
                );
                assert!(
                    (inner_radius - 1.8198679616369122).abs() <= 1e-9,
                    "inner={inner_radius}"
                );
                assert!(
                    (outer_radius - 2.619867961636912).abs() <= 1e-9,
                    "outer={outer_radius}"
                );
                assert!(
                    (start_angle - 2.692760559012144).abs() <= 1e-9,
                    "start={start_angle}"
                );
                assert!(
                    (end_angle - 0.4488320945776491).abs() <= 1e-9,
                    "end={end_angle}"
                );
            }
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn roi_from_draw_rejects_impossible_pairings() {
        // roi_draw_mode never pairs Rect with a Line params, etc. — such a pair
        // is dropped rather than mis-built.
        let line = DrawParams::Line {
            start: (0.0, 0.0),
            end: (1.0, 1.0),
        };
        assert_eq!(roi_from_draw(RoiDrawKind::Rect, &line), None);
        assert_eq!(roi_from_draw(RoiDrawKind::Point, &line), None);
        // An HLine params (no creation kind ever produces it) is dropped.
        let hline = DrawParams::HLine { y: 3.0 };
        assert_eq!(roi_from_draw(RoiDrawKind::HRange, &hline), None);
    }

    // --- roi_grab_at: edge wins over body, topmost wins, outside -> None ---

    #[test]
    fn roi_grab_at_edge_then_body_then_none() {
        let t = pick_transform();
        // Rect data x[2,8] y[3,7] -> screen left 20, right 80, top 30, bottom 70.
        let rois = vec![ManagedRoi::new(Roi::Rect {
            x: (2.0, 8.0),
            y: (3.0, 7.0),
        })];
        // Near the left edge -> Edge(Left).
        assert_eq!(
            roi_grab_at(&rois, &t, pos2(21.0, 50.0), 4.0),
            Some((0, RoiGrab::Edge(RoiEdge::Left)))
        );
        // Inside the body, away from any edge -> Translate.
        assert_eq!(
            roi_grab_at(&rois, &t, pos2(50.0, 50.0), 4.0),
            Some((0, RoiGrab::Translate))
        );
        // Fully outside the shape -> None.
        assert_eq!(roi_grab_at(&rois, &t, pos2(95.0, 95.0), 4.0), None);
    }

    #[test]
    fn roi_grab_at_topmost_wins_with_overlap() {
        let t = pick_transform();
        // Two overlapping rects covering the cursor's body region; the second
        // (drawn last, highest z) wins the translate grab.
        let rois = vec![
            ManagedRoi::new(Roi::Rect {
                x: (1.0, 9.0),
                y: (1.0, 9.0),
            }),
            ManagedRoi::new(Roi::Rect {
                x: (2.0, 8.0),
                y: (2.0, 8.0),
            }),
        ];
        // Cursor at data (5,5) -> pixel (50,50): inside both, away from edges.
        assert_eq!(
            roi_grab_at(&rois, &t, pos2(50.0, 50.0), 4.0),
            Some((1, RoiGrab::Translate))
        );
    }
}