eov-plugin-api 1.1.0

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

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::BTreeMap;

/// Host-assigned identifier of an open slide, stable for the session.
pub type FileId = i64;

/// Host-assigned, stable identifier of a viewer pane (not its position).
pub type PaneId = u32;

// ---------------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------------

/// Information handed to a plugin when it is created.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PluginInit {
    /// The plugin id from its manifest.
    pub plugin_id: String,
    /// The plugin version from its manifest.
    pub plugin_version: String,
    /// Host application name (`"eov"`).
    pub host_name: String,
    /// Host application version.
    pub host_version: String,
    /// The `eov-plugin-api` version the host was built with.
    pub api_version: String,
    /// Root of the extracted plugin package (read-only).
    pub plugin_root: String,
    /// Durable, writable per-plugin data directory (created by the host).
    pub data_dir: String,
    /// Disposable, writable per-plugin cache directory (created by the host).
    pub cache_dir: String,
    /// Persisted per-plugin settings (see `settings.*` methods).
    #[serde(default)]
    pub settings: Map<String, Value>,
    /// Where eov before 1.0 kept per-user files (e.g. `~/.config/eov`), for
    /// migrating data a plugin stored there. Read it; don't write it.
    #[serde(default)]
    pub legacy_config_dir: Option<String>,
    /// The plugin runs without a window, for `eov batch` (see
    /// [`methods::BATCH_REGISTER`]): toolbar buttons, tools, layers and
    /// surfaces are accepted but not shown, so skip expensive UI set-up.
    #[serde(default)]
    pub headless: bool,
    /// The language of eov's interface: a tag of
    /// [`crate::i18n::LANGUAGES`] (`"de"`, `"pt-BR"`, `"zh-Hant"`). `None`
    /// from hosts before plugin API 1.1, which are English only. The SDK loads the
    /// plugin's catalog for it before `Plugin::create` (see
    /// [`crate::i18n`]); later changes arrive as
    /// [`HostEvent::LanguageChanged`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
}

// ---------------------------------------------------------------------------
// Shared value types
// ---------------------------------------------------------------------------

/// An axis-aligned rectangle in level-0 pixels.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct Rect {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

/// One pyramid level of a slide.
///
/// `downsample` is the level-0 size divided by this level's size as the
/// format reports it. It is **not** always a power of two (Aperio pyramids
/// commonly go 1, 4, 16).
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct LevelInfo {
    pub level: u32,
    pub width: u64,
    pub height: u64,
    pub downsample: f64,
}

/// Metadata of an open slide.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileInfo {
    pub file_id: FileId,
    /// Path as text (lossy for non-UTF-8 paths; read pixels through the host).
    pub path: String,
    pub filename: String,
    /// Level-0 dimensions.
    pub width: u64,
    pub height: u64,
    #[serde(default)]
    pub levels: Vec<LevelInfo>,
    #[serde(default)]
    pub mpp_x: Option<f64>,
    #[serde(default)]
    pub mpp_y: Option<f64>,
    #[serde(default)]
    pub objective_power: Option<f64>,
    #[serde(default)]
    pub vendor: Option<String>,
    #[serde(default)]
    pub scan_date: Option<String>,
    /// Bounding box of the scanned area (`openslide.bounds-*`), if reported.
    #[serde(default)]
    pub bounds: Option<Rect>,
    /// A stable identity of the slide content (e.g. derived from
    /// `openslide.quickhash-1`), suitable as a database key.
    #[serde(default)]
    pub identity: Option<String>,
    /// Names of associated images (`label`, `macro`, `thumbnail`, …).
    #[serde(default)]
    pub associated_images: Vec<String>,
    /// The slide has an ICC colour profile. eov converts its colours to
    /// sRGB for display and export (unless the user turns that off, see
    /// [`DisplayAdjustments::color_managed`]); region reads and filter
    /// frames always carry the slide's own, unconverted colours.
    #[serde(default)]
    pub has_icc_profile: bool,
    /// Stain label parsed from slide metadata (e.g. `"H&E"`), if any.
    #[serde(default)]
    pub stain: Option<String>,
    /// Channel names of a multichannel slide (fluorescence or multiplexed
    /// immunofluorescence OME-TIFF), in file order; empty for RGB slides.
    ///
    /// Pixels from `read_region` are always RGBA: the visible channels
    /// composited with the colours, windows and gammas the user set in the
    /// Channels panel, the same image the viewer shows. Raw channel values
    /// are not available through plugin API 1.x.
    #[serde(default)]
    pub channel_names: Vec<String>,
}

/// The visible state of a pane showing a slide.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewInfo {
    pub pane: PaneId,
    pub file_id: FileId,
    /// Level-0 coordinates of the pane centre.
    pub center_x: f64,
    pub center_y: f64,
    /// Screen (logical) pixels per level-0 pixel.
    pub zoom: f64,
    /// Pane size in logical pixels.
    pub width: f64,
    pub height: f64,
    /// Physical pixels per logical pixel of the window.
    #[serde(default = "default_scale_factor")]
    pub scale_factor: f64,
    /// Clockwise view rotation in degrees, `0 <= rotation_deg < 360`: any
    /// angle (eov keeps it to a millionth of a degree; quarter turns are
    /// exactly 90, 180 and 270). Map points with
    /// [`image_to_screen`](Self::image_to_screen) and
    /// [`screen_to_image`](Self::screen_to_image); `visible` is the turned
    /// area's bounding box.
    #[serde(default)]
    pub rotation_deg: f64,
    /// The view is mirrored left to right, after the rotation.
    #[serde(default)]
    pub flipped: bool,
    /// Level-0 bounding box of the visible area.
    pub visible: Rect,
}

fn default_scale_factor() -> f64 {
    1.0
}

// `Default` is written out here, as for `MenuItem` and `ToolbarButtonSpec`,
// so that it is what a message leaving the optional fields out deserializes
// to: a derived one sets `false`/`0` where the wire format defaults to
// `true`/`1`, and plugins build their values with `..Default::default()`.
impl Default for ViewInfo {
    fn default() -> Self {
        Self {
            pane: Default::default(),
            file_id: Default::default(),
            center_x: 0.0,
            center_y: 0.0,
            zoom: 0.0,
            width: 0.0,
            height: 0.0,
            scale_factor: default_scale_factor(),
            rotation_deg: 0.0,
            flipped: false,
            visible: Rect::default(),
        }
    }
}

impl ViewInfo {
    /// An image-space direction as it points on the pane (rotation, then
    /// mirror).
    fn turn(&self, x: f64, y: f64) -> (f64, f64) {
        let (sin, cos) = self.rotation_deg.to_radians().sin_cos();
        let (tx, ty) = (x * cos - y * sin, x * sin + y * cos);
        if self.flipped { (-tx, ty) } else { (tx, ty) }
    }

    /// Logical pane position of level-0 point `(x, y)`, accounting for the
    /// view's rotation and mirror.
    pub fn image_to_screen(&self, x: f64, y: f64) -> (f64, f64) {
        let (dx, dy) = self.turn(x - self.center_x, y - self.center_y);
        (
            self.width / 2.0 + dx * self.zoom,
            self.height / 2.0 + dy * self.zoom,
        )
    }

    /// The level-0 point at logical pane position `(x, y)`.
    pub fn screen_to_image(&self, x: f64, y: f64) -> (f64, f64) {
        let zoom = if self.zoom > 0.0 { self.zoom } else { 1.0 };
        let (mut dx, dy) = (
            (x - self.width / 2.0) / zoom,
            (y - self.height / 2.0) / zoom,
        );
        if self.flipped {
            dx = -dx;
        }
        let (sin, cos) = (-self.rotation_deg).to_radians().sin_cos();
        (
            self.center_x + dx * cos - dy * sin,
            self.center_y + dx * sin + dy * cos,
        )
    }
}

/// One pane in display order.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PaneInfo {
    pub pane: PaneId,
    /// Position from the left, starting at 0.
    pub index: u32,
    #[serde(default)]
    pub file_id: Option<FileId>,
    #[serde(default)]
    pub view: Option<ViewInfo>,
}

/// Reference to a tool: the owning plugin (`None` for host tools) and its id.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ToolRef {
    #[serde(default)]
    pub plugin_id: Option<String>,
    pub tool_id: String,
}

/// A consistent, recent view of the host state.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct HostSnapshot {
    pub host_version: String,
    /// Whether an eov window has keyboard focus.
    #[serde(default)]
    pub window_focused: bool,
    #[serde(default)]
    pub render_backend: String,
    #[serde(default)]
    pub filtering_mode: String,
    #[serde(default)]
    pub focused_pane: Option<PaneId>,
    #[serde(default)]
    pub panes: Vec<PaneInfo>,
    #[serde(default)]
    pub files: Vec<FileInfo>,
    #[serde(default)]
    pub active_tool: Option<ToolRef>,
}

impl HostSnapshot {
    /// The view of the focused pane, if it shows a slide.
    pub fn focused_view(&self) -> Option<&ViewInfo> {
        let pane = self.focused_pane?;
        self.panes.iter().find(|p| p.pane == pane)?.view.as_ref()
    }

    /// Metadata of an open file.
    pub fn file(&self, file_id: FileId) -> Option<&FileInfo> {
        self.files.iter().find(|f| f.file_id == file_id)
    }
}

/// Keyboard modifiers held during an input event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Modifiers {
    #[serde(default)]
    pub shift: bool,
    /// The physical Control key.
    #[serde(default)]
    pub control: bool,
    #[serde(default)]
    pub alt: bool,
    /// Command (macOS) / Windows / Super key.
    #[serde(default)]
    pub meta: bool,
    /// The platform's command modifier: ⌘ on macOS, Control elsewhere.
    #[serde(default)]
    pub primary: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PointerButton {
    #[default]
    None,
    Left,
    Right,
    Middle,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PointerKind {
    Down,
    Move,
    Up,
    /// Second press of a double click (delivered after the matching `Down`).
    DoubleClick,
    Wheel,
    /// The pointer left the pane.
    Leave,
}

/// A pointer event for a plugin-owned custom tool.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct PointerEvent {
    pub kind: PointerKind,
    #[serde(default)]
    pub button: PointerButton,
    pub image_x: f64,
    pub image_y: f64,
    pub screen_x: f64,
    pub screen_y: f64,
    #[serde(default)]
    pub modifiers: Modifiers,
    /// Wheel delta in logical pixels (positive = away from the user).
    #[serde(default)]
    pub wheel_delta: f64,
}

/// A geometric shape in level-0 pixel coordinates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Shape {
    Point {
        x: f64,
        y: f64,
    },
    Polyline {
        points: Vec<[f64; 2]>,
    },
    Polygon {
        exterior: Vec<[f64; 2]>,
        #[serde(default)]
        holes: Vec<Vec<[f64; 2]>>,
    },
    Rectangle {
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    },
    Ellipse {
        cx: f64,
        cy: f64,
        rx: f64,
        ry: f64,
    },
    /// Text anchored at its top-left corner; drawn at a constant screen size
    /// (`Style::font_size`, `Style::text_color`).
    Text {
        x: f64,
        y: f64,
        text: String,
    },
}

