chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using OpenTap.Addin.Annotation;
using OpenTap.Translation;
 
namespace OpenTap
{
    /// <summary> Annotators can be used to annotation objects with data for display. </summary>
    public interface IAnnotator : ITapPlugin
    {
        /// <summary> The priority of this annotator. Specifies which orders annotations are added. </summary>
        double Priority { get; }
        /// <summary> Implements annotation for an object. </summary>
        /// <param name="annotations">The current collection of annotations for an object. This method can add to the collection.</param>
        void Annotate(AnnotationCollection annotations);
    }
 
    /// <summary>
    /// Marker interface to indicate that a type represents annotation data for an object.
    /// </summary>
    public interface IAnnotation { }
 
    /// <summary> Specifies how a display is implemented and presented to user </summary>
    public interface IDisplayAnnotation : IAnnotation
    {
        /// <summary> Optional text that provides a description of the item. </summary>
        string Description { get; }
        /// <summary> Optional text used to group displayed items. </summary>
        string[] Group { get; }
        /// <summary> Name displayed by the UI. </summary>
        string Name { get; }
        /// <summary> Optional double that ranks items and groups in ascending order relative to other items/groups. 
        /// Default is -10000. For a group, the order is the average order of the elements inside the group. 
        /// Any double value is allowed. Items with same order are ranked alphabetically.
        /// </summary>
        double Order { get; }
        /// <summary> Boolean setting that indicates whether a group's default appearance is collapsed. </summary>
        bool Collapsed { get; }
    }
 
    /// <summary> Gets or sets the value of a thing. </summary>
    public interface IObjectValueAnnotation : IAnnotation
    {
        /// <summary> Gets or sets the current value. Note, for the value to be written to the owner object, Annotation.Write has to be called.</summary>
        object Value { get; set; }
    }
 
    /// <summary>
    /// A marker interface for object value annotations that comes from a merged source instead of a single-value source.
    /// </summary>
    public interface IMergedValueAnnotation : IObjectValueAnnotation
    {
 
    }
 
    /// <summary> Specifies how available values proxies are implemented. This class should rarely be implemented. Consider implementing just IAvailableValuesAnnotation instead.</summary>
    public interface IAvailableValuesAnnotationProxy : IAnnotation
    {
        /// <summary> Annotated available values. </summary>
        IEnumerable<AnnotationCollection> AvailableValues { get; }
        /// <summary> Annotated selected value. Note this should belong to the set of AvailableValues as well.</summary>
        AnnotationCollection SelectedValue { get; set; }
    }
    /// <summary> Specifies how suggested value proxies are implemented. This class should rarely be implemented. Consider implementing just ISuggestedValuesAnnotation instead.</summary>
 
    public interface ISuggestedValuesAnnotationProxy : IAnnotation
    {
        /// <summary>
        /// Annotated suggested values.
        /// </summary>
        IEnumerable<AnnotationCollection> SuggestedValues { get; }
        /// <summary>
        /// Annotated selected value.
        /// </summary>
        AnnotationCollection SelectedValue { get; set; }
    }
 
    /// <summary>Specifies how multi selection annotation proxies are implemented. Not this should rarely need to be implemented </summary>
    public interface IMultiSelectAnnotationProxy : IAnnotation
    {
        /// <summary> The annotated selected values. </summary>
        IEnumerable<AnnotationCollection> SelectedValues { get; set; }
    }
 
    /// <summary>
    /// Defines a available values implementation. Implement this to extend the data annotation system with a new available values.
    /// </summary>
    public interface IAvailableValuesAnnotation : IAnnotation
    {
        /// <summary> The available values. </summary>
        IEnumerable AvailableValues { get; }
    }
 
    /// <summary>
    /// Enhances the IAvailableValuesAnnotation with a 'SelectedValue'. Having this ensures that objects that has been transformed can get read back in the correct way.
    /// </summary>
    interface IAvailableValuesSelectedAnnotation : IAvailableValuesAnnotation
    {
        /// <summary> Gets or sets the selected value. </summary>
        object SelectedValue { get; set; }
    }
 
    /// <summary> Defines a suggested values implementation.  </summary>
    public interface ISuggestedValuesAnnotation : IAnnotation
    {
        /// <summary> The currently suggested values </summary>
        IEnumerable SuggestedValues { get; }
    }
 
    /// <summary>
    /// Defines a string value annotation implementation. This can be implemented for any type which can be converted to/from a string value. Note: IStringReadOnlyValueAnnotation can be implemented in the read-only case.
    /// </summary>
    public interface IStringValueAnnotation : IStringReadOnlyValueAnnotation
    {
        /// <summary> The string value representation of an object. The setter can throw an exception if the format is not correctly used. </summary>
        new string Value { get; set; }
    }
 
    /// <summary>
    /// If the object value is based on copying values, some performance optimizations can be done, so these string value annotations can be marked with this interface.
    /// </summary>
    interface ICopyStringValueAnnotation : IStringValueAnnotation
    {
        
    }
    
    /// <summary> Defines a read-only string value annotation implementation. </summary>
    public interface IStringReadOnlyValueAnnotation : IAnnotation
    {
        /// <summary> The string value representation of the object. </summary>
        string Value { get; }
    }
 
    /// <summary> Makes it possible to get an example of a value from a property. </summary>
    public interface IStringExampleValueAnnotation : IAnnotation
    {
        /// <summary> Gets an example of what the current value could be. </summary>
        string Example { get; }
    }
 
    /// <summary> Defines how an error annotation works. Note: Multiple of IErrorAnnotation can be used in the same annotation. In this case the errors will be concatenated. </summary>
    public interface IErrorAnnotation : IAnnotation
    {
        /// <summary> The list of errors for this annotation. </summary>
        IEnumerable<string> Errors { get; }
    }
 
    /// <summary> Specifies the access to an annotation. </summary>
    public interface IAccessAnnotation : IAnnotation
    {
        /// <summary> Gets if the annotation is read-only. This state can be temporary or permanent. </summary>
        bool IsReadOnly { get; }
 
        /// <summary> Gets if the annotation is visible. This state can be temporary or permanent. </summary>
        bool IsVisible { get; }
    }
    
    /// <summary>
    /// Owned annotations interacts directly with the source object. It is updated through the Read operation and changes are written with the Write operation. Specialized knowledge about the object is needed for implementation.
    /// </summary>
    public interface IOwnedAnnotation : IAnnotation
    {
        /// <summary> Read changes from the source. </summary>
        /// <param name="source"></param>
        void Read(object source);
        /// <summary> Write changes to the source. </summary>
        /// <param name="source"></param>
        void Write(object source);
    }
 
    /// <summary> Marks that an annotation reflects a member of an object. </summary>
    public interface IMemberAnnotation : IReflectionAnnotation
    {
        /// <summary> Gets the member. </summary>
        IMemberData Member { get; }
    }
 
    /// <summary> Reflects the type of the object value being annotated.</summary>
    public interface IReflectionAnnotation : IAnnotation
    {
        /// <summary> The reflection info object. </summary>
        ITypeData ReflectionInfo { get; }
    }
 
    /// <summary> The object can be used for multi select operations. Example: FlagAttribute enums can be multi-selected. </summary>
    public interface IMultiSelect : IAnnotation
    {
        /// <summary> The currently selected values. </summary>
        IEnumerable Selected { get; set; }
    }
 
    /// <summary> The annotation can be invoked to do some action. </summary> 
    public interface IMethodAnnotation : IAnnotation
    {
        /// <summary> Invokes the action.  </summary>
        void Invoke();
    }
 
    /// <summary>
    /// The merged method annotation marks a custom method annotation which overrides
    /// the standard behavior in the case where multiple values are merged.
    /// This can happen during multi select of a test step with a method.
    /// </summary>
    public interface IMergedMethodAnnotation : IMethodAnnotation
    {
 
    }
 
    /// <summary> Specifies how to implement basic collection annotations. </summary>
    public interface IBasicCollectionAnnotation : IAnnotation
    {
        /// <summary> he currently selected elements in the list. </summary>
        IEnumerable Elements { get; set; }
    }
    
    /// <summary> Used to mark a collection as fixed-size. </summary>
    public interface IFixedSizeCollectionAnnotation : IAnnotation
    {
        /// <summary> Gets if the collection annotated is fixed size. </summary>
        bool IsFixedSize { get; }
    }
    /// <summary> Specifies that the annotation reflects some kind of collection.</summary>
    public interface ICollectionAnnotation : IAnnotation
    {
        /// <summary> The reflected elements. </summary>
        IEnumerable<AnnotationCollection> AnnotatedElements { get; set; }
        /// <summary> Creates a new element that can be put into the collection. Note that initially the element should not be added to the collection. This task is for the user. </summary>
        /// <returns>The new element. </returns>
        AnnotationCollection NewElement();
    }
 
    /// <summary> The annotation reflects multiple members on an object. </summary>
    public interface IMembersAnnotation : IAnnotation
    {
        /// <summary> The reflected members. </summary>
        IEnumerable<AnnotationCollection> Members { get; }
    }
 
    /// <summary> Like IMembersAnnotation, but a specific member can be fetched.</summary>
    public interface INamedMembersAnnotation : IAnnotation
    {
        /// <summary> Returns the annotated member. </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        AnnotationCollection GetMember(IMemberData name);
    }
 
    /// <summary> Marks that a property should be ignored when annotating members.
    /// This can be applied as an optimization to properties in order to improve annotation performance. </summary>
    [AttributeUsage(AttributeTargets.Property )]
    public class AnnotationIgnoreAttribute : Attribute
    {
        
    } 
 
    /// <summary> Can be used to forward a set of members from one annotation to another.</summary>
    public interface IForwardedAnnotations : IAnnotation
    {
        /// <summary> The forwarded annotations. </summary>
        IEnumerable<AnnotationCollection> Forwarded { get; }
    }
 
    /// <summary> Interface for providing annotations with a way of explaining the value. </summary>
    public interface IValueDescriptionAnnotation : IAnnotation
    {
        /// <summary> Description of a value. </summary>
        /// <returns>A string describing the current value.</returns>
        string Describe();
    }
 
    /// <summary> Annotation for marking something as enabled or disabled. </summary>
    public interface IEnabledAnnotation : IAnnotation
    {
        /// <summary> Gets if an annotation is enabled. </summary>
        bool IsEnabled { get; }
    }
 
    /// <summary>
    /// Annotates that a member is read only.
    /// </summary>
    public class ReadOnlyMemberAnnotation : IAccessAnnotation
    {
        /// <summary> Always returns true.</summary>
        public bool IsReadOnly => true;
        /// <summary> Always returns true.</summary>
        public bool IsVisible => true;
    }
 
    class MembersAnnotation : INamedMembersAnnotation, IMembersAnnotation, IOwnedAnnotation
    {
        Dictionary<IMemberData, AnnotationCollection> members = new Dictionary<IMemberData, AnnotationCollection>();
        IEnumerable<AnnotationCollection> getMembers()
        {
 
            var val2 = fac.Get<IObjectValueAnnotation>().Value;
            var val = fac.Get<IReflectionAnnotation>();
            IEnumerable<IMemberData> _members;
            if (val2 != null)
                _members = TypeData.GetTypeData(val2).GetMembers();
            else _members = val.ReflectionInfo.GetMembers();
            var cnt = _members.Count();
            if (members.Count == cnt) return members.Values;
            if (members.Count == 0)
                members = new Dictionary<IMemberData, AnnotationCollection>(cnt);
 
            var members2 = val.ReflectionInfo.GetMembers();
            foreach (var item in members2)
            {
                if (item.HasAttribute<AnnotationIgnoreAttribute>()) continue;
                if (item.Readable == false) continue;
                GetMember(item);
            }
 
            return members.Values;
 
        }
 
        public IEnumerable<AnnotationCollection> Members => getMembers();
 
        readonly AnnotationCollection fac;
        public MembersAnnotation(AnnotationCollection fac)
        {
            this.fac = fac;
        }
 
        public void Read(object source)
        {
            var val = fac.Get<IObjectValueAnnotation>()?.Value;
            if (val == null) return;
            foreach (var mem in members)
            {
                mem.Value.Read(val);
            }
        }
 
        public void Write(object source)
        {
            var val = fac.Get<IObjectValueAnnotation>()?.Value;
            if (val == null) return;
            foreach (var mem in members)
            {
                mem.Value.Write(val);
            }
        }
 
        public AnnotationCollection GetMember(IMemberData member)
        {
            if (members.TryGetValue(member, out AnnotationCollection value)) return value;
            var objectValue = fac.Get<IObjectValueAnnotation>().Value;
 
            var annotation = fac.AnnotateMember(member, objectValue);
            members[member] = annotation;
            if (objectValue != null)
            {
                annotation.Read(objectValue);
            }
 
            return annotation;
        }
    }
 
    class EnabledIfAnnotation : IAccessAnnotation, IOwnedAnnotation, IEnabledAnnotation
    {
 
        public bool IsReadOnly
        {
            get
            {
                doRead();
                return isReadOnly;
            }   
        }
 
        public bool IsVisible
        {
            get
            {
                doRead();
                return isVisible;
            }
        }
 
        bool isReadOnly;
        bool isVisible;
        object source;
 
        void doRead()
        {
            if (source != null)
            {
                isReadOnly = !EnabledIfAttribute
                    .IsEnabled(mem.Member, source, out IMemberData _, out IComparable __, out bool hidden);
                isVisible = !hidden;
                source = null;
            }
        }
 
        public void Read(object source)
        {
            this.source = source;
        }
 
        public void Write(object source)
        {
 
        }
 
        IMemberAnnotation mem;
        public EnabledIfAnnotation(IMemberAnnotation mem)
        {
            this.mem = mem;
        }
 
        public bool IsEnabled => IsReadOnly == false;
    }
 
    class ValidationErrorAnnotation : IErrorAnnotation, IOwnedAnnotation
    {
        IMemberAnnotation mem;
        string error;
        public ValidationErrorAnnotation(IMemberAnnotation mem)
        {
            this.mem = mem;
        }
 
        public IEnumerable<string> Errors
        {
            get
            {
                DoRead();
                if (string.IsNullOrWhiteSpace(error) == false)
                    return new[] { error };
                return Array.Empty<string>();
            }
        }
 
        object source;
        void DoRead()
        {
            var source = this.source;
            var mem = this.mem.Member;
            
            // Special case to add support for EmbeddedMemberData.
            // The embedded member may be nested in multiple layers
            // of embeddings normally it is just one level though.
            // iterate to grab the innermost source and member.
            while (mem is EmbeddedMemberData m2)
            {   
                if (source == null) return;
                source = m2.OwnerMember.GetValue(source);
                mem = m2.InnerMember;
            }
 
            if (source is IDataErrorInfo dataErrorInfo)
            {
                try
                {
                    error = dataErrorInfo[mem.Name];
                }
                catch (Exception e)
                {
                    error = e.Message;
                }
                // set source to null to signal that errors has been read this time.
            }
            this.source = null; 
        }
 
        public void Read(object source) => this.source = source;
 
        public void Write(object source) { }
    }
 
 
    class NumberAnnotation : IStringValueAnnotation, IErrorAnnotation, ICopyStringValueAnnotation
    {
        public Type NullableType { get; set; }
        string currentError;
        public string Value
        {
            get
            {
                var value = annotation.Get<IObjectValueAnnotation>();
                if (value != null)
                {
                    var unit = annotation.Get<UnitAttribute>();
                    var value2 = value.Value;
                    if (NullableType != null && value2 == null)
                        return "";
                    return new NumberFormatter(CultureInfo.CurrentCulture, unit).FormatNumber(value2);
                }
                return null;
            }
            set
            {
                if (NullableType != null && value == "")
                {
                    var val = annotation.Get<IObjectValueAnnotation>();
                    val.Value = null;
                    return;
                }
 
                currentError = null;
                var unit = annotation.Get<UnitAttribute>();
                if (annotation.Get<IReflectionAnnotation>()?.ReflectionInfo is TypeData cst)
                {
                    object number = null;
                    try
                    {
                        number = new NumberFormatter(CultureInfo.CurrentCulture, unit).ParseNumber(value, NullableType ?? cst.Type);
                    }
                    catch (Exception e)
                    {
                        currentError = e.Message;
                    }
 
                    if (number != null)
                    {
                        var val = annotation.Get<IObjectValueAnnotation>();
                        val.Value = number;
                    }
 
                }
                else
                {
                    throw new InvalidOperationException("Number converter supports only C# types");
                }
            }
        }
        AnnotationCollection annotation;
        public NumberAnnotation(AnnotationCollection mem)
        {
            this.annotation = mem;
        }
 
        public IEnumerable<string> Errors => currentError == null ? Array.Empty<string>() : new[] { currentError };
    }
 
    class TimeSpanAnnotation : IStringValueAnnotation, ICopyStringValueAnnotation, IErrorAnnotation
    {
        public string Value
        {
            get
            {
 
                if (annotation.Get<IObjectValueAnnotation>(from: this).Value is TimeSpan timespan)
                    return TimeSpanFormatter.Format(timespan, fmt.Verbosity);
                return "";
            }
 
            set
            {
                try
                {
                    var timespan = TimeSpanParser.Parse(value);
                    annotation.Get<IObjectValueAnnotation>(from: this).Value = timespan;
                    Errors = [];
                }
                catch (Exception ex)
                {
                    Errors = [ex.Message];
                }
            }
        }
        AnnotationCollection annotation;
        TimeSpanFormatAttribute fmt;
        public TimeSpanAnnotation(AnnotationCollection annotation)
        {
            fmt = annotation?.Get<IMemberAnnotation>()?.Member.GetAttribute<TimeSpanFormatAttribute>();
            if (fmt == null) fmt = new TimeSpanFormatAttribute();
            this.annotation = annotation;
        }
 
        public IEnumerable<string> Errors { get; private set; }
    }
 
    class NumberSequenceAnnotation : IStringValueAnnotation, ICopyStringValueAnnotation, IErrorAnnotation
    {
        string currentError;
        public IEnumerable<string> Errors => currentError == null ? Array.Empty<string>() : new[] { currentError };
        public string Value
        {
            get
            {
                var member = mem.Get<IObjectValueAnnotation>();
                var value = (IEnumerable)member.Value;
                if (value == null) return "";
                var unit = mem.Get<UnitAttribute>();
 
                return new NumberFormatter(System.Globalization.CultureInfo.CurrentCulture, unit).FormatRange(value);
            }
            set
            {
                var objVal = mem.Get<IObjectValueAnnotation>();
                var reflect = mem.Get<IReflectionAnnotation>();
                var unit = mem.Get<UnitAttribute>();
                if (reflect.ReflectionInfo is TypeData cst)
                {
                    currentError = null;
                    try
                    {
                        var numbers = DoConvertBack(value, cst.Type, unit, CultureInfo.CurrentCulture);
                        objVal.Value = numbers;
                    }
                    catch (Exception e)
                    {
                        currentError = e.Message;
                    }    
                }
                else
                {
                    throw new InvalidOperationException("Number converter supports only C# types");
                }
            }
        }
 
        public object DoConvertBack(object _value, Type targetType, UnitAttribute unit, CultureInfo culture)
        {
            string value = _value as string;
            if (value == null)
                return null;
 
            Type elementType = targetType.GetEnumerableElementType();
 
            IEnumerable seq = null;
            if (elementType.IsNumeric())
            {
                seq = new NumberFormatter(culture, unit).Parse(value).CastTo(elementType);
            }
            else
            {
                var items = value.Split(new string[] { culture.NumberFormat.NumberGroupSeparator }, StringSplitOptions.RemoveEmptyEntries);
                if (elementType.IsEnum)
                {
                    seq = items.Select(item => Enum.Parse(elementType, item));
                }
                else
                {
                    seq = items.Select(item => System.Convert.ChangeType(item, elementType));
                }
            }
 
            Type genericBaseType = null;
            if (targetType.IsArray)
            {
                elementType = targetType.GetElementType();
            }
            else if (targetType.IsGenericType)
            {
                genericBaseType = targetType.GetGenericTypeDefinition();
            }
 
            if (typeof(IEnumerable<>) == genericBaseType)
            {
                var genarg = targetType.GetGenericArguments().FirstOrDefault();
                if (genarg != null && genarg.IsNumeric())
                {
                    var comb = seq as ICombinedNumberSequence;
                    if (comb != null)
                        return comb.CastTo(genarg);
                    return seq.Cast<object>().Select(v => System.Convert.ChangeType(v, genarg));
                }
            }
            else if (seq.Cast<object>().IsLongerThan(100000))
                throw new Exception("Sequence is too large. (max number of elements is 100000).");
 
            if (targetType.IsArray)
            {
                Array array = Array.CreateInstance(elementType, seq.Cast<object>().Count());
                int idx = 0;
                foreach (var item in seq)
                    array.SetValue(System.Convert.ChangeType(item, elementType), idx++);
                return array;
            }
            else if (targetType.DescendsTo(typeof(System.Collections.ObjectModel.ReadOnlyCollection<>)))
            {
                var lst = Activator.CreateInstance(typeof(List<>).MakeGenericType(elementType), seq);
                return Activator.CreateInstance(targetType, lst);
            }
            else
            {
                Type typeToInstanciate = targetType;
                object l2 = Activator.CreateInstance(typeToInstanciate);
 
                IList lst = l2 as IList;
                if (lst != null)
                {
                    foreach (object item in seq)
                        lst.Add(item);
 
                }
                else
                {
                    dynamic lst_dynamic = l2;
                    foreach (dynamic item in seq)
                        lst_dynamic.Add(item);
                }
 
                return l2;
            }
        }
 
 
        AnnotationCollection mem;
        public NumberSequenceAnnotation(AnnotationCollection mem)
        {
            this.mem = mem;
        }
    }
 
    class BooleanValueAnnotation : IStringValueAnnotation, ICopyStringValueAnnotation
    {
        AnnotationCollection annotation;
        public BooleanValueAnnotation(AnnotationCollection annotation)
        {
            this.annotation = annotation;
        }
 
        bool parseBool(string str) {
            if (string.Compare(str, "true", true) == 0)
                return true;
            if (string.Compare(str, "false", true) == 0)
                return false;
            throw new FormatException("Unable to parse string as boolean.");
 
        }
        public string Value
        {
            get => annotation.Get<IObjectValueAnnotation>().Value?.ToString();
            set => annotation.Get<IObjectValueAnnotation>().Value = parseBool(value);
        }
 
    }
 
    class MergedValueAnnotation : IMergedValueAnnotation, IOwnedAnnotation
    {
        public IEnumerable<AnnotationCollection> Merged => merged;
        readonly List<AnnotationCollection> merged;
        public MergedValueAnnotation(List<AnnotationCollection> merged)
        {
            this.merged = merged;
        }
 
        public object Value
        {
            get
            {
                if (merged.Count == 0) return null;
                // this getter is performance critical. Avoid doing any allocations or unnessesary operations here.
                var first = merged[0];
                object selectedValue = first.Get<IObjectValueAnnotation>().Value;
                if (selectedValue != null)
                {
                    for (int i = 1; i < merged.Count; i++)
                    {
                        var x = merged[i];
                        var thisVal = x.Get<IObjectValueAnnotation>().Value;
                        if (thisVal == selectedValue) 
                            continue;
                        if (selectedValue is IEnumerable ie1 && !(selectedValue is string))
                        {
                            // if the two lists has the same content it is fine to just return one of them.
                            // upon writing the two values will be cloned back.
                            // if they are not the same, null should be returned to signal this.
                            if (thisVal is IEnumerable ie2)
                            {
                                if (ie2.Cast<object>().SequenceEqual(ie1.Cast<object>()))
                                    continue;
                            }
 
                            return null;
                        }
 
                        if (Equals(selectedValue, thisVal) == false)
                            return null;
                    }
                }
                return selectedValue;
            }
            set
            {
 
                if (value is ValueType || value is string)
                {
                    //  The trivial case - just copy the values.
                    foreach (var m in merged)
                        m.Get<IObjectValueAnnotation>().Value = value;
                    return;
                }
 
                // same as for parameters.
                var first = merged[0];
                first.Get<IObjectValueAnnotation>().Value = value;
                var cloner = new ObjectCloner(value);
                foreach (var m in merged.Skip(1))
                {
                    var memberType = m.Get<IMemberAnnotation>()?.ReflectionInfo ?? TypeData.GetTypeData(value);
                    var context = m.ParentAnnotation?.Source;
                    // use the source of the parent annotation as the context object because it may contain
                    // additional information about how to decode the value internally
                    if (cloner.TryClone(context, memberType, false, out var val))
                        m.Get<IObjectValueAnnotation>().Value = val;
                }
            }
        }
 
        public void Read(object source)
        {
            foreach (var annotation in merged)
            {
                annotation.Read();
            }
        }
 
        public void Write(object source)
        {
            // Force align the value using the object cloner.
            var currentValue = Value;
            if(currentValue != null)
                Value = Value;
            
            foreach (var annotation in merged)
                annotation.Write();
        }
    }
 
    /// <summary>
    /// Marker interface that indicates that an IAnnotation does not support multi-selecting. 
    /// When multi-selecting, the UI should not show properties annotated with this. 
    /// </summary>
    // Used by ManyToOneAnnotation
    public interface IHideOnMultiSelectAnnotation : IAnnotation { }
 
    class ManyToOneMethodAnnotation : IMethodAnnotation
    {
        AnnotationCollection annotation;
        public void Invoke()
        {
            foreach (var merged in annotation.Get<MergedValueAnnotation>().Merged)
            {
                var m = merged.Get<IMethodAnnotation>();
                m?.Invoke();
            }
        }
 
        public ManyToOneMethodAnnotation(AnnotationCollection a) => annotation = a;
    }
    
    class ManyToOneAnnotation : IMembersAnnotation, IOwnedAnnotation
    {
        AnnotationCollection[] members;
        public AnnotationCollection[] Members
        {
            get
            {
                if (members != null) return members;
                var c = parentAnnotation.Get<ICollectionAnnotation>();
                var rdOnly = parentAnnotation.Get<ReadOnlyMemberAnnotation>() == null;
                AnnotationCollection[] annotatedElements;
                bool collectAll = rdOnly;
                if (c == null)
                {
                    var merged = parentAnnotation.Get<MergedValueAnnotation>();
                    annotatedElements = merged.Merged.ToArray();
                }
                else
                {
                    annotatedElements = c.AnnotatedElements.ToArray();
                }
 
                var sources = annotatedElements;
                var mems = sources.Select(x => x.Get<IMembersAnnotation>()?.Members ?? Array.Empty<AnnotationCollection>()).ToArray();
                if (mems.Length == 0) return Array.Empty<AnnotationCollection>();
                Dictionary<string, AnnotationCollection>[] dicts = mems.Select(x =>
                {
                    var dict = new Dictionary<string, AnnotationCollection>();
                    foreach (var d in x)
                    {
                        if (d.Get<IHideOnMultiSelectAnnotation>() != null)
                            continue;
                        var mem = d.Get<IMemberAnnotation>()?.Member;
                        var key = mem.GetDisplayAttribute().GetFullName() + mem.TypeDescriptor.Name;
                        if (dict.ContainsKey(key) == false)
                            dict[key] = d;
                    }
                    return dict;
                }).ToArray();
                var union = dicts.SelectMany(x => x.Keys).Distinct().ToArray();
                List<AnnotationCollection> CommonAnnotations = new List<AnnotationCollection>();
 
                foreach (var name in union)
                {
                    List<AnnotationCollection> mergething = new List<AnnotationCollection>();
                    IMemberData mem = null;
                    foreach (var thing2 in dicts)
                    {
                        if (!thing2.ContainsKey(name))
                        {
                            if (collectAll)
                                continue;
                            goto next_thing;
                        }
 
                        var otherAnnotation = thing2[name];
 
                        var othermember = otherAnnotation.Get<IMemberAnnotation>()?.Member;
                        if (mem == null) mem = othermember;
 
                        mergething.Add(thing2[name]);
                    }
                    if (mem == null) continue;
                    var newa = parentAnnotation.AnnotateMember(mem, sources[0].ExtraAnnotations.Append(new MergedValueAnnotation(mergething)).ToArray());
                    if(parentAnnotation.Get<MergedValueAnnotation>()?.Merged.First().Get<BreakConditionsAnnotation>() is BreakConditionsAnnotation br)
                    {
                        if(br.Value.Get<IMemberAnnotation>().Member.Name == mem.Name)
                            newa.Add(new BreakConditionsAnnotation.BreakConditionValueAnnotation(br) { valueAnnotation = newa });
                    }
 
                    var manyAccess = new ManyAccessAnnotation(mergething.SelectValues(x => x.Get<IAccessAnnotation>()).ToArray());
                    // Enabled if is not supported when multi-selecting.
                    newa.RemoveType<EnabledIfAnnotation>();
                    var method = newa.Get<IMethodAnnotation>();
                    if (method != null)
                    {
                        // skip adding many-to-one method annotation.
                        // if the method annotation can already handle the merged case.
                        if(!(method is IMergedMethodAnnotation))
                            newa.Add(new ManyToOneMethodAnnotation(newa));
                    }
 
                    var enabledValue = newa.Get<IEnabledValueAnnotation>();
                    if (enabledValue != null)
                    {
                        newa.Add(new ManyIEnabledValueAnnotation(newa));
                        newa.Remove(enabledValue);
                    }
                    
                    newa.Add(manyAccess);
 
                    var enabledAnnotations = mergething.SelectMany(x => x.GetAll<IEnabledAnnotation>()).ToArray();
                    if (enabledAnnotations.Length > 0)
                    {
                        var manyEnabled = new ManyEnabledAnnotation(enabledAnnotations);
                        newa.RemoveType<IEnabledAnnotation>();
                        newa.Add(manyEnabled);
                    }
 
                    newa.Read(parentAnnotation.Get<IObjectValueAnnotation>().Value);
 
                    if (newa.Get<IStringValueAnnotation>() is IStringValueAnnotation strValueAnnotation && (strValueAnnotation is ICopyStringValueAnnotation == false))
                    {
                        // see comment on ManyToOneStringValueAnnotation
                        var merged = newa.Get<MergedValueAnnotation>();
                        if (merged != null)
                        {
                            int idx = newa.IndexWhen(x => x == strValueAnnotation);
                            // insert after last string value annotation.
                            newa.Insert(idx + 1, new ManyToOneStringValueAnnotation(merged));
                        }
                    }
 
                    IconAnnotationHelper.AddParameter(newa, mem, newa.Source);
                    
                    CommonAnnotations.Add(newa);
 
                next_thing:;
                }
                return members = CommonAnnotations.ToArray();
            }
        }
 
        class ManyIEnabledValueAnnotation : IEnabledValueAnnotation
        {
            AnnotationCollection annotation;
            public ManyIEnabledValueAnnotation(AnnotationCollection annotation) => this.annotation = annotation;
 
            public AnnotationCollection IsEnabled
            {
                get
                {
                    var eMember = annotation.Get<ManyToOneAnnotation>().Members
                        .FirstOrDefault(x => x.Get<IMemberAnnotation>()?.Member.Name == "IsEnabled");
                    return eMember;
                }
            }
 