impl Shape {
    /// Whether every coordinate is finite and the shape has enough vertices
    /// (polylines ≥ 2, polygon rings ≥ 3) and non-negative extents.
    pub fn is_valid(&self) -> bool {
        let finite = |p: &[f64; 2]| p[0].is_finite() && p[1].is_finite();
        match self {
            Shape::Point { x, y } | Shape::Text { x, y, .. } => x.is_finite() && y.is_finite(),
            Shape::Polyline { points } => points.len() >= 2 && points.iter().all(finite),
            Shape::Polygon { exterior, holes } => {
                exterior.len() >= 3
                    && exterior.iter().all(finite)
                    && holes
                        .iter()
                        .all(|ring| ring.len() >= 3 && ring.iter().all(finite))
            }
            Shape::Rectangle {
                x,
                y,
                width,
                height,
            } => {
                [x, y, width, height].iter().all(|v| v.is_finite())
                    && *width >= 0.0
                    && *height >= 0.0
            }
            Shape::Ellipse { cx, cy, rx, ry } => {
                [cx, cy, rx, ry].iter().all(|v| v.is_finite()) && *rx >= 0.0 && *ry >= 0.0
            }
        }
    }

    /// Level-0 bounding box. Text has a zero-size box at its anchor.
    pub fn bounds(&self) -> Rect {
        fn of_points<'a>(points: impl Iterator<Item = &'a [f64; 2]>) -> Rect {
            let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
            for p in points {
                x0 = x0.min(p[0]);
                y0 = y0.min(p[1]);
                x1 = x1.max(p[0]);
                y1 = y1.max(p[1]);
            }
            if x0 > x1 {
                return Rect::default();
            }
            Rect {
                x: x0,
                y: y0,
                width: x1 - x0,
                height: y1 - y0,
            }
        }
        match self {
            Shape::Point { x, y } | Shape::Text { x, y, .. } => Rect {
                x: *x,
                y: *y,
                width: 0.0,
                height: 0.0,
            },
            Shape::Polyline { points } => of_points(points.iter()),
            Shape::Polygon { exterior, .. } => of_points(exterior.iter()),
            Shape::Rectangle {
                x,
                y,
                width,
                height,
            } => Rect {
                x: *x,
                y: *y,
                width: *width,
                height: *height,
            },
            Shape::Ellipse { cx, cy, rx, ry } => Rect {
                x: cx - rx,
                y: cy - ry,
                width: rx * 2.0,
                height: ry * 2.0,
            },
        }
    }
}

/// Identifies an overlay object: a plugin-scoped layer id plus an object id.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ObjectRef {
    pub layer_id: String,
    pub object_id: String,
}

/// A vector object in an overlay layer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OverlayObject {
    /// Unique within the layer; upserting an existing id replaces it.
    pub object_id: String,
    pub shape: Shape,
    /// Overrides the layer style for this object.
    #[serde(default)]
    pub style: Option<Style>,
    /// Text drawn next to the object (constant screen size).
    #[serde(default)]
    pub label: Option<String>,
    /// The label as it is burned into exported images and copied views:
    /// English wording, Western digits and `.` decimals, Latin letters.
    /// Give it when `label` is translated (see [`crate::i18n`]): an image
    /// travels beyond the language it was made in, and eov draws its text
    /// with a font that has basic Latin and Greek letters only, so other
    /// letters would be left blank. When absent, `label` is used; without
    /// `label` nothing is drawn. Hosts before plugin API 1.1 ignore it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub export_label: Option<String>,
    /// Shown when the pointer rests on the object.
    #[serde(default)]
    pub tooltip: Option<String>,
    /// Overrides the layer's `editable` flag for this object.
    #[serde(default)]
    pub editable: Option<bool>,
}

impl OverlayObject {
    pub fn new(object_id: impl Into<String>, shape: Shape) -> Self {
        Self {
            object_id: object_id.into(),
            shape,
            style: None,
            label: None,
            export_label: None,
            tooltip: None,
            editable: None,
        }
    }

    pub fn with_style(mut self, style: Style) -> Self {
        self.style = Some(style);
        self
    }

    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// The label in English for exported images and copied views (see
    /// [`OverlayObject::export_label`]): give it with a translated label.
    ///
    /// ```
    /// use eov_plugin_api::i18n::{self, tr};
    /// use eov_plugin_api::protocol::{OverlayObject, Shape};
    ///
    /// let area = 0.2376;
    /// let object = OverlayObject::new("field", Shape::Point { x: 10.0, y: 20.0 })
    ///     // On screen, in the language of the interface.
    ///     .with_label(tr!("Field: {} mm²", i18n::format_decimal(area, 4)))
    ///     // In images, in English.
    ///     .with_export_label(format!(
    ///         "Field: {} mm²",
    ///         i18n::format_decimal_for(i18n::source(), area, 4)
    ///     ));
    /// assert_eq!(object.export_label.as_deref(), Some("Field: 0.2376 mm²"));
    /// ```
    pub fn with_export_label(mut self, label: impl Into<String>) -> Self {
        self.export_label = Some(label.into());
        self
    }

    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

    pub fn with_editable(mut self, editable: bool) -> Self {
        self.editable = Some(editable);
        self
    }
}

/// A measurement made with the host's measurement tools.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MeasurementInfo {
    pub measurement_id: String,
    pub file_id: FileId,
    pub shape: Shape,
    /// Length (lines/polylines) or perimeter (closed shapes) in µm, when the
    /// slide is calibrated.
    #[serde(default)]
    pub length_um: Option<f64>,
    /// Area in µm² for closed shapes, when calibrated.
    #[serde(default)]
    pub area_um2: Option<f64>,
    /// Angle in degrees for angle measurements.
    #[serde(default)]
    pub angle_deg: Option<f64>,
}

/// An entry of a menu (context menu, HUD drop-down). Enabled unless
/// `enabled` says otherwise, also when built with `..Default::default()`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MenuItem {
    pub item_id: String,
    pub label: String,
    /// Built-in icon name (`"copy"`, `"export"`, `"delete"`, `"point"`,
    /// `"measure"`, `"plugin"`, `"open"`) or empty; other names show none.
    #[serde(default)]
    pub icon: String,
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Draw a check mark (for toggles / radio groups).
    #[serde(default)]
    pub checked: Option<bool>,
    /// Display-only shortcut text (e.g. `"Del"`).
    #[serde(default)]
    pub shortcut: String,
    #[serde(default)]
    pub separator_after: bool,
}

fn default_true() -> bool {
    true
}

impl Default for MenuItem {
    fn default() -> Self {
        Self {
            item_id: String::new(),
            label: String::new(),
            icon: String::new(),
            enabled: default_true(),
            checked: None,
            shortcut: String::new(),
            separator_after: false,
        }
    }
}

/// The name of a key as [`Hotkey::key`] and [`ToolSpec::keys`] write it,
/// from the raw text of [`HostEvent::Key`]: a character in lower case
/// (`"a"`, `"+"`) or a named key (`"Escape"`, `"Enter"`, `"Tab"`,
/// `"Backspace"`, `"Delete"`, `"Space"`, `"ArrowLeft"`, `"F2"`, `"Home"`,
/// `"PageUp"`, …).
pub fn key_name(text: &str) -> String {
    let mut chars = text.chars();
    let (Some(c), None) = (chars.next(), chars.next()) else {
        return text.to_lowercase();
    };
    match c {
        '\u{8}' => "Backspace".into(),
        '\t' => "Tab".into(),
        '\n' | '\r' => "Enter".into(),
        '\u{1b}' => "Escape".into(),
        '\u{7f}' => "Delete".into(),
        ' ' => "Space".into(),
        '\u{F700}' => "ArrowUp".into(),
        '\u{F701}' => "ArrowDown".into(),
        '\u{F702}' => "ArrowLeft".into(),
        '\u{F703}' => "ArrowRight".into(),
        '\u{F704}'..='\u{F71B}' => format!("F{}", c as u32 - 0xF704 + 1),
        '\u{F729}' => "Home".into(),
        '\u{F72B}' => "End".into(),
        '\u{F72C}' => "PageUp".into(),
        '\u{F72D}' => "PageDown".into(),
        c => c.to_lowercase().collect(),
    }
}

/// A hotkey binding. `key` is a single character (case-insensitive) or a
/// named key such as `"F2"`, `"Delete"`, `"Escape"` (see [`key_name`]).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Hotkey {
    pub key: String,
    #[serde(default)]
    pub modifiers: Modifiers,
    /// Hold-to-use: the tool is active only while the key is held.
    #[serde(default)]
    pub momentary: bool,
}

/// A plugin key binding (see [`methods::HOTKEY_REGISTER`]).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct HotkeySpec {
    pub hotkey_id: String,
    pub hotkey: Hotkey,
    /// What the key does, for listings of key bindings.
    #[serde(default)]
    pub description: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LogLevel {
    Trace,
    Debug,
    #[default]
    Info,
    Warn,
    Error,
}

// ---------------------------------------------------------------------------
// Overlay styles and layers
// ---------------------------------------------------------------------------

/// An RGBA colour, each channel 0–255.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Rgba(pub u8, pub u8, pub u8, pub u8);

impl Rgba {
    pub const TRANSPARENT: Self = Self(0, 0, 0, 0);

    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self(r, g, b, 255)
    }

    pub const fn with_alpha(self, alpha: u8) -> Self {
        Self(self.0, self.1, self.2, alpha)
    }

    /// Packs into `0xRRGGBBAA`.
    pub const fn to_u32(self) -> u32 {
        ((self.0 as u32) << 24) | ((self.1 as u32) << 16) | ((self.2 as u32) << 8) | self.3 as u32
    }

    /// Unpacks `0xRRGGBBAA`.
    pub const fn from_u32(value: u32) -> Self {
        Self(
            (value >> 24) as u8,
            (value >> 16) as u8,
            (value >> 8) as u8,
            value as u8,
        )
    }

    /// Parses `#RRGGBB` or `#RRGGBBAA`.
    pub fn from_hex(text: &str) -> Option<Self> {
        let hex = text.strip_prefix('#')?;
        if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
            return None;
        }
        let byte = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
        match hex.len() {
            6 => Some(Self(byte(0)?, byte(2)?, byte(4)?, 255)),
            8 => Some(Self(byte(0)?, byte(2)?, byte(4)?, byte(6)?)),
            _ => None,
        }
    }

    pub fn to_hex(self) -> String {
        if self.3 == 255 {
            format!("#{:02X}{:02X}{:02X}", self.0, self.1, self.2)
        } else {
            format!("#{:02X}{:02X}{:02X}{:02X}", self.0, self.1, self.2, self.3)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Dash {
    #[default]
    Solid,
    Dashed,
    Dotted,
}

/// The unit an object's stroke width or point size is expressed in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SizeUnit {
    /// Logical screen pixels (constant on screen at every zoom).
    #[default]
    Screen,
    /// Micrometres on the slide (scales with zoom; needs MPP).
    Micrometre,
    /// Level-0 pixels (scales with zoom).
    Image,
}

/// Visual style of overlay objects.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Style {
    #[serde(default)]
    pub fill: Rgba,
    #[serde(default = "default_stroke")]
    pub stroke: Rgba,
    #[serde(default = "default_stroke_width")]
    pub stroke_width: f32,
    #[serde(default)]
    pub dash: Dash,
    /// Radius of point markers.
    #[serde(default = "default_point_radius")]
    pub point_radius: f32,
    /// Unit of `stroke_width` and `point_radius`.
    #[serde(default)]
    pub size_unit: SizeUnit,
    /// Text colour for labels and text objects.
    #[serde(default = "default_text_color")]
    pub text_color: Rgba,
    #[serde(default = "default_font_size")]
    pub font_size: f32,
}