            public AnnotationCollection Value
            {
                get
                {
                    var eMember = annotation.Get<ManyToOneAnnotation>().Members
                        .FirstOrDefault(x => x.Get<IMemberAnnotation>()?.Member.Name != "IsEnabled")?.Clone();
                    if(annotation.Get<UnitAttribute>() is UnitAttribute attr)
                        eMember.Add(attr);
                    if(annotation.Get<IAvailableValuesAnnotation>() is IAvailableValuesAnnotation avail)
                        eMember.Add(avail);
                    return eMember;
                }
            }
        }
 
        class ManyEnabledAnnotation : IEnabledAnnotation
        {
            readonly IEnabledAnnotation[] subAnnotations;
 
            public ManyEnabledAnnotation(IEnabledAnnotation[] subAnnotationsAnnotations)
            {
                subAnnotations = subAnnotationsAnnotations;
            }
 
            public bool IsEnabled => subAnnotations.All(x => x.IsEnabled);
        }
 
        /// <summary>
        /// Some string value annotations does not work very well with multi-select
        /// to mitigate that, a ManyToOneStringValueAnnotation is used.
        /// one example is MacroString.
        /// </summary>
        class ManyToOneStringValueAnnotation : IStringValueAnnotation
        {
            MergedValueAnnotation merged;
 
            public string Value
            {
                get
                {
                    string value = null;
                    bool first = true;
                    foreach (var m in merged.Merged)
                    {
                        var val = m.Get<IStringValueAnnotation>()?.Value;
                        if (first)
                        {
                            value = val;
                            first = false;
                        }
                        else
                        {
                            if (!object.Equals(val, value))
                                return null;
                        }
                    }
 
                    return value;
                }
                set
                {
                    foreach (var m in merged.Merged)
                    {
                        var sv = m.Get<IStringValueAnnotation>();
                        if (sv != null) sv.Value = value;
                    }
                }
            }
 
            public ManyToOneStringValueAnnotation(MergedValueAnnotation mva) => merged = mva;
        }
 
        IEnumerable<AnnotationCollection> IMembersAnnotation.Members => Members;
 
        public ManyToOneAnnotation(AnnotationCollection parentAnnotation)
        {
            this.parentAnnotation = parentAnnotation;
        }
 
        AnnotationCollection parentAnnotation;
 
        public void Read(object source)
        {
            if (members == null) return;
            foreach (var annotation in members)
            {
                annotation.Read();
            }
        }
 
        public void Write(object source)
        {
            if (members != null)
            {
                foreach (var mem in members)
                    mem.Write(source);
            }
        }
    }
 
    class ManyToOneAvailableValuesAnnotation : IAvailableValuesAnnotation
    {
        public IEnumerable AvailableValues
        {
            get
            {
                var sets = others.Select(x => x.AvailableValues.Cast<object>().ToHashSet()).ToArray();
                HashSet<object> r = sets.FirstOrDefault();
                foreach (var set in sets.Skip(1))
                {
                    r.ExceptWith(set);
                }
                return (IEnumerable)r ?? Array.Empty<object>();
            }
        }
 
        IAvailableValuesAnnotation[] others;
 
        public ManyToOneAvailableValuesAnnotation(IAvailableValuesAnnotation[] others)
        {
            this.others = others;
        }
    }
 
    class ManyAccessAnnotation : IAccessAnnotation
    {
        public bool IsReadOnly => others.Any(x => x.IsReadOnly);
        public bool IsVisible => others.Any(x => x.IsVisible);
 
        IAccessAnnotation[] others;
        public ManyAccessAnnotation(IAccessAnnotation[] others)
        {
            this.others = others;
        }
    }
    class MemberValueAnnotation : IObjectValueAnnotation, IOwnedAnnotation, IErrorAnnotation
    {
        readonly AnnotationCollection annotation;
        object currentValue;
 
        bool wasRead;
        bool wasSet;
        // the the member is a parameter we may need to update it
        // even if the value is the same as the cached one.
        bool isParameter; 
        public object Value
        {
            get
            {
                if (!wasRead)
                    read(); // lazy read.
                return currentValue;
            }
            set
            {
                wasSet = true;
                // current value is cached until next Read().
                wasRead = true;
                currentValue = value;
            }
        }
 
        public MemberValueAnnotation(AnnotationCollection annotation, IMemberAnnotation mem = null)
        {
            this.annotation = annotation;
            memberCache = mem;
        }
 
        // often the member annotation is know at 'annotate' time, so it is better to cache it here.
        // this section of the code is also performance-critical.
        IMemberAnnotation memberCache;
        void read()
        {
            if (annotation.Source == null) return;
            var m = memberCache ?? (memberCache = annotation.Get<IMemberAnnotation>());
            isParameter = m.Member is IParameterMemberData;
            try
            {
                currentValue = m.Member.GetValue(annotation.Source);
                // This value is now being cached until the next Read().
                wasRead = true;
            }
            catch
            {
                // the member itself threw an exception. 
            }
        }
        public void Read(object source)
        {
            wasRead = false;
            wasSet = false;
        }
 
        public void Write(object source)
        {
            if (annotation.Source == null) return;
            
            var m = memberCache ?? (memberCache = annotation.Get<IMemberAnnotation>());
            if (m.Member.Writable == false) return;
            
            if (wasSet == false && !isParameter) return;
            
            error = null;
            try
            {
                if (isParameter || object.Equals(currentValue, m.Member.GetValue(source)) == false)
                    m.Member.SetValue(source, currentValue);
            }
            catch (Exception e)
            {
                error = e.GetInnerMostExceptionMessage();
            }
        }
 
        string error = null;
 
        public IEnumerable<string> Errors => error == null ? Array.Empty<string>() : new[] { error };
    }
    class ObjectValueAnnotation : IObjectValueAnnotation, IReflectionAnnotation, IOwnedAnnotation
    {
        public object Value { get; set; }
 
        public ITypeData ReflectionInfo => cachedType ?? (cachedType = (initType ?? TypeData.GetTypeData(Value)));
        ITypeData cachedType;
        ITypeData initType;
        public ObjectValueAnnotation(object value, ITypeData reflect) : this(value)
        {
            initType = reflect;
        }
        
        public ObjectValueAnnotation(object value) => Value = value;
 
        public void Read(object source)
        {
            // invalidate.
            cachedType = null; 
        }
 
        public void Write(object source) { }
    }
    class AvailableMemberAnnotation : IAnnotation
    {
        public AnnotationCollection AvailableMember;
        public AvailableMemberAnnotation(AnnotationCollection annotation)
        {
            this.AvailableMember = annotation;
        }
    }
    
    /// <summary>
    /// This is interface is used for generating something from a string.
    /// Currently it is used only for PluginTypeSelectorAttribute
    /// </summary>
    interface IAnnotationStringer : IAnnotation
    {
        /// <summary> Gets the string value of an object.  </summary>
        string GetString(AnnotationCollection item);
    }
 
 
    /// <summary> The default data annotator plugin. This normally forms the basis for annotation. </summary>
    public class DefaultDataAnnotator : IAnnotator
    {
        double IAnnotator.Priority => 1;
 
        class AvailableValuesAnnotation : IAvailableValuesAnnotation
        {
            string availableValuesMember;
 
            public IEnumerable AvailableValues
            {
                get
                {
                    var mem = annotation.ParentAnnotation.Get<IMembersAnnotation>()?.Members;
                    var mem2 = mem.FirstOrDefault(x => x.Get<IMemberAnnotation>()?.Member.Name == availableValuesMember);
                    if (mem2?.Get<IObjectValueAnnotation>() is MergedValueAnnotation merged)
                    {
                        // special handling for 'MergedValueAnnotation'
                        // let's try to intersect the lists.
                        
                        var lists = merged.Merged.Select(x => x.Get<IObjectValueAnnotation>().Value).OfType<IEnumerable>()
                            .ToArray();
                        
                        if (lists.FirstOrDefault() is IEnumerable lst)
                        {
                            var set = lst.Cast<object>().ToHashSet();
                            foreach (var subset in lists.Skip(1))
                            {
                                set.IntersectWith(subset.Cast<object>());
                            }
 
                            return set;
                        }
                    }
                        
 
                    return mem2?.Get<IObjectValueAnnotation>().Value as IEnumerable ?? Enumerable.Empty<object>();
                }
            }
 
            AnnotationCollection annotation;
            public AvailableValuesAnnotation(AnnotationCollection annotation, string available)
            {
                availableValuesMember = available;
                this.annotation = annotation;
            }
        }
 
        class MultipleAvailableValuesAnnotation : IAvailableValuesAnnotation, IMultiSelect
        {
            AvailableValuesAnnotation avail;
            AnnotationCollection annotation;
            string availableValuesMember;
            public MultipleAvailableValuesAnnotation(AnnotationCollection annotation, string avail2PropertyName)
            {
                availableValuesMember = avail2PropertyName;
                this.annotation = annotation;
                avail = new AvailableValuesAnnotation(annotation, avail2PropertyName);
            }
 
            public IEnumerable AvailableValues => avail.AvailableValues;
 
            public IEnumerable Selected
            {
                get => annotation.Get<IBasicCollectionAnnotation>().Elements;
                set
                {
                    var asCollection = annotation.Get<IBasicCollectionAnnotation>();
                    asCollection.Elements = value;
                }
 
            }
        }
 
        class InputStepAnnotation : IAvailableValuesSelectedAnnotation, IOwnedAnnotation, IStringReadOnlyValueAnnotation
        {
            class Strings : IStringLocalizer
            {
                // this should always be private.
                static readonly Strings strings = new();
 
                public static string NoSteps => strings.Translate("None");
                public static FormatString InputFormat => strings.TranslateFormat("{0} from {1}");
            }
 
            struct InputThing
            {
                public ITestStep Step { get; set; }
                public IMemberData Member { get; set; }
                public override string ToString()
                {
                    if (Step == null) return Strings.NoSteps;
                    return Strings.InputFormat.Format(Member.GetTranslatedDisplayAttribute().Name, Step.GetFormattedName());
                }
 
                public static InputThing FromInput(IInput inp)
                {
                    return new InputThing { Step = inp.Step, Member = inp.Property };
                }
 
                public override bool Equals(object obj)
                {
                    if (obj is InputThing other)
                    {
                        return other.Step == Step && other.Member == Member;
                    }
                    return false;
                }
 
                public override int GetHashCode()
                {
                    return (Step?.GetHashCode() ?? 1) ^ (Member?.GetHashCode() ?? 2);
                }
 
            }
 
            ITestStepParent getContextStep()
            {
                ITestStepParent step;
                if (parameterized)
                {
                    step = (annotation.Get<IMemberAnnotation>()?.Member as IParameterMemberData)
                        ?.ParameterizedMembers.Select(x => x.Source).OfType<ITestStep>()
                        .FirstOrDefault();
                }
                else
                {
                    AnnotationCollection parent = annotation;
                    while (parent.ParentAnnotation != null)
                        parent = parent.ParentAnnotation;
 
                    object context = parent.Get<IObjectValueAnnotation>().Value;
                    step = context as ITestStep;
                
                    if (context is IEnumerable enumerable_context)
                    {
                        step = enumerable_context.OfType<ITestStep>().FirstOrDefault();
                    }
                }
 
                while (step.Parent != null)
                    step = step.Parent;
                return step;
            }
            
            public IEnumerable AvailableValues
            {
                get
                {
                    var inp = getInput();
                    if (inp == null)
                        return Enumerable.Empty<object>();
 
                    ITestStepParent step = getContextStep();
 
                    var steps = Utils.FlattenHeirarchy(step.ChildTestSteps, x => x.ChildTestSteps);
 
                    List<InputThing> accepted = new List<InputThing>();
                    accepted.Add(new InputThing() );
                    if (inp is IInputTypeRestriction res)
                    {
                        foreach (var s in steps)
                        {
                            var t = TypeData.GetTypeData(s);
                            foreach (var mem in t.GetMembers())
                            {
                                if (mem.HasAttribute<OutputAttribute>())
                                {
                                    if (res.SupportsType(mem.TypeDescriptor))
                                    {
                                        accepted.Add(new InputThing { Step = s, Member = mem });
                                    }
                                }
                            }
                        }
                    }
 
                    return accepted;
                }
            }
 
            IInput getInput() => annotation.GetAll<IObjectValueAnnotation>()
                .FirstNonDefault(x => x.Value as IInput);
 
            // Use this when an instance of IInput is required, but the exact one is not critical
            IInput getInputRecursive()
            {
                // Recursively search for IInput instances. This should only be used during Write.
                // This is only relevant if the ObjectValueAnnotation is a MergedValueAnnotation.
                // If we are dealing with a merged value, we don't care if the current values are not aligned,
                // because they will be aligned after we call the setter.
                foreach (var ova in annotation.GetAll<IObjectValueAnnotation>())
                {
                    // This is the case in almost all instances
                    if (ova.Value is IInput i)
                        return i;
 
                    // This is the case when using unaligned merged values
                    if (ova is MergedValueAnnotation merged)
                    {
                        foreach (var m in merged.Merged)
                        {
                            if (m.Get<IObjectValueAnnotation>().Value is IInput i2)
                                return i2;
                        }
                    }
                }
 
                return null;
            }
 
            public void Read(object source)
            {
                setValue = null;
            }
 
            public void Write(object source)
            {
                if (!(setValue is InputThing v)) return;
                
                var inp = getInputRecursive();
                if (inp == null) return;
 
                inp.Step = v.Step;
                inp.Property = v.Member;
                 
                // If we are dealing with a MergedValueAnnotation, call the setter to propagate the IInput changes
                var merged = annotation.Get<MergedValueAnnotation>();
                if (merged != null) merged.Value = inp;
            }
 
            InputThing? setValue = null;
 
            public object SelectedValue
            {
                get
                {
                    if (setValue.HasValue == false)
                    {
                        var input = getInput();
                        if (input != null)
                            setValue = InputThing.FromInput(input);
                    }
 
                    return setValue;
                }
 
                set => setValue = value as InputThing?;
            }
 
            AnnotationCollection annotation;
            readonly bool parameterized;
 
            public InputStepAnnotation(AnnotationCollection annotation) => this.annotation = annotation;
 
            public InputStepAnnotation(AnnotationCollection annotation, bool parameterized) : this(annotation) =>
                this.parameterized = parameterized;
            
            public string Value
            {
                get 
                { 
                    var currentValue = annotation.GetAll<IObjectValueAnnotation>()
                        .FirstNonDefault(x => x.Value as IInput);
                    if(currentValue != null && currentValue.Property != null && currentValue.Step != null)
                        return $"{currentValue.Property?.GetDisplayAttribute().Name} from {currentValue.Step?.GetFormattedName()}";
                    return "None";
                }
            }
        }
 
        class EnumValuesAnnotation : IAvailableValuesAnnotation
        {
            IEnumerable availableValues;
            public IEnumerable AvailableValues
            {
                get
                {
                    // This cache is disabled for two reasons:
                    // 1. Changing language requires invalidating this cache. Otherwise weird issues can occur.
                    // 2. Translations are automatically reloaded on change. This also requires invalidating this cache.
                    // There is currently no good mechanism to handle these scenarios.
                    // TODO: Find the golden path to language based cache invalidation.
                    // if (availableValues == null)
                    {
                        var names = Enum.GetNames(enumType);
                        var values = Enum.GetValues(enumType);
                        
                        var orders = names.Select((x, i) =>
                        {
                            var enumValue = values.GetValue(i) as Enum;
                            var disp = TranslationManager.TranslateEnum(enumValue);
                            var memberInfo = enumType.GetMember(x).FirstOrDefault();
                            return (Display: disp, IsBrowsable: memberInfo.IsBrowsable());
                        }).ToArray();
                        availableValues = Enumerable.Range(0, names.Length)
                            .Where(i => orders[i].IsBrowsable)
                            .OrderBy(i => orders[i].Display.Order)
                            .Select(i => values.GetValue(i))
                            .ToArray();
                    }
                    return availableValues;
                }
            }
 
            readonly Type enumType;
            EnumValuesAnnotation(Type enumType) => this.enumType = enumType;
 
            static readonly ConcurrentDictionary<Type, EnumValuesAnnotation> lookup =
                new ConcurrentDictionary<Type, EnumValuesAnnotation>();
            public static EnumValuesAnnotation FromEnumType(Type type) =>
                lookup.GetOrAdd(type, x => new EnumValuesAnnotation(x));
        }
 
        class EnumStringAnnotation : IStringValueAnnotation, IValueDescriptionAnnotation, ICopyStringValueAnnotation
        {
 
            Enum evalue
            {
                get => a.Get<IObjectValueAnnotation>()?.Value as Enum;
                set => a.Get<IObjectValueAnnotation>().Value = value;
            }
 
            public string Value
            {
                get => Utils.EnumToReadableString(evalue);
                set {
                    var values = Enum.GetValues(enumType).Cast<Enum>();
 
                    var newvalue = values.FirstOrDefault(x => Utils.EnumToReadableString(x) == value);
                    if (newvalue == null)
                    {
                        newvalue = values.FirstOrDefault(x => Utils.EnumToReadableString(x).ToLower() == value.ToLower());
                    }
                    if (newvalue != null)
                        evalue = newvalue;
                    else
                        throw new FormatException($"Unable to parse {value} as an {enumType}");
                }
            }
 
            AnnotationCollection a;
            Type enumType;
            public EnumStringAnnotation(Type enumType, AnnotationCollection annotation)
            {
                this.a = annotation;
                this.enumType = enumType;
            }
 
            public string Describe()
            {
                if (evalue is Enum e)
                    return Utils.EnumToDescription(e);
                return null;
            }
        }
 
        class FlagEnumAnnotation : IMultiSelect
        {
            public IEnumerable Selected
            {
                get
                {
                    List<Enum> items = new List<Enum>();
                    if (this.val.Value is Enum value)
                    {
                        var zeroVal = Enum.ToObject(enumType, 0);
                        foreach (Enum enumValue in Enum.GetValues(enumType))
                        {
                            if (value.HasFlag(enumValue))
                            {
                                // To remove default value 0 for any value > 0 selected, else just select 0
                                if (value.Equals(zeroVal) || !enumValue.Equals(zeroVal))
                                    items.Add(enumValue);
                            }
                        }
                    }
                    prevSelected = items;
                    return items;
                }
                set
                {
                    var currSelected = value.Cast<Enum>();
 
                    // Get prev state
                    long prevBits = GetBitState(prevSelected);
 
                    long bits = SetBitState(prevBits, currSelected);
                    val.Value = Enum.ToObject(enumType, bits);
                }
            }
 
            IEnumerable<Enum> prevSelected = Enumerable.Empty<Enum>();
            IObjectValueAnnotation val => annotation.Get<IObjectValueAnnotation>();
            Type enumType;
            AnnotationCollection annotation;
 
            public FlagEnumAnnotation(AnnotationCollection annotation, Type enumType)
            {
                this.annotation = annotation;
                this.enumType = enumType;
            }
 
            private long GetBitState(IEnumerable state)
            {
                long bitValue = 0;
                foreach (Enum item in state)
                    bitValue |= Convert.ToInt64(item);
 
                return bitValue;
            }
 
            private long SetBitState(long bits, IEnumerable<Enum> currSelected)
            {
                // Get the diff (ie selection or unselection value)
                IEnumerable<Enum> diff = prevSelected.Except(currSelected);
                long removedBits = GetBitState(diff);
                if (diff.Any())
                    bits ^= removedBits;
 
                diff = currSelected.Except(prevSelected);
                long addedBits = GetBitState(diff);
                if (diff.Count() > 0)
                {
                    if (addedBits == 0)
                        bits = 0;   // Special handling for zero value to unselect all values
                    else
                        bits |= addedBits;
                }
 
                return bits;
            }
        }
 
        class StringValueAnnotation : IStringValueAnnotation, ICopyStringValueAnnotation
        {
            public string Value
            {
                get => (string)annotation.Get<IObjectValueAnnotation>().Value;
                set => annotation.Get<IObjectValueAnnotation>().Value = value;
            }
 
            AnnotationCollection annotation;
            public StringValueAnnotation(AnnotationCollection dataAnnotation)
            {
                annotation = dataAnnotation;
            }
        }
 
        class MacroStringValueAnnotation : IStringValueAnnotation, IValueDescriptionAnnotation, IStringExampleValueAnnotation
        {
            public string Value
            {
                get => ((MacroString)annotation.Get<IObjectValueAnnotation>().Value)?.Text;
                set
                {
                    var mcs = annotation.Get<IObjectValueAnnotation>().Value as MacroString;
                    if (mcs == null)
                    {
                        mcs = new MacroString();
                        annotation.Get<IObjectValueAnnotation>().Value = mcs;
                    }
                    mcs.Text = value;
                }
            }
 
            AnnotationCollection annotation;
            public MacroStringValueAnnotation(AnnotationCollection dataAnnotation)
            {
                annotation = dataAnnotation;
            }
 
            public string Describe()
            {
                var mcs = annotation.Get<IObjectValueAnnotation>().Value as MacroString;
                return mcs?.Expand();
            }
 
            public string Example => Describe();
        }
 
        class ColumnAccessAnnotation : IAccessAnnotation
        {
            public bool IsReadOnly => true;
 
            public bool IsVisible => true;
        }
 
        class StepNameStringValue : IStringReadOnlyValueAnnotation
        {
            AnnotationCollection annotation;
            bool member;
            public StepNameStringValue(AnnotationCollection annotation, bool member)
            {
                this.annotation = annotation;
                this.member = member;
            }
            public string Value
            {
                get
                {
                    object value;
                    if (member)
                    {
                        value = annotation.ParentAnnotation.Get<IObjectValueAnnotation>().Value;
                    }
                    else
                    {
                        value = annotation.Get<IObjectValueAnnotation>().Value;
                    }
 
                    if (value is ITestStep step)
                    {
                        return step.GetFormattedName();
                    }
                    
                    if (value is IEnumerable<ITestStep> steps)
                    {
                        string formattedName = steps.FirstOrDefault()?.GetFormattedName();
                        return steps.Skip(1).Any(s => s.GetFormattedName() != formattedName) ? null : formattedName;
                    }
 
                    return null;
                }
            }
        }
 
        class MethodAnnotation : IMethodAnnotation, IOwnedAnnotation
        {
            public void Invoke()
            {
                if (source == null)
                    throw new InvalidOperationException("Unable to invoke method");
                if(member.GetValue(source) is Action action)
                    action();
            }
 
            public MethodAnnotation(IMemberData member) => this.member = member;
 
            IMemberData member;
            object source;
 
            public void Read(object source) => this.source = source;
 
            public void Write(object source) { }
        }
 
        class BasicCollectionAnnotation : IBasicCollectionAnnotation, IOwnedAnnotation, IFixedSizeCollectionAnnotation
        {
            public IEnumerable Elements { get; set; }
 
            public bool IsFixedSize
            {
                get
                {
                    if (Elements is Array) return false; // to maintain backwards compatibility Array is not fixed size.
                    if (Elements is IList l) return l.IsFixedSize;
                    return false;
                }
            }
 
            IEnumerable origin;
            public void Read(object source)
            {
                Elements = annotations.Get<IObjectValueAnnotation>().Value as IEnumerable;
                origin = Elements;
            }
 
            bool isWriting;
            
            public void Write(object source)
            {
                if (isWriting) return;
                if (object.ReferenceEquals(origin, Elements)) return;
                var fac = annotations;
                bool rdonly = fac.Get<ReadOnlyMemberAnnotation>() != null;
                var objValue = fac.Get<IObjectValueAnnotation>();
                var lst = objValue.Value;
                if (lst is IList lst2)
                {
                    if (lst2.IsReadOnly)
                        rdonly = true;
                    if (!rdonly)
                    {
                        // Arrays must be re-allocated
                        if (lst2.GetType().IsArray)
                        {
                            // If lst2 is an array, re-allocate it to have the exact number of elements required
                            var cnt = Elements.Count();
                            if (cnt != lst2.Count)
                            {
                                var elemType = lst2.GetType().GetElementType();
                                lst2 = Array.CreateInstance(elemType!, cnt);
                                objValue.Value = lst2;
                            }
                        }
                        // Dynamic collections can just be cleared
                        else
                        {
                            lst2.Clear();
                        }
                    }
 
                    int index = 0;
                    foreach (var val in Elements)
                    {
                        if (!rdonly)
                        {
                            if (lst2.IsFixedSize)
                            {
                                lst2[index] = val;
                                index++;
                            }
                            else
                            {
                                lst2.Add(val);
                            }
                        }
                    }
                }
                isWriting = true;
                try
                {
                    fac.Write(source);
                }
                finally
                {
                    isWriting = false;
                }
            }
 
            readonly AnnotationCollection annotations;
 
            public BasicCollectionAnnotation(AnnotationCollection annotations)
            {
                this.annotations = annotations;
            }
        }
 
        class MemberDataSequenceStringAnnotation : IStringReadOnlyValueAnnotation
        {
            readonly AnnotationCollection annotations;
 
            public MemberDataSequenceStringAnnotation(AnnotationCollection annotations) =>
                this.annotations = annotations;
 
            public string Value
            {
                get
                {
                    var seq = annotations.Get<IObjectValueAnnotation>().Value as IEnumerable;
                    var mems = seq?.OfType<IMemberData>() ?? Array.Empty<IMemberData>();
                    if (mems.Any() == false) return "None";
                    return string.Join(", ", mems.Select(x => x.GetDisplayAttribute().Name));
                }
            }
        }
 
        class GenericSequenceAnnotation : ICollectionAnnotation, IOwnedAnnotation, IStringReadOnlyValueAnnotation
        {
            public IEnumerable Elements => fac.Get<IObjectValueAnnotation>().Value as IEnumerable;
            /// <summary>
            /// Invalidated means that the values needs to get re-evaluated.
            /// So it may be that the previous value is used if the values are the same.
            /// This is also why Read needs to be called even if invalidate gets set.
            /// </summary>
            bool invalidated;
 
            IEnumerable<AnnotationCollection> annotatedElements;
 
            public IEnumerable<AnnotationCollection> AnnotatedElements
            {
                get
                {
                    if (invalidated || annotatedElements == null)
                    {
                        invalidated = false;
                        
                        var elements = Elements;
                        // if the elements is null, just return an empty array (below).
                        if (elements != null)
                        {
                            if (annotatedElements != null && elements.Cast<object>()
                                    .SequenceEqual(annotatedElements.Select(x => x.Source)))
                            {
                                // The values has not changed. Don't create a new list of annotation, just re-use the old.
                                return annotatedElements;
                            }
 
                            List<AnnotationCollection> annotations = new List<AnnotationCollection>();
                            foreach (var elem in elements)
                                annotations.Add(fac.AnnotateSub(null, elem));
 
                            annotatedElements = annotations;
                        }
                    }
 
                    return annotatedElements ?? Array.Empty<AnnotationCollection>();
 
                }
                set
                {
                    annotatedElements = value;
                }
            }
 
            public string Value => string.Format("Count: {0}", Elements?.Cast<object>().Count() ?? 0);
 
            AnnotationCollection fac;
            public GenericSequenceAnnotation(AnnotationCollection fac)
            {
                this.fac = fac;
            }
 
            public void Read(object source)     
            {
                invalidated = true;
                foreach (var elem in annotatedElements ?? Array.Empty<AnnotationCollection>())
                    elem.Read();
            }
 
            bool isWriting = false;
            public void Write(object source)
            {
                if (isWriting) return;
                if (annotatedElements == null) return;
                bool rdonly = fac.Get<ReadOnlyMemberAnnotation>() != null;
                var objValue = fac.Get<IObjectValueAnnotation>();
                var lst = objValue.Value;
                if (lst == null)
                { 
                    // if the list is null, create a new instance as long as the member is writable.
                    
                    if ((fac.Get<IMemberAnnotation>()?.Member?.Writable) == false)
                        throw new Exception($"Cannot add elements to collection because it is not writable.");
                    
                    var typedata = fac.Get<IReflectionAnnotation>().ReflectionInfo.AsTypeData();
                    if (typedata.DescendsTo(typeof(Array)))
                    {                    
                        // A new array of different length is created further down.
                        lst = Array.CreateInstance(typedata.ElementType.Type, 0);               
                    }
                    else if(typedata.CanCreateInstance)
                    {
                        lst = typedata.CreateInstance();
                    }
 
                    objValue.Value = lst;
                }
 
                if (lst is IList lst2)
                {
                    if (lst2.IsReadOnly)
                        rdonly = true;
 
                    if (!rdonly && !lst2.IsFixedSize)
                    {
                        // this clause contains a special case for lists
                        // Emulate adding/removing elements to the list
                        // calculate the changes so that fewest possible changes are done
                        // to the source list.
 
                        foreach (var elem in annotatedElements)
                        {
                            var val = elem.Get<IObjectValueAnnotation>().Value;
                            elem.Write(val);
                        }
 
                        var values = annotatedElements.Select(x => x.Get<IObjectValueAnnotation>().Value).ToList();
 
                        {   // remove elements that does no longer exists.
 
                            var hsh = values.ToHashSet();
                            for (int i = 0; i < lst2.Count; i++)
                            {
                                var e = lst2[i];
                                if (hsh.Contains(e) == false)
                                {
                                    lst2.RemoveAt(i);
                                    i--;
                                }
                            }
                        }
 
                        // now iteratively add/move elements
                        // so that lst2 becomes the same as 'values'
 
                        for (int i1 = 0,  i2 = 0; i1 < values.Count; i1++, i2++)
                        {
                            if (i1 >= lst2.Count)
                            {
                                lst2.Add(values[i1]);
                                continue;
                            }
                            if (lst2[i2] == values[i1])
                                continue; // same element.. we can continue.
 
                            for (int i3 = i2; i3 < lst2.Count; i3++)
                            {
                                // before inserting the element check that it does not figure further ahead in the list.
                                // if this is the case, remove it. This handles cases where things has been moved.
                                if (values[i1] == lst2[i3])
                                {
                                    lst2.RemoveAt(i3);
                                    break;
                                }
                            }
 
                            var val = values[i1];
                            if (val == null)
                            {
                                var typedata = fac.Get<IReflectionAnnotation>().ReflectionInfo.AsTypeData().ElementType;
                                if (typedata.CanCreateInstance || typedata.IsValueType)
                                    val = typedata.Type.CreateInstance();
                            }
 
                            lst2.Insert(i2, val);
                        }
                        while (lst2.Count > values.Count)
                        {
                            lst2.RemoveAt(lst2.Count - 1);
                        }
 
                    }
                    else
                    {
 
                        if (!rdonly)
                            lst2.Clear();
 
                        if (lst2.IsFixedSize)
                        {
                            var nElements = annotatedElements.Count();
                            if (nElements != lst2.Count)
                            {
                                var typedata = fac.Get<IReflectionAnnotation>().ReflectionInfo.AsTypeData();
                                if (typedata.DescendsTo(typeof(Array)))
                                {
                                    if ((fac.Get<IMemberAnnotation>()?.Member?.Writable) == false)
                                        throw new Exception($"Cannot add elements to collection because it is not writable.");
                                        
                                    lst2 = Array.CreateInstance(typedata.ElementType.Type, nElements);
                                    lst = lst2;
 
                                }
                                else
                                {
                                    throw new Exception("Could not extend container of fixed size.");
                                }
                            }
                        }
 
                        int index = 0;
                        foreach (var elem in annotatedElements)
                        {
                            var val = elem.Get<IObjectValueAnnotation>().Value;
 
                            elem.Write(val);
                            if (!rdonly)
                            {
                                if (lst2.IsFixedSize)
                                {
                                    lst2[index] = val;
                                    index++;
                                }
                                else
                                {
                                    lst2.Add(val);
                                }
                            }
                        }
                    }
                }
 
                if (rdonly && lst == null)
                {
                    //throw new Exception("Unable to show list value");
                    // an error should be thrown here, but that will critically break current implementations
                    // lets wait a few releases before we do that.
                    return;
                }
 
                // Some IObjectValue annotations works best if they are notified of a modification this way.
                // for example MergedValueAnnotation.
                objValue.Value = lst;
                
                isWriting = true;
                try
                {
                    fac.Write(source);
                }
                finally
                {
                    isWriting = false;
                }
            }
 
 
            public AnnotationCollection NewElement()
            {
                var reflect = fac.Get<IReflectionAnnotation>();
 
                if (reflect.ReflectionInfo is TypeData cstype)
                {
                    var elemType = cstype.Type.GetEnumerableElementType();
 
                    var elem2 = TypeData.FromType(elemType);
                    if (elem2.CanCreateInstance == false)
                    {
                        if (elem2.Type == typeof(string))
                            return fac.AnnotateSub(elem2, "");
                        if (elem2.IsNumeric)
                            return fac.AnnotateSub(elem2, Convert.ChangeType(0, elem2.Type));
                        object instance = null;
                        var member = fac.Get<IMemberAnnotation>()?.Member;
                       
                        if(member?.GetAttribute<ElementFactoryAttribute>() is ElementFactoryAttribute f)
                        {
                            var source = fac.Source;
                            if (member is IParameterMemberData param)
                            {
                                source = (param.ParameterizedMembers.FirstOrDefault(x => x.Member.GetAttribute<ElementFactoryAttribute>() == f).Source) ?? source;
                            }
                            instance = FactoryAttribute.Create(source, f);
                        }
                        if (instance != null)
                            return fac.AnnotateSub(null, instance);
                        
                        if (elem2.IsValueType)
                        {
                            if (elem2.DescendsTo(typeof(Enum)))
                                return fac.AnnotateSub(elem2, Enum.ToObject(elem2.Type, 0));
                            if(elem2.DescendsTo(typeof(DateTime)))
                                return fac.AnnotateSub(elem2, DateTime.MinValue);
                            if(elem2.DescendsTo(typeof(TimeSpan)))
                                return fac.AnnotateSub(elem2, TimeSpan.MinValue);
                            if(elem2.DescendsTo(typeof(bool)))
                                return fac.AnnotateSub(elem2, false);
                        }
                        return fac.AnnotateSub(elem2, null);
                    }
                    else
                    {
                        object instance = null;
                        try
                        {
                            var member = fac.Get<IMemberAnnotation>()?.Member;
                            if(member?.GetAttribute<ElementFactoryAttribute>() is ElementFactoryAttribute f)
                            {
                                var source = fac.Source;
                                if (member is IParameterMemberData param)
                                {
                                    source = (param.ParameterizedMembers.FirstOrDefault(x => x.Member.GetAttribute<ElementFactoryAttribute>() == f).Source) ?? source;
                                }
                                instance = FactoryAttribute.Create(source, f);
                            }
                            if(instance == null)
                            {
                               instance = elem2.CreateInstance(Array.Empty<object>());
                            }
                        }
                        catch
                        {
 
                        }
                        return fac.AnnotateSub(null, instance);
                    }
                }
                throw new InvalidOperationException();
            }
        }
 
        
        class ResourceAnnotation : IAvailableValuesAnnotation, IStringValueAnnotation, ICopyStringValueAnnotation, IErrorAnnotation
        {
            readonly Type baseType;
            readonly AnnotationCollection a;
 