fn default_stroke() -> Rgba {
    Rgba::rgb(0x2E, 0xCC, 0x71)
}
fn default_stroke_width() -> f32 {
    1.5
}
fn default_point_radius() -> f32 {
    5.0
}
fn default_text_color() -> Rgba {
    Rgba::rgb(255, 255, 255)
}
fn default_font_size() -> f32 {
    12.0
}

impl Default for Style {
    fn default() -> Self {
        Self {
            fill: Rgba::TRANSPARENT,
            stroke: default_stroke(),
            stroke_width: default_stroke_width(),
            dash: Dash::Solid,
            point_radius: default_point_radius(),
            size_unit: SizeUnit::Screen,
            text_color: default_text_color(),
            font_size: default_font_size(),
        }
    }
}

/// Declares an overlay layer. Layers belong to one open file and are drawn
/// only in panes showing it; they are discarded when the file closes.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LayerSpec {
    /// Plugin-scoped layer id. Ids are unique per plugin across all open
    /// slides, so include the file id when a layer exists for each slide
    /// (e.g. `format!("cells-{file_id}")`).
    pub layer_id: String,
    pub file_id: FileId,
    #[serde(default)]
    pub name: String,
    /// Draw order; higher is on top. Host layers use the range -100..=100.
    #[serde(default)]
    pub z: i32,
    #[serde(default = "default_true")]
    pub visible: bool,
    /// 0.0–1.0, applied to the whole layer.
    #[serde(default = "default_opacity")]
    pub opacity: f32,
    /// Objects can be hovered and clicked (`ObjectClicked`, `ObjectHovered`).
    #[serde(default)]
    pub interactive: bool,
    /// Objects flagged editable can be reshaped with the host's editing
    /// gestures (`ObjectEdited`).
    #[serde(default)]
    pub editable: bool,
    #[serde(default)]
    pub style: Style,
    /// Override used for selected objects (default: a highlight of `style`).
    #[serde(default)]
    pub selected_style: Option<Style>,
    /// Override used for the hovered object.
    #[serde(default)]
    pub hover_style: Option<Style>,
    /// Hide the layer below this zoom (screen px per level-0 px).
    #[serde(default)]
    pub min_zoom: Option<f64>,
}

fn default_opacity() -> f32 {
    1.0
}

impl LayerSpec {
    /// A visible, non-interactive layer with the default style.
    pub fn new(layer_id: impl Into<String>, file_id: FileId) -> Self {
        Self {
            layer_id: layer_id.into(),
            file_id,
            name: String::new(),
            z: 0,
            visible: true,
            opacity: 1.0,
            interactive: false,
            editable: false,
            style: Style::default(),
            selected_style: None,
            hover_style: None,
            min_zoom: None,
        }
    }

    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    pub fn with_style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    pub fn interactive(mut self, interactive: bool) -> Self {
        self.interactive = interactive;
        self
    }

    pub fn editable(mut self, editable: bool) -> Self {
        self.editable = editable;
        self
    }

    pub fn at_z(mut self, z: i32) -> Self {
        self.z = z;
        self
    }
}

/// Partial update of a layer; `None` leaves a field unchanged.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct LayerUpdate {
    pub layer_id: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub z: Option<i32>,
    #[serde(default)]
    pub visible: Option<bool>,
    #[serde(default)]
    pub opacity: Option<f32>,
    #[serde(default)]
    pub interactive: Option<bool>,
    #[serde(default)]
    pub editable: Option<bool>,
    #[serde(default)]
    pub style: Option<Style>,
    #[serde(default)]
    pub selected_style: Option<Style>,
    #[serde(default)]
    pub hover_style: Option<Style>,
}

// ---------------------------------------------------------------------------
// UI contributions
// ---------------------------------------------------------------------------

/// A button in the main window toolbar. Enabled unless `enabled` says
/// otherwise, also when built with `..Default::default()`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolbarButtonSpec {
    pub button_id: String,
    pub tooltip: String,
    /// Inline SVG.
    pub icon_svg: String,
    #[serde(default)]
    pub toggled_icon_svg: Option<String>,
    /// Render as active/pressed.
    #[serde(default)]
    pub active: bool,
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Optional hotkey that clicks the button.
    #[serde(default)]
    pub hotkey: Option<Hotkey>,
    /// Ordering among this plugin's buttons.
    #[serde(default)]
    pub order: i32,
}

impl Default for ToolbarButtonSpec {
    fn default() -> Self {
        Self {
            button_id: String::new(),
            tooltip: String::new(),
            icon_svg: String::new(),
            toggled_icon_svg: None,
            active: false,
            enabled: default_true(),
            hotkey: None,
            order: 0,
        }
    }
}

/// Partial update of a toolbar or HUD button.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ButtonUpdate {
    pub button_id: String,
    /// Restrict the update to one pane (HUD buttons only).
    #[serde(default)]
    pub pane: Option<PaneId>,
    #[serde(default)]
    pub active: Option<bool>,
    #[serde(default)]
    pub enabled: Option<bool>,
    #[serde(default)]
    pub tooltip: Option<String>,
    #[serde(default)]
    pub icon_svg: Option<String>,
    #[serde(default)]
    pub menu: Option<Vec<MenuItem>>,
}

/// A button in every viewport's HUD toolbar. When `menu` is non-empty the
/// button opens a drop-down and clicks report the chosen `item_id`.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct HudButtonSpec {
    pub button_id: String,
    pub tooltip: String,
    pub icon_svg: String,
    #[serde(default)]
    pub toggled_icon_svg: Option<String>,
    #[serde(default)]
    pub active: bool,
    #[serde(default)]
    pub menu: Vec<MenuItem>,
    #[serde(default)]
    pub order: i32,
}

/// What the host does while a tool is active.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolKind {
    /// Click places a point → `ShapeDrawn(Point)`.
    Point,
    /// Click adds vertices, double-click/Enter finishes → `Polyline`.
    Polyline,
    /// Click adds vertices; clicking the first vertex, double-click or Enter
    /// closes → `Polygon`.
    Polygon,
    /// Drag a rectangle → `Rectangle`.
    Rectangle,
    /// Drag an ellipse → `Ellipse`.
    Ellipse,
    /// Drag a free-hand outline (simplified) → `Polygon`.
    Freehand,
    /// No host gestures: the plugin receives raw `Pointer`/`Key` events.
    Custom,
    /// No drawing; clicks select objects and enable host editing gestures
    /// on the plugin's editable layers.
    Select,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Cursor {
    #[default]
    Default,
    Crosshair,
    Pointer,
    Move,
    Text,
    NotAllowed,
}

/// A tool contributed by a plugin. It appears in the toolbar's tool group.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolSpec {
    pub tool_id: String,
    pub label: String,
    pub icon_svg: String,
    pub kind: ToolKind,
    #[serde(default)]
    pub hotkey: Option<Hotkey>,
    #[serde(default)]
    pub cursor: Cursor,
    /// Layers (of this plugin) whose editable objects may be reshaped while
    /// the tool is active. Empty = all of the plugin's editable layers.
    #[serde(default)]
    pub edit_layers: Vec<String>,
    /// Style of the in-progress shape preview.
    #[serde(default)]
    pub preview_style: Option<Style>,
    /// Douglas–Peucker tolerance (screen px) for `Freehand`.
    #[serde(default = "default_freehand_tolerance")]
    pub freehand_tolerance_px: f32,
    #[serde(default)]
    pub order: i32,
    /// For a `Custom` tool: the keys it handles, by [`key_name`]
    /// (case-insensitive). Other keys keep working as they do without the
    /// tool (eov's shortcuts, other tools' keys, plugin hotkeys; Escape
    /// leaves the tool). Unset: the tool gets every key but Tab and
    /// Ctrl/⌘ shortcuts.
    #[serde(default)]
    pub keys: Option<Vec<String>>,
}

fn default_freehand_tolerance() -> f32 {
    1.5
}

impl ToolSpec {
    pub fn new(
        tool_id: impl Into<String>,
        label: impl Into<String>,
        icon_svg: impl Into<String>,
        kind: ToolKind,
    ) -> Self {
        Self {
            tool_id: tool_id.into(),
            label: label.into(),
            icon_svg: icon_svg.into(),
            kind,
            hotkey: None,
            cursor: Cursor::Crosshair,
            edit_layers: Vec::new(),
            preview_style: None,
            freehand_tolerance_px: default_freehand_tolerance(),
            order: 0,
            keys: None,
        }
    }

    pub fn with_hotkey(mut self, hotkey: Hotkey) -> Self {
        self.hotkey = Some(hotkey);
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SurfaceKind {
    /// Docked panel at the side of the main window (one visible at a time).
    Sidebar,
    /// Separate top-level window.
    Window,
    /// Modal dialog over the main window.
    Modal,
}

/// A Slint UI surface. `ui_path` is relative to the plugin root.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SurfaceSpec {
    pub kind: SurfaceKind,
    pub ui_path: String,
    pub component: String,
    /// A window's title, like its minimum size, is its component's: inherit
    /// `Window` and set `title`, `min-width` and `min-height` there. eov 1.x
    /// only passes this to a `title` property the component declares, if any.
    #[serde(default)]
    pub title: Option<String>,
    /// Preferred size in logical pixels (sidebar: width only). Windows are
    /// never opened larger than eov's main window.
    #[serde(default)]
    pub width: Option<f32>,
    #[serde(default)]
    pub height: Option<f32>,
    /// Unused by eov 1.x (see `title`).
    #[serde(default)]
    pub min_width: Option<f32>,
    /// Unused by eov 1.x (see `title`).
    #[serde(default)]
    pub min_height: Option<f32>,
    /// Initial property values (by Slint property name).
    #[serde(default)]
    pub properties: Map<String, Value>,
    /// Keep keyboard shortcuts away from the host while this surface has
    /// keyboard focus (text entry).
    #[serde(default = "default_true")]
    pub capture_keyboard: bool,
}

impl SurfaceSpec {
    /// A surface showing `component` from `ui_path` (relative to the plugin
    /// root).
    pub fn new(
        kind: SurfaceKind,
        ui_path: impl Into<String>,
        component: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            ui_path: ui_path.into(),
            component: component.into(),
            title: None,
            width: None,
            height: None,
            min_width: None,
            min_height: None,
            properties: Map::new(),
            capture_keyboard: true,
        }
    }

    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn with_size(mut self, width: f32, height: Option<f32>) -> Self {
        self.width = Some(width);
        self.height = height;
        self
    }

    pub fn with_property(mut self, name: impl Into<String>, value: Value) -> Self {
        self.properties.insert(name.into(), value);
        self
    }
}