            public IEnumerable AvailableValues 
            {
                get
                {
                    // We need all items (from any resource container) which can be assigned to a property of type baseType.
                    var x = ComponentSettingsList.GetResourceContainers()
                        .Select(x => x.Cast<object>())
                        .SelectMany(x => x);
                    var cv = a.Get<IObjectValueAnnotation>()?.Value as IResource;
                    var result = x.Where(y => y.GetType().DescendsTo(baseType)).ToList();
                    // if the selected value is not in the list show it anyway.
                    if (cv != null && result.Contains(cv) == false)
                        result.Add(cv);
 
                    return result;
                }
            }
            
            string IStringReadOnlyValueAnnotation.Value => (a.Get<IObjectValueAnnotation>()?.Value as IResource)?.ToString();
 
            public string Value
            {
                get => (a.Get<IObjectValueAnnotation>()?.Value as IResource)?.ToString();
                set
                {
                    var values = AvailableValues.OfType<IResource>();
                    var resource = values.FirstOrDefault(x => x.Name == value) ?? values.FirstOrDefault(x => x.ToString() == value);
                    if(resource == null)
                        throw new FormatException("Unknown resource: " + value ?? "");
                    var objectValue = a.Get<IObjectValueAnnotation>();
                    if (objectValue != null)
                        objectValue.Value = resource;
                    else 
                        throw new Exception("Cannot set resource value");
                } 
            }
 
            public ResourceAnnotation(AnnotationCollection a, Type lowerstType)
            {
                baseType = lowerstType;
                this.a = a;
            }
 
            static readonly string[] errorResponse = {"The selected value has been deleted."};
            public IEnumerable<string> Errors
            {
                get
                {
                    var list = ComponentSettingsList.GetContainer(baseType) as IComponentSettingsList;
                    // if the selected value has been deleted. This can occur with resources referencing other resources.
                    if (a.Get<IObjectValueAnnotation>()?.Value is IResource cv && list?.GetRemovedAliveResources().Contains(cv) == true) 
                        return errorResponse;
                    return Array.Empty<string>();   
                }
            }
        }
 
        class DefaultAccessAnnotation : IAccessAnnotation
        {
            public bool IsReadOnly => rdonly;
 
            public bool IsVisible => browsable;
            bool rdonly;
            bool browsable;
 
            public DefaultAccessAnnotation(bool rdonly, bool browsable)
            {
                this.rdonly = rdonly;
                this.browsable = browsable;
            }
        }
 
        class MemberToStringAnnotation : IStringValueAnnotation, ICopyStringValueAnnotation
        {
            public string Value
            {
                get
                {
                    var mem = (annotation.Get<IObjectValueAnnotation>()?.Value as IMemberData);
                    return mem?.GetDisplayAttribute().GetFullName();
                }
                set => throw new NotImplementedException();
            }
 
            AnnotationCollection annotation;
            public MemberToStringAnnotation(AnnotationCollection da)
            {
                annotation = da;
            }
        }
 
        class MultiResourceSelector : IMultiSelect, IStringReadOnlyValueAnnotation
        {
            public IEnumerable Selected
            {
                get => annotation.Get<IObjectValueAnnotation>().Value as IEnumerable;
                set
                {
                    var seq = annotation.Get<ICollectionAnnotation>();
                    var anot = seq.AnnotatedElements.ToArray();
                    List<AnnotationCollection> elements = new List<AnnotationCollection>();
                    var values = value.Cast<object>().ToArray();
                    for (int i = 0; i < values.Length; i++)
                    {
                        if (anot.Length < i)
                        {
                            var val = anot[i].Get<IObjectValueAnnotation>();
                            val.Value = values[i];
                            elements.Add(anot[i]);
                        }
                        else
                        {
                            var anot2 = seq.NewElement();
                            anot2.Get<IObjectValueAnnotation>().Value = values[i];
                            elements.Add(anot2);
                        }
                    }
                    seq.AnnotatedElements = elements;
                }
            }
 
            public string Value => string.Join(", ", Selected.Cast<IResource>().Select(s => s?.Name ?? ""));
 
            AnnotationCollection annotation;
            Type baseType;
            public MultiResourceSelector(AnnotationCollection annotation, Type baseType)
            {
                this.baseType = baseType;
                this.annotation = annotation;
            }
 
            public override string ToString()
            {
                return $"{Selected.Cast<object>().Count()} objects selected";
            }
        }
 
        class EnabledAnnotation : IEnabledValueAnnotation, IMembersAnnotation, IOwnedAnnotation
        {
            class EnabledAccessAnnotation : IAccessAnnotation
            {
                AnnotationCollection parentAnnotation;
                public EnabledAccessAnnotation(AnnotationCollection parentAnnotation)
                {
                    this.parentAnnotation = parentAnnotation;
                }
                public bool IsReadOnly => (parentAnnotation.Get<IObjectValueAnnotation>().Value as IEnabled)?.IsEnabled == false;
 
                public bool IsVisible => true;
            }
 
            readonly AnnotationCollection annotations;
 
            private AnnotationCollection isEnabled;
            public AnnotationCollection IsEnabled
            {
                get
                {
                    if (isEnabled == null)
                        isEnabled = annotations.Get<IMembersAnnotation>(from : this).Members
                                               .FirstOrDefault(x => x.Get<IMemberAnnotation>().Member.Name == nameof(Enabled<int>.IsEnabled));
                    return isEnabled;
                }
            }
            private AnnotationCollection value;
            public AnnotationCollection Value
            {
                get
                {
                    if (value != null) return value;
                    var unit = annotations.Get<UnitAttribute>();
                    var avail = annotations.Get<IAvailableValuesAnnotation>();
                    List<IAnnotation> extra = new List<IAnnotation>();
                    if (unit != null) { extra.Add(unit); }
                    if (avail != null) { extra.Add(avail); }
                    if (annotations.Get<DirectoryPathAttribute>() is DirectoryPathAttribute d)
                        extra.Add(d);
                    if (annotations.Get<FilePathAttribute>() is FilePathAttribute f)
                        extra.Add(f);
                    if (annotations.Get<DynamicSelectAttribute>() is DynamicSelectAttribute ds)
                        extra.Add(ds);
                    if (annotations.Get<TreeDataAttribute>() is TreeDataAttribute tda)
                        extra.Add(tda);
                    if (annotations.Get<ISuggestedValuesAnnotation>() is ISuggestedValuesAnnotation s)
                        extra.Add(s);
 
                    extra.Add(new EnabledAccessAnnotation(annotations));
                    var valueMember = annotations.Get<IMembersAnnotation>(from: this).Members.FirstOrDefault(x => x.Get<IMemberAnnotation>().Member.Name != nameof(Enabled<int>.IsEnabled));
                    var src = annotations.Get<IObjectValueAnnotation>().Value as IEnabledValue;
                    var sub = annotations.AnnotateSub(valueMember.Get<IReflectionAnnotation>().ReflectionInfo, src?.Value, extra.ToArray());
                    sub.Add(new AnnotationCollection.MemberAnnotation(TypeData.GetTypeData(src).GetMember("Value") ?? TypeData.FromType(typeof(IEnabledValue)).GetMember("Value"))); // for compatibility with 9.8 UIs, emulate that this is a Value member from a Enabled<T> class
                    value = sub;
                    return value;
                }
            }
 
            public IEnumerable<AnnotationCollection> Members => new [] { IsEnabled, Value };
 
            public EnabledAnnotation(AnnotationCollection annotations)
            {
                this.annotations = annotations;
            }
 
            public void Read(object source)
            {
                if (Members != null)
                {
                    var val = annotations.Get<IObjectValueAnnotation>().Value;
                    if (val == null) return;
                    foreach (var member in Members)
                        member.Read(val);
                }
 
                if (value != null)
                {
                    var val = annotations.Get<IObjectValueAnnotation>().Value as IEnabledValue;
                    value.Get<ObjectValueAnnotation>().Value = val?.Value;
                }
            }
 
            public void Write(object source)
            {
                if (Members != null)
                {
                    var val = annotations.Get<IObjectValueAnnotation>().Value;
                    foreach (var member in Members)
                        member.Write(val);
                    {
                        // since the Enabled annotation overrides the other IMembersAnnotation
                        // we need to make sure to update that too.
                        var otherMembers = annotations.Get<IMembersAnnotation>(from: this);
                        foreach (var member in otherMembers.Members)
                            member.Read();
                    }
                }
                if (value != null)
                {
                    if(annotations.Get<IObjectValueAnnotation>().Value is IEnabledValue en)
                        en.Value = value.Get<ObjectValueAnnotation>().Value;
                }
            }
        }
 
        class DeviceAddressAnnotation : ISuggestedValuesAnnotation
        {
            public IEnumerable SuggestedValues => getDeviceAddresses();
 
            public IEnumerable<string> getDeviceAddresses()
            {
                var mem = annotation.Get<IMemberAnnotation>();
                var device_attr = mem.Member.GetAttribute<DeviceAddressAttribute>();
                var plugins = PluginManager.GetPlugins<IDeviceDiscovery>();
                List<string> result = new List<string>();
                foreach (var plugin in plugins)
                {
                    try
                    {
                        var device_discoverer = (IDeviceDiscovery)Activator.CreateInstance(plugin);
                        if (device_discoverer.CanDetect(device_attr))
                        {
                            result.AddRange(device_discoverer.DetectDeviceAddresses(device_attr));
                        }
                    }
                    catch
                    {
 
                    }
                }
                return result.Distinct().ToArray();
            }
 
            AnnotationCollection annotation;
 
            public DeviceAddressAnnotation(AnnotationCollection annotation)
            {
                this.annotation = annotation;
            }
        }
 
        class SuggestedValueAnnotation : ISuggestedValuesAnnotation
        {
            string suggestedValuesMember;
            public IEnumerable SuggestedValues => getSuggestedValues();
 
            public IEnumerable getSuggestedValues()
            {
                var mem = annotation.ParentAnnotation.Get<IMembersAnnotation>()?.Members;
                var mem2 = mem.FirstOrDefault(x => x.Get<IMemberAnnotation>()?.Member.Name == suggestedValuesMember);
 
                return mem2?.Get<IObjectValueAnnotation>().Value as IEnumerable ?? Enumerable.Empty<object>();
            }
 
            AnnotationCollection annotation;
 
            public SuggestedValueAnnotation(AnnotationCollection annotation, string suggestedValuesMember)
            {
                this.annotation = annotation;
                this.suggestedValuesMember = suggestedValuesMember;
            }
        }
 
        class PortAnnotation : IAvailableValuesAnnotation, IStringReadOnlyValueAnnotation
        {
            public IEnumerable AvailableValues
            {
                get
                {
                    IEnumerable<Port> getPorts(IResource res) => res.GetConstProperties<Port>();
 
                    var dutPorts = DutSettings.Current.SelectMany(getPorts);
                    var instrumentPorts = InstrumentSettings.Current.SelectMany(getPorts);
                    var availablePorts = dutPorts.Concat(instrumentPorts);
                    return availablePorts;
                }
            }
 
            public string Value
            {
                get
                {
                    var port = annotation.Get<IObjectValueAnnotation>().Value as Port;
                    if (port == null) return "";
                    return port.ToString();
                }
            }
 
            AnnotationCollection annotation;
            public PortAnnotation(AnnotationCollection annotation)
            {
                this.annotation = annotation;
            }
        }
 
        class ViaPointAnnotation : IAvailableValuesAnnotation, IMultiSelect, IStringReadOnlyValueAnnotation
        {
            AnnotationCollection annotation;
            public ViaPointAnnotation(AnnotationCollection annotation)
            {
                this.annotation = annotation;
            }
 
            public IEnumerable AvailableValues
            {
                get
                {
                    List<ViaPoint> all = InstrumentSettings.Current.SelectMany(instr => instr.GetConstProperties<ViaPoint>()).ToList();
                    return all;
                }
            }
 
            public IEnumerable Selected
            {
                get
                {
                    return (IEnumerable)annotation.Get<IObjectValueAnnotation>(from: this).Value;
                }
                set
                {
                    var lst = (IList)annotation.Get<IObjectValueAnnotation>(from: this).Value;
                    lst.Clear();
                    foreach (var val in value)
                        lst.Add(val);
                }
            }
 
            public string Value => string.Format("Via {0} Points", Selected?.Cast<object>().Count() ?? 0);
        }
 