impl Hotkey {
    /// A plain key without modifiers.
    pub fn key(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            modifiers: Modifiers::default(),
            momentary: false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileFilter {
    pub name: String,
    /// Extensions without the leading dot.
    pub extensions: Vec<String>,
}

/// A viewport filter (CPU post-processing of rendered frames).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FilterSpec {
    /// Plugin-scoped filter id.
    pub filter_id: String,
    pub name: String,
    /// Lower runs first. Ties are broken by plugin id, then filter id.
    #[serde(default)]
    pub priority: i32,
    #[serde(default)]
    pub enabled: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NotifyLevel {
    #[default]
    Info,
    Success,
    Warning,
    Error,
}

// ---------------------------------------------------------------------------
// Host → plugin events
// ---------------------------------------------------------------------------

/// Messages the host sends to a plugin's `handle_event`.
///
/// Unless documented otherwise the response is ignored (return `null`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum HostEvent {
    /// The host finished starting up; every plugin has been created and the
    /// main window exists. Restore surfaces and layers here.
    Ready {
        /// This plugin's sidebar was open when eov last exited; re-open it
        /// to restore the user's layout.
        #[serde(default)]
        restore_sidebar: bool,
    },
    /// The application is exiting. Flush state; no further events follow.
    Shutdown,
    FileOpened {
        file: FileInfo,
    },
    /// The file is closed; its layers were discarded.
    FileClosed {
        file_id: FileId,
    },
    /// The focused pane changed, or the file shown in it.
    ActiveChanged {
        #[serde(default)]
        pane: Option<PaneId>,
        #[serde(default)]
        file_id: Option<FileId>,
    },
    /// A pane's view settled after navigation (debounced).
    ViewChanged {
        view: ViewInfo,
    },
    WindowFocusChanged {
        focused: bool,
    },
    ToolbarButtonClicked {
        button_id: String,
    },
    HudButtonClicked {
        button_id: String,
        #[serde(default)]
        item_id: Option<String>,
        pane: PaneId,
        #[serde(default)]
        view: Option<ViewInfo>,
    },
    /// The context menu is opening. Respond with [`ContextMenuResponse`].
    ContextMenuRequested(MenuContext),
    /// One of the plugin's context-menu items was chosen.
    ContextMenuItemSelected {
        item_id: String,
        context: MenuContext,
    },
    ToolActivated {
        tool_id: String,
    },
    ToolDeactivated {
        tool_id: String,
    },
    /// A host-drawn shape for one of the plugin's tools was completed.
    ShapeDrawn {
        tool_id: String,
        pane: PaneId,
        file_id: FileId,
        shape: Shape,
        #[serde(default)]
        modifiers: Modifiers,
    },
    /// Raw pointer input for an active `Custom` tool.
    Pointer {
        tool_id: String,
        pane: PaneId,
        file_id: FileId,
        event: PointerEvent,
    },
    /// Key input for an active `Custom` tool, or a plugin hotkey. `key` is
    /// the raw key text; [`key_name`] names it.
    Key {
        #[serde(default)]
        tool_id: Option<String>,
        #[serde(default)]
        pane: Option<PaneId>,
        key: String,
        #[serde(default)]
        modifiers: Modifiers,
        pressed: bool,
        #[serde(default)]
        repeat: bool,
    },
    ObjectClicked {
        object: ObjectRef,
        pane: PaneId,
        #[serde(default)]
        button: PointerButton,
        #[serde(default)]
        modifiers: Modifiers,
        /// 1 for a click, 2 for a double click.
        #[serde(default = "default_click_count")]
        click_count: u32,
    },
    ObjectHovered {
        #[serde(default)]
        object: Option<ObjectRef>,
        pane: PaneId,
    },
    /// A host editing gesture reshaped an editable object. The host already
    /// shows the new geometry; persist it (or upsert the old one to revert).
    ObjectEdited {
        object: ObjectRef,
        shape: Shape,
    },
    /// The user asked to delete objects (Delete key or context menu).
    ObjectsDeleteRequested {
        objects: Vec<ObjectRef>,
    },
    /// The host-side selection of the plugin's objects changed (click,
    /// Escape, layer removal). `objects` is the complete new selection.
    SelectionChanged {
        objects: Vec<ObjectRef>,
    },
    /// Delivered on the UI thread in response to the `post` method.
    Posted {
        token: String,
    },
    /// A click in Navigate/Select mode hit none of the plugin's objects.
    EmptyAreaClicked {
        pane: PaneId,
        #[serde(default)]
        file_id: Option<FileId>,
        #[serde(default)]
        modifiers: Modifiers,
    },
    /// Undo the plugin-pushed history entry.
    Undo {
        entry_id: String,
    },
    Redo {
        entry_id: String,
    },
    /// A callback declared in a surface's `.slint` file was invoked.
    UiCallback {
        surface_id: String,
        name: String,
        #[serde(default)]
        args: Vec<Value>,
    },
    /// The user closed a surface (window close button, Escape on a modal).
    SurfaceClosed {
        surface_id: String,
    },
    /// Result of `dialog.open_file` / `dialog.save_file`; empty = cancelled.
    DialogResult {
        request_id: String,
        #[serde(default)]
        paths: Vec<String>,
    },
    ConfirmResult {
        request_id: String,
        confirmed: bool,
    },
    JobCancelRequested {
        job_id: String,
    },
    /// The user toggled one of the plugin's filters in the host UI.
    FilterToggled {
        filter_id: String,
        enabled: bool,
    },
    /// The host dropped some of the plugin's undo entries (the history is
    /// bounded, and a new change discards the redo history of its slide):
    /// they will never be undone or redone, so their data can be freed.
    UndoDropped {
        entry_ids: Vec<String>,
    },
    /// A hotkey registered with [`methods::HOTKEY_REGISTER`] was pressed.
    HotkeyPressed {
        hotkey_id: String,
        /// The focused pane, if any.
        #[serde(default)]
        pane: Option<PaneId>,
    },
    /// Part of a registration was refused, e.g. a hotkey that eov or
    /// another plugin already uses (`what`: `"hotkey"`; `id`: the button,
    /// tool or hotkey id). eov has told the user and written it to its log.
    ///
    /// Show `shown_reason` when it is there, else `reason` (wrapped in
    /// [`crate::i18n::isolate`] inside a translated text). After a change of
    /// language, registering the contribution again brings the reason in
    /// the new language (eov does not warn the user twice).
    RegistrationRefused {
        what: String,
        id: String,
        /// Why, in English, as eov's log has it: for logs and for code.
        reason: String,
        /// Why, in the interface's language when eov refused it, for
        /// plugins to show; names in it are isolated for right-to-left
        /// languages. `None` from hosts before plugin API 1.1.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        shown_reason: Option<String>,
    },
    /// How a pane displays its slide changed (see
    /// [`methods::VIEW_DISPLAY`]).
    DisplayChanged {
        pane: PaneId,
        display: DisplayAdjustments,
    },
    /// A slide's region of interest was drawn, changed or removed (`None`).
    RoiChanged {
        file_id: FileId,
        #[serde(default)]
        roi: Option<Rect>,
    },
    /// A headless batch run (`eov batch run`, see
    /// [`methods::BATCH_REGISTER`]) asks for `file` to be analysed with
    /// `command_id`, writing results under `output_dir`. Slides come one at
    /// a time; work may continue on the plugin's own threads, and the run
    /// waits until [`methods::BATCH_FINISH`] names `run_id`.
    BatchRun {
        run_id: String,
        command_id: String,
        file: FileInfo,
        /// An existing, writable folder for this slide's results.
        output_dir: String,
        /// `--param name=value` values (JSON when they parse, else
        /// strings), over the command's defaults.
        #[serde(default)]
        params: Map<String, Value>,
    },
    /// The answer to [`methods::MODEL_FETCH`]: the model is stored and
    /// verified (`path` and `model`), or it is not (`error`). The host has
    /// already told the user why a download failed or was refused; plugins
    /// need not repeat it. `cancelled` is set when the user declined the
    /// download or cancelled it (and `error` says so).
    ModelFetched {
        request_id: String,
        /// The model's main file.
        #[serde(default)]
        path: Option<String>,
        #[serde(default)]
        model: Option<ModelRecord>,
        /// Why not, as eov told the user: in the interface's language when
        /// eov answered (English from hosts before plugin API 1.1), with
        /// names isolated for right-to-left languages. For showing, not
        /// for logs or code.
        #[serde(default)]
        error: Option<String>,
        #[serde(default)]
        cancelled: bool,
    },
    /// The user chose another language for the interface: a tag of
    /// [`crate::i18n::LANGUAGES`]. The SDK has already switched
    /// [`tr!`](crate::tr!) and the surfaces' `@tr` texts to it when the
    /// plugin receives this; hand eov again the texts it shows for the
    /// plugin (toolbar tooltips, tool names, status texts) and update the
    /// texts surfaces got as properties. Not sent by hosts before plugin API
    /// 1.1.
    LanguageChanged {
        language: String,
    },
    /// Sent by newer hosts for events this plugin version does not know.
    #[serde(other)]
    Unknown,
}

fn default_click_count() -> u32 {
    1
}

/// Where a context menu was opened.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MenuContext {
    pub pane: PaneId,
    pub view: ViewInfo,
    /// Level-0 coordinates under the pointer.
    pub image_x: f64,
    pub image_y: f64,
    /// The plugin's topmost object under the pointer, if any.
    #[serde(default)]
    pub hit: Option<ObjectRef>,
    /// The plugin's currently selected objects.
    #[serde(default)]
    pub selection: Vec<ObjectRef>,
}

/// Response to [`HostEvent::ContextMenuRequested`].
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ContextMenuResponse {
    #[serde(default)]
    pub items: Vec<MenuItem>,
}

// ---------------------------------------------------------------------------
// Plugin → host methods
// ---------------------------------------------------------------------------

/// Names of the methods a plugin can invoke through `HostApi::call`.
///
/// Arguments and results are JSON; the argument type of each method is noted.
pub mod methods {
    /// `LogArgs` → `null`
    pub const LOG: &str = "log";
    /// `NotifyArgs` → `null`. Shows a toast and records it in the log.
    pub const NOTIFY: &str = "notify";
    /// `StatusArgs` → `null`. Plugin-owned status bar segment.
    pub const STATUS: &str = "status";
    /// `{}` → `HostSnapshot`
    pub const SNAPSHOT: &str = "snapshot";
    /// `FileArgs` → `FileInfo`
    pub const FILE_INFO: &str = "file.info";
    /// `FileArgs` → `{ "<name>": "<value>" }` (all slide properties)
    pub const FILE_PROPERTIES: &str = "file.properties";
    /// `OpenFileArgs` → `null`
    pub const FILE_OPEN: &str = "file.open";

    /// `ToolbarButtonSpec` → `null`
    pub const TOOLBAR_ADD: &str = "toolbar.add";
    /// `ButtonUpdate` → `null`
    pub const TOOLBAR_UPDATE: &str = "toolbar.update";
    /// `IdArgs { id: button_id }` → `null`
    pub const TOOLBAR_REMOVE: &str = "toolbar.remove";
    /// `HudButtonSpec` → `null`
    pub const HUD_ADD: &str = "hud.add";
    /// `ButtonUpdate` → `null`
    pub const HUD_UPDATE: &str = "hud.update";
    /// `IdArgs { id: button_id }` → `null`
    pub const HUD_REMOVE: &str = "hud.remove";

    /// `HotkeySpec` → `null`. A key binding of its own, not tied to a
    /// toolbar button or tool; presses arrive as `HotkeyPressed`.
    pub const HOTKEY_REGISTER: &str = "hotkey.register";
    /// `IdArgs { id: hotkey_id }` → `null`
    pub const HOTKEY_UNREGISTER: &str = "hotkey.unregister";
    /// `ToolSpec` → `null`
    pub const TOOL_REGISTER: &str = "tool.register";
    /// `IdArgs { id: tool_id }` → `null`
    pub const TOOL_UNREGISTER: &str = "tool.unregister";
    /// `IdArgs { id: tool_id }` → `null`
    pub const TOOL_ACTIVATE: &str = "tool.activate";
    /// `{}` → `null`. Returns to Navigate if one of this plugin's tools is active.
    pub const TOOL_DEACTIVATE: &str = "tool.deactivate";

    /// `LayerSpec` → `null` (replaces an existing layer with the same id)
    pub const LAYER_CREATE: &str = "layer.create";
    /// `LayerUpdate` → `null`
    pub const LAYER_UPDATE: &str = "layer.update";
    /// `IdArgs { id: layer_id }` → `null`
    pub const LAYER_REMOVE: &str = "layer.remove";
    /// `SelectArgs` → `null`
    pub const LAYER_SELECT: &str = "layer.select";
    /// `UpsertObjectsArgs` → `null`. Parsed and indexed on the calling
    /// thread; call it from a worker thread for large batches.
    pub const LAYER_UPSERT: &str = "layer.upsert";
    /// `RemoveObjectsArgs` → `null`
    pub const LAYER_REMOVE_OBJECTS: &str = "layer.remove_objects";
    /// `IdArgs { id: layer_id }` → `null`. Removes every object.
    pub const LAYER_CLEAR: &str = "layer.clear";
    /// `BadgeArgs` → `null`. Shows (or with `text: None` removes) a short
    /// notice fixed to the corner of every pane showing a slide, which does
    /// not move with the view (e.g. "Predicted — research use only").
    pub const BADGE_SET: &str = "badge.set";
    /// `SelectArgs` → `null`. Draws these objects with the layer's hover
    /// style (an empty list clears it), e.g. while a list row is hovered.
    pub const LAYER_HIGHLIGHT: &str = "layer.highlight";
    /// `MinZoomArgs` → `null`. Hides the layer below a zoom level.
    pub const LAYER_SET_MIN_ZOOM: &str = "layer.set_min_zoom";
    /// `PaneVisibilityArgs` → `null`. Shows or hides the layer in one pane
    /// (on top of the layer's own visibility).
    pub const LAYER_SET_PANE_VISIBILITY: &str = "layer.set_pane_visibility";
    /// `PaneFilterArgs` → `null`. Shows the layer only in these panes
    /// (`None`: in every pane), including panes opened later.
    pub const LAYER_SET_PANES: &str = "layer.set_panes";

    /// `SurfaceSpec` → `SurfaceOpened`
    pub const SURFACE_OPEN: &str = "surface.open";
    /// `SurfaceProperties` → `null`. Values the surface already shows are left alone.
    pub const SURFACE_SET: &str = "surface.set";
    /// `IdArgs { id: surface_id }` → `null`
    pub const SURFACE_CLOSE: &str = "surface.close";
    /// `IdArgs { id: surface_id }` → `bool`
    pub const SURFACE_IS_OPEN: &str = "surface.is_open";

    /// `ConfirmArgs` → `RequestId` (result arrives as `ConfirmResult`)
    pub const DIALOG_CONFIRM: &str = "dialog.confirm";
    /// `FileDialogArgs` → `RequestId` (result arrives as `DialogResult`)
    pub const DIALOG_OPEN_FILE: &str = "dialog.open_file";
    /// `FileDialogArgs` → `RequestId` (result arrives as `DialogResult`)
    pub const DIALOG_SAVE_FILE: &str = "dialog.save_file";

    /// `ViewSetArgs` → `null`
    pub const VIEW_SET: &str = "view.set";
    /// `ViewPanArgs` → `null`
    pub const VIEW_PAN: &str = "view.pan";
    /// `ViewZoomArgs` → `null`
    pub const VIEW_ZOOM: &str = "view.zoom";
    /// `PaneArgs` → `null`
    pub const VIEW_FIT: &str = "view.fit";
    /// `ViewFrameArgs` → `null`
    pub const VIEW_FRAME: &str = "view.frame";
    /// `ViewOrientationArgs` → `null`: turns a pane's view, by any angle
    /// (it must be finite), about the pane centre.
    pub const VIEW_ORIENTATION: &str = "view.orientation";
    /// `PaneArgs` → `DisplayAdjustments`: how the pane renders the slide,
    /// so overlays derived from slide pixels can match it.
    pub const VIEW_DISPLAY: &str = "view.display";

    /// `BatchCommandSpec` → `null`: offers a command for headless batch
    /// runs over many slides (`eov batch run <plugin>:<command> SLIDES`).
    /// Register it in `create`; slides then arrive as
    /// [`HostEvent::BatchRun`](super::HostEvent::BatchRun).
    pub const BATCH_REGISTER: &str = "batch.register";
    /// `BatchProgressArgs` → `null`: how far a batch run's slide is.
    pub const BATCH_PROGRESS: &str = "batch.progress";
    /// `BatchFinishArgs` → `null`: a batch run's slide is done.
    pub const BATCH_FINISH: &str = "batch.finish";

    /// `OffsetArgs` → `null`
    pub const APP_CYCLE_PANE: &str = "app.cycle_pane";
    /// `OffsetArgs` → `null`
    pub const APP_CYCLE_TAB: &str = "app.cycle_tab";
    /// `SeriesArgs` → `null`
    pub const APP_SERIES: &str = "app.series";
    /// `{}` → `null`
    pub const RENDER_REQUEST: &str = "render.request";

    /// `UndoPushArgs` → `null`
    pub const UNDO_PUSH: &str = "undo.push";
    /// `UndoClearArgs` → `null`
    pub const UNDO_CLEAR: &str = "undo.clear";

    /// `FilterSpec` → `null`
    pub const FILTER_REGISTER: &str = "filter.register";
    /// `FilterEnableArgs` → `null`
    pub const FILTER_SET_ENABLED: &str = "filter.set_enabled";
    /// `IdArgs { id: filter_id }` → `null`
    pub const FILTER_UNREGISTER: &str = "filter.unregister";

    /// `KeyArgs` → value or `null`
    pub const SETTINGS_GET: &str = "settings.get";
    /// `SettingsSetArgs` → `null` (persisted by the host)
    pub const SETTINGS_SET: &str = "settings.set";

    /// `JobStartArgs` → `JobStarted`
    pub const JOB_START: &str = "job.start";
    /// `JobUpdateArgs` → `null`
    pub const JOB_UPDATE: &str = "job.update";
    /// `JobFinishArgs` → `null`
    pub const JOB_FINISH: &str = "job.finish";

    /// `TextArgs` → `null`
    pub const CLIPBOARD_SET_TEXT: &str = "clipboard.set_text";

    /// `FileArgs` → `Option<Rect>` (the host region of interest of a slide)
    pub const ROI_GET: &str = "roi.get";
    /// `FileArgs` → `Vec<MeasurementInfo>`
    pub const MEASUREMENTS_LIST: &str = "measurements.list";

    /// `ModelFetchArgs` → `RequestId`: makes a model available in eov's
    /// model store, downloading it (after the user agrees, with progress in
    /// the status bar) when it is not stored yet, and verifying every file
    /// against its SHA-256. The answer arrives as
    /// [`HostEvent::ModelFetched`](super::HostEvent::ModelFetched).
    pub const MODEL_FETCH: &str = "model.fetch";
    /// `ModelResolveArgs` → `Option<ModelRecord>`: the stored model whose
    /// main file has this SHA-256, if any (never downloads).
    pub const MODEL_RESOLVE: &str = "model.resolve";
    /// `{}` → `Vec<ModelRecord>`: every stored model.
    pub const MODEL_LIST: &str = "model.list";

    /// `PostArgs` → `null`. Delivers `Posted { token }` on the UI thread.
    pub const POST: &str = "post";
    /// `SubscribeArgs` → `null`. Restricts the events delivered to the
    /// plugin; by default every event is delivered.
    pub const EVENTS_SUBSCRIBE: &str = "events.subscribe";
}