        class ToStringAnnotation : IStringReadOnlyValueAnnotation
        {
            public string Value => annotations.Get<IObjectValueAnnotation>().Value?.ToString();
 
            AnnotationCollection annotations;
            public ToStringAnnotation(AnnotationCollection annotations)
            {
                this.annotations = annotations;
            }
        }
 
        class TestStepMultiSelectAnnotation : IAvailableValuesAnnotation, IMultiSelect, IStringReadOnlyValueAnnotation
        {
            AnnotationCollection annotation;
            public TestStepMultiSelectAnnotation(AnnotationCollection annotation) => this.annotation = annotation;
 
            public IEnumerable AvailableValues => annotation.Get<TestStepSelectAnnotation>().AvailableValues;
            public IEnumerable Selected
            {
                get => annotation.Get<IBasicCollectionAnnotation>().Elements;
                set => annotation.Get<IBasicCollectionAnnotation>().Elements = value;
            }
 
            public string Value => $"{Selected?.Cast<object>().Count()} Steps Selected";
        }
 
        class TestStepSelectAnnotation : IAvailableValuesAnnotation, IStringValueAnnotation, ICopyStringValueAnnotation
        {
            public IEnumerable AvailableValues
            {
                get
                {
                    var member = annotation.Get<IMemberAnnotation>()?.Member;
                    if (member == null) return Enumerable.Empty<object>();
                    var sibling = member.GetAttribute<StepSelectorAttribute>();
                    if (sibling == null) sibling = new StepSelectorAttribute(StepSelectorAttribute.FilterTypes.All);
                    var step = annotation.ParentAnnotation.Get<IObjectValueAnnotation>().Value as ITestStep;
                    var basicType = member.TypeDescriptor;
                    if (basicType is TypeData td && td.ElementType is ITypeData)
                        basicType = td.ElementType; // for enumerables of steps
                    return getSteps(step, sibling.Filter).Where(x => TypeData.GetTypeData(x).DescendsTo(basicType));
                }
            }
 
            public string Value {
                get {
                    var step = annotation.Get<IObjectValueAnnotation>().Value;
                    if (step is ITestStep _step) return _step.GetFormattedName();
                    return (step ?? "").ToString();
                }
                set => throw new NotSupportedException();
            }
 
            IEnumerable<ITestStep> getSteps(ITestStep step, StepSelectorAttribute.FilterTypes filter)
            {
                switch (filter)
                {
                    case StepSelectorAttribute.FilterTypes.All:
                        return Utils.FlattenHeirarchy(step.GetParent<TestPlan>().ChildTestSteps, x => x.ChildTestSteps);
                    case StepSelectorAttribute.FilterTypes.AllExcludingSelf:
                        return getSteps(step, StepSelectorAttribute.FilterTypes.All).Where(x => x.Id != step.Id);
                    case StepSelectorAttribute.FilterTypes.Children:
                        return step.ChildTestSteps;
                    case StepSelectorAttribute.FilterTypes.Sibling:
                        return step.Parent.ChildTestSteps.Where(x => x.Id != step.Id);
                    default:
                        throw new InvalidOperationException("Invalid filter type: " + filter);
                }
            }
 
            AnnotationCollection annotation;
            public TestStepSelectAnnotation(AnnotationCollection annotation)
            {
                this.annotation = annotation;
            }
        }
 
  
        class PluginTypeSelectAnnotation : IAvailableValuesAnnotation, IAnnotationStringer
        {
            /// <summary> This is used for generating strings for available and selected values. </summary>
            public string GetString(AnnotationCollection item)
            {
                return item.Get<IDisplayAnnotation>()?.Name;
            }
            
            IEnumerable<object> selection;
            public IEnumerable AvailableValues {
                get
                {
                    var currentValue = annotation.Get<IObjectValueAnnotation>()?.Value ?? null;
                    if (selection != null) return selection;
                    var member = annotation.Get<IMemberAnnotation>()?.Member;
                    var attrib = member.GetAttribute<PluginTypeSelectorAttribute>();
                    if (attrib == null)
                    {
                        selection = Enumerable.Empty<object>();
                        return selection;
                    }
                    if (member.TypeDescriptor is TypeData cst)
                    {
                        var currentType = TypeData.GetTypeData(currentValue);
                        List<object> selection = new List<object>();
                        
                        if (attrib.ObjectSourceProperty != null)
                        {
                            // if there is a source property, look for that. 
                            var obj = annotation.ParentAnnotation.Source;
                            var mem = TypeData.GetTypeData(obj).GetMember(attrib.ObjectSourceProperty);
                            var src = mem.GetValue(obj) as IEnumerable;
                            foreach (var item in src)
                                selection.Add(item);
                        }
                        else
                        {
                            // there is no objects source, so just generate them from the plugins.
                            foreach (var type in PluginManager.GetPlugins(cst.Type))
                            {
                                try
                                {
                                    var cstt = TypeData.FromType(type);
                                    if (cstt == currentType)
                                    {
                                        selection.Add(currentValue);
                                    }
                                    else
                                    {
                                        var obj = Activator.CreateInstance(type);
                                        selection.Add(obj);
                                    }
                                }
                                catch
                                {
 
                                }
                            }
                        }
                        this.selection = selection;
                    }
                    return selection ?? Enumerable.Empty<object>();
                }
            }
 
            AnnotationCollection annotation;
            public PluginTypeSelectAnnotation(AnnotationCollection annotation) => this.annotation = annotation;
 
        }
 
        /// <summary>
        /// For annotating MetaDataPromptObjects. This is only used when running the test plan with AllowPromptMetaData enabled.
        /// </summary>
        class MetaDataPromptAnnotation : IForwardedAnnotations, IOwnedAnnotation
        {
            AnnotationCollection annotation;
            public MetaDataPromptAnnotation(AnnotationCollection annotation)
            {
                this.annotation = annotation;
            }
 
            IEnumerable<AnnotationCollection> forwarded;
            
            public IEnumerable<AnnotationCollection> Forwarded
            {
                get
                {
                    if (forwarded != null) return forwarded;
                        
                    List<AnnotationCollection> metadataAnnotations = new List<AnnotationCollection>();
                    MetadataPromptObject obj = (MetadataPromptObject)annotation.Get<IObjectValueAnnotation>().Value;
                    var named = annotation.Get<INamedMembersAnnotation>();
                    if (named == null) return Enumerable.Empty<AnnotationCollection>();
                    var member = named.GetMember(TypeData.GetTypeData(obj).GetMember(nameof(MetadataPromptObject.Resources)));
                    var col = member.Get<ICollectionAnnotation>();
                    foreach (var annotatedResource in col.AnnotatedElements) {
                        object resource = annotatedResource.Get<IObjectValueAnnotation>().Value;
                        var named2 = annotatedResource.Get<INamedMembersAnnotation>();
                        var type = TypeData.GetTypeData(resource);
                        var rname = annotatedResource.Get<IStringReadOnlyValueAnnotation>()?.Value ?? resource.ToString();
                        foreach (var member2 in type.GetMembers())
                        {
                            if (member2.GetAttribute<MetaDataAttribute>() is MetaDataAttribute attr && attr.PromptUser)
                            {
                                var namedmember = named2.GetMember(member2);
                                if (namedmember == null) continue;
                                var disp = namedmember.Get<DisplayAttribute>();
                                var disp2 = new DisplayAttribute(disp.Name, disp.Description, Groups: new[] { rname }.Append(disp.Group).ToArray());
                                namedmember.Add(disp2);
                                metadataAnnotations.Add(namedmember);
                            }
                        }
                    }
 
                    forwarded = metadataAnnotations;
                    return metadataAnnotations;
                }
            }
 
            public void Read(object source) => forwarded?.ForEach(elem => elem.Read());
            public void Write(object source) => forwarded?.ForEach(elem => elem.Write());
        }
 
        void IAnnotator.Annotate(AnnotationCollection annotation)
        {
            var reflect = annotation.Get<IReflectionAnnotation>();
            var mem = annotation.Get<IMemberAnnotation>();
            if (mem == null && reflect != null)
            {
                if (reflect.ReflectionInfo.DescendsTo(typeof(IDisplayAnnotation)))
                    annotation.Add(new DisplayAnnotationWrapper());
                else
                    annotation.Add(reflect.ReflectionInfo.GetTranslatedDisplayAttribute());
            }
 
            bool rd_only = annotation.Get<ReadOnlyMemberAnnotation>() != null;
            if (reflect != null)
            {
                var help = reflect.ReflectionInfo.GetHelpLink();
                if (help != null)
                    annotation.Add(help);
                if (reflect.ReflectionInfo is TypeData ct)
                {
                    if (ct.Type.DescendsTo(typeof(IMemberData)))
                    {
                        annotation.Add(new MemberToStringAnnotation(annotation));
                    }
                    if (reflect.ReflectionInfo.DescendsTo(typeof(Port)))
                    {
                        annotation.Add(new PortAnnotation(annotation));
                    }
                    if (reflect.ReflectionInfo.DescendsTo(typeof(ViaPoint)))
                    {
                        annotation.Add(new ToStringAnnotation(annotation));
                    }
                }
            }
 
            if (annotation.Source is ITestStep step)
            {
                // if any parent step has disabled their child steps list.
                // then the settings of this step should be disabled.
                // There is an overlap between it being "ReadOnly" and "Disabled"
                // in this case we want it to be disabled, because e.g buttons should not be clickable.
                if(step.GetParents().Any(parent => parent.ChildTestSteps.IsReadOnly))
                    annotation.Add(DisabledSettingsAnnotation.Instance);
            }
 
            if (mem != null)
            {
                if (annotation.Get<IObjectValueAnnotation>() == null)
                    annotation.Add(new MemberValueAnnotation(annotation));
 
                var attributes = mem.Member.Attributes;
                Sequence.ProcessPattern(attributes,
                    (SuggestedValuesAttribute suggested) => annotation.Add(new SuggestedValueAnnotation(annotation, suggested.PropertyName)),
                    (DeviceAddressAttribute x) => annotation.Add(new DeviceAddressAnnotation(annotation)),
                    (PluginTypeSelectorAttribute x) => annotation.Add(new PluginTypeSelectAnnotation(annotation)));
 
                var translatedDisplay = mem.Member.GetTranslatedDisplayAttribute();
                annotation.Add(translatedDisplay);
 
                var browsable = mem.Member.GetAttribute<BrowsableAttribute>();
                if(mem.Member.Writable == false || browsable != null)
                    annotation.Add(new DefaultAccessAnnotation(mem.Member.Writable == false, browsable?.Browsable ?? true));
 
                if (mem.Member.TypeDescriptor.DescendsTo(typeof(Action<object>)) || mem.Member.TypeDescriptor.DescendsTo(typeof(Action)))
                    annotation.Add(new MethodAnnotation(mem.Member));
 
 
                if (mem.ReflectionInfo.DescendsTo(typeof(TimeSpan)))
                    annotation.Add(new TimeSpanAnnotation(annotation));
                if (mem.ReflectionInfo.DescendsTo(typeof(DateTime)))
                    annotation.Add(new DateTimeAnnotation(annotation));
 
                Sequence.ProcessPattern(attributes,
                    (UnitAttribute x) => annotation.Add(x),
                    (HelpLinkAttribute x) => annotation.Add(x),
                    (ColumnDisplayNameAttribute x) => annotation.Add(x),
                    (FilePathAttribute x) => annotation.Add(x),
                    (DirectoryPathAttribute x) => annotation.Add(x),
                    (IconAnnotationAttribute x) => annotation.Add(x)
                );
 
                Sequence.ProcessPattern(attributes,
                  (DynamicSelectAttribute x) => annotation.Add(new DynamicSelectAttribute(x.SourceName)),
                  (BindingListAttribute x) => annotation.Add(x));
 
                IconAnnotationHelper.AddParameter(annotation, mem.Member, annotation.Source);
                
            }
 
            var availMem = annotation.Get<AvailableMemberAnnotation>();
            if (availMem != null)
            {
                var da = availMem.AvailableMember.Get<UnitAttribute>();
                if (da != null)
                    annotation.Add(da);
            }
 
            if (mem != null)
            {
                var member = mem.Member;
                if (member.DeclaringType.DescendsTo(typeof(IValidatingObject)))
                {
                    annotation.Add(new ValidationErrorAnnotation(mem));
                }
                else if (member is EmbeddedMemberData emb)
                {
                    // if the member is not part of a validating object, but
                    // it comes from an embedded property which is, then the annotation
                    // should also be added.
                    while (emb != null)
                    {
                        if (emb.InnerMember.DeclaringType.DescendsTo(typeof(IValidatingObject)))
                        {
                            annotation.Add(new ValidationErrorAnnotation(mem));
                            break;
                        }
                        emb = emb.InnerMember as EmbeddedMemberData;
                    }
                }
 
                if (member.HasAttribute<EnabledIfAttribute>())
                {
                    annotation.Add(new EnabledIfAnnotation(mem));
                }
                if (member.Writable == false)
                {
                    annotation.Add(new ReadOnlyMemberAnnotation());
                }
                
                    
            }
 
            if (reflect?.ReflectionInfo is TypeData csharpType)
            {
                var type = csharpType.Load();
                
                bool isNullable = type.IsPrimitive == false && type.IsGenericType && csharpType.IsValueType && type.DescendsTo(typeof(Nullable<>));
                if (isNullable)
                {
                    Type type2 = type.GetGenericArguments().FirstOrDefault();
                    if (type2.IsNumeric())
                    {
                        annotation.Add(new NumberAnnotation(annotation) { NullableType = type2 });
                    }
                }
 
                if (type.IsNumeric())
                {
                    annotation.Add(new NumberAnnotation(annotation));
                }
                if (type == typeof(bool)) {
                    annotation.Add(new BooleanValueAnnotation(annotation));
                }
                if (type == typeof(string))
                    annotation.Add(new StringValueAnnotation(annotation));
                if (type == typeof(MacroString))
                {
                    annotation.Add(new MacroStringValueAnnotation(annotation));
                }
                if (type == typeof(MetadataPromptObject))
                {
                    annotation.Add(new MetaDataPromptAnnotation(annotation));
                }
 
                if (type.IsPrimitive == false)
                {
                    if (type != typeof(String) && csharpType.ElementType != null)
                    {
                        annotation.Add(new BasicCollectionAnnotation(annotation));
                        var innerType = csharpType.ElementType;
                        if (innerType.IsNumeric)
                        {
                            annotation.Add(new NumberSequenceAnnotation(annotation));
                        }
                        else
                        {
                            // the type must implement IList, otherwise it cannot be used by generic sequence annotation.
                            // this excludes IEnumerable, but not array types or List<T> types. 
                            annotation.Add(new GenericSequenceAnnotation(annotation));
                            if (!rd_only && innerType.DescendsTo(typeof(IResource)))
                            {
                                annotation.Add(new ResourceAnnotation(annotation, innerType.Type));
                                annotation.Add(new MultiResourceSelector(annotation, innerType.Type));
                            }
                            else if (!rd_only && innerType.DescendsTo(typeof(ITestStep)))
                            {
                                annotation.Add(new TestStepSelectAnnotation(annotation));
                                annotation.Add(new TestStepMultiSelectAnnotation(annotation));
                            }
                            else if (innerType.DescendsTo(typeof(ViaPoint)))
                                annotation.Add(new ViaPointAnnotation(annotation));
                            else if (innerType.DescendsTo(typeof(IMemberData)))
                                annotation.Add(new MemberDataSequenceStringAnnotation(annotation));
                        }
                    }
 
                    if (type.IsEnum)
                    {
                        if (type == typeof(BreakCondition))
                        {
                            annotation.Add(new BreakConditionsAnnotation(annotation));
                        }
                        else
                        {    
                            annotation.Add(EnumValuesAnnotation.FromEnumType(type));
                            annotation.Add(new EnumStringAnnotation(type, annotation));
 
                            if (csharpType.HasFlags())
                            {
                                annotation.Add(new FlagEnumAnnotation(annotation, type));
                            }
                        }
                    }
 
                    if (csharpType.IsValueType == false && type.DescendsTo(typeof(IResource)))
                        annotation.Add(new ResourceAnnotation(annotation, type));
                    else if (csharpType.IsValueType == false && type.DescendsTo(typeof(ITestStep)) && mem?.Member.DeclaringType?.DescendsTo(typeof(ITestStepParent)) == true)
                        annotation.Add(new TestStepSelectAnnotation(annotation));
                }
            }
 
            if (mem?.Member is IMemberData mem2)
            {
                if (mem2.GetAttribute<AvailableValuesAttribute>() is AvailableValuesAttribute avail)
                {
                    if (mem2.TypeDescriptor.DescendsTo(typeof(IEnumerable<>)) && mem2.TypeDescriptor.IsA(typeof(string)) == false)
                    {
                        annotation.Add(new MultipleAvailableValuesAnnotation(annotation, avail.PropertyName));
                    }
                    else
                    {
                        annotation.Add(new AvailableValuesAnnotation(annotation, avail.PropertyName));
                    }
                }
 
                if (mem2.TypeDescriptor.DescendsTo(typeof(IPicture)))
                {
                    annotation.Add(new PictureAnnotation(annotation));
                }
 
                if (mem2.DeclaringType.DescendsTo(typeof(ITestStep)))
                {
 
                    if (mem2.Name == nameof(ITestStep.Name))
                        annotation.Add(new StepNameStringValue(annotation, member: true));
                    
                    if (mem2.TypeDescriptor.DescendsTo(typeof(IInput)))
                        annotation.Add(new InputStepAnnotation(annotation));
                }else if (mem2 is IParameterMemberData param)
                {
                    if (mem2.TypeDescriptor.DescendsTo(typeof(IInput)) 
                        && param.ParameterizedMembers.All(x => x.Member.DeclaringType.DescendsTo(typeof(ITestStep))))
                        annotation.Add(new InputStepAnnotation(annotation, true));
                }
 
                if (mem2.DeclaringType.DescendsTo(typeof(ITestStepParent)))
                {
                    annotation.Add(new MenuAnnotation(mem2, mem2.DeclaringType, annotation.ParentAnnotation));
                }
 
                if (mem2.Name == nameof(ParameterManager.NamingQuestion.Settings) && mem2.DeclaringType.DescendsTo(TypeData.FromType(typeof(ParameterManager.NamingQuestion))))
                    annotation.Add(new ParameterManager.SettingsName(annotation));
            }
            
            if (reflect?.ReflectionInfo is ITypeData tp)
            {
                if (tp.DescendsTo(typeof(ITestStep)))
                {
                    annotation.Add(new StepNameStringValue(annotation, member: false));                
                }
 
                // When not annotating a member, but an object, we add type annotation.
                if (annotation.Any(x => x is MenuAnnotation) == false && (tp.DescendsTo(typeof(ITestStepParent)) || tp.DescendsTo(typeof(IResource))))
                    annotation.Add(new MenuAnnotation(tp));
          
                bool csharpPrimitive = tp is TypeData cst && (cst.Type.IsPrimitive || cst.Type == typeof(string));
                if (tp.GetMembers().Any(x => x.HasAttribute<AnnotationIgnoreAttribute>() == false) && !csharpPrimitive)
                {
                    annotation.Add(new MembersAnnotation(annotation));
                    if (tp.DescendsTo(typeof(IEnabled)))
                    {
                        annotation.Add(new EnabledAnnotation(annotation));
                    }
                }
            }
 
            {
                var attr = annotation.Get<ColumnDisplayNameAttribute>();
                if (attr != null && attr.IsReadOnly)
                {
                    annotation.Add(new ColumnAccessAnnotation());
                }
            }
        }
    }
 
    
    internal class DisabledSettingsAnnotation : IEnabledAnnotation
    {
        public bool IsEnabled => false;
        public static DisabledSettingsAnnotation Instance { get; } = new DisabledSettingsAnnotation();
    }
 