/// The `type` tags of [`HostEvent`] variants, for `events.subscribe`.
///
/// Lifecycle events (`ready`, `shutdown`) and responses to the plugin's own
/// requests (dialogs, confirmations, UI callbacks, undo/redo, posts) are always
/// delivered.
pub mod event_names {
    pub const FILE_OPENED: &str = "file_opened";
    pub const FILE_CLOSED: &str = "file_closed";
    pub const ACTIVE_CHANGED: &str = "active_changed";
    pub const VIEW_CHANGED: &str = "view_changed";
    pub const WINDOW_FOCUS_CHANGED: &str = "window_focus_changed";
    pub const OBJECT_HOVERED: &str = "object_hovered";
    pub const EMPTY_AREA_CLICKED: &str = "empty_area_clicked";
    pub const CONTEXT_MENU_REQUESTED: &str = "context_menu_requested";
    pub const ROI_CHANGED: &str = "roi_changed";
    pub const HOTKEY_PRESSED: &str = "hotkey_pressed";
    pub const DISPLAY_CHANGED: &str = "display_changed";
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LogArgs {
    pub level: LogLevel,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct NotifyArgs {
    #[serde(default)]
    pub level: NotifyLevel,
    pub message: String,
    /// Optional longer text (shown on demand, e.g. an error chain).
    #[serde(default)]
    pub detail: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct StatusArgs {
    /// `None` clears the plugin's status segment.
    #[serde(default)]
    pub text: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct FileArgs {
    pub file_id: FileId,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OpenFileArgs {
    pub path: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IdArgs {
    pub id: String,
}

/// A command a plugin offers for headless batch runs (see
/// [`methods::BATCH_REGISTER`]).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BatchCommandSpec {
    /// `^[a-z0-9][a-z0-9_-]{0,63}$`
    pub command_id: String,
    /// One line, for `eov batch list`.
    pub description: String,
    /// The parameters it takes, for `--param name=value`.
    #[serde(default)]
    pub params: Vec<BatchParam>,
}

/// A parameter of a [`BatchCommandSpec`].
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BatchParam {
    pub name: String,
    #[serde(default)]
    pub description: String,
    /// Used when the run does not set it (`null`: no default).
    #[serde(default)]
    pub default: Value,
}

/// Arguments of [`methods::BATCH_PROGRESS`].
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BatchProgressArgs {
    pub run_id: String,
    /// 0–1, when known.
    #[serde(default)]
    pub fraction: Option<f32>,
    #[serde(default)]
    pub message: Option<String>,
}

/// Arguments of [`methods::BATCH_FINISH`].
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BatchFinishArgs {
    pub run_id: String,
    /// `false` when the slide could not be analysed (`message` says why).
    pub ok: bool,
    #[serde(default)]
    pub message: Option<String>,
    /// The files written, relative to the slide's `output_dir`.
    #[serde(default)]
    pub outputs: Vec<String>,
    /// Results and provenance for the run manifest: counts, scores, the
    /// model and its hash, the level or resolution read, the device…
    #[serde(default)]
    pub summary: Value,
}

/// Arguments of [`methods::BADGE_SET`].
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BadgeArgs {
    pub badge_id: String,
    /// The slide whose panes show it; `None`: every pane with a slide.
    #[serde(default)]
    pub file_id: Option<FileId>,
    /// At most 200 characters; `None` removes the badge.
    #[serde(default)]
    pub text: Option<String>,
}

/// Arguments of [`methods::LAYER_SET_MIN_ZOOM`].
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct MinZoomArgs {
    pub layer_id: String,
    /// Screen pixels per level-0 pixel below which the layer is not drawn;
    /// `None` draws it at every zoom.
    #[serde(default)]
    pub min_zoom: Option<f64>,
}

/// Arguments of [`methods::LAYER_SET_PANE_VISIBILITY`].
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PaneVisibilityArgs {
    pub layer_id: String,
    pub pane: PaneId,
    pub visible: bool,
}

/// Arguments of [`methods::LAYER_SET_PANES`].
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PaneFilterArgs {
    pub layer_id: String,
    /// The only panes that show the layer; `None` shows it in every pane.
    #[serde(default)]
    pub panes: Option<Vec<PaneId>>,
}

/// How a pane displays its slide (the answer of [`methods::VIEW_DISPLAY`]).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DisplayAdjustments {
    /// 1.0 is unchanged.
    pub gamma: f32,
    /// Added to every channel (0.0 is unchanged; −1…1).
    pub brightness: f32,
    /// 1.0 is unchanged.
    pub contrast: f32,
    /// Sharpening amount (0.0 is off).
    pub sharpness: f32,
    /// Stain normalisation method (`"macenko"`, `"vahadane"`), if any.
    #[serde(default)]
    pub stain_normalization: Option<String>,
    /// Whether any colour processing is applied.
    pub modified: bool,
    /// The viewer's colour badge in English (empty when unmodified), as
    /// plugin API 1.0 sent it whatever the interface's language. Show
    /// `shown_badge` to people; to know what is applied, read
    /// `stain_normalization` and `stain_colors` rather than this text.
    #[serde(default)]
    pub badge: String,
    /// The colour badge as the viewer shows it, in the language of the
    /// interface. `None` from hosts before plugin API 1.1 (use `badge`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shown_badge: Option<String>,
    /// Whether stain normalisation, colour-deconvolution adjustments or an
    /// isolated stain change the slide's stain colours in this pane. `None`
    /// from hosts before plugin API 1.1, which said so only in the (then
    /// English) `badge`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stain_colors: Option<bool>,
    /// The pane converts the slide's colours from its ICC profile to sRGB
    /// (colour management), after every other adjustment and after plugin
    /// filters. Region reads and filter frames are never converted: to
    /// match an overlay derived from slide pixels to the screen exactly,
    /// convert it with the slide's profile too.
    #[serde(default)]
    pub color_managed: bool,
}

impl Default for DisplayAdjustments {
    fn default() -> Self {
        Self {
            gamma: 1.0,
            brightness: 0.0,
            contrast: 1.0,
            sharpness: 0.0,
            stain_normalization: None,
            modified: false,
            badge: String::new(),
            shown_badge: None,
            stain_colors: None,
            color_managed: false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SelectArgs {
    pub layer_id: String,
    pub object_ids: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UpsertObjectsArgs {
    pub layer_id: String,
    pub objects: Vec<OverlayObject>,
    /// Remove every existing object first (atomic replace).
    #[serde(default)]
    pub replace_all: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RemoveObjectsArgs {
    pub layer_id: String,
    pub object_ids: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PostArgs {
    pub token: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SubscribeArgs {
    /// Event `type` tags (see [`event_names`]).
    pub events: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SurfaceOpened {
    pub surface_id: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SurfaceProperties {
    pub surface_id: String,
    pub properties: Map<String, Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConfirmArgs {
    pub title: String,
    pub message: String,
    #[serde(default = "default_confirm_label")]
    pub confirm_label: String,
    #[serde(default = "default_cancel_label")]
    pub cancel_label: String,
    /// Style the confirm button as destructive.
    #[serde(default)]
    pub destructive: bool,
}

fn default_confirm_label() -> String {
    "OK".to_string()
}
fn default_cancel_label() -> String {
    "Cancel".to_string()
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileDialogArgs {
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub filters: Vec<FileFilter>,
    /// Suggested file name (save dialogs).
    #[serde(default)]
    pub default_name: Option<String>,
    /// Pick directories instead of files (open dialogs).
    #[serde(default)]
    pub directory: bool,
    /// Allow several selections (open dialogs).
    #[serde(default)]
    pub multiple: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RequestId {
    pub request_id: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct PaneArgs {
    /// Defaults to the focused pane.
    #[serde(default)]
    pub pane: Option<PaneId>,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewSetArgs {
    #[serde(default)]
    pub pane: Option<PaneId>,
    pub center_x: f64,
    pub center_y: f64,
    pub zoom: f64,
    #[serde(default)]
    pub animate: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewPanArgs {
    #[serde(default)]
    pub pane: Option<PaneId>,
    /// Logical screen pixels.
    pub dx: f64,
    pub dy: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewZoomArgs {
    #[serde(default)]
    pub pane: Option<PaneId>,
    /// > 1 zooms in.
    pub factor: f64,
    /// Screen anchor; defaults to the pane centre.
    #[serde(default)]
    pub anchor_x: Option<f64>,
    #[serde(default)]
    pub anchor_y: Option<f64>,
    #[serde(default)]
    pub animate: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewOrientationArgs {
    #[serde(default)]
    pub pane: Option<PaneId>,
    /// Clockwise rotation in degrees: any finite angle (normalised to
    /// `0..360`).
    pub rotation_deg: f64,
    /// Mirror left to right after the rotation.
    #[serde(default)]
    pub flipped: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewFrameArgs {
    #[serde(default)]
    pub pane: Option<PaneId>,
    pub rect: Rect,
    /// Fraction of the pane kept as margin (default 0.1).
    #[serde(default)]
    pub padding: Option<f64>,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct OffsetArgs {
    pub offset: i32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SeriesAction {
    Toggle,
    Next,
    Previous,
    OpenSelected,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct SeriesArgs {
    pub action: SeriesAction,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UndoPushArgs {
    /// Plugin-chosen id, echoed back in `Undo`/`Redo`.
    pub entry_id: String,
    /// The slide the change applies to (scopes Ctrl+Z to that slide).
    #[serde(default)]
    pub file_id: Option<FileId>,
    /// Shown in menus ("Undo Add Point").
    pub label: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct UndoClearArgs {
    /// Clear entries of one file; `None` clears all of the plugin's entries.
    #[serde(default)]
    pub file_id: Option<FileId>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FilterEnableArgs {
    pub filter_id: String,
    pub enabled: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KeyArgs {
    pub key: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SettingsSetArgs {
    pub key: String,
    /// `null` removes the key.
    pub value: Value,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobStartArgs {
    pub title: String,
    #[serde(default)]
    pub cancellable: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobStarted {
    pub job_id: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobUpdateArgs {
    pub job_id: String,
    /// 0.0–1.0, or `None` for indeterminate.
    #[serde(default)]
    pub fraction: Option<f32>,
    #[serde(default)]
    pub message: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JobFinishArgs {
    pub job_id: String,
    /// `Some` marks the job failed and shows the error.
    #[serde(default)]
    pub error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TextArgs {
    pub text: String,
}

/// A file a model needs next to its main file, such as the external
/// weights of an ONNX model (`model.onnx.data`).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelFileSpec {
    /// Lower-case hex SHA-256 of the file.
    pub sha256: String,
    /// Where to download it: absolute, or relative to the main file's URL.
    /// `None`: the main file's folder with `file_name`.
    #[serde(default)]
    pub url: Option<String>,
    /// The name it is stored under. Required when `url` is `None`;
    /// otherwise the URL's last path segment by default.
    #[serde(default)]
    pub file_name: Option<String>,
    /// Its size in bytes, when known: checked, and a download stops as
    /// soon as it would be larger.
    #[serde(default)]
    pub size: Option<u64>,
}

/// Arguments of [`methods::MODEL_FETCH`]. Models are stored by the
/// SHA-256 of their main file, so the same model is downloaded once for
/// every plugin and every eov of this user.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelFetchArgs {
    /// Where to download the main file. The administrator's policy can
    /// provide a site copy by SHA-256 (it then wins), so `None` is allowed;
    /// without either, only a model already stored can be answered.
    #[serde(default)]
    pub url: Option<String>,
    /// Lower-case hex SHA-256 of the main file.
    pub sha256: String,
    /// Its size in bytes, when known (checked; caps the download).
    #[serde(default)]
    pub size: Option<u64>,
    /// The name the main file is stored under (default: the URL's last
    /// path segment).
    #[serde(default)]
    pub file_name: Option<String>,
    /// What the model is called, shown when asking the user and recorded.
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub version: Option<String>,
    /// Files stored in the same folder as the main file.
    #[serde(default)]
    pub companions: Vec<ModelFileSpec>,
}

/// Arguments of [`methods::MODEL_RESOLVE`].
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelResolveArgs {
    /// SHA-256 of the main file.
    pub sha256: String,
}

/// A companion file of a stored model.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelCompanion {
    pub file_name: String,
    pub sha256: String,
    pub size: u64,
    /// Its absolute path (next to the main file).
    #[serde(default)]
    pub path: String,
}

/// A model in eov's model store (`eov model list`).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ModelRecord {
    /// SHA-256 of the main file: the model's identity in the store.
    pub sha256: String,
    /// Absolute path of the main file.
    pub path: String,
    pub file_name: String,
    /// Size of the main file in bytes.
    pub size: u64,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub version: Option<String>,
    /// Where it was downloaded from (without credentials or query);
    /// `None` for a file imported with `eov model import`.
    #[serde(default)]
    pub source: Option<String>,
    /// When it was stored (UTC, RFC 3339).
    #[serde(default)]
    pub fetched_at: Option<String>,
    /// The plugin that asked for it, or `eov` for the command line.
    #[serde(default)]
    pub requested_by: Option<String>,
    #[serde(default)]
    pub companions: Vec<ModelCompanion>,
    /// Provided read-only by the administrator (`model_dirs` in the
    /// policy).
    #[serde(default)]
    pub read_only: bool,
}

impl ModelRecord {
    /// Whether the record holds a companion with this SHA-256 and name.
    pub fn has_companion(&self, sha256: &str, file_name: &str) -> bool {
        self.companions
            .iter()
            .any(|c| c.sha256.eq_ignore_ascii_case(sha256) && c.file_name == file_name)
    }
}

/// Whether `text` is a SHA-256 in hex (64 digits, either case).
pub fn is_sha256_hex(text: &str) -> bool {
    text.len() == 64 && text.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Checks a name a model file is stored under: one plain file name that
/// every platform accepts.
pub fn check_model_file_name(name: &str) -> Result<(), String> {
    // Windows device names, with or without an extension.
    let stem = name.split('.').next().unwrap_or_default();
    let reserved = ["CON", "PRN", "AUX", "NUL"]
        .iter()
        .any(|r| stem.eq_ignore_ascii_case(r))
        || (stem.len() == 4
            && stem.is_ascii()
            && ["COM", "LPT"]
                .iter()
                .any(|p| stem[..3].eq_ignore_ascii_case(p))
            && stem.as_bytes()[3].is_ascii_digit());
    if name.is_empty()
        || name.len() > 200
        || name.starts_with('.')
        || name.ends_with('.')
        || name.ends_with(' ')
        || name.chars().any(|c| {
            c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')
        })
        || reserved
    {
        return Err(format!(
            "'{name}' cannot be a model's file name (use a plain name such as model.onnx)"
        ));
    }
    Ok(())
}

impl ModelFileSpec {
    fn check(&self, what: &str) -> Result<(), String> {
        if !is_sha256_hex(&self.sha256) {
            return Err(format!(
                "the {what}'s sha256 must be 64 hex digits, not '{}'",
                self.sha256
            ));
        }
        if let Some(name) = &self.file_name {
            check_model_file_name(name)?;
        }
        if self.size == Some(0) {
            return Err(format!("the {what}'s size cannot be 0"));
        }
        Ok(())
    }
}

impl ModelFetchArgs {
    /// Checks what the host checks before it accepts a request (URLs are
    /// checked by the host).
    pub fn validate(&self) -> Result<(), String> {
        ModelFileSpec {
            sha256: self.sha256.clone(),
            url: self.url.clone(),
            file_name: self.file_name.clone(),
            size: self.size,
        }
        .check("model")?;
        let mut names: Vec<&str> = self.file_name.iter().map(String::as_str).collect();
        for companion in &self.companions {
            companion.check("companion")?;
            let name = companion.file_name.as_deref();
            if companion.url.is_none() && name.is_none() {
                return Err("a companion without a url needs a file_name".to_string());
            }
            if let Some(name) = name {
                if names.iter().any(|n| n.eq_ignore_ascii_case(name)) {
                    return Err(format!("two files of the model are named '{name}'"));
                }
                names.push(name);
            }
        }
        if self.companions.len() > 64 {
            return Err("a model has at most 64 companion files".to_string());
        }
        Ok(())
    }
}

/// Slide-wide JSON map type used by `file.properties`.
pub type PropertyMap = BTreeMap<String, String>;

// ---------------------------------------------------------------------------
// Slide formats
// ---------------------------------------------------------------------------

/// Most pyramid levels a [`SlideInfo`] may list.
pub const MAX_SLIDE_LEVELS: usize = 64;

/// Longest side, in pixels, of a slide eov accepts (2^24 = 16,777,216).
pub const MAX_SLIDE_SIDE: u64 = 1 << 24;

/// Most associated images a [`SlideInfo`] may list.
pub const MAX_ASSOCIATED_IMAGES: usize = 32;

/// Most pixels of one associated image (2^28).
pub const MAX_ASSOCIATED_IMAGE_PIXELS: u64 = 1 << 28;

/// What the host asks a plugin's slide source to open
/// ([`crate::abi::SlideSourceFfi::open`], `Plugin::open_slide` in the SDK).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SlideOpenRequest {
    /// The `id` of the manifest's `[[slide_formats]]` entry whose extension
    /// or URI scheme matched.
    pub format_id: String,
    /// The slide: an absolute file path, or the URI as the user gave it.
    pub location: String,
    /// Whether `location` is a URI (`scheme://…`) rather than a file path.
    #[serde(default)]
    pub is_uri: bool,
}

/// One pyramid level of a slide a plugin opened.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub struct SlideLevel {
    pub width: u64,
    pub height: u64,
    /// Level-0 size divided by this level's size (1 for level 0). When
    /// absent it is computed from the sizes, as OpenSlide does (the mean of
    /// the two ratios).
    #[serde(default)]
    pub downsample: Option<f64>,
    /// The format's native tile size, if it has a tile grid (a hint: eov
    /// aligns its reads with it).
    #[serde(default)]
    pub tile_width: Option<u32>,
    #[serde(default)]
    pub tile_height: Option<u32>,
}

/// An associated image (`label`, `macro`, `thumbnail`, …) of a slide.
///
/// The label often shows the accession number or the patient's name; eov
/// treats it as protected health information (it can be hidden, and
/// de-identified copies leave it out).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct AssociatedImageInfo {
    pub name: String,
    pub width: u32,
    pub height: u32,
}

/// The metadata of a slide a plugin opened
/// ([`crate::abi::SlideFfi::info`], `SlideReader::info` in the SDK).
///
/// eov refuses a slide whose levels or associated images are inconsistent
/// (see [`validate`](Self::validate)), and ignores optional values it
/// cannot use (a pixel size that is not a positive number, a tile size
/// above 8192, bounds outside the slide, …).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SlideInfo {
    /// The pyramid, full resolution first: sizes never grow and downsamples
    /// never shrink from one level to the next.
    pub levels: Vec<SlideLevel>,
    /// The scanner vendor or format (`"philips"`, `"olympus"`); the format
    /// id when absent.
    #[serde(default)]
    pub vendor: Option<String>,
    /// Micrometres per level-0 pixel.
    #[serde(default)]
    pub mpp_x: Option<f64>,
    #[serde(default)]
    pub mpp_y: Option<f64>,
    /// The objective's magnification (20, 40, 2.5, …).
    #[serde(default)]
    pub objective_power: Option<f64>,
    /// The scan date as the format records it.
    #[serde(default)]
    pub scan_date: Option<String>,
    #[serde(default)]
    pub comment: Option<String>,
    /// The stain (`"H&E"`), if the format records it.
    #[serde(default)]
    pub stain: Option<String>,
    /// Colour of areas without image data, `[r, g, b]`; white when absent.
    #[serde(default)]
    pub background: Option<[u8; 3]>,
    /// The level-0 rectangle that holds image data, if smaller than the
    /// slide (for fitting the view and thumbnails).
    #[serde(default)]
    pub bounds: Option<Rect>,
    /// Every property of the slide, shown in Slide Information. Keys under
    /// `openslide.` and `eov.` are set by eov from the fields above.
    #[serde(default)]
    pub properties: PropertyMap,
    #[serde(default)]
    pub associated_images: Vec<AssociatedImageInfo>,
    /// For slides opened from a URI, which have no file eov could hash: a
    /// stable, globally unique id of the image (e.g.
    /// `omero:omero.example.org:image:1234`), the key bookmarks,
    /// annotations and results are kept under. Without it the URI is the
    /// key. Ignored for files, which are identified by their content.
    #[serde(default)]
    pub identity: Option<String>,
    /// Other files the slide consists of (absolute, or relative to the
    /// opened file's folder), hashed into its identity together with the
    /// opened file, e.g. the `.ets` files of a VSI slide.
    #[serde(default)]
    pub member_files: Vec<String>,
}

impl SlideInfo {
    /// The checks eov refuses a slide for: 1–[`MAX_SLIDE_LEVELS`] levels,
    /// sides of 1–[`MAX_SLIDE_SIDE`] pixels that never grow, finite
    /// downsamples that never shrink (1 for level 0) and lie within a
    /// factor of two of the size ratio, and at most
    /// [`MAX_ASSOCIATED_IMAGES`] uniquely named associated images of at
    /// most [`MAX_ASSOCIATED_IMAGE_PIXELS`] pixels.
    pub fn validate(&self) -> Result<(), String> {
        let count = self.levels.len();
        if count == 0 || count > MAX_SLIDE_LEVELS {
            return Err(format!(
                "a slide has 1–{MAX_SLIDE_LEVELS} levels, not {count}"
            ));
        }
        let base = self.levels[0];
        let mut previous: Option<(SlideLevel, f64)> = None;
        for (index, level) in self.levels.iter().enumerate() {
            if level.width == 0
                || level.height == 0
                || level.width > MAX_SLIDE_SIDE
                || level.height > MAX_SLIDE_SIDE
            {
                return Err(format!(
                    "level {index} is {}×{}; sides must be 1–{MAX_SLIDE_SIDE} pixels",
                    level.width, level.height
                ));
            }
            let ratio = (base.width as f64 / level.width as f64
                + base.height as f64 / level.height as f64)
                / 2.0;
            let downsample = level.downsample.unwrap_or(ratio);
            if !downsample.is_finite() || downsample < 1.0 {
                return Err(format!(
                    "level {index} has downsample {downsample}; it must be a number of at least 1"
                ));
            }
            if index == 0 && (downsample - 1.0).abs() > 1e-6 {
                return Err(format!("level 0 has downsample {downsample}, not 1"));
            }
            if downsample > ratio * 2.0 || downsample < ratio / 2.0 {
                return Err(format!(
                    "level {index} is {}×{} but has downsample {downsample}",
                    level.width, level.height
                ));
            }
            if let Some((prev, prev_downsample)) = previous {
                if level.width > prev.width || level.height > prev.height {
                    return Err(format!(
                        "level {index} ({}×{}) is larger than level {} ({}×{})",
                        level.width,
                        level.height,
                        index - 1,
                        prev.width,
                        prev.height
                    ));
                }
                if downsample < prev_downsample {
                    return Err(format!(
                        "level {index} has a smaller downsample than level {}",
                        index - 1
                    ));
                }
            }
            previous = Some((*level, downsample));
        }
        if self.associated_images.len() > MAX_ASSOCIATED_IMAGES {
            return Err(format!(
                "a slide has at most {MAX_ASSOCIATED_IMAGES} associated images"
            ));
        }
        let mut names = std::collections::BTreeSet::new();
        for image in &self.associated_images {
            let name = image.name.as_str();
            if name.is_empty() || name.chars().count() > 64 || name.chars().any(char::is_control) {
                return Err(format!(
                    "associated image names are 1–64 printable characters, not {name:?}"
                ));
            }
            if !names.insert(name) {
                return Err(format!("associated image {name:?} is listed twice"));
            }
            let pixels = u64::from(image.width) * u64::from(image.height);
            if pixels == 0 || pixels > MAX_ASSOCIATED_IMAGE_PIXELS {
                return Err(format!(
                    "associated image {name:?} is {}×{}",
                    image.width, image.height
                ));
            }
        }
        Ok(())
    }
}

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

    #[test]
    fn views_map_screen_and_image_through_their_turn() {
        let mut view = ViewInfo {
            center_x: 100.0,
            center_y: 50.0,
            zoom: 2.0,
            width: 300.0,
            height: 200.0,
            ..Default::default()
        };
        assert_eq!(view.image_to_screen(110.0, 50.0), (170.0, 100.0));
        // Turned clockwise, a point right of the centre shows below it.
        view.rotation_deg = 90.0;
        let (x, y) = view.image_to_screen(110.0, 50.0);
        assert!((x - 150.0).abs() < 1e-9 && (y - 120.0).abs() < 1e-9);
        for rotation in [0.0, 90.0, 180.0, 270.0, 37.5, 301.25] {
            for flipped in [false, true] {
                view.rotation_deg = rotation;
                view.flipped = flipped;
                let (sx, sy) = view.image_to_screen(37.0, 81.0);
                let (ix, iy) = view.screen_to_image(sx, sy);
                assert!((ix - 37.0).abs() < 1e-9 && (iy - 81.0).abs() < 1e-9);
            }
        }
        // Views from older hosts read as upright.
        let old: ViewInfo = serde_json::from_str(
            r#"{"pane":1,"file_id":1,"center_x":0,"center_y":0,"zoom":1,"width":1,"height":1,"visible":{"x":0,"y":0,"width":1,"height":1}}"#,
        )
        .unwrap();
        assert_eq!((old.rotation_deg, old.flipped), (0.0, false));
    }

    #[test]
    fn unknown_events_deserialize_to_unknown() {
        let event: HostEvent =
            serde_json::from_str(r#"{"type":"something_from_the_future","x":1}"#).unwrap();
        assert_eq!(event, HostEvent::Unknown);
    }

    #[test]
    fn events_round_trip() {
        let event = HostEvent::ShapeDrawn {
            tool_id: "poly".into(),
            pane: 3,
            file_id: 7,
            shape: Shape::Polygon {
                exterior: vec![[0.0, 0.0], [10.0, 0.0], [5.0, 8.0]],
                holes: vec![],
            },
            modifiers: Modifiers::default(),
        };
        let text = serde_json::to_string(&event).unwrap();
        assert!(text.contains(r#""type":"shape_drawn""#), "{text}");
        assert!(text.contains(r#""kind":"polygon""#), "{text}");
        assert_eq!(serde_json::from_str::<HostEvent>(&text).unwrap(), event);
    }

    #[test]
    fn optional_fields_may_be_absent() {
        let event: HostEvent = serde_json::from_str(
            r#"{"type":"object_clicked","object":{"layer_id":"l","object_id":"o"},"pane":1}"#,
        )
        .unwrap();
        match event {
            HostEvent::ObjectClicked {
                click_count,
                button,
                ..
            } => {
                assert_eq!(click_count, 1);
                assert_eq!(button, PointerButton::None);
            }
            other => panic!("unexpected {other:?}"),
        }
        let spec: LayerSpec = serde_json::from_str(r#"{"layer_id":"a","file_id":1}"#).unwrap();
        assert!(spec.visible);
        assert_eq!(spec.opacity, 1.0);
        assert_eq!(spec.style, Style::default());
    }

    /// `..Default::default()` builds what a message without the optional
    /// fields deserializes to. Plugins build their buttons and menu items
    /// that way, and derived defaults (`enabled: false`) left every plugin
    /// toolbar button disabled.
    #[test]
    fn defaults_are_what_absent_fields_deserialize_to() {
        let button: ToolbarButtonSpec =
            serde_json::from_str(r#"{"button_id":"","tooltip":"","icon_svg":""}"#).unwrap();
        assert_eq!(button, ToolbarButtonSpec::default());
        assert!(button.enabled);
        let item: MenuItem = serde_json::from_str(r#"{"item_id":"","label":""}"#).unwrap();
        assert_eq!(item, MenuItem::default());
        assert!(item.enabled);
        let view: ViewInfo = serde_json::from_str(
            r#"{"pane":0,"file_id":0,"center_x":0,"center_y":0,"zoom":0,"width":0,"height":0,
                "visible":{"x":0,"y":0,"width":0,"height":0}}"#,
        )
        .unwrap();
        assert_eq!(view, ViewInfo::default());
        assert_eq!(view.scale_factor, 1.0);

        // Built from the default, a button still says it is enabled on the
        // wire, and an explicit `false` still disables it.
        let sent = serde_json::to_value(ToolbarButtonSpec {
            button_id: "b".into(),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(sent["enabled"], true);
        let disabled: ToolbarButtonSpec =
            serde_json::from_str(r#"{"button_id":"b","tooltip":"","icon_svg":"","enabled":false}"#)
                .unwrap();
        assert!(!disabled.enabled);
    }

    #[test]
    fn channel_names_are_optional_both_ways() {
        // An older host sends no channel names.
        let file: FileInfo = serde_json::from_str(
            r#"{"file_id":1,"path":"/s.svs","filename":"s.svs","width":10,"height":20}"#,
        )
        .unwrap();
        assert!(file.channel_names.is_empty());
        // A newer host's field round-trips, and older plugins ignore it.
        let file = FileInfo {
            channel_names: vec!["DAPI".into(), "CD45".into()],
            ..file
        };
        let text = serde_json::to_string(&file).unwrap();
        assert!(
            text.contains(r#""channel_names":["DAPI","CD45"]"#),
            "{text}"
        );
        assert_eq!(serde_json::from_str::<FileInfo>(&text).unwrap(), file);
    }

    /// A plugin before 1.1 sends no export label, and an object without
    /// one is sent as before; a translated label's English form round-trips.
    #[test]
    fn export_labels_are_optional_both_ways() {
        let old: OverlayObject = serde_json::from_str(
            r#"{"object_id":"o","shape":{"kind":"point","x":1,"y":2},"label":"Tumour"}"#,
        )
        .unwrap();
        assert_eq!(old.label.as_deref(), Some("Tumour"));
        assert_eq!(old.export_label, None);
        let plain = OverlayObject::new("o", Shape::Point { x: 1.0, y: 2.0 }).with_label("Tumour");
        let text = serde_json::to_string(&plain).unwrap();
        assert!(!text.contains("export_label"), "{text}");

        let translated = plain
            .with_label("Tumeur")
            .with_export_label("Tumour \u{b7} 0.25 mm\u{b2}");
        let text = serde_json::to_string(&translated).unwrap();
        assert!(
            text.contains(r#""export_label":"Tumour · 0.25 mm²""#),
            "{text}"
        );
        assert_eq!(
            serde_json::from_str::<OverlayObject>(&text).unwrap(),
            translated
        );
    }

    /// A host before 1.1 sends no shown reason, and an event without one is
    /// sent as before; a plugin before 1.1 reads a newer host's event, with
    /// its English reason.
    #[test]
    fn shown_refusal_reasons_are_optional_both_ways() {
        let old = r#"{"type":"registration_refused","what":"hotkey","id":"t","reason":"Hotkey 'f' of p:t was ignored: it is a key eov already uses."}"#;
        let event: HostEvent = serde_json::from_str(old).unwrap();
        assert_eq!(
            event,
            HostEvent::RegistrationRefused {
                what: "hotkey".into(),
                id: "t".into(),
                reason: "Hotkey 'f' of p:t was ignored: it is a key eov already uses.".into(),
                shown_reason: None,
            }
        );
        assert_eq!(
            serde_json::to_value(&event).unwrap(),
            serde_json::from_str::<Value>(old).unwrap()
        );

        let new = HostEvent::RegistrationRefused {
            what: "hotkey".into(),
            id: "t".into(),
            reason: "Hotkey 'f' of p:t was ignored: it is a key eov already uses.".into(),
            shown_reason: Some(
                "Tastenkürzel „f“ von p:t wurde ignoriert: eov verwendet diese Taste bereits."
                    .into(),
            ),
        };
        let text = serde_json::to_string(&new).unwrap();
        assert_eq!(serde_json::from_str::<HostEvent>(&text).unwrap(), new);
        // The event as plugin API 1.0 declared it.
        #[derive(Debug, PartialEq, Deserialize)]
        #[serde(tag = "type", rename_all = "snake_case")]
        enum OldEvent {
            RegistrationRefused {
                what: String,
                id: String,
                reason: String,
            },
        }
        assert_eq!(
            serde_json::from_str::<OldEvent>(&text).unwrap(),
            OldEvent::RegistrationRefused {
                what: "hotkey".into(),
                id: "t".into(),
                reason: "Hotkey 'f' of p:t was ignored: it is a key eov already uses.".into(),
            }
        );
    }

    fn level(width: u64, height: u64, downsample: Option<f64>) -> SlideLevel {
        SlideLevel {
            width,
            height,
            downsample,
            ..SlideLevel::default()
        }
    }

    #[test]
    fn slide_infos_are_validated_as_eov_does() {
        let good = SlideInfo {
            levels: vec![
                level(1000, 800, None),
                level(250, 200, Some(4.0)),
                level(63, 50, None),
            ],
            associated_images: vec![AssociatedImageInfo {
                name: "label".into(),
                width: 10,
                height: 10,
            }],
            ..SlideInfo::default()
        };
        assert_eq!(good.validate(), Ok(()));
        // Sparse JSON is enough.
        let parsed: SlideInfo =
            serde_json::from_str(r#"{"levels":[{"width":10,"height":10}]}"#).unwrap();
        assert_eq!(parsed.validate(), Ok(()));

        let bad = |change: &dyn Fn(&mut SlideInfo)| {
            let mut info = good.clone();
            change(&mut info);
            info.validate().unwrap_err()
        };
        assert!(bad(&|i| i.levels.clear()).contains("levels"));
        assert!(bad(&|i| i.levels[0].width = 0).contains("sides"));
        assert!(bad(&|i| i.levels[0].height = MAX_SLIDE_SIDE + 1).contains("sides"));
        assert!(bad(&|i| i.levels[1].width = 2000).contains("larger"));
        assert!(bad(&|i| i.levels[0].downsample = Some(2.0)).contains("level 0"));
        assert!(bad(&|i| i.levels[1].downsample = Some(f64::NAN)).contains("downsample"));
        assert!(bad(&|i| i.levels[1].downsample = Some(40.0)).contains("downsample 40"));
        // A level of the previous one's size with a smaller downsample.
        assert!(bad(&|i| i.levels[2] = level(250, 200, Some(3.9))).contains("smaller downsample"));
        assert!(bad(&|i| i.levels[2].downsample = Some(3.5)).contains("downsample 3.5"));
        assert!(
            bad(&|i| i.associated_images.push(i.associated_images[0].clone())).contains("twice")
        );
        assert!(bad(&|i| i.associated_images[0].width = 0).contains("label"));
        assert!(bad(&|i| i.associated_images[0].name = String::new()).contains("names"));
    }

    #[test]
    fn model_events_and_requests_are_additive() {
        // Only the request id is required, so later fields stay optional.
        let event: HostEvent =
            serde_json::from_str(r#"{"type":"model_fetched","request_id":"model-1"}"#).unwrap();
        assert_eq!(
            event,
            HostEvent::ModelFetched {
                request_id: "model-1".into(),
                path: None,
                model: None,
                error: None,
                cancelled: false,
            }
        );
        let args: ModelFetchArgs = serde_json::from_str(
            r#"{"sha256":"70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92"}"#,
        )
        .unwrap();
        assert!(args.validate().is_ok());
        let record: ModelRecord =
            serde_json::from_str(r#"{"sha256":"a","path":"/m","file_name":"m","size":1}"#).unwrap();
        assert!(record.companions.is_empty() && !record.read_only);
    }

    #[test]
    fn model_requests_are_validated() {
        let sha = "70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92";
        let base = ModelFetchArgs {
            sha256: sha.into(),
            ..Default::default()
        };
        assert!(base.validate().is_ok());
        let upper = ModelFetchArgs {
            sha256: sha.to_ascii_uppercase(),
            ..base.clone()
        };
        assert!(upper.validate().is_ok(), "either case is hex");
        for bad in [
            ModelFetchArgs {
                sha256: "70a8".into(),
                ..base.clone()
            },
            ModelFetchArgs {
                size: Some(0),
                ..base.clone()
            },
            ModelFetchArgs {
                file_name: Some("../escape.onnx".into()),
                ..base.clone()
            },
            ModelFetchArgs {
                file_name: Some("m.onnx".into()),
                companions: vec![ModelFileSpec {
                    sha256: sha.into(),
                    file_name: Some("M.ONNX".into()),
                    ..Default::default()
                }],
                ..base.clone()
            },
        ] {
            assert!(bad.validate().is_err(), "{bad:?}");
        }
        for name in [
            "",
            ".hidden",
            "a/b",
            "a\\b",
            "c:x",
            "CON",
            "com1.onnx",
            "x.",
            "x\n",
        ] {
            assert!(check_model_file_name(name).is_err(), "{name:?}");
        }
        for name in [
            "model.onnx",
            "HistoVae_reconstruct.onnx.data",
            "console.onnx",
            "aaé.onnx",
        ] {
            assert!(check_model_file_name(name).is_ok(), "{name:?}");
        }
    }

    #[test]
    fn rgba_hex_round_trip() {
        assert_eq!(Rgba::from_hex("#FF8000"), Some(Rgba(255, 128, 0, 255)));
        assert_eq!(Rgba::from_hex("#ff800080"), Some(Rgba(255, 128, 0, 128)));
        assert_eq!(Rgba::from_hex("FF8000"), None);
        assert_eq!(Rgba::from_hex("#aé0000"), None);
        assert_eq!(Rgba(1, 2, 3, 255).to_hex(), "#010203");
        assert_eq!(Rgba::from_u32(Rgba(9, 8, 7, 6).to_u32()), Rgba(9, 8, 7, 6));
    }
}