    internal class DisplayAnnotationWrapper : IAnnotation, IDisplayAnnotation, IOwnedAnnotation
    {
        public string Description { get; private set; }
 
        public string[] Group { get; private set; }
 
        public string Name { get; private set; }
 
        public double Order { get; private set; }
 
        public bool Collapsed { get; private set; }
 
        public void Read(object source)
        {
            if (source is IDisplayAnnotation src)
            {
                Name = src.Name;
                Description = src.Description;
                Group = src.Group;
                Order = src.Order;
                Collapsed = src.Collapsed;
            }
        }
 
        public void Write(object source)
        {
           
        }
    }
 
 
    /// <summary> Proxy annotation for wrapping simpler annotation types. For example IAvailableValuesAnnotation is wrapped in a IAvailableValuesAnnotationProxy.</summary>
    public class ProxyAnnotation : IAnnotator
    {
        class AvailableValuesAnnotationProxy : IAvailableValuesAnnotationProxy, IOwnedAnnotation
        {
            IEnumerable<AnnotationCollection> annotations;
            object[] prevValues = Array.Empty<object>();
            // when the object has been re-read, we need to check if the AvailableValues annotations needs update.
            bool invalidated;
 
            public IEnumerable<AnnotationCollection> AvailableValues
            {
                get
                {
                    IEnumerable values;
                    if (annotations != null)
                    {
                        if (invalidated)
                        {
                            invalidated = false;
                            values = a.Get<IAvailableValuesAnnotation>()?.AvailableValues;
                            if (prevValues.SequenceEqual(values?.Cast<object>() ?? Array.Empty<object>()))
                                return annotations;
                        }
                        else
                        {
                            return annotations;
                        }
                    }
                    else
                    {
                        values = a.Get<IAvailableValuesAnnotation>()?.AvailableValues ?? Array.Empty<object>();    
                    }
 
                    if (a?.Get<MergedValueAnnotation>() is MergedValueAnnotation merged)
                    {
                        // Merged available value fields are the common of all the original available values.
                        HashSet<object> values2 = null;
                        foreach (var m in merged.Merged)
                        {
                            var e =
                                (m.Get<IAvailableValuesAnnotation>()?.AvailableValues as IEnumerable)?.Cast<object>();
                            if (e == null) continue;
                            if (values2 == null)
                            {
                                values2 = new HashSet<object>(e);
                                continue;
                            }
 
                            foreach (var value in values2.ToArray())
                            {
                                if (e.Contains(value) == false)
                                {
                                    values2.Remove(value);
                                }
                            }
                        }
 
                        values = values2;
                    }
 
                    if (values != null)
                        prevValues = values.Cast<object>().ToArray();
                    else
                    {
                        prevValues = Array.Empty<object>();
                    }
 
                    var readOnly = new ReadOnlyMemberAnnotation();
                    var lst = new List<AnnotationCollection>();
                    foreach (var obj in prevValues)
                    {
                        if (obj is AnnotationCollection da)
                        {
                            lst.Add(da);
                        }
                        else
                        {
                            var da2 = a.AnnotateSub(TypeData.GetTypeData(obj), obj, readOnly,
                                new AvailableMemberAnnotation(a));
                            
                            // the annotation stringer is just used for PluginTypeSelector
                            var annotationStringer = a.Get<IAnnotationStringer>();
                            if (annotationStringer != null)
                                da2.Add(new ConstStringAnnotation(annotationStringer.GetString(da2)));
                            
                            lst.Add(da2);
                        }
                    }
 
                    lst.RemoveIf(x => x.Get<IAccessAnnotation>()?.IsVisible == false);
                    annotations = lst;
                    return annotations;
                }
            }
 
            /// <summary>  This is just a constant string shown in the UI. </summary>
            class ConstStringAnnotation : IStringReadOnlyValueAnnotation
            {
                public ConstStringAnnotation(string str) => Value = str;
                public string Value { get; }
            }
            
            public AnnotationCollection SelectedValue
            {
                get
                {
                    object current;
 
                    if (a.Get<IAvailableValuesSelectedAnnotation>() is IAvailableValuesSelectedAnnotation x)
                        current = x.SelectedValue;
                    else
                        current = a.Get<IObjectValueAnnotation>()?.Value;
 
                    if (current == null) return null;
                    foreach (var a2 in AvailableValues)
                    {
                        if (object.Equals(current, a2.Get<IObjectValueAnnotation>()?.Value))
                        {
                            return a2;
                        }
                    }
 
                    var a3 = a.AnnotateSub(TypeData.GetTypeData(current), current, new ReadOnlyMemberAnnotation(), new AvailableMemberAnnotation(a));
 
                    {   // the annotation stringer is just used for PluginTypeSelector
                        var stringer = a.Get<IAnnotationStringer>();
                        if (stringer != null) a3.Add(new ConstStringAnnotation(stringer.GetString(a3)));
                    }
 
                    return a3;
                }
                set
                {
                    if (value == null) return;
                    if (a.Get<IAvailableValuesSelectedAnnotation>() is IAvailableValuesSelectedAnnotation x)
                        x.SelectedValue = value.Get<IObjectValueAnnotation>().Value;
                    else
                        a.Get<IObjectValueAnnotation>().Value = value.Get<IObjectValueAnnotation>().Value;
                }
            }
 
            AnnotationCollection a;
            
            public AvailableValuesAnnotationProxy(AnnotationCollection a)
            {
                this.a = a;
            }
 
 
            
            public void Read(object source)
            {
                invalidated = true;
                if (annotations == null) return;
            }
 
            public void Write(object source)
            {
 
            }
        }
 
        // Note: This class is more or less a clone of the AvailableValuesAnnotationProxy, but it cannot exactly be reused.
        class SuggestedValuesAnnotationProxy : ISuggestedValuesAnnotationProxy, IOwnedAnnotation
        {
            IEnumerable<AnnotationCollection> annotations = null;
            IEnumerable prevValues = Enumerable.Empty<object>();
            // when the object has been re-read, we need to check if the AvailableValues annotations needs update.
            bool invalidated;
 
            public IEnumerable<AnnotationCollection> SuggestedValues
            {
                get
                {
                    if (annotations == null || invalidated)
                    {
                        invalidated = false;
                        var values = a.Get<ISuggestedValuesAnnotation>()?.SuggestedValues ?? Enumerable.Empty<object>();
                        // the same reference of an the value may be updated, so keep a copy of the values instead of a reference.
                        prevValues = values.OfType<object>().ToArray();
 
                        var readOnly = new ReadOnlyMemberAnnotation();
                        var lst = new List<AnnotationCollection>();
                        foreach (var obj in prevValues)
                        {
                            if (obj is AnnotationCollection da)
                            {
                                lst.Add(da);
                            }
                            else
                            {
                                var da2 = a.AnnotateSub(TypeData.GetTypeData(obj), obj, readOnly, new AvailableMemberAnnotation(a));
                                lst.Add(da2);
                            }
                        }
                        annotations = lst;
 
                    }
                    return annotations;
                }
            }
            public AnnotationCollection SelectedValue
            {
                get
                {
                    var current = a.Get<IObjectValueAnnotation>()?.Value;
                    if (current == null) return null;
                    foreach (var a in SuggestedValues)
                    {
                        if (object.Equals(current, a.Get<IObjectValueAnnotation>()?.Value))
                        {
                            return a;
                        }
                    }
                    var val = a.Get<IObjectValueAnnotation>().Value;
                    return a.AnnotateSub(TypeData.GetTypeData(val), val, new ReadOnlyMemberAnnotation(), new AvailableMemberAnnotation(a));
                }
                set
                {
                    if (value == null) return;
                    a.Get<IObjectValueAnnotation>().Value = value.Get<IObjectValueAnnotation>().Value;
                }
            }
 
            AnnotationCollection a;
            public SuggestedValuesAnnotationProxy(AnnotationCollection a)
            {
                this.a = a;
            }
 
            public void Read(object source)
            {
                invalidated = true;
                if (annotations == null) return;
                if (annotations == null) return;
                var values = a.Get<ISuggestedValuesAnnotation>()?.SuggestedValues;
                if (Enumerable.SequenceEqual(prevValues.Cast<object>(), values.Cast<object>()) == false)
                    annotations = null;
            }
 
            public void Write(object source)
            {
 
            }
        }
        
        /// <summary>
        /// For things that can be multi-selected, for example flag enum.
        /// </summary>
        class MultiSelectProxy : IMultiSelectAnnotationProxy
        {
            IEnumerable<AnnotationCollection> annotations => annotation.Get<IAvailableValuesAnnotationProxy>().AvailableValues;
 
            IEnumerable selection
            {
                get => annotation.Get<IMultiSelect>().Selected;
                set => annotation.Get<IMultiSelect>().Selected = value;
            }
 
            public IEnumerable<AnnotationCollection> SelectedValues
            {
                get
                {
                    var select = (selection ?? Array.Empty<object>()).Cast<object>().ToHashSet();
                    foreach (var a in annotations)
                    {
                        var val = a.Get<IObjectValueAnnotation>().Value;
                        if (select.Contains(val))
                            yield return a;
                    }
                }
                set
                {
                    selection = value.Select(x => x.Get<IObjectValueAnnotation>().Value).ToArray();
                }
            }
 
            readonly AnnotationCollection annotation;
 
            public MultiSelectProxy(AnnotationCollection annotation)
            {
                this.annotation = annotation;
            }
        }
 
        class AccessProxy : IAccessAnnotation, IOwnedAnnotation
        {
            AnnotationCollection annotations;
            public AccessProxy(AnnotationCollection annotations)
            {
                this.annotations = annotations;
            }
 
            bool isReadOnly = false;
            public bool IsReadOnly
            {
                get
                {
                    doRead();
                    return isReadOnly;
                }
            }
 
            bool isVisible = true;
 
            public bool IsVisible {
                get
                {
                    doRead();
                    return isVisible;
                }
            }
 
            bool wasRead = false;
            void doRead()
            {
                if (wasRead) return;
                wasRead = true;
                isReadOnly = false;
                isVisible = true;
                foreach (var access in annotations.GetAll<IAccessAnnotation>())
                {
                    isReadOnly |= access.IsReadOnly;
                    isVisible &= access.IsVisible;
                }
            }
 
            public void Read(object source)
            {
                wasRead = false;
            }
 
            public void Write(object source)
            {
 
            }
        }
        double IAnnotator.Priority => 20;
 
        void IAnnotator.Annotate(AnnotationCollection annotation)
        {
            var rdonly = annotation.Get<ReadOnlyMemberAnnotation>();
            if (rdonly == null)
            {
                var avail = annotation.Get<IAvailableValuesAnnotation>();
                var multi = annotation.Get<IMultiSelect>();
                if (avail != null)
                {
                    annotation.Add(new AvailableValuesAnnotationProxy(annotation));
                }
 
                if (multi != null)
                {
                    annotation.Add(new MultiSelectProxy(annotation));
                }
 
                if (annotation.Get<ISuggestedValuesAnnotation>() != null)
                    annotation.Add(new SuggestedValuesAnnotationProxy(annotation));
            }
            
            annotation.Add(new AccessProxy(annotation));
            
        }
    }
 
    /// <summary>
    /// Used for wrapping multi selections of objects.
    /// </summary>
    public class MultiObjectAnnotator : IAnnotator
    {
        class MergedValidationErrorAnnotation : IErrorAnnotation
        {
            readonly AnnotationCollection annotation;
            public MergedValidationErrorAnnotation(AnnotationCollection annotation)
            {
                this.annotation = annotation;
            }
 
            public IEnumerable<string> Errors => annotation.Get<MergedValueAnnotation>().Merged
                .SelectMany(a => a.Get<ValidationErrorAnnotation>()?.Errors ?? Enumerable.Empty<string>())
                .Distinct();
        }
        class MergedAvailableValues : IAvailableValuesAnnotation
        {
            public IEnumerable AvailableValues
            {
                get
                {
                    var merged = annotation.Get<MergedValueAnnotation>();
                    if (merged == null) return Enumerable.Empty<object>();
 
                    Dictionary<object, int> counts = new Dictionary<object, int>();
                    int maxCount = 0;
                    foreach (var annotation in merged.Merged)
                    {
                        maxCount += 1;
                        var values = annotation.Get<IAvailableValuesAnnotation>()?.AvailableValues;
                        if (values != null)
                        {
                            foreach (var value in values)
                            {
                                counts.TryGetValue(value, out int val);
                                counts[value] = val + 1;
                            }
                        }
                    }
                    return counts.Where(x => x.Value == maxCount).Select(x => x.Key).ToArray();
                }
            }
            AnnotationCollection annotation;
            public MergedAvailableValues(AnnotationCollection annotation)
            {
                this.annotation = annotation;
            }
        }
        double IAnnotator.Priority => ((IAnnotator)new ProxyAnnotation()).Priority - 1;
 
        void IAnnotator.Annotate(AnnotationCollection annotation)
        {
            if (annotation.ParentAnnotation == null)
            {
                var collection = annotation.Get<ICollectionAnnotation>();
                if (collection != null)
                {
                    var manyToOne = new ManyToOneAnnotation(annotation);
                    annotation.Add(manyToOne);
 
                }
            }
            var merged = annotation.Get<MergedValueAnnotation>();
            if (merged == null) return;
 
            var validationErrors = annotation.Get<ValidationErrorAnnotation>();
            if (validationErrors != null)
            {
                annotation.Remove(validationErrors);
                annotation.Add(new MergedValidationErrorAnnotation(annotation));
            }
            
            var members = annotation.Get<IMembersAnnotation>();
            
            if (members != null)
            {
                var manyToOne = new ManyToOneAnnotation(annotation);
                annotation.Add(manyToOne);
            }
            var manyAnnotation = annotation.Get<ManyToOneAnnotation>();
            if (manyAnnotation == null) return;
 
            var avail = annotation.Get<IAvailableValuesAnnotation>();
            if (avail == null) return;
 
            annotation.Add(new MergedAvailableValues(annotation));
 
            /*var avail = manyAnnotation.Members.Select(a => a?.Get<IAvailableValuesAnnotationProxy>()).Where(x => x != null).ToArray();
            if(avail.Length > 0)
            {
                annotation.Add(new ManyToOneAvailableValuesAnnotation(avail));
            }
            var access = manyAnnotation.Members.Select(a => a.Get<IAccessAnnotation>()).Where(x => x != null).ToArray();
            if(access.Length > 0)
            {
                annotation.Add(new ManyAccessAnnotation(access));
            }*/
        }
    }
 
    /// <summary>
    /// Used for resolving data annotation. Loops through the various IDataAnnotator implementations.
    /// </summary>
    internal class AnnotationResolver
    {
        static readonly TraceSource log = Log.CreateSource("AnnotationResolver");
 
        List<IAnnotator> annotators;
        /// <summary> The current annotation. </summary>
        public AnnotationCollection Annotations { get; private set; }
        bool stop = false;
        int offset = 0;
 
        [ThreadStatic] static List<IAnnotator> Annotators;
        /// <summary> </summary>
        public AnnotationResolver()
        {
            var annotatorTypes = PluginManager.GetPlugins<IAnnotator>();
            
            if (Annotators == null || Annotators.Count != annotatorTypes.Count)
            {
                Annotators = annotatorTypes
                    .Select(x =>
                    {
                        try
                        {
                            
                            return (IAnnotator)Activator.CreateInstance(x);
                        }
                        catch (Exception ex)
                        {   
                            log.Error($"Failed to instantiate annotator: {ex.Message}");
                            log.Debug(ex);
                            return null;
                        }
                    })
                    .Where(a => a != null)
                    .ToList();
                Annotators.Sort((x, y) => x.Priority.CompareTo(y.Priority));
            }
 
            annotators = Annotators;
        }
 
        /// <summary>
        /// Iterates through the data annotation process.
        /// </summary>
        /// <param name="annotation"></param>
        public void Iterate(AnnotationCollection annotation)
        {
            this.Annotations = annotation;
            while (offset < annotators.Count && !stop)
            {
                var provider = annotators[offset];
                offset++;
                provider.Annotate(this.Annotations);
            }
        }
 
    }
 
    /// <summary> A collection of annotations. Used to store high-level information about an object. </summary>
    public class AnnotationCollection : IEnumerable<IAnnotation>
    {
        internal class MemberAnnotation : IMemberAnnotation, IReflectionAnnotation
        {
            public IMemberData Member { get; private set; }
            public ITypeData ReflectionInfo => Member.TypeDescriptor;
 
            public MemberAnnotation(IMemberData member)
            {
                this.Member = member;
            }
        }
 
        /// <summary> Creates a new shallow clone of the object. The Annotations list is clone, but the elements are not. </summary>
        /// <returns></returns>
        public AnnotationCollection Clone()
        {
            return new AnnotationCollection(Annotations)
            {
                ParentAnnotation = ParentAnnotation,
                source = source
            };
        }
 
        /// <summary>
        /// The annotation that created this annotation.
        /// </summary>
        public AnnotationCollection ParentAnnotation { get; private set; }
 
        /// <summary> The source object currently used for this annotation. </summary>
        public object Source => source;
 
        /// <summary>
        /// The list of annotation that the is object represents.
        /// </summary>
        private List<IAnnotation> Annotations = new List<IAnnotation>(16);
        /// <summary> </summary>
        public AnnotationCollection()
        {
 
        }
 
        private AnnotationCollection(IEnumerable<IAnnotation> annotation)
        {
            Annotations = annotation.ToList();
        }
 
        /// <summary> Adds an annotation. </summary>
        /// <param name="annotation"></param>
        public void Add(IAnnotation annotation)
        {
            Annotations.Add(annotation);
        }
        /// <summary> adds a list of annotations. </summary>
        /// <param name="elements"></param>
        public void Add(params IAnnotation[] elements)
        {
            this.AddRange(elements);
        }
 
        /// <summary> adds a list of annotations. </summary>
        /// <param name="elements"></param>
        public void AddRange(IEnumerable<IAnnotation> elements)
        {
            Annotations.AddRange(elements);
        }
 
        /// <summary>
        /// Removes all annotations of a specific type from the collection.
        /// </summary>
        public void RemoveType<T>() where T : IAnnotation
        {
            Annotations.RemoveIf(x => x is T);
        }
 
        /// <summary>
        /// Removes a specific annotation from the collection.
        /// </summary>
        public void Remove(IAnnotation item)
        {
            Annotations.Remove(item);
        }
 
        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        public IEnumerator<IAnnotation> GetEnumerator()
        {
            return Annotations.GetEnumerator();
        }
 
        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return Annotations.GetEnumerator();
        }
 
        /// <summary>
        /// Gets the first annotation of a specific kind. Note this goes by the most-recently added principle. 
        /// </summary>
        /// <typeparam name="T">The kind of annotation to look for.</typeparam>
        /// <param name="recursive">Whether to include parent annotation search.</param>
        /// <param name="from">Where the search should start. </param>
        /// <returns></returns>
        public T Get<T>(bool recursive = false, object from = null) where T : IAnnotation
        {
            int i = 0;
            if (from != null)
            {
                for (; i < Annotations.Count; i++)
                {
                    if (Annotations[Annotations.Count - i - 1] == from)
                    {
                        i++;
                        break;
                    }
                }
            }
 
            for (; i < Annotations.Count; i++)
            {
                var x = Annotations[Annotations.Count - i - 1];
                if (x is T y) return y;
            }
            if (recursive && ParentAnnotation != null)
                return ParentAnnotation.Get<T>(true);
 
            return default(T);
        }
 
        /// <summary> Updates the annotation based on a source object. </summary>
        /// <param name="source"></param>
        public void Read(object source)
        {
            this.source = source;
            Read();
        }
 
        /// <summary> Updates the annotation based on that last specified source object. </summary>
        public void Read()
        {
            if (source == null) return;
            foreach (var annotation in Annotations)
            {
                if (annotation is IOwnedAnnotation owned)
                    owned.Read(source);
            }
        }
 
        /// <summary> Writes the annotation data to the last specified source object. </summary>
        public void Write()
        {
            if (source != null)
                Write(source);
        }
 
        /// <summary> Writes the annotation data to a specific source object. </summary>
        /// <param name="target"></param>
        public void Write(object target)
        {
            
            this.source = target;
            for (int i = 0; i < Annotations.Count; i++)
            {
                var annotation = Annotations[Annotations.Count - 1 - i];
                if (annotation is IOwnedAnnotation owned)
                    owned.Write(target);
            }
        }
 
        /// <summary>
        /// Gets all the annotations of a specific kind.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="recursive"></param>
        /// <returns></returns>
        public IEnumerable<T> GetAll<T>(bool recursive = false) where T : IAnnotation
        {
            for (int i = 0; i < Annotations.Count; i++)
            {
                var x = Annotations[Annotations.Count - i - 1];
                if (x is T y) yield return y;
            }
            if (recursive && ParentAnnotation != null)
            {
                foreach (var elem in ParentAnnotation.GetAll<T>())
                {
                    yield return elem;
                }
            }
        }
 
        /// <summary> Creates a new data annotation. </summary>
        /// <param name="object"></param>
        /// <param name="member"></param>
        /// <param name="extraAnnotations"></param>
        /// <returns></returns>
        public static AnnotationCollection Create(object @object, IReflectionData member, params IAnnotation[] extraAnnotations)
        {
            var annotation = new AnnotationCollection();
 
            if (member is IMemberData mem)
            {
                var memberAnnotation = new MemberAnnotation(mem);
                annotation.Add(memberAnnotation, new MemberValueAnnotation(annotation, memberAnnotation));
            }
            annotation.AddRange(extraAnnotations);
            var resolver = new AnnotationResolver();
            resolver.Iterate(annotation);
            if (@object != null)
                annotation.Read(@object);
            return annotation;
        }
 
        object source;
        /// <summary> Additional annotations added to the current one. </summary>
        public IAnnotation[] ExtraAnnotations = Array.Empty<IAnnotation>();
 
        /// <summary>
        /// Annotates an object.
        /// </summary>
        /// <param name="object"></param>
        /// <param name="extraAnnotations"></param>
        /// <returns></returns>
        public static AnnotationCollection Annotate(object @object, params IAnnotation[] extraAnnotations)
        {
            var annotation = new AnnotationCollection { source = @object, ExtraAnnotations = extraAnnotations ?? Array.Empty<IAnnotation>() };
            annotation.AddRange(extraAnnotations);
            annotation.Add(new ObjectValueAnnotation(@object));
            var resolver = new AnnotationResolver();
            resolver.Iterate(annotation);
            annotation.Read(@object);
            return annotation;
        }
 
        /// <summary> Annotates a member of the object annotated by this. </summary>
        /// <param name="member"></param>
        /// <param name="Source"></param>
        /// <param name="extraAnnotations"></param>
        /// <returns></returns>
        public AnnotationCollection AnnotateMember(IMemberData member, object Source, params IAnnotation[] extraAnnotations)
        {
            var annotation = new AnnotationCollection { ParentAnnotation = this, source = Source, ExtraAnnotations = extraAnnotations ?? Array.Empty<IAnnotation>() };
            annotation.Add(new MemberAnnotation(member));
            annotation.AddRange(extraAnnotations);
            var resolver = new AnnotationResolver();
            resolver.Iterate(annotation);
            return annotation;
        }
 
        /// <summary> Annotates a member of the object annotated by this. </summary>
        /// <param name="member"></param>
        /// <param name="extraAnnotations"></param>
        /// <returns></returns>
        public AnnotationCollection AnnotateMember(IMemberData member, params IAnnotation[] extraAnnotations)
        {
            return AnnotateMember(member, null, extraAnnotations);
        }
 
        /// <summary> Annotates a sub-object of the object annotated by this. </summary>
        /// <param name="reflect"></param>
        /// <param name="obj"></param>
        /// <param name="extraAnnotations"></param>
        /// <returns></returns>
        public AnnotationCollection AnnotateSub(ITypeData reflect, object obj, params IAnnotation[] extraAnnotations)
        {
            var cache = Get<AnnotationCache>();
            if (cache?.GetCached(obj) is AnnotationCollection cached)
                return cached;
            
            var annotation = new AnnotationCollection { ParentAnnotation = this, ExtraAnnotations = extraAnnotations ?? Array.Empty<IAnnotation>() };
 
            annotation.AddRange(extraAnnotations);
            annotation.Add(new ObjectValueAnnotation(obj, reflect));
 
            var resolver = new AnnotationResolver();
            resolver.Iterate(annotation);
            if (obj != null)
                annotation.Read(obj);
            cache?.Register(annotation);
            return annotation;
        }
 
        /// <summary> Print the display name of this level of the annotation.</summary>
        internal string Name
        {
            get
            {
                var disp = Get<IDisplayAnnotation>()?.Name ?? Get<IReflectionAnnotation>()?.ReflectionInfo?.Name;
                return disp ?? "?";
            }
        }
        /// <summary> Creates a string from this. This is useful for debugging.</summary>
        /// <returns></returns>
        public override string ToString()
        {
            // the wanted format is: "Delay Step / DelaySecs: 1.0 s"
            StringBuilder sb = new StringBuilder();
            sb.Append(Name);
            sb.Append(": ");
            sb.Append(Get<IStringValueAnnotation>()?.Value ?? Get<IObjectValueAnnotation>()?.Value?.ToString() ?? "?");
            var p = ParentAnnotation;
            while (p != null)
            {
                sb.Insert(0, " / ");
                sb.Insert(0, p.Name);
                p = p.ParentAnnotation;
            }
 
            return sb.ToString();
        } 
 
        /// <summary> Insert an annotation at a location. </summary>
        /// <param name="index"></param>
        /// <param name="v"></param>
        public void Insert(int index, IAnnotation v)
        {
            Annotations.Insert(index, v);
        }
    }
 
    /// <summary> Helper methods for working with annotations. </summary>
    internal static class AnnotationExtensions
    {
        /// <summary> Recurse to find member annotation 'X.Y.Z'</summary>
        public static AnnotationCollection GetMember(this AnnotationCollection col, string name)
        {
            var name2 = name;
            foreach (var mem in col.Get<IMembersAnnotation>().Members)
            {
                var memberName = mem.Get<IMemberAnnotation>()?.Member.Name;
                var found = memberName == name2;
                if (found) return mem;
            }
            foreach (var mem in col.Get<IMembersAnnotation>().Members)
            {
                if (mem.Name == name)
                    return mem;
            }
            return null;
        }
 
        /// <summary>  helper method to get the icon annotation collection. Will return null if the item could not be found. </summary>
        public static AnnotationCollection GetIcon(this AnnotationCollection col, string iconName)
        {
            return col.Get<MenuAnnotation>()?.MenuItems
                .FirstOrDefault(c => c.Get<IIconAnnotation>()?.IconName == iconName);
        }
        public static void ExecuteIcon(this AnnotationCollection col, string iconName)
        {
            var icon = col.GetIcon(iconName);
            if (!icon.Get<IEnabledAnnotation>().IsEnabled == true)
                throw new Exception("Icon action is not enabled");
            icon.Get<IMethodAnnotation>().Invoke();
        }
 
        public static void SetValue(this AnnotationCollection col, object value)
        {
            // this function could be extended to support more types if needed.
            var strVal = col.Get<IStringValueAnnotation>();
            if (strVal != null)
            {
                strVal.Value = StringConvertProvider.GetString(value);
                col.Write();
            }
            else throw new Exception("SetValue failed.");
 
        }
    }
}