File: coot_gui.py

package info (click to toggle)
coot 1.1.18%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 219,964 kB
  • sloc: cpp: 495,934; python: 35,043; ansic: 26,143; lisp: 22,768; sh: 13,186; makefile: 2,746; awk: 441; xml: 245; csh: 14
file content (6510 lines) | stat: -rw-r--r-- 248,279 bytes parent folder | download | duplicates (2)
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
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
# coot-gui.py
#
# Copyright 2001 by Neil Jerram
# Copyright 2002-2008, 2009 by The University of York
# Copyright 2007 by Paul Emsley
# Copyright 2006, 2007, 2008, 2009 by Bernhard Lohkamp
# with adaptions from
#   Interactive Python-GTK Console
#   Copyright (C), 1998 James Henstridge <james@daa.com.au>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or (at
# your option) any later version.

# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA


# Fire up the coot scripting gui.  This function is called from the
# main C++ code of coot.  Not much use if you don't have a gui to
# type functions in to start with.
#

# import pygtk, gtk, pango

import os
import types
from typing import Callable, Any
import gi
gi.require_version("Gtk", "4.0")
from gi.repository import Gtk, GObject
from gi.repository import Gio
from gi.repository import GLib
import coot
import coot_utils
import coot_gui_api # this is imported on binary startup
import coot_acedrg_link
import coot_sharpen_blur
import coot_redefine_functions as rf
# import get_recent_pdbe # not used
# import interactive_nudge_residues # not yet converted


# thank you ebassi!
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)


# try:
#     import gobject
# except:
#     print("WARNING:: no gobject available")


global histpos
global history
histpos = 0
history = ['']

global probe_command
probe_command = "molprobity.probe"

# The callback from pressing the Go button in the smiles widget, an
# interface to run libcheck.
#
def handle_smiles_go(tlc_entry, smiles_entry):

    import coot_generator_3d_import

    tlc_text = tlc_entry.get_text()
    smiles_text = smiles_entry.get_text()
    use_libcheck = False
    if coot_utils.is_windows():
        use_libcheck = True
    coot_generator_3d_import.new_molecule_by_smiles_string(tlc_text, smiles_text, force_libcheck=use_libcheck)

# smiles GUI
#


def smiles_gui():

    def smiles_gui_internal():
        def delete_event(*args):
            smiles_window.destroy()
            return False

        def go_button_pressed(widget, tlc_entry, smiles_entry, smiles_window):
            handle_smiles_go(tlc_entry, smiles_entry)
            smiles_window.destroy()
            delete_event()

        def smiles_connect(widget, event, tlc_entry, smiles_entry, smiles_window):
            if (event.keyval == 65293):
                handle_smiles_go(tlc_entry, smiles_entry)
                smiles_window.destroy()

        smiles_window = Gtk.Window()
        smiles_window.set_title("SMILES GUI")
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        hbox1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        tlc_label = Gtk.Label(label="  3-letter code ")
        tlc_entry = Gtk.Entry(max=3)
        tlc_entry.set_text("")
        smiles_label = Gtk.Label(label="SMILES string ")
        smiles_entry = Gtk.Entry()
        if coot.enhanced_ligand_coot_p():
            text = Gtk.Label(label="  [SMILES interface works by using Pyrogen]  ")
        else:
            text = Gtk.Label(label="  [SMILES interface works by using CCP4's LIBCHECK]  ")
        go_button = Gtk.Button(label="  Go  ")
        vbox.append(hbox1)
        vbox.append(hbox2)
        vbox.append(text)
        vbox.append(go_button)
        hbox1.append(tlc_label)
        hbox1.append(tlc_entry)
        hbox2.append(smiles_label)
        hbox2.append(smiles_entry)
        smiles_window.set_child(vbox)
        # vbox.set_border_width(6)

        smiles_entry.connect("key-press-event", smiles_connect,
                             tlc_entry, smiles_entry, smiles_window)
        go_button.connect("clicked", go_button_pressed,
                          tlc_entry, smiles_entry, smiles_window)
        smiles_window.connect("delete_event", delete_event)

        smiles_window.show()

    # first check that libcheck is available... if not put up and info
    # dialog.
    if coot.enhanced_ligand_coot_p():
        smiles_gui_internal()
    else:
        print("No enhanced ligand detected")


# Generic single entry widget
#
# Pass the hint labels of the entries and a function that gets called
# when user hits "Go".  The handle-go-function accepts one argument
# that is the entry text when the go button is pressed.
#
def generic_single_entry(function_label, entry_1_default_text, go_button_label, handle_go_function):

    def delete_event(*args):
        window.destroy()
        return False

    def go_function_event(widget, smiles_entry, *args):
        handle_go_function(smiles_entry.get_text())
        delete_event()

    def smiles_entry_activate(entry):
        txt = entry.get_text()
        handle_go_function(txt)

    window = Gtk.Window()
    window.set_title('Coot')
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    hbox1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    hbox2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    hbox3 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    function_label = Gtk.Label(label=function_label)
    smiles_entry = Gtk.Entry()
    cancel_button = Gtk.Button(label="  Cancel  ")
    go_button = Gtk.Button(label=go_button_label)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)

    function_label.set_margin_start(10)
    function_label.set_margin_end(10)
    function_label.set_margin_top(6)
    function_label.set_margin_bottom(6)

    smiles_entry.set_margin_start(6)
    smiles_entry.set_margin_end(6)
    smiles_entry.set_margin_top(2)
    smiles_entry.set_margin_bottom(2)

    cancel_button.set_margin_start(6)
    cancel_button.set_margin_end(6)
    cancel_button.set_margin_top(2)
    cancel_button.set_margin_bottom(2)

    h_sep.set_margin_top(4)
    h_sep.set_margin_bottom(4)

    vbox.append(hbox1)
    vbox.append(hbox2)
    vbox.append(h_sep)
    vbox.append(hbox3)
    hbox3.append(cancel_button)
    hbox3.append(go_button)
    hbox1.append(function_label)
    hbox2.append(smiles_entry)
    window.set_child(vbox)
    # vbox.set_border_width(6)

    if isinstance(entry_1_default_text, (str,)):
        smiles_entry.set_text(entry_1_default_text)
    else:
        print("BL WARNING:: entry_1_default_text was no string!!")

    cancel_button.connect("clicked", delete_event)

    go_button.connect("clicked", go_function_event, smiles_entry)

    # old: smiles_entry.connect("key_press_event", key_press_event, smiles_entry)
    smiles_entry.connect("activate", smiles_entry_activate, smiles_entry)

    window.show()

# generic double entry widget, now with a check button
# ...and returns the widget if requested
#
# pass a the hint labels of the entries and a function
# (handle-go-function) that gets called when user hits "Go" (which
# takes two string aguments and the active-state of the check button
# (either True of False).
#
# if check-button-label not a string, then we don't display (or
# create, even) the check-button.  If it *is* a string, create a
# check button and add the callback handle-check-button-function
# which takes as an argument the active-state of the the checkbutton.
#


def generic_double_entry(label_1, label_2,
                         entry_1_default_text, entry_2_default_text,
                         check_button_label, handle_check_button_function,
                         go_button_label, handle_go_function,
                         return_widget=False):

    def delete_event(*args):
        window.destroy()
        return False

    def go_function_event(*args):
        if check_button:
            handle_go_function(tlc_entry.get_text(),
                               smiles_entry.get_text(),
                               check_button.get_active())
        else:
            handle_go_function(tlc_entry.get_text(), smiles_entry.get_text())
            delete_event()

    def key_press_event(widget, event, tlc_entry, smiles_entry, check_button):
        if (event.keyval == 65293):
            if check_button:
                handle_go_function(tlc_entry.get_text(
                ), smiles_entry.get_text(), check_button.get_active())
            else:
                handle_go_function(tlc_entry.get_text(),
                                   smiles_entry.get_text())
                delete_event()

    window = Gtk.Window()
    window.set_title('Coot')
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    hbox1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    hbox2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    hbox3 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    tlc_label = Gtk.Label(label=label_1)
    tlc_entry = Gtk.Entry()
    smiles_label = Gtk.Label(label=label_2)
    smiles_entry = Gtk.Entry()
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    cancel_button = Gtk.Button(label="  Cancel  ")
    go_button = Gtk.Button(label=go_button_label)

    vbox.append(hbox1)
    vbox.append(hbox2)
    hbox3.append(go_button)
    hbox3.append(cancel_button)
    hbox1.append(tlc_label)
    hbox1.append(tlc_entry)
    hbox2.append(smiles_label)
    hbox2.append(smiles_entry)

    try:

        def check_callback(*args):
            active_state = c_button.get_active()
            handle_check_button_function(active_state)

        c_button = Gtk.CheckButton(check_button_label)
        vbox.append(c_button)
        c_button.connect("toggled", check_callback)
        check_button = c_button

    except:
        check_button = False 	# the check-button when we don't want to see it

    vbox.append(h_sep)
    vbox.append(hbox3)
    window.set_child(vbox)
    # vbox.set_border_width(6)

    if isinstance(entry_1_default_text, (str,)):
        tlc_entry.set_text(entry_1_default_text)
    else:
        print("BL WARNING:: entry_1_default_text was no string!!")

    if isinstance(entry_2_default_text, (str,)):
        smiles_entry.set_text(entry_2_default_text)
    else:
        print("BL WARNING:: entry_2_default_text was no string!!")

    go_button.connect("clicked", go_function_event)
    cancel_button.connect("clicked", delete_event)

    smiles_entry.connect("key-press-event", key_press_event,
                         tlc_entry, smiles_entry, check_button)

    window.set_default_size(400, 100)
    window.show()

    # return the widget
    if (return_widget):
        return window

# generic double entry widget, now with a check button
#
# OLD
#
#
# pass a the hint labels of the entries and a function
# (handle-go-function) that gets called when user hits "Go" (which
# takes two string aguments and the active-state of the check button
# (either True of False).
#
# if check-button-label not a string, then we don't display (or
# create, even) the check-button.  If it *is* a string, create a
# check button and add the callback handle-check-button-function
# which takes as an argument the active-state of the the checkbutton.
#


def generic_multiple_entries_with_check_button(entry_info_list, check_button_info, go_button_label, handle_go_function):

    def delete_event(*args):
        window.destroy()
        return False

    def go_function_event(*args):
        if check_button:
            handle_go_function([entry.get_text()
                                for entry in entries], check_button.get_active())
        else:
            handle_go_function([entry.get_text() for entry in entries])
        delete_event()

    window = Gtk.Window()
    window.set_title('Coot')
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    hbox3 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    cancel_button = Gtk.Button(label="  Cancel  ")
    go_button = Gtk.Button(label=go_button_label)

    # all the labelled entries
    #
    entries = []
    for entry_info in entry_info_list:

        entry_1_hint_text = entry_info[0]
        entry_1_default_text = entry_info[1]
        hbox1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        label = Gtk.Label(label=entry_1_hint_text)
        entry = Gtk.Entry()
        entries.append(entry)

        try:
            entry.set_text(entry_1_default_text)
        except:
            pass

        hbox1.append(label)
        hbox1.append(entry)
        vbox.append(hbox1)

    # print "debug:: check-button-info: ", check_button_info
    # print "debug:: entry-info-list: ", entry_info_list

    try:
        def check_callback(*args):
            active_state = c_button.get_active()
            check_button_info[1] = active_state

        c_button = Gtk.CheckButton(check_button_info[0])
        vbox.append(c_button)
        c_button.connect("toggled", check_callback)
        check_button = c_button
    except:
        check_button = False

    print("debug:: Here check button creation........ check-button is ", check_button)
    vbox.append(h_sep)
    vbox.append(hbox3)
    window.set_child(vbox)
    # vbox.set_border_width(6)

    hbox3.append(go_button)
    hbox3.append(cancel_button)

    cancel_button.connect("clicked", delete_event)
    go_button.connect("clicked", go_function_event)

    window.show()


def molecule_centres_gui():

    def delete_event(*args):
        window.destroy()
        return False

    def callback_func(widget, molecule_number, label):
        s = "Centred on " + label
        coot.add_status_bar_text(s)
        coot.set_rotation_centre(*coot.molecule_centre(molecule_number))

    # first, we create a window and a frame to be put into it.
    #
    # we create a vbox (a vertical box container) that will contain the
    # buttons for each of the coordinate molecules
    #
    window = Gtk.Window()
    # frame = Gtk.Frame("Molecule Centres") # take no arguments in GKT4, it seems
    frame = Gtk.Frame()
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

    # add the frame to the window and the vbox to the frame
    #
    window.set_child(frame)
    frame.set_child(vbox)
    # vbox.set_border_width(6)

    # for each molecule, test if this is a molecule that has a
    # molecule (it might have been closed or contain a map).  The we
    # construct a button label that is the molecule number and the
    # molecule name and create a button with that label.
    #
    # then we attach a signal to the "clicked" event on the newly
    # created button.  In the function that subsequently happen (on a
    # click) we add a text message to the status bar and set the
    # graphics rotation centre to the centre of the molecule.  Each
    # of these buttons is packed into the vbox (the #f #f means no
    # expansion and no filling).  The padding round each button is 3
    # pixels.
    #
    for molecule_number in coot_utils.molecule_number_list():
        if (coot.is_valid_model_molecule(molecule_number)):
            name = coot.molecule_name(molecule_number)
            label = str(molecule_number) + " " + name
            button = Gtk.Button(label=label)
            button.connect("clicked", callback_func, molecule_number, label)
            vbox.add(button)
    window.show()

# A BL function to analyse the libcheck log file
#


def check_libcheck_logfile(logfile_name):
    # to check if error or warning occured in libcheck
    # maybe want to have something like that for all logfiles
    # and produce a warning for users...

    fp = open(logfile_name, 'r')
    lines = fp.readlines()
    for line in lines:
        if "WARNING: no such keyword :FILE" in line:
            print(
                "BL WARNING:: libcheck didn't seem to run ok! Please check output carefully!!")
        else:
            pass
    fp.close()

# old coot test


def old_coot_qm():

    import time
    import random
    # when making a new date, recall that guile times seem to be
    # differently formatted to python times (god knows why)
    # run e.g.: time.mktime((2008, 7, 24, 0,0,0,0,0,0))
    #
    # new_release_time = 1199919600 # 10 Jan 2008
    # new_release_time = 1205622000 # 16 Mar 2008 0.3.3
    # new_release_time = 1216854000 # 24 Jul 2008 0.4
    # new_release_time = 1237244400 # 17 March 2009
    # new_release_time = 1249945200 # 11 August 2009 : 0.5
    # new_release_time = 1279926000 # 24 July 2010 : --
    # new_release_time = 1310000000 #  7 July 2011 : 0.6
    # new_release_time = 1330000000 # 23 Jan 2012
    new_release_time = 1352674800  # 12 Nov 2012
    current_time = int(time.time())
    time_diff = current_time - new_release_time
    if (time_diff > 0):
        if (time_diff > 8600):
            s = "You've got an Old Coot!\n\nIt's time to upgrade."
        else:
            if (random.randint(0, 10) == 0):
                # Jorge Garcia:
                s = "(Nothing says \"patriotism\" like an Ireland shirt...)\n"
            else:
                s = "You've got an Old Coot!\n\nIt's time to upgrade."
        coot.info_dialog(s)

# if (not coot.coot_has_guile()):
#   old_coot_qm()

# We can either go to a place (in which case the element is a list of
# button label (string) and 3 numbers that represent the x y z
# coordinates) or an atom (in which case the element is a list of a
# button label (string) followed by the molecule-number chain-id
# residue-number ins-code atom-name altconf)
#
# e.g. interesting_things_gui(
#       "Bad things by Analysis X",
#       [["Bad Chiral",0,"A",23,"","CA","A"],
#        ["Bad Density Fit",0,"B",65,"","CA",""],
#        ["Interesting blob",45.6,46.7,87.5]]
#


def interesting_things_gui(title, baddie_list):

    interesting_things_with_fix_maybe(title, baddie_list)

# In this case, each baddie can have a function at the end which is
# called when the fix button is clicked.
# And extra string arguments can give the name of the button and a tooltip
# as these two are ambigious, they can only be:
# 1 extra string:  button name
# 2 extra strings: button name and tooltip
#


def interesting_things_with_fix_maybe(title, baddie_list):

    # does this baddie have a fix at the end?.  If yes, return the
    # func, if not, return #f.
    # BL says::
    # OBS in python the fix function is a list with the 1st element the function
    # hope this will work!?
    def baddie_had_fix_qm(baddie):

        l = len(baddie)
        if (l < 5):
            # certainly no fix
            return False, False, False
        else:
            func_maybe1 = baddie[l-1]
            func_maybe2 = baddie[l-2]
            func_maybe3 = baddie[l-3]

            if (isinstance(func_maybe1, list) and len(func_maybe1) > 0):
                # the last one is probably a funcn (no button name)
                func_maybe_strip = func_maybe1[0]
                #  print "BL DEBUG:: func_maybe_strip is", func_maybe_strip
                if (callable(func_maybe_strip)):
                    return func_maybe1, False, False
                else:
                    return False, False, False

            elif (isinstance(func_maybe2, list) and len(func_maybe2) > 0
                  and isinstance(func_maybe1, bytes)):
                # the second last is function, last is button name
                func_maybe_strip = func_maybe2[0]
                button_name = func_maybe1
                if (callable(func_maybe_strip)):
                    return func_maybe2, button_name, False
                else:
                    return False, False, False

            elif (isinstance(func_maybe3, list) and len(func_maybe3) > 0
                  and isinstance(func_maybe2, bytes)
                  and isinstance(func_maybe1, bytes)):
                # the third last is function, second last is button name, last is tooltip
                func_maybe_strip = func_maybe3[0]
                button_name = func_maybe2
                tooltip_str = func_maybe1
                if (callable(func_maybe_strip)):
                    return func_maybe3, button_name, tooltip_str
                elif (func_maybe_strip == "dummy"):
                    return False, False, tooltip_str
                else:
                    return False, False, False

            else:
                return False, False, False

    def fix_func_call(widget, call_func):
        func_maybe_strip = call_func[0]
        func_args = call_func[1:len(call_func)]
        func_maybe_strip(*func_args)

    def delete_event(*args):
        window.destroy()
        Gtk.main_quit()
        return False

    def callback_func1(widget, coords):
        coot.set_rotation_centre(*coords)

    def callback_func2(widget, mol_no, atom_info):
        print("Attempt to go to chain: %s resno: %s atom-name: %s" %
              (atom_info[0], atom_info[1], atom_info[2]))
        coot.set_go_to_atom_molecule(mol_no)
        success = coot.set_go_to_atom_chain_residue_atom_name(*atom_info)
        if success == 0:           # failed?!
            new_name = coot.unmangle_hydrogen_name(atom_info[2])
            success2 = coot.set_go_to_atom_chain_residue_atom_name(atom_info[0], atom_info[1], new_name)
            if success2 == 0:
                print("Failed to centre on demangled name: ", new_name)
                coot.set_go_to_atom_chain_residue_atom_name(atom_info[0], atom_info[1], " CA ")

    # main body
    # to accomodated tooltips we need to either have a Gtk.Window with Gtk.main()
    # or a dialog and run() it! We use Window to not block events and hope not to
    # interfere with the gtk_main() of coot itself
    window = Gtk.Window()
    scrolled_win = Gtk.ScrolledWindow()
    outside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    inside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

    window.set_default_size(250, 250)
    window.set_title(title)
    # inside_vbox.set_border_width(4)

    window.set_child(outside_vbox)
    outside_vbox.append(scrolled_win)
    scrolled_win.add_with_viewport(inside_vbox)
    #tooltips = Gtk.Tooltips()

    for baddie_items in baddie_list:

        if baddie_items == '':
            print('Done')
        else:
            hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
            # and fix it button

            label = baddie_items[0]
            button = Gtk.Button(label=label)

            inside_vbox.append(hbox)
            hbox.append(button)

            # add the a button for the fix func if it exists.  Add
            # the callback.
            fix_func, button_name, tooltip_str = baddie_had_fix_qm(
                baddie_items)
            if (fix_func):
                if (button_name):
                    fix_button_name = button_name
                else:
                    fix_button_name = "  Fix  "
                fix_button = Gtk.Button(label=fix_button_name)
                hbox.pack_end(fix_button, False, False, 2)
                fix_button.show()
                fix_button.connect("clicked", fix_func_call, fix_func)

            if (tooltip_str):
                # we have a tooltip str
               #  if Gtk.pygtk_version >= (2, 12):
               #      button.set_tooltip_text(tooltip_str)
               #  else:
               #      coot_tooltips.set_tip(button, tooltip_str)
               pass

            if (len(baddie_items) == 4):               # e.g. ["blob",1,2,3]
                # we go to a place
                coords = [baddie_items[1], baddie_items[2], baddie_items[3]]
                button.connect("clicked", callback_func1, coords)

            else:
                # we go to an atom
                mol_no = baddie_items[1]
                atom_info = [baddie_items[2], baddie_items[3], baddie_items[5]]
                button.connect("clicked", callback_func2, mol_no, atom_info)

    # outside_vbox.set_border_width(4)
    ok_button = Gtk.Button(label="  OK  ")
    outside_vbox.append(ok_button)
    ok_button.connect("clicked", delete_event)

    window.connect("destroy", delete_event)

    window.show()
    Gtk.main()

#interesting_things_gui("Bad things by Analysis X",[["Bad Chiral",0,"A",23,"","CA","A"],["Bad Density Fit",0,"B",65,"","CA",""],["Interesting blob",45.6,46.7,87.5],["Interesting blob 2",45.6,41.7,80.5]])
#interesting_things_gui("Bad things by Analysis X",[["Bad Chiral",0,"A",23,"","CA","A",[print_sequence_chain,0,'A']],["Bad Density Fit",0,"B",65,"","CA",""],["Interesting blob",45.6,46.7,87.5],["Interesting blob 2",45.6,41.7,80.5]])


# Fill an option menu with the "right type" of molecules.  If
# filter_function returns True then add it.  Typical value of
# filter_function is valid-model-molecule_qm
#
def fill_option_menu_with_mol_options(menu, filter_function):

    mol_no_ls = []

    for mol_no in coot_utils.molecule_number_list():
        if filter_function(mol_no):
            label_str = coot.molecule_name(mol_no)
            if (isinstance(label_str, (str,))):
                mlabel_str = str(mol_no) + " " + label_str
                menu.append_text(mlabel_str)
                menu.set_active(0)
                mol_no_ls.append(mol_no)
            else:
                print("OOps molecule name for molecule %s is %s" %(mol_no_ls, label_str))
    return mol_no_ls

# Fill an option menu with maps and return the list of maps
#

# Helper function for molecule chooser.  Not really for users.
#
# Return a list of models, corresponding to the menu items of the
# option menu.
#
# The returned list will not contain references to map or closed
# molecules.
#

def fill_combobox_with_number_options(combobox, number_list, active_value):

    def make_store(number_list):
        name_store = Gtk.ListStore(int, str)
        for i in number_list:
            label_str = str(i)
            name_store.append([i, label_str])
        return name_store

    combobox_items = make_store(number_list)
    renderer_text = Gtk.CellRendererText()
    combobox.set_entry_text_column(1)
    combobox.pack_start(renderer_text, True)
    combobox.add_attribute(renderer_text, "text", 1)
    for i in number_list:
        print("debug: comparing", i, active_value)
        if i == active_value:
            combobox.set_active(i)
    return combobox_items


# Helper function for molecule chooser.  Not really for users.
#
# return the molecule number of the active item in the option menu,
# or return False if there was a problem (e.g. closed molecule)
#
# BL says:: we do it for gtk_combobox instead! option_menu is deprecated
#
# Get rid of this. Search for references and replace them
#

# 20220228-PE commented out on merge - let's usee get_combobox_active_molecule() now
# def get_option_menu_active_molecule(option_menu, model_mol_list):

#     model = option_menu.get_model()
#     active_item = option_menu.get_active()
#     # combobox has no children as such, so we just count the rows
#     children = len(model)

#     if (children == len(model_mol_list)):
#         try:
#             all_model = model[active_item][0]
#             imol_model, junk = all_model.split(' ', 1)

#             return int(imol_model)
#         except:
#             print("INFO:: could not get active_item")
#             return False
#     else:
#         print("Failed children length test : ", children, model_mol_list)
#         return False
#        print "get_option_menu_active_molecule(): Failed children length test : ",children, model_mol_list
#        return False

def get_combobox_active_molecule(combobox, model_mol_list):

    model = combobox.get_model()
    active_item = combobox.get_active()
    # combobox has no children as such, so we just count the rows
    children = len(model)

    if (children == len(model_mol_list)):
       try:
          all_model = model[active_item][0]
          imol_model, junk = all_model.split(' ', 1)

          return int(imol_model)
       except:
          print("WARNING:: could not get active_item", combobox)
          return False
    else:
       print("WARNING:: get_combobox_active_molecule(): Failed children length test : ", children, model_mol_list)
       return False


# Get rid of this also
#
def get_option_menu_active_item(option_menu, item_list):

    model = option_menu.get_model()
    active_item = option_menu.get_active()
    # combobox has no children as such, so we just count the rows
    children = 0
    for i in model:
        children += 1

    if (children == len(item_list)):
        try:
            all_model = model[active_item][0]
            return all_model
        except:
            print("INFO:: could not get active_item")
            return False
    else:
        print("Failed children length test : ", children, item_list)
        return False

# see acedrg_link for how this is used
def make_store_for_string_list_combobox(combobox, string_list, default_string):
    mol_store = Gtk.ListStore(str)
    for item in string_list:
        mol_store.append([item])
    return mol_store

def make_store_for_molecule_combobox(filter_function):
    mol_store = Gtk.ListStore(int, str)
    for imol in coot_utils.molecule_number_list():
        if filter_function(imol) == 1:
            label_str = coot.molecule_name(imol)
            m_label_str = str(imol) + ' ' + label_str
            mol_store.append([imol, m_label_str])
    return mol_store

def make_store_for_map_molecule_combobox():
    mol_store = Gtk.ListStore(int, str)
    for imol in coot_utils.molecule_number_list():
        if coot.is_valid_map_molecule(imol) == 1:
            label_str = coot.molecule_name(imol)
            m_label_str = str(imol) + ' ' + label_str
            mol_store.append([imol, m_label_str])
    return mol_store

def make_store_for_diff_map_molecule_combobox():
    mol_store = Gtk.ListStore(int, str)
    for imol in coot_utils.molecule_number_list():
        if coot.is_valid_map_molecule(imol) == 1:
            if coot.map_is_difference_map(imol) == 1:
                label_str = coot.molecule_name(imol)
                m_label_str = str(imol) + ' ' + label_str
                mol_store.append([imol, m_label_str])
    return mol_store


def make_store_for_model_molecule_combobox():
    mol_store = Gtk.ListStore(int, str)
    for imol in coot_utils.model_molecule_number_list():
        if coot.is_valid_model_molecule(imol) == 1:
            label_str = coot.molecule_name(imol)
            m_label_str = str(imol) + ' ' + label_str
            print("debug:: make_store_for_model_molecule_combobox appending", imol, m_label_str)
            mol_store.append([imol, m_label_str])
    return mol_store

def fill_combobox_with_molecule_options(combobox, filter_function):
    mols_ls = []
    name_store = Gtk.ListStore(int, str)
    for imol in coot_utils.molecule_number_list():
        if filter_function(imol):
            label_str = coot.molecule_name(imol)
            m_label_str = str(imol) + ' ' + label_str
            name_store.append([imol, m_label_str])
            mols_ls.append(imol)

    print("###### debug fill_combobox_with_molecule_options() returning name_store", name_store)
    return name_store


def fill_combobox_with_model_molecule_options(combobox):
    name_store = Gtk.ListStore(int, str)
    for imol in coot_utils.molecule_number_list():
        if coot.is_valid_model_molecule(imol):
            label_str = coot.molecule_name(imol)
            m_label_str = str(imol) + ' ' + label_str
            name_store.append([imol, m_label_str])

    return name_store

# Typically option_menu_fill_function is
# fill_option_menu_with_coordinates_mol_options
#


def molecule_chooser_gui_generic(chooser_label, callback_function, molecule_filter_function):

    def delete_event(*args):
        window.destroy()
        return False

    def on_ok_button_clicked(*args):
        tree_iter = combobox.get_active_iter()
        if tree_iter is not None:
            model = combobox.get_model()
            it = model[tree_iter]
            imol_model = it[0]
            callback_function(imol_model)
            window.destroy()

    def on_mol_combobox_changed(combobox):
        # this function is not useful. For this dialog, we want to do things when
        # the "OK" button is pressed
        tree_iter = combobox.get_active_iter()
        if tree_iter is not None:
            model = combobox.get_model()
            it = model[tree_iter]
            print("Selected: imol=%s" % it)

    window = Gtk.Window(title="Molecule Chooser")
    window.set_title('Coot: Molecule Chooser')
    label = Gtk.Label(label=chooser_label)
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,spacing=10)
    vbox.set_margin_top(10)
    vbox.set_margin_bottom(10)
    vbox.set_margin_start(10)
    vbox.set_margin_end(10)
    hbox_buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,spacing=5)
    hbox_buttons.set_halign(Gtk.Align.END)
    hbox_buttons.set_homogeneous(True)

    # -------- replacing an option menu of molecules: here's how to do it --------------
    #          (also see the on_ok_button_clicked callback)

    # option_menu = Gtk.combo_box_new_text()
    combobox_items = make_store_for_molecule_combobox(molecule_filter_function)
    combobox = Gtk.ComboBox.new_with_model(combobox_items)
    renderer_text = Gtk.CellRendererText()
    if len(combobox_items) > 0:
        combobox.set_active(0)
    combobox.set_entry_text_column(1) # Sets the model column which combo_box
                                      # should use to get strings from to be text_column
    combobox.pack_start(renderer_text,  True)
    combobox.add_attribute(renderer_text, "text", 1)
    # this line is often not needed in other cases.
    combobox.connect("changed", on_mol_combobox_changed)

    # ----------------------------------------------------------------------------------

    ok_button = Gtk.Button(label="OK")
    cancel_button = Gtk.Button(label=" Cancel ")
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)

    vbox.append(label)
    vbox.append(combobox)
    vbox.append(h_sep)
    vbox.append(hbox_buttons)
    hbox_buttons.append(cancel_button)
    hbox_buttons.append(ok_button)
    window.set_child(vbox)

    # button callbacks:
    ok_button.connect("clicked", on_ok_button_clicked, combobox)
    cancel_button.connect("clicked", delete_event)

    window.show()


# molecule_chooser_gui("test-gui",print_sequence_chain(0,"A"))

# Fire up a coordinates/model molecule chooser dialog, with a given
# label and on OK we call the callback_fuction with an argument of
# the chosen molecule number.
#
# chooser_label is a directive to the user such as "Choose a Molecule"
#
# callback_function is a function that takes a molecule number as an
# argument.
#
def molecule_chooser_gui(label, callback_fn):
    molecule_chooser_gui_generic(label, callback_fn, coot.is_valid_model_molecule)

# Fire up a map molecule chooser dialog, with a given label and on OK we
# call the callback_fuction with an argument of the chosen molecule
# number.
#
# chooser_label is a directive to the user such as "Choose a Molecule"
#
# callback_function is a function that takes a molecule number as an
# argument.
#


def map_molecule_chooser_gui(label, callback_fn):
    molecule_chooser_gui_generic(label, callback_fn, coot.is_valid_map_molecule)

# A pair of widgets, a molecule chooser and an entry.  The
# callback_function is a function that takes a molecule number and a
# text string.
#


def generic_chooser_and_entry(chooser_label, entry_hint_text,
                              default_entry_text, callback_function,
                              always_dismiss_on_ok_clicked=True):

    generic_chooser_and_entry_and_check_button(chooser_label, entry_hint_text,
                                               default_entry_text, False,
                                               callback_function,
                                               always_dismiss_on_ok_clicked)

# as above , plus we also have a check-button
# [and an additional argument in the callback - actually not I think ]
# If check-button-label is false, then don't create a check-button.


def generic_chooser_and_entry_and_check_button(chooser_label, entry_hint_text,
                                               default_entry_text, check_button_label,
                                               callback_function,
                                               always_dismiss_on_ok_clicked=True):

    import operator

    def delete_event(*args):
        window.destroy()
        return False

    def combobox_to_molecule_number(combobox):
        imol = -1
        tree_iter = combobox.get_active_iter()
        if tree_iter is not None:
            model = combobox.get_model()
            it = model[tree_iter]
            imol = it[0]
        return imol

    def on_ok_button_clicked(*args):
        # active_mol_no = get_option_menu_active_molecule(option_menu, model_mol_list)
        active_mol_no = combobox_to_molecule_number(combobox)

        try:
            active_mol_no = int(active_mol_no)
            print("INFO: operating on molecule number ", active_mol_no)
            text = entry.get_text()
            if check_button:
                check_button_state = check_button.get_active()
                cbf_ret = callback_function(active_mol_no, text, check_button_state)
            else:
                cbf_ret = callback_function(active_mol_no, text)
            if always_dismiss_on_ok_clicked:
                delete_event()
            else:
                if cbf_ret:
                    delete_event()
                else:
                    return True
        except KeyError as e:
            print("WARNING:: Failed to get a (molecule) number")
            print("WARNING:: KeyError Failed to get a (molecule) number", e)

    window = Gtk.Window()
    window.set_title('Coot')
    label = Gtk.Label(label=chooser_label)
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    hbox_for_entry = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    entry = Gtk.Entry()
    entry_label = Gtk.Label(label=entry_hint_text)
    hbox_buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    # option_menu = Gtk.combo_box_new_text()

    combobox_items = make_store_for_model_molecule_combobox()
    combobox = Gtk.ComboBox.new_with_model(combobox_items)
    renderer_text = Gtk.CellRendererText()
    if len(combobox_items) > 0:
        combobox.set_active(0)
    combobox.set_entry_text_column(1) # Sets the model column which combo_box
                                      # should use to get strings from to be text_column
    combobox.pack_start(renderer_text, True)
    combobox.add_attribute(renderer_text, "text", 1)

    ok_button = Gtk.Button(label="  OK  ")
    cancel_button = Gtk.Button(label=" Cancel ")
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)

    window.set_default_size(400, 100)
    window.set_child(vbox)
    vbox.append(label)
    vbox.append(combobox)
    vbox.append(hbox_for_entry)
    if check_button_label:
        check_button = Gtk.CheckButton(check_button_label)
        vbox.append(check_button)
    else:
        check_button = False
    vbox.append(h_sep)
    vbox.append(hbox_buttons)
    hbox_buttons.append(ok_button)
    hbox_buttons.append(cancel_button)
    hbox_for_entry.append(entry_label)
    hbox_for_entry.append(entry)
    entry.set_text(default_entry_text)

    # button callbacks
    ok_button.connect("clicked", on_ok_button_clicked, entry, combobox, callback_function, check_button)
    cancel_button.connect("clicked", delete_event)

    window.show()

# Create a window
#
# Return a pair of widgets, a chooser entry and a file selector.  The
# callback_function is a function that takes a molecule number and a
# text string (e.g. chain_id and file_name)
#
# chooser_filter is typically coot_utils.valid_map_molecule_qm or coot_utils.valid_model_molecule_qm
#
# Add option to add a checkbutton
#


def generic_chooser_entry_and_file_selector(chooser_label, chooser_filter,
                                            entry_hint_text, default_entry_text,
                                            file_selector_hint, callback_function,
                                            use_check_button=False,
                                            check_button_label="",
                                            alternative_callback_function=None):

    import operator

    def delete_event(*args):
        window.destroy()
        return False

    def get_molecule():
        tree_iter = combobox.get_active_iter()
        imol = -1
        if tree_iter is not None:
            model = combobox.get_model()
            it = model[tree_iter]
            imol = it[0]
        return imol

    def on_ok_button_clicked(*args):
        # what is the molecule number of the option menu?
        # active_mol_no = get_option_menu_active_molecule(option_menu, model_mol_list)
        imol = get_molecule()
        print("on_ok_button_clicked, got imol", imol)

        try:
            active_mol_no = int(imol)
            text = entry.get_text()
            file_sel_text = file_sel_entry.get_text()
            if (c_button and c_button.get_active()):
                # use alt function
                alternative_callback_function(imol, text, file_sel_text)
            else:
                callback_function(imol, text, file_sel_text)
            delete_event()
        except KeyError as e:
            print(e)
            print("Failed to get a (molecule) number")

    window = Gtk.Window()
    window.set_title("Coot Chooser")
    label = Gtk.Label(label=chooser_label)
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    hbox_for_entry = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    entry = Gtk.Entry()
    entry_label = Gtk.Label(label=entry_hint_text)
    hbox_buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    ok_button = Gtk.Button(label="  OK  ")
    cancel_button = Gtk.Button(label=" Cancel ")
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    # model_mol_list = fill_option_menu_with_mol_options(option_menu, chooser_filter)
    # name_store = fill_combobox_with_model_molecule_options(combobox)
    combobox = Gtk.ComboBox()
    combobox_mol_items = make_store_for_model_molecule_combobox()
    combobox.set_model(combobox_mol_items)
    renderer_text = Gtk.CellRendererText()
    combobox.pack_start(renderer_text, True)
    combobox.add_attribute(renderer_text, "text", 1)
    combobox.set_active(0)

    window.set_default_size(400, 100)
    window.set_child(vbox)
    vbox.append(label)
    vbox.append(combobox)
    vbox.append(hbox_for_entry)
    hbox_buttons.append(cancel_button)
    hbox_buttons.append(ok_button)
    hbox_for_entry.append(entry_label)
    hbox_for_entry.append(entry)
    entry.set_text(default_entry_text)

    for button in [ok_button, cancel_button]:
        button.set_margin_start(8)
        button.set_margin_end(2)
        button.set_margin_top(10)
        button.set_margin_bottom(10)

    c_button = None
    if use_check_button:
        # now add a check button
        c_button = Gtk.CheckButton(check_button_label)
        vbox.append(c_button)

    file_sel_entry = file_chooser_entry(window, vbox, file_selector_hint)
    vbox.append(h_sep)
    vbox.append(hbox_buttons)

    # button callbacks
    ok_button.connect("clicked", on_ok_button_clicked, entry, combobox,
                      callback_function, c_button, alternative_callback_function)
    cancel_button.connect("clicked", delete_event)

    window.show()

# Create a window.
#
# Return a pair of widgets, a molecule chooser and a file selector.  The
# callback_function is a function that takes a molecule number and a
# file_name
#
# chooser_filter is typically coot_utils.valid_map_molecule_qm or coot_utils.valid_model_molecule_qm
#


def generic_chooser_and_file_selector(chooser_label,
                                      chooser_filter,
                                      file_selector_hint,
                                      default_file_name,
                                      callback_function):

    import operator

    def delete_event(*args):
        window.destroy()
        return False

    def combobox_to_molecule_number(combobox):
        imol = -1
        tree_iter = combobox.get_active_iter()
        if tree_iter is not None:
            model = combobox.get_model()
            it = model[tree_iter]
            imol = it[0]
        return imol

    def on_ok_button_clicked(*args):
        # what is the molecule number of the option menu?
        active_mol_no = combobox_to_molecule_number(combobox)

        try:
            active_mol_no = int(active_mol_no)
            file_sel_text = file_sel_entry.get_text()
            callback_function(active_mol_no, file_sel_text)
            delete_event()
        except:
            print("Failed to get a (molecule) number")

    window = Gtk.Window()
    label = Gtk.Label(label=chooser_label)
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    hbox_for_entry = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    hbox_buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
    hbox_buttons.set_homogeneous(True)
    # option_menu = Gtk.combo_box_new_text()
    combobox_items = make_store_for_model_molecule_combobox()
    combobox = Gtk.ComboBox.new_with_model(combobox_items)
    renderer_text = Gtk.CellRendererText()
    if len(combobox_items) > 0:
        combobox.set_active(0)
    combobox.set_entry_text_column(1) # Sets the model column which combo_box
                                      # should use to get strings from to be text_column
    combobox.pack_start(renderer_text, True)
    combobox.add_attribute(renderer_text, "text", 1)

    ok_button = Gtk.Button(label="OK")
    cancel_button = Gtk.Button(label="Cancel")
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)

    window.set_default_size(400, 100)
    window.set_child(vbox)
    vbox.append(label)
    vbox.append(combobox)
    hbox_buttons.append(ok_button)
    hbox_buttons.append(cancel_button)

    file_sel_entry = file_chooser_entry(window, vbox, file_selector_hint, default_file_name)
    vbox.append(h_sep)
    vbox.append(hbox_buttons)

    # button callbacks
    ok_button.connect("clicked", on_ok_button_clicked, combobox, callback_function)
    cancel_button.connect("clicked", delete_event)

    window.show()


# If a menu with label menu-label is not found in the coot main
# menubar, then create it and return it.
# If it does exist, simply return it.
#
def coot_menubar_menu(menu_label):

    try:
        coot_main_menumodel = coot_gui_api.main_menumodel()
        # print("%%%%%% in coot_menubar_menu, coot_main_menumodel is", coot_main_menumodel)
        # print("%%%%%% in coot_menubar_menu, dir coot_main_menumodel is", dir(coot_main_menumodel))

        def menu_bar_label_list_old():
            ac_lab_ls = []
            for menu_child in coot_main_menumodel.get_children():
                lab = []
                # lab is a GtkAccelLabel list
                lab.append(menu_child.get_children()[0].get_text())
                lab.append(menu_child)
                ac_lab_ls.append(lab)
            return ac_lab_ls

        def menu_bar_label_list():
            ac_lab_ls = []
            n = coot_main_menumodel.get_n_items()
            print("%%%%%% in coot_menubar_menu, n_items is", n)
            for i in range(n):
                il = coot_main_menumodel.get_item_attribute_value(i, "label", GLib.VariantType.new("s"))
                print(i, il)
            return ac_lab_ls

        # main body
        #
        #   found_menu = False
        #   l = menu_bar_label_list()
        #   print("%%%%%% in coot_menubar_menu, l is", l)
        #   for f in l:
        #       if menu_label.lstrip("_") in f:
        #           # we shall return the submenu and not the menuitem
        #           found_menu = f[1].get_submenu()
        #   if found_menu:
        #       return found_menu
        #   else:
        #       menu = Gtk.Menu()
        #       menuitem = Gtk.MenuItem(menu_label)
        #       menuitem.set_submenu(menu)
        #       coot_main_menumodel.append(menuitem)
        #       menuitem.show()
        #       return menu

        found_menu = False
        n = coot_main_menumodel.get_n_items()
        for i in range(n):
            mmml = coot_main_menumodel.get_item_attribute_value(i, "label", GLib.VariantType.new("s"))
            if menu_label.lstrip("_") in mmml:
               found_menu = coot_main_menumodel.get_item(i)

        if found_menu:
            return found_menu
        else:
            menuitem = Gio.Menu()
            coot_main_menumodel.append(menu_label)
            return menuitem

    except KeyError as e:
        print("ERROR:: python coot_coot_gui_api.main_menumodel() an error occurs using coot_gui_api", e)


def add_simple_action_to_menu(menu: Gio.Menu, displayed_name: str, action_name: str, on_activate_callback: Callable[[Gio.SimpleAction,Any],Any]):
    """Creates and adds a stateless Gio.SimpleAction globally to the app and appends a corresponding menu item to the menu"""
    app = coot_gui_api.application()
    action = Gio.SimpleAction.new(action_name, None)
    action.connect("activate", on_activate_callback)
    app.add_action(action)
    menu.append(displayed_name,f"app.{action_name}")

# Make an interesting things GUI for residues of molecule number
# imol that have alternate conformations.
#
def alt_confs_gui(imol):

    residues_list = coot_utils.residues_with_alt_confs(imol)
    interesting_residues_gui(imol, "Residues with Alt Confs", residues_list)

# Make an interesting things GUI for residues with missing atoms
#


def missing_atoms_gui(imol):

    interesting_residues_gui(imol, "Residues with missing atoms",
                             coot.missing_atom_info_py(imol))

# Make an interesting things GUI for residues with zero occupancy atoms
#


def zero_occ_atoms_gui(imol):

    atom_ls = coot_utils.atoms_with_zero_occ(imol)
    if atom_ls:
        interesting_things_gui("Residues with zero occupancy atoms",
                               atom_ls)
    else:
        s = "No atoms with zero occupancy found\n"
        s += "in molecule "
        s += str(imol)
        coot.info_dialog(s)


# Make an interesting things GUI for residues of molecule number
# imol for the given imol.   A generalization of alt-confs gui.
#
def interesting_residues_gui(imol, title, interesting_residues):

    # from types import ListType
    centre_atoms = []
    if coot_utils.valid_model_molecule_qm(imol):
        residues = interesting_residues
        for i in range(len(residues)):
            # if we get here with a 4-element spec, then fix that now
            sp = residues[i]
            if len(sp) == 4:
                residues[i] = sp[1:]

        for spec in residues:
            if spec:
                centre_atoms.append(coot_utils.residue_spec_to_atom_for_centre(imol, *spec)) # debracket spec
            else:
                centre_atoms.append([False])

        interesting_things_gui(title,
                    list(map(lambda residue_cpmd, centre_atom:
                             [residue_cpmd[0] + " " +
                              str(residue_cpmd[1]) + " " +
                              residue_cpmd[2] + " " +
                              centre_atom[0] + " " + centre_atom[1],
                              imol,
                              residue_cpmd[0],
                              residue_cpmd[1],
                              residue_cpmd[2],
                              centre_atom[0],
                              centre_atom[1]] if centre_atom else
                             ["[oops - why did this happen?]", 0, 0, 0, 0, 0, 0],
                             residues, centre_atoms)))
    else:
        print("BL WARNING:: no valid molecule", imol)


# If a toolbutton with label button_label is not found in the coot main
# toolbar, then create it and return it.
# If it does exist, the icon will be overwritten. The callback function wont!
# [NOTE: if its a Coot internal Toolbar you can
# only add a function but not overwrite its internal function!!!]
#
# return False if we cannot create the button and/or wrong no of arguments
#
# we accept 6 arguments:
#   button_label
#   callback_function   (can be a string or callable function, or list
#                        with first element fucntion, then args, i.e.
#                        [function, arg1, arg2, ...])
#   gtk-stock-item      (or icon_widget, whatever that is)
#   tooltip             a text to present as tooltip
#   toggle_button_flag  toggle button instead of normal button
#   use_button          pass the button widget onto the function
#
def coot_toolbar_button(button_label, cb_function,
                        icon_name=False, tooltip=False,
                        toggle_button_flag=False, use_button_flag=False):

    coot_main_toolbar = coot_gui_api.main_toolbar()

    # main body
    #
    found_button = False
    tll = toolbar_label_list()
    print("debug:: in coot_toolbar_button: toolbar_label_list() returned", tll)
    for f in toolbar_label_list():
        print("#### debug coot_toolbar_button", f)
    for f in toolbar_label_list():
        if f: # it might be None (i.e. currently all the icons don't have labels!)
            if button_label in f:
                found_button = f[1]
    if found_button:
        # here we only try to add a new icon, we cannot overwrite the callback function!
        toolbutton = found_button
    else:
        if toggle_button_flag:
            toolbutton = Gtk.ToggleButton()
            toolbutton.set_label(button_label)
        else:
            toolbutton = Gtk.Button(label=button_label) # how do we set the icon?
        print("This is the coot_main_toolbar:")
        print(coot_main_toolbar)
        print(dir(coot_main_toolbar))
        coot_main_toolbar.append(toolbutton)       # insert at the end
        # toolbutton.set_is_important(True)          # to display the text. 20230427-PE Not in gtk4
        # otherwise only icon

        def cb_wrapper(widget, callback_function):
            print("DEBUG:: in cb_wrapper() for coot_toolbar_button(): widget is", widget, "and callback_function is", callback_function)
            if True:
                # have function as callable and maybe extra args (all in one list)
                args = []
                function = callback_function
                if type(callback_function) is list:
                    function = callback_function[0]
                    args = callback_function[1:]
                # pass the widget/button as well? Maybe the cb function can
                # make use of it
                if use_button_flag:
                    args.append(widget)
                if callable(function):
                    print("DEBUG:: in cb_wrapper() was callable", function, "with args", *args)
                    function(*args)
                else:
                    print("BL ERROR:: cannot evaluate or call function", function)
        #toolbutton.connect("clicked", lambda w: eval(cb_function))
        toolbutton.connect("clicked", cb_wrapper, cb_function)
        toolbutton.show()

    if icon_name:
        # try to add a stock item
        try:
            toolbutton.set_stock_id(icon_name)
        except:
            # try to add a icon widget
            try:
                toolbutton.set_icon_widget(icon_name)
            except:
                print("BL INFO::  icon name/widget given but could not add the icon")

    return toolbutton

# If a combobox with name is not found in the coot main
# toolbar, then create it and return it. If it is there give a warning
#
# return False if we cannot create the button and/or wrong no of arguments
#
# we accept 3 arguments:
#   label               name of the tool item (to keep track)
#   entry_list          labels for all entries of the box
#   callback_function   (can be a string or callable function, or list
#                        with first element fucntion, then args, i.e.
#                        [function, arg1, arg2, ...])
#   tooltip             a text to present as tooltip
#


def coot_toolbar_combobox(label, entry_list, cb_function, tooltip=""):

    coot_main_toolbar = coot_gui_api.main_toolbar()

    # main body
    #
    found_combobox = False
    for f in toolbar_label_list():
        if label in f:
            found_combobox = f[1]
    if found_combobox:
        s = "BL WARNING:: already have a comboxbox with name %s. Please " +\
            "try again!" % found_combobox
        coot.info_dialog(s)
        return False
    else:
        toolitem = Gtk.ToolItem()
        toolitem.set_name(label)
        combobox = Gtk.combo_box_new_text()
        for text in entry_list:
            combobox.append_text(text)
        combobox.set_active(0)

        def cb_wrapper(widget, callback_function):
            pos = widget.get_active()
            if (type(callback_function) is bytes):
                # old style with string as function
                # does not take into account the positions pos! Or how?
                # FIXME? Maybe
                eval(callback_function)
            else:
                # have function as callable and maybe extra args (all in one list)
                args = []
                function = callback_function
                # if there is a list, then we add the pos as last arg
                if (isinstance(callback_function, list)):
                    function = callback_function[0]
                    args = callback_function[1:]
                    args.append(pos)
                # pass the widget/button as well? Maybe the cb function can
                # make use of it
                if callable(function):
                    function(*args)
                else:
                    print("BL ERROR:: cannot evaluate or call function", function)

        combobox.connect("changed", cb_wrapper, cb_function)
        toolitem.add(combobox)
        coot_main_toolbar.insert(toolitem, -1)
        toolitem.show()

    return toolitem

def toolbar_label_list():

    button_label_ls = []
    coot_main_toolbar = coot_gui_api.main_toolbar()
    print("coot_main_toolbar", coot_main_toolbar)
    child = coot_main_toolbar.get_first_child()
    print("coot_main_toolbar first child ", child)

    while child is not None:
        print("child:", child)
        label = child.get_label()
        print("child label:", label)
        button_label_ls.append(label)
        child = child.get_next_sibling()

    print("returning", button_label_ls)
    return button_label_ls

# returns a list of existing toolbar buttons
# [[label, toolbutton],[]...]
# or False if coot_python is not available
#
def toolbar_label_list_old():

    coot_main_toolbar = coot_gui_api.main_toolbar()
    button_label_ls = []
    # for toolbar_child in coot_main_toolbar.get_children():
    n = coot_main_toolbar.get_n_items()
    print("debug:: coot_main_toolbar has",n,"items")
    box = coot_main_toolbar.get_nth_item(0)
    n = box.get_n_items()
    for idx in range(n):
        toolbar_child = coot_main_toolbar.get_nth_item(idx)
        ls = []
        try:
            label = toolbar_child.get_label()
            ls.append(label)
            ls.append(toolbar_child)
            button_label_ls.append(ls)
        except:
            # some toolitems we have from GTK2 cannot be accessed here
            # so we pass it and dont add it to the list.
            # nothing we can do about it. Probably good as we dont want to
            # play with the GTK2 toolitems only with the PYGTK ones.
            #
            # try if it has a name instead, e.g. toolitem
            try:
                label = toolbar_child.get_name()
                ls.append(label)
                ls.append(toolbar_child)
                button_label_ls.append(ls)
            except:
                pass

    return button_label_ls


# button-list is a list of pairs (improper list) the first item of
# which is the button label text the second item is a lambda
# function, what to do when the button is pressed.
#
def generic_button_dialog(dialog_name, button_list):

    def delete_event(*args):
        window.destroy()
        return False

    # main body
    window = Gtk.Window()
    scrolled_win = Gtk.ScrolledWindow()
    outside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    inside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

    window.set_default_size(250, 250)
    window.set_title(dialog_name)
    # inside_vbox.set_border_width(4)

    window.set_child(outside_vbox)
    outside_vbox.append(scrolled_win)
    scrolled_win.add_with_viewport(inside_vbox)

    for button_item in button_list:
        if button_item and len(button_item) == 2:
            button_label = button_item[0]
            action = button_item[1]

            button = Gtk.Button(label=button_label)
            inside_vbox.append(button)
            button.connect("clicked", action)
            button.show()

    # outside_vbox.set_border_width(4)
    ok_button = Gtk.Button(label="  OK  ")
    outside_vbox.append(ok_button)
    ok_button.connect("clicked", delete_event)

    window.show()


# Generic interesting things gui: user passes a function that takes 4
# args: the chain-id, resno, inscode and residue-serial-number
# (should it be needed) and returns either #f or something
# interesting (e.g. a label/value).  It is the residue-test-func of
# the residue-matching-criteria function.
#
def generic_interesting_things(imol, gui_title_string, residue_test_func):

    if coot_utils.valid_model_molecule_qm(imol):

        interesting_residues = coot_utils.residues_matching_criteria(imol, residue_test_func)
        for i in range(len(interesting_residues)):
            interesting_residues[i][0] = imol
        residue_spec = interesting_residues[i][1] # is this right?
        centre_atoms = list(map(residue_spec, interesting_residues))
        if centre_atoms:
            # BL says:: ignoring "Atom in residue name failure" for nor
            interesting_things_gui(gui_title_string,
                                   list(map(lambda interesting_residue, centre_atom:
                                            [interesting_residue[0] + " "
                                             + interesting_residue[1] + " "
                                                + str(interesting_residue[2]) + " "
                                                + interesting_residue[3] + " "
                                                + centre_atom[0] + " " + centre_atom[1]]
                                            + interesting_residue[1:len(interesting_residue)] + centre_atom,
                                            interesting_residues, centre_atoms))
                                   )
    else:
        print("BL WARNING:: no valid model molecule ", imol)

# A gui that makes a generic number chooser: the go_function is a
# function that takes the value of the active menu item - as a
# number.
#
def generic_number_chooser(number_list, default_option_value, hint_text,
                           go_button_label, go_function):

    def delete_event(*args):
        window.destroy()
        return False

    def go_button_pressed(button, combobox, go_function):

        print("########### go_button_pressed: button", button)
        print("########### go_button_pressed: combobox", combobox)
        print("########### go_button_pressed: go_function", go_function)
        active_item_index = combobox.get_active()
        print("########### go_button_pressed: active_item_index", active_item_index)

        imol = -1
        tree_iter = combobox.get_active_iter()
        if tree_iter is not None:
            model = combobox.get_model()
            it = model[tree_iter]
            imol = it[0]
            pass
        print("########### go_button_pressed: imol", imol)
        go_function(imol)
        # print("Failed to get execute function")
        delete_event()

    window = Gtk.Window()
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    hbox1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    hbox2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)      # for Go and Cancel
    function_label = Gtk.Label(label=hint_text)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    go_button = Gtk.Button(label=go_button_label)
    cancel_button = Gtk.Button(label="  Cancel  ")

    # fill_option_menu_with_number_options(option_menu, number_list, default_option_value)

    def make_store(number_list):
        name_store = Gtk.ListStore(int, str)
        for i in number_list:
            label_str = str(i)
            name_store.append([i, label_str])
        return name_store

    combobox_items = make_store(number_list)
    combobox = Gtk.ComboBox.new_with_model(combobox_items)
    renderer_text = Gtk.CellRendererText()
    combobox.set_entry_text_column(1)
    combobox.pack_start(renderer_text, True)
    combobox.add_attribute(renderer_text, "text", 1)
    for i in number_list:
        if i == default_option_value:
            combobox.set_active(i)

    vbox.append(hbox1)
    vbox.append(function_label)
    vbox.append(combobox)
    vbox.append(h_sep)
    vbox.append(hbox2)
    hbox2.append(go_button)
    hbox2.append(cancel_button)
    window.set_child(vbox)
    #  vbox.set_border_width(6)
    # hbox1.set_border_width(6)
    # hbox2.set_border_width(6)
    go_button.connect("clicked", go_button_pressed, combobox, go_function)
    cancel_button.connect("clicked", delete_event)

    window.show()

# vbox is the vbox to which this compound widget should be added.
# button-press-func is the lambda function called on pressing return
# or the button, which takes one argument, the entry.
#
# Add this widget to the vbox here.
#


def entry_do_button(vbox, hint_text, button_label, button_press_func, entry_text=False):

    hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    entry = Gtk.Entry()
    button = Gtk.Button(label=button_label)
    label = Gtk.Label(label=hint_text)

    hbox.append(label)
    hbox.append(entry)
    hbox.append(button)
    button.connect("clicked", button_press_func, entry)

    if entry_text:
        entry.set_text(entry_text)
    label.show()
    button.show()
    entry.show()
    hbox.show()
    vbox.append(hbox)
    return entry

# pack a hint text and a molecule chooser option menu into the given vbox.
#
# return the option-menu and model molecule list:


def generic_molecule_chooser(hbox, hint_text):
    # option_menu = Gtk.combo_box_new_text()
    combobox_items = make_store_for_model_molecule_combobox()
    combobox = Gtk.ComboBox.new_with_model(combobox_items)
    renderer_text = Gtk.CellRendererText()
    if len(combobox_items) > 0:
        combobox.set_active(0)
    combobox.set_entry_text_column(1) # Sets the model column which combo_box
                                      # should use to get strings from to be text_column
    combobox.pack_start(renderer_text, True)
    combobox.add_attribute(renderer_text, "text", 1)

    label = Gtk.Label(label=hint_text)
    # label.set_alignment(0, -1) # what's the new way?

    hbox.append(label)
    hbox.append(combobox)

    # we used to return the molecule list here also, but the combo box can
    # get its own active item using combobox_to_molecule_number()
    return combobox

# Return an entry, the widget is inserted into the hbox passed to
# this function
#


# This is the same as the file_selector_entry, but using the modern FileChooser
# Return an entry, the widget is inserted into the hbox passed to
# this function
#


def file_chooser_entry(parent_window, hbox, hint_text, default_file_name=False):

    #$ if Gtk.pygtk_version > (2, 3, 90):
    if True:

        def file_func1(*args):

            def file_ok_sel(*args):
                t = file_chooser_dialog.get_filename()
                print(t)
                entry.set_text(t)
                file_chooser_dialog.destroy()

            file_chooser_dialog = Gtk.FileChooserDialog("Please choose a file", parent_window,
                                                        Gtk.FileChooserAction.OPEN,
                                                        (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                                         Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

            response = file_chooser_dialog.run()
            if response == Gtk.ResponseType.OK:
                file_ok_sel(file_chooser_dialog, entry)
            elif response == Gtk.ResponseType.CANCEL:
                file_chooser_dialog.destroy()

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        entry = entry_do_button(vbox, hint_text, "  File...  ", file_func1, default_file_name)
        hbox.append(vbox)
        vbox.show()
        return entry
    else:
        return False

# The gui for the strand placement function
#


def place_strand_here_gui():

    generic_number_chooser(coot_utils.number_list(4, 12), 7,
                           " Estimated number of residues in strand",
                           "  Go  ",
                           lambda n: coot.place_strand_here(n, 15))

# Cootaneer gui
#


def cootaneer_gui(imol):

    def delete_event(*args):
        window.destroy()
        return False

    def go_function_event(widget, imol):
        print("apply the sequence info here\n")
        print("then cootaneer\n")

        # no active atom won't do.  We need
        # to find the nearest atom in imol to (rotation-centre).
        #
        # if it is too far away, give a
        # warning and do't do anything.

        n_atom = coot.closest_atom(imol)
        if n_atom:
            imol = n_atom[0]
            chain_id = n_atom[1]
            resno = n_atom[2]
            inscode = n_atom[3]
            at_name = n_atom[4]
            alt_conf = n_atom[5]
            cootaneer_results = coot.cootaneer(imol_map, imol, [chain_id, resno, inscode, at_name, alt_conf])
            print("Cootaneering status:", cootaneer_results)
            if (cootaneer_results == 0):
                s = "Insufficiently confident in alignment to make a fit." + \
                    "\n" + "Perhaps you could improve or extend this fragment."
                window.destroy()
                coot.info_dialog(s)
        else:
            print("WARNING:: no close atom found!")
            window.destroy()

    def add_text_to_text_box(text_box, description):
        start = text_box.get_start_iter()
        text_box.create_tag("tag", foreground="black",
                            background="#c0e6c0")
        text_box.insert_with_tags_by_name(start, description, "tag")

        # return the (entry . textbuffer/box)
        #
    def entry_text_pair_frame(seq_info):

        frame = Gtk.Frame()
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        entry = Gtk.Entry()
        textview = Gtk.TextView()
        textview.set_wrap_mode(Gtk.WRAP_WORD_CHAR)
        text_box = textview.get_buffer()
        chain_id_label = Gtk.Label(label="Chain ID")
        sequence_label = Gtk.Label(label="Sequence")

        frame.add(vbox)
        vbox.append(chain_id_label)
        vbox.append(entry)
        vbox.append(sequence_label)
        vbox.append(textview)
        add_text_to_text_box(text_box, seq_info[1])
        entry.set_text(seq_info[0])
        return [frame, entry, text_box]

        # main body
    imol_map = coot.imol_refinement_map()
    if (imol_map == -1):
        coot.show_select_map_dialog()
        print("BL DEBUG:: probably should wait here for input!?")

    window = Gtk.Window()
    outside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    inside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    buttons_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    go_button = Gtk.Button(label="  Cootaneer!  ")
    cancel_button = Gtk.Button(label="  Cancel  ")

    seq_info_ls = coot.sequence_info(imol)
    # print "BL DEBUG:: sequence_list and imol is", seq_info_ls, imol

    if not seq_info_ls:
        s = "No sequence assigned for molecule number " + str(imol)
        print(s)
        coot.info_dialog(s)
    else:

        for seq_info in seq_info_ls:
            seq_widgets = entry_text_pair_frame(seq_info)
            inside_vbox.append(seq_widgets[0])

        outside_vbox.append(inside_vbox)
        outside_vbox.append(h_sep)
        outside_vbox.append(buttons_hbox)
        buttons_hbox.append(go_button)
        buttons_hbox.append(cancel_button)

        cancel_button.connect("clicked", delete_event)

        go_button.connect("clicked", go_function_event, imol)

        window.set_child(outside_vbox)
        window.show()


# The gui for saving views
#
def view_saver_gui():

    def local_view_name():
        view_count = 0
        while view_count or view_count == 0:
            strr = "View"
            if view_count > 0:
                strr = strr + "-" + str(view_count)
            # now is a view already called str?
            jview = 0
            while jview or jview == 0:
                jview_name = coot.view_name_py(jview)
                if jview >= coot.n_views():
                    return strr
                elif jview_name == False:
                    return strr
                elif strr == jview_name:
                    view_count += 1
                    break
                else:
                    jview += 1
        return strr

    def add_view_local_func(text):
        new_view_number = coot.add_view_here(text)
        add_view_to_views_panel(text, new_view_number)

    generic_single_entry("View Name: ", local_view_name(), " Add View ",
                         lambda text: add_view_local_func(text))


def add_view_to_views_panel(view_name, view_number):
    global views_dialog_vbox
    if (views_dialog_vbox):
        button = Gtk.Button(label=view_name)
        button.connect(
            "clicked", lambda func: coot.go_to_view_number(view_number, 0))
        views_dialog_vbox.append(button)
        button.show()


def dialog_box_of_buttons(window_name, geometry, buttons, close_button_label, post_hook=None):
    """
    Returns a list of [h_box_buttons, window]

    a button is a list of [label, callback, text_description]
    """
    return dialog_box_of_buttons_with_check_button(window_name, geometry,
                                                   buttons, close_button_label,
                                                   False, False, False, post_hook)

def dialog_box_of_buttons_with_check_button(window_name, geometry,
                                            buttons, close_button_label,
                                            check_button_label,
                                            check_button_func,
                                            check_button_is_initially_on_flag,
                                            post_close_hook=None):
    """
    geometry is an improper list of ints

    return a list of [h_box_buttons, window]

    a button is a list of [label, callback, (optional: text_description)]
    where callback is a function that takes one argument (I think).

    If check_button_label is False, don't make one, otherwise create with
    the given label and "on" state

    Add a post hook, to execute a function after the dialog is closed.
    Default is None.

    Note:
    - if label is "HSep" a horizontal separator is inserted instead of a button
    - the description is optional
    """

    def add_text_to_text_widget(text_box, description):
        textbuffer = text_box.get_buffer()
        start = textbuffer.get_start_iter()
        textbuffer.create_tag("tag", foreground="black", background="#c0e6c0")
        textbuffer.insert_with_tags_by_name(start, description, "tag")

    def close_cb_func(*args):
        if post_close_hook:
            post_close_hook()
        window.hide()

    def hide_this_window(widget):
        # gtk_widget_hide(widget)
        widget.hide()

    # main line
    window = Gtk.Window()
    scrolled_win = Gtk.ScrolledWindow()
    outside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing = 10)
    outside_vbox.set_margin_bottom(10)
    
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    inside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing = 10)
    inside_vbox.set_margin_start(10)
    inside_vbox.set_margin_end(10)
    inside_vbox.set_margin_top(10)
    inside_vbox.set_margin_bottom(10)

    window.set_default_size(geometry[0], geometry[1])
    window.set_title(window_name)
    # inside_vbox.set_border_width(2)
    window.set_child(outside_vbox)

    if check_button_label:
        check_button = Gtk.CheckButton(label=check_button_label)
        # somehow need to execute the function before we can use it in the
        # callback. This is odd to say the least. FIXME
        check_button_func(check_button, inside_vbox)
        check_button.connect("toggled", lambda func: check_button_func(check_button, inside_vbox))
        if check_button_is_initially_on_flag:
            check_button.set_active(True)
        outside_vbox.append(check_button)

    outside_vbox.append(scrolled_win)
    scrolled_win.set_child(inside_vbox)
    inside_vbox.set_hexpand(True)
    inside_vbox.set_vexpand(True)

    for button_info in buttons:
        # print("DEBUG:: in dialog_box_of_buttons_with_check_button(): button_info:", button_info)
        add_button_info_to_box_of_buttons_vbox(button_info, inside_vbox)

    # outside_vbox.set_border_width(2)
    outside_vbox.append(h_sep)
    ok_button = Gtk.Button(label=close_button_label)
    ok_button.set_margin_end(10)
    ok_button.set_halign(Gtk.Align.END)
    outside_vbox.append(ok_button)
    ok_button.connect("clicked", close_cb_func, window, post_close_hook)
    window.connect("destroy", lambda widget : hide_this_window(widget))

    window.show()
    return [inside_vbox, window]

def dialog_box_of_buttons_from_specs(window_name, geometry, imol, specs):

   # not needed, why here Paul?
   #func = [cmd2str(set_go_to_atom_molecule, imol),
   #        cmd2str(set_go_to_atom_chain_residue_atom_name,
   #                chain_id, res_no, atom_name)]

   buttons = []

   # These days buttons should have functions attached, not strings.
   #
   # for spec in specs:
   #    label = coot.residue_spec_to_string(spec)
   #    cbf = [cmd2str(coot.set_go_to_atom_molecule, imol),
   #           cmd2str(coot.set_go_to_atom_chain_residue_atom_name,
   #                   coot.residue_spec_to_chain_id(spec),
   #                   coot.residue_spec_to_res_no(spec), " C  ")]
   #    buttons.append([label, cbf])

   return dialog_box_of_buttons(window_name, geometry, buttons, " Close ")

# This is exported outside of the box-of-buttons gui because the
# clear_and_add_back function (e.g. from using the check button)
# needs to add buttons - let's not duplicate that code.
#


def add_button_info_to_box_of_buttons_vbox(button_info, vbox):

    def add_text_to_text_buffer(text_buffer, description):
        start = text_buffer.get_start_iter()
        text_buffer.create_tag("tag", foreground="black",
                               background="#c0e6c0")
        text_buffer.insert_with_tags_by_name(start, description, "tag")

    # main line

    # print("debug:: add_button_info_to_box_of_buttons_vbox() button_info:", button_info)

    button_label = button_info[0]
    # print("debug in add_button_info_to_box_of_buttons_vbox with button bits", button_label, button_info[1])
    if ((button_label == "HSep") and (len(button_info) == 1)):
        # insert a HSeparator rather than a button
        button = Gtk.HSeparator()
    else:
        callback = button_info[1]
        # print("debug:: in add_button_info_to_box_of_buttons_vbox, callback is", callback)
        if (len(button_info) == 2):
            description = False
        else:
            description = button_info[2]
        button = Gtk.Button(label=button_label)

        # 20210827-PE functions must be real functions, not strings
        button.connect("clicked", callback)

        if description:
            text_view = Gtk.TextView()
            text_view.set_editable(False)
            buff = text_view.get_buffer()
            add_text_to_text_buffer(buff, description)
            vbox.append(text_view)

    vbox.append(button)
    button.show()


# geometry is an improper list of ints
# buttons is a list of: [[["button_1_label, button_1_action],
#                         ["button_2_label, button_2_action]], [next pair of buttons]]
# The button_1_action function is a string
# The button_2_action function is a string
#
def dialog_box_of_pairs_of_buttons(imol, window_name, geometry, buttons, close_button_label):

    window = Gtk.Window()
    scrolled_win = Gtk.ScrolledWindow()
    outside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    inside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

    window.set_default_size(geometry[0], geometry[1])
    window.set_title(window_name)
    # inside_vbox.set_border_width(2)
    window.set_child(outside_vbox)
    outside_vbox.append(scrolled_win)
    scrolled_win.add_with_viewport(inside_vbox)

    for button_info in buttons:
        # print "button_info ", button_info
        # if type(button_info) is ListType: # syntax error now
        if True:
            button_label_1 = button_info[0][0]
            callback_1 = button_info[0][1]

            button_label_2 = button_info[1][0]
            callback_2 = button_info[1][1]

            button_1 = Gtk.Button(label=button_label_1)
            h_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

            # print "button_label_1 ", button_label_1
            # print "callback_1 ", callback_1
            # print "button_label_2 ", button_label_2
            # print "callback_2 ", callback_2

            def callback_func(button, call):
                eval(call)
            button_1.connect("clicked", callback_func, callback_1)
            h_box.append(button_1)

            if callback_2:
                button_2 = Gtk.Button(label=button_label_2)
                button_2.connect("clicked", callback_func, callback_2)
                h_box.append(button_2)
            inside_vbox.append(h_box)

    outside_vbox.set_border_width(2)
    ok_button = Gtk.Button(label=close_button_label)
    outside_vbox.pack_end(ok_button, False, False, 2)
    ok_button.connect("clicked", lambda w: window.destroy())
    window.show()

# as the dialog_box_of_buttons, but we can put in an extra widget (extra_widget)
#


def dialog_box_of_buttons_with_widget(window_name, geometry,
                                      buttons, extra_widget,
                                      close_button_label):

    def add_text_to_text_widget(text_box, description):
        textbuffer = text_box.get_buffer()
        start = textbuffer.get_start_iter()
        textbuffer.create_tag("tag", foreground="black",
                              background="#c0e6c0")
        textbuffer.insert_with_tags_by_name(start, description, "tag")

    # main line
    window = Gtk.Window()
    scrolled_win = Gtk.ScrolledWindow()
    outside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    inside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)

    window.set_default_size(geometry[0], geometry[1])
    window.set_title(window_name)
    # inside_vbox.set_border_width(2)
    window.set_child(outside_vbox)
    outside_vbox.append(scrolled_win)
    scrolled_win.add_with_viewport(inside_vbox)

    for button_info in buttons:
        button_label = button_info[0]
        callback = button_info[1]
        if len(button_info) == 2:
            description = False
        else:
            description = button_info[2]
        button = Gtk.Button(label=button_label)

      # this whole block is outdated and needs to be replaced
      #
      #   if type(callback) is StringType:
      #       def callback_func(button, call):
      #           eval(call)
      #       button.connect("clicked", callback_func, callback)
      #   elif (type(callback) is ListType):
      #       def callback_func(button, call):
      #           for item in call:
      #               eval(item)
      #       button.connect("clicked", callback_func, callback)
      #   else:
      #       button.connect("clicked", callback)

      #   if type(description) is StringType:
      #       text_box = Gtk.TextView()
      #       text_box.set_editable(False)
      #       add_text_to_text_widget(text_box, description)
      #       inside_vbox.append(text_box)
      #       text_box.realize()


        inside_vbox.append(button)

    # for the extra widget
    inside_vbox.append(h_sep)
    inside_vbox.append(extra_widget)

    outside_vbox.set_border_width(2)
    ok_button = Gtk.Button(label=close_button_label)
    outside_vbox.pack_end(ok_button, False, False, 0)
    ok_button.connect("clicked", lambda w: window.destroy())

    window.show()

# A dialog box with radiobuttons e.g. to cycle thru loops
#
# the button list shall be in the form of:
# [[button_label1, "button_function1"],
#  [button_label2, "button_function2"]]
#
# function happens when toggled
# obs: button_functions are strings, but can be tuples for multiple functions
# go_function is string too!
# selected button is the button to be toggled on (default is first)
#


def dialog_box_of_radiobuttons(window_name, geometry, buttons,
                               go_button_label, go_button_function,
                               selected_button=0,
                               cancel_button_label="",
                               cancel_function=False):

    def go_function_event(widget, button_ls):
        eval(go_button_function)
        window.destroy()
        return False

    def cancel_function_cb(widget):
        # print "BL DEBUG:: just for the sake"
        if (cancel_function):
            eval(cancel_function)
        window.destroy()
        return False

    # main line
    window = Gtk.Window()
    scrolled_win = Gtk.ScrolledWindow()
    outside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    inside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    button_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

    window.set_default_size(geometry[0], geometry[1])
    window.set_title(window_name)
    # inside_vbox.set_border_width(2)
    window.set_child(outside_vbox)
    outside_vbox.append(scrolled_win)
    scrolled_win.add_with_viewport(inside_vbox)

    button = None
    button_ls = []
    for button_info in buttons:
        button_label = button_info[0]
        callback = button_info[1]
        button = Gtk.RadioButton(button, button_label)

        # if type(callback) is StringType: # syntax error now
        button.connect("toggled", callback)

        inside_vbox.append(button)
        button_ls.append(button)

    outside_vbox.set_border_width(2)
    go_button = Gtk.Button(label=go_button_label)
    outside_vbox.append(button_hbox)
    button_hbox.append(go_button)
    go_button.connect("clicked", go_function_event, button_ls)
    if (cancel_button_label):
        cancel_button = Gtk.Button(label=cancel_button_label)
        button_hbox.append(cancel_button)
        cancel_button.connect("clicked", cancel_function_cb)

    # switch on the first or selected button
    # somehow I need to emit the toggled signal too (shouldnt have to!?)
    button_ls[selected_button].set_active(True)
    button_ls[selected_button].toggled()

    window.show()


global views_dialog_vbox
views_dialog_vbox = False
# A gui showing views
#


def views_panel_gui():

    global views_dialog_vbox
    number_of_views = coot.n_views()
    buttons = []

    def generator(button_number):
        func = lambda button_number_c=button_number : coot.go_to_view_number(button_number_c, 0)
        def action(arg):
            print("DEBUG:: in views_panel_gui(): action() arg is", arg, "button_number is", button_number)
            func(button_number)
        return action

    for button_number in range(number_of_views):
        button_label = coot.view_name_py(button_number)
        description = coot.view_description_py(button_number)
        # BL says:: add the description condition
        # func = "go_to_view_number(" + str(button_number) + ",0)" 20211115-PE no to string functions
        func = generator(button_number)
        buttons.append([button_label, func, description])

    if len(buttons) > 1:
        def view_button_func():
            import time
            coot.go_to_first_view(1)
            time.sleep(1)
            coot.play_views()
        view_button = ["  Play Views ", lambda func: view_button_func()]
        buttons.insert(0, view_button)

    views_vbox = dialog_box_of_buttons("Views", [200, 140], buttons, "  Close  ")
    views_dialog_vbox = views_vbox

# nudge screen centre box.  Useful when Ctrl left-mouse has been
# taken over by another function.
#
# This is using the absolute coordinates
#


def nudge_screen_centre_paule_gui():

    zsc = 0.02
# BL says:: in python we need some helper functn, no 'proper' lambda
# axis 0-2 = x,y,z and 0=+ and 1=-

    def nudge_screen_func(axis, operand):
        nudge = zsc * coot.zoom_factor()
        rc = coot_utils.rotation_centre()
        if operand == 0:
            rc[axis] += nudge
        elif operand == 1:
            rc[axis] -= nudge
        else:
            # We should never be here
            print("BL WARNING:: something went wrong!!!")
        coot.set_rotation_centre(*rc)

    buttons = [
        ["Nudge +X", lambda func: nudge_screen_func(0, 0)],
        ["Nudge -X", lambda func: nudge_screen_func(0, 1)],
        ["Nudge +Y", lambda func: nudge_screen_func(1, 0)],
        ["Nudge -Y", lambda func: nudge_screen_func(1, 1)],
        ["Nudge +Z", lambda func: nudge_screen_func(2, 0)],
        ["Nudge -Z", lambda func: nudge_screen_func(2, 1)],
    ]

    dialog_box_of_buttons("Nudge Screen Centre", [200, 240], buttons, "  Close ")


# nudge screen centre box.  Useful when Ctrl left-mouse has been
# taken over by another function.
#
# This is using the viewing coordinates
#
def nudge_screen_centre_gui():

    zsc = 0.02
# BL says:: in python we need some helper functn, no 'proper' lambda
# axis 0-2 = x,y,z and 0=+ and 1=-

    def nudge_screen_func(axis, operand):
        nudge_factor = zsc * coot.zoom_factor()
        rc = coot_utils.rotation_centre()
        mat = coot_utils.view_matrix_transp()
        nudge_vector = []
        for i in range(axis, axis + 7, 3):
            nudge_vector.append(mat[i])
        if operand == 0:
            rc = list(map(lambda x, y: x + y, rc, nudge_vector))
        elif operand == 1:
            rc = list(map(lambda x, y: x - y, rc, nudge_vector))
        else:
            # We should never be here
            print("BL WARNING:: something went wrong!!!")
        coot.set_rotation_centre(*rc)

    buttons = [
        ["Nudge +X", lambda func: nudge_screen_func(0, 0)],
        ["Nudge -X", lambda func: nudge_screen_func(0, 1)],
        ["Nudge +Y", lambda func: nudge_screen_func(1, 0)],
        ["Nudge -Y", lambda func: nudge_screen_func(1, 1)],
        ["Nudge +Z", lambda func: nudge_screen_func(2, 0)],
        ["Nudge -Z", lambda func: nudge_screen_func(2, 1)],
    ]

    dialog_box_of_buttons("Nudge Screen Centre", [200, 240], buttons, "  Close ")

# as nudge_screen_centre_gui but with clipping and zoom control


def nudge_screen_centre_extra_gui():

    # this is for the centre nudging
    zsc = 0.02
# BL says:: in python we need some helper functn, no 'proper' lambda
# axis 0-2 = x,y,z and 0=+ and 1=-

    def nudge_screen_func(axis, operand):
        nudge_factor = zsc * coot.zoom_factor()
        rc = coot_utils.rotation_centre()
        mat = coot_utils.view_matrix_transp()
        nudge_vector = []
        for i in range(axis, axis + 7, 3):
            nudge_vector.append(mat[i])
        if operand == 0:
            rc = list(map(lambda x, y: x + y, rc, nudge_vector))
        elif operand == 1:
            rc = list(map(lambda x, y: x - y, rc, nudge_vector))
        else:
            # We should never be here
            print("BL WARNING:: something went wrong!!!")
        coot.set_rotation_centre(*rc)

    buttons = [
        ["Nudge +X", lambda func: nudge_screen_func(0, 0)],
        ["Nudge -X", lambda func: nudge_screen_func(0, 1)],
        ["Nudge +Y", lambda func: nudge_screen_func(1, 0)],
        ["Nudge -Y", lambda func: nudge_screen_func(1, 1)],
        ["Nudge +Z", lambda func: nudge_screen_func(2, 0)],
        ["Nudge -Z", lambda func: nudge_screen_func(2, 1)],
    ]

    # and this is for the clipping and zooming
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

    def change_clipp(*args):
        coot.set_clipping_front(clipp_adj.value)
        coot.set_clipping_back(clipp_adj.value)

    def change_zoom(*args):
        coot.set_zoom(zoom_adj.value)
        coot.graphics_draw()

    # for clipping
    clipp_label = Gtk.Label(label="Clipping")
    clipp_adj = Gtk.Adjustment(0.0, -10.0, 20.0, 0.05, 4.0, 10.1)
    clipp_scale = Gtk.HScale(clipp_adj) # needs fixing probably
    # vbox.append(clipp_label)
    # vbox.append(clipp_scale)
    vbox.append(clipp_label)
    vbox.append(clipp_scale)
    clipp_label.show()
    clipp_scale.show()

    clipp_adj.connect("value_changed", change_clipp)

    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    vbox.append(h_sep)

    # for zooming
    zoom = coot.zoom_factor()
    zoom_label = Gtk.Label(label="Zoom")
    zoom_adj = Gtk.Adjustment(zoom, zoom*0.125, zoom*8, 0.01, 0.5, zoom)
    zoom_scale = Gtk.HScale(zoom_adj)
    vbox.append(zoom_label)
    vbox.append(zoom_scale)
    zoom_label.show()
    zoom_scale.show()

    zoom_adj.connect("value_changed", change_zoom)

    dialog_box_of_buttons_with_widget("Nudge Screen Centre with Extras", [200, 400], buttons, vbox, "  Close ")


# A gui to make a difference map (from arbitrarily gridded maps
# (that's it's advantage))
#
def make_difference_map_gui():

    def delete_event(*args):
        window.destroy()
        return False

    def go_function(widget):
        print("make diff map here\n")
        # active_mol_no_ref = get_option_menu_active_molecule(option_menu_ref_mol, coot_utils.map_molecule_list_ref)
        # active_mol_no_sec = get_option_menu_active_molecule(option_menu_sec_mol, coot_utils.map_molecule_list_sec)

        tree_iter_ref = ref_combobox.get_active_iter()
        tree_iter_sec = sec_combobox.get_active_iter()
        model_ref = ref_combobox.get_model()
        model_sec = sec_combobox.get_model()
        it_ref = model_ref[tree_iter_ref]
        it_sec = model_sec[tree_iter_sec]
        imol_1 = it_ref[0]
        imol_2 = it_sec[0]
        scale_text = scale_entry.get_text()
        scale = False
        try:
            scale = float(scale_text)
        except:
            print("WARNING:: make_difference_map_gui(): can't decode scale", scale_text)
        if scale:
            coot.difference_map(imol_1, imol_2, scale)
        delete_event()

    window = Gtk.Window()
    diff_map_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    title = Gtk.Label(label="Make a Difference Map")
    ref_label = Gtk.Label(label="Reference Map:")
    sec_label = Gtk.Label(label="Substract this map:")
    second_map_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    buttons_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    # option_menu_ref_mol = Gtk.combo_box_new_text()
    # option_menu_sec_mol = Gtk.combo_box_new_text()

    scale_label = Gtk.Label(label="Scale")
    scale_entry = Gtk.Entry()
    ok_button = Gtk.Button(label="   OK   ")
    cancel_button = Gtk.Button(label=" Cancel ")

    # map_molecule_list_ref = fill_option_menu_with_map_mol_options(option_menu_ref_mol)
    # map_molecule_list_sec = fill_option_menu_with_map_mol_options(option_menu_sec_mol)

    # ----------------- replacing option menu -----------------------

    ref_combobox_items = make_store_for_map_molecule_combobox()
    sec_combobox_items = make_store_for_map_molecule_combobox()
    ref_combobox = Gtk.ComboBox.new_with_model(ref_combobox_items)
    sec_combobox = Gtk.ComboBox.new_with_model(sec_combobox_items)
    if len(ref_combobox_items) > 0:
        ref_combobox.set_active(0)
    if len(sec_combobox_items) > 0:
        sec_combobox.set_active(0)
    ref_combobox.set_entry_text_column(1)
    sec_combobox.set_entry_text_column(1)
    ref_renderer_text = Gtk.CellRendererText()
    sec_renderer_text = Gtk.CellRendererText()
    ref_combobox.pack_start(ref_renderer_text, True)
    sec_combobox.pack_start(sec_renderer_text, True)
    ref_combobox.add_attribute(ref_renderer_text, "text", 1)
    sec_combobox.add_attribute(sec_renderer_text, "text", 1)

    # ---------------------------------------------------------------

    window.set_child(diff_map_vbox)
    diff_map_vbox.append(title)
    diff_map_vbox.append(ref_label)
    # diff_map_vbox.append(option_menu_ref_mol)
    diff_map_vbox.append(ref_combobox)

    diff_map_vbox.append(sec_label)
    diff_map_vbox.append(second_map_hbox)

    # second_map_hbox.append(option_menu_sec_mol)
    second_map_hbox.append(sec_combobox)
    second_map_hbox.append(scale_label)
    second_map_hbox.append(scale_entry)

    diff_map_vbox.append(h_sep)
    diff_map_vbox.append(buttons_hbox)
    buttons_hbox.append(ok_button)
    buttons_hbox.append(cancel_button)
    scale_entry.set_text("1.0")

    ok_button.connect("clicked", go_function)

    cancel_button.connect("clicked", delete_event)

    window.show()


def cis_peptides_gui(imol):

    def get_ca(atom_list):

        if (atom_list == []):
            return False
        else:
            for atom in atom_list:
                atom_name = atom[0][0]
                if (atom_name == ' CA '):
                    print("BL DEBUG:: returning ", atom)
                    return atom     # check me

    def make_list_of_cis_peps(imol, list_of_cis_peps):

        ret = []

        for cis_pep_spec in list_of_cis_peps:
            r1 = cis_pep_spec[0]
            r2 = cis_pep_spec[1]
            omega = cis_pep_spec[2]
            atom_list_r1 = coot.residue_info_py(imol, *r1[1:4])
            atom_list_r2 = coot.residue_info_py(imol, *r2[1:4])
            ca_1 = get_ca(atom_list_r1)
            ca_2 = get_ca(atom_list_r2)
            chain_id = r1[1]

            if ((not ca_1) and (not ca_2)):
                ret.append(["Cis Pep (atom failure) " + r1[1] + " " + str(r1[2]),
                            imol, chain_id, r1[3], r1[2], "CA", ""])
            else:
                p1 = ca_1[2]
                p2 = ca_2[2]
                pos = list(map(lambda x, y: (x + y) / 2.0, p1, p2))
                tors_s1 = str(omega)
                if (len(tors_s1) < 6):
                    tors_string = tors_s1
                else:
                    tors_string = tors_s1[0:6]
                mess = ("Cis Pep: " + chain_id + " " +
                        str(r1[2]) + " " +
                        coot.residue_name(imol, *r1[1:4]) + " - " +
                        str(r2[2]) + " " +
                        coot.residue_name(imol, *r2[1:4]) + "   " +
                        tors_string)
                ls = pos
                ls.insert(0, mess)
                ret.append(ls)
        return ret

    cis_peps = coot.cis_peptides_py(imol)

    if (cis_peps == []):
        coot.info_dialog("No Cis Peptides found")
    else:
        list_of_cis_peptides = make_list_of_cis_peps(imol, cis_peps)
        interesting_things_gui("Cis Peptides:", list_of_cis_peptides)

#


def transform_map_using_lsq_matrix_gui():

    def delete_event(*args):
        window.destroy()
        return False

    def on_ok_button_clicked(*args):
        # active_mol_ref = get_option_menu_active_molecule(frame_info_ref[1], frame_info_ref[2])
        # active_mol_mov = get_option_menu_active_molecule(frame_info_mov[1], frame_info_mov[2])

        combobox_ref = frame_info_ref[1]
        combobox_mov = frame_info_mov[1]

        tree_iter = combobox_ref.get_active_iter()
        if tree_iter is not None:
            model = combobox_ref.get_model()
            it = model[tree_iter]
            imol_ref = it[0]

        tree_iter = combobox_mov.get_active_iter()
        if tree_iter is not None:
            model = combobox_mov.get_model()
            it = model[tree_iter]
            imol_mov = it[0]

        print("debug:: imol_ref", imol_ref)
        print("debug:: imol_mov", imol_mov)

        chain_id_ref     = frame_info_ref[2].get_text()
        resno_1_ref_text = frame_info_ref[3].get_text()
        resno_2_ref_text = frame_info_ref[4].get_text()

        chain_id_mov     = frame_info_mov[2].get_text()
        resno_1_mov_text = frame_info_mov[3].get_text()
        resno_2_mov_text = frame_info_mov[4].get_text()

        radius_text = radius_entry.get_text()

        imol_map = coot.imol_refinement_map()
        cont = False
        try:
            resno_1_ref = int(resno_1_ref_text)
            resno_2_ref = int(resno_2_ref_text)
            resno_1_mov = int(resno_1_mov_text)
            resno_2_mov = int(resno_2_mov_text)
            radius = float(radius_text)

            if not coot_utils.valid_map_molecule_qm(imol_map):
                coot.info_dialog("WARNING:: Must set the refinement map")
            else:
                imol_copy = coot.copy_molecule(imol_mov)
                new_map_number = coot_utils.transform_map_using_lsq_matrix(imol_ref, chain_id_ref,
                                                                           resno_1_ref, resno_2_ref,
                                                                           imol_copy, chain_id_mov,
                                                                           resno_1_mov, resno_2_mov,
                                                                           imol_map, coot_utils.rotation_centre(), radius)
                sp = coot_utils.strip_path(coot.molecule_name(imol_mov))
                coot.set_molecule_name(imol_copy, "Transformed copy of " + sp)

                s = "Transformed map: from map " + str(imol_map) + " by matrix that created coords " + str(imol_copy)
                coot.set_molecule_name(new_map_number, s)
                coot.set_mol_active(imol_copy, 0)
                coot.set_mol_displayed(imol_copy, 0)

        except KeyError as e:
            coot.info_dialog("ERROR:: conversion from input text to numbers failed")

        window.destroy()

    # atom-sel-type is either 'Reference or 'Moving
    #
    # return the list [frame, option_menu, model_mol_list, entries...]
    def atom_sel_frame(atom_sel_type):
        frame = Gtk.Frame()

        # ----------------- replacing option_menu ------------------------

        # option_menu = Gtk.combo_box_new_text()
        # model_mol_list = fill_option_menu_with_coordinates_mol_options(option_menu)

        combobox_items = make_store_for_model_molecule_combobox()
        combobox = Gtk.ComboBox.new_with_model(combobox_items)
        renderer_text = Gtk.CellRendererText()
        if len(combobox_items)> 0:
            combobox.set_active(0)
        combobox.set_entry_text_column(1)
        combobox.pack_start(renderer_text, True)
        combobox.add_attribute(renderer_text, "text", 1)

        atom_sel_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        atom_sel_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        chain_id_label = Gtk.Label(label=" Chain ID ")
        resno_1_label = Gtk.Label(label=" Resno Start ")
        resno_2_label = Gtk.Label(label=" Resno End ")
        chain_id_entry = Gtk.Entry()
        resno_1_entry = Gtk.Entry()
        resno_2_entry = Gtk.Entry()

        frame.add(atom_sel_vbox)
        atom_sel_vbox.append(combobox)
        atom_sel_vbox.append(atom_sel_hbox)
        atom_sel_hbox.append(chain_id_label)
        atom_sel_hbox.append(chain_id_entry)
        atom_sel_hbox.append(resno_1_label)
        atom_sel_hbox.append(resno_1_entry)
        atom_sel_hbox.append(resno_2_label)
        atom_sel_hbox.append(resno_2_entry)

        return [frame, combobox, chain_id_entry, resno_1_entry, resno_2_entry]

    window = Gtk.Window()
    dialog_name = "Map Transformation"
    main_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    buttons_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    cancel_button = Gtk.Button(label="  Cancel  ")
    ok_button = Gtk.Button(label="  Transform  ")
    usage = "Note that this will transform the current refinement map " + \
            "to around the screen centre"
    usage_label = Gtk.Label(label=usage)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    frame_info_ref = atom_sel_frame("Reference")
    frame_info_mov = atom_sel_frame("Moving")
    radius_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    radius_label = Gtk.Label(label="  Radius ")
    radius_entry = Gtk.Entry()
    window.set_title(dialog_name)

    radius_hbox.append(radius_label)
    radius_hbox.append(radius_entry)

    buttons_hbox.append(ok_button)
    buttons_hbox.append(cancel_button)

    window.set_child(main_vbox)
    main_vbox.append(frame_info_ref[0])
    main_vbox.append(frame_info_mov[0])
    main_vbox.append(radius_hbox)
    main_vbox.append(usage_label)
    main_vbox.append(h_sep)
    main_vbox.append(buttons_hbox)

    frame_info_ref[2].set_text("A")
    frame_info_ref[3].set_text("1")
    frame_info_ref[4].set_text("10")
    frame_info_mov[2].set_text("B")
    frame_info_mov[3].set_text("1")
    frame_info_mov[4].set_text("10")

    radius_entry.set_text("8.0")

    cancel_button.connect("clicked", delete_event)
    ok_button.connect("clicked", on_ok_button_clicked)

    window.show()
    if (not coot_utils.valid_map_molecule_qm(coot.imol_refinement_map())):
        coot.show_select_map_dialog()


def ncs_ligand_gui():

    import coot_ncs as ncs

    def delete_event(*args):
        window.destroy()
        return False

    def go_button_function(widget):
        print("ncs ligand function here\n")
        # active_mol_no_ref = get_option_menu_active_molecule(option_menu_ref_mol, molecule_list_ref)
        # active_mol_no_lig = get_option_menu_active_molecule(option_menu_lig_mol, molecule_list_lig)
        # these need fixing obviously.
        active_mol_no_ref = -1
        active_mol_no_lig = -1
        chain_id_lig = chain_id_lig_entry.get_text()
        chain_id_ref = chain_id_ref_entry.get_text()
        resno_start = False
        resno_end = False
        try:
            resno_start = int(resno_start_entry.get_text())
        except:
            print("can't decode resno_start", resno_start_entry.get_text())

        resno_end_t = resno_end_entry.get_text()
        try:
            resno_end = int(resno_end_t)
        except:
            if (resno_end_t == ""):
                resno_end = resno_start
            else:
                print("can't decode resno_end", resno_end_t)

        if (resno_end and resno_start):
            coot.make_ncs_ghosts_maybe(active_mol_no_ref)
            print("ncs ligand with", active_mol_no_ref,
                  chain_id_ref, active_mol_no_lig, chain_id_lig,
                  resno_start, resno_end)
            ncs.ncs_ligand(active_mol_no_ref,
                           chain_id_ref,
                           active_mol_no_lig,
                           chain_id_lig,
                           resno_start,
                           resno_end)

        delete_event()

    window = Gtk.Window()
    ncs.ncs_ligands_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    title = Gtk.Label(label="Find NCS-Related Ligands")
    ref_label = Gtk.Label(label="Protein with NCS:")
    ref_chain_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    chain_id_ref_label = Gtk.Label(label="NCS Master Chain")
    chain_id_ref_entry = Gtk.Entry()
    lig_label = Gtk.Label(label="Molecule containing ligand")
    specs_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    buttons_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    chain_id_lig_label = Gtk.Label(label="Chain ID: ")
    resno_start_label = Gtk.Label(label=" Residue Number ")
    to_label = Gtk.Label(label="  to  ")
    chain_id_lig_entry = Gtk.Entry()
    resno_start_entry = Gtk.Entry()
    resno_end_entry = Gtk.Entry()
    ok_button = Gtk.Button(label="   Find Candidate Positions  ")
    cancel_button = Gtk.Button(label="    Cancel    ")
    combo_box_ref_mol = Gtk.combo_box_new_text()
    combo_box_lig_mol = Gtk.combo_box_new_text()

    molecule_list_ref = fill_combobox_with_model_molecule_options(combo_box_ref_mol)
    molecule_list_lig = fill_combobox_with_model_molecule_options(combo_box_lig_mol)

    window.set_child(ncs.ncs_ligands_vbox)
    ncs.ncs_ligands_vbox.append(title)
    ncs.ncs_ligands_vbox.append(ref_label)
    ncs.ncs_ligands_vbox.append(combo_box_ref_mol)
    ncs.ncs_ligands_vbox.append(ref_chain_hbox)
    ncs.ncs_ligands_vbox.append(lig_label)
    ncs.ncs_ligands_vbox.append(combo_box_lig_mol)
    ncs.ncs_ligands_vbox.append(specs_hbox)
    ncs.ncs_ligands_vbox.append(h_sep)
    ncs.ncs_ligands_vbox.append(buttons_hbox)

    buttons_hbox.append(ok_button)
    buttons_hbox.append(cancel_button)

    ref_chain_hbox.append(chain_id_ref_label)
    ref_chain_hbox.append(chain_id_ref_entry)

    specs_hbox.append(chain_id_lig_label)
    specs_hbox.append(chain_id_lig_entry)
    specs_hbox.append(resno_start_label)
    specs_hbox.append(resno_start_entry)
    specs_hbox.append(to_label)
    specs_hbox.append(resno_end_entry)
    specs_hbox.append(Gtk.Label(label=" "))

    chain_id_lig_entry.set_size_request(32, -1)
    chain_id_ref_entry.set_size_request(32, -1)
    resno_start_entry.set_size_request(50, -1)
    resno_end_entry.set_size_request(50, -1)
    chain_id_ref_entry.set_text("A")
    chain_id_lig_entry.set_text("A")
    resno_start_entry.set_text("1")

    #tooltips = Gtk.Tooltips()
    chain_tip = "'A' is a reasonable guess at the NCS master chain id.  " + \
                "If your ligand (specified below) is NOT bound to the protein's " + \
                "'A' chain, then you will need to change this chain and also " + \
                "make sure that the master molecule is specified appropriately " + \
                "in the Draw->NCS Ghost Control window."
    resno_tip = "Leave blank for a single residue"
    # no tooltips

    ok_button.connect("clicked", go_button_function)

    cancel_button.connect("clicked", delete_event)

    window.show()


# NCS jumping GUI
global ncs_jumping_time_step
ncs_jumping_time_step = 500


def ncs_jumping_gui():

    import coot_ncs as ncs

    global ncs_jumping_time_step
    global timeout_function_token
    timeout_function_token = False

    def delete_event(*args):
        # first stop the jumping (if necessary)
        global timeout_function_token
        timeout_function_token = False

        window.destroy()
        return False

    # FIXME check this. Not sure if we can get a number from timeout_add or
    # if we better make a new function which returns True/False to continue/stop

    # need to return True to be called again. I return False if stop (bug in
    # gobject.source_remove prevents me from using this.
    def skip_ncs_timeout_func():
        global timeout_function_token
        ncs.skip_to_next_ncs_chain("forward")
        if timeout_function_token:
            return True
        else:
            return False

    def start_function_event(*args):
        global timeout_function_token
        if not coot_utils.isNumber(timeout_function_token):
            timeout_function_token = GObject.timeout_add(ms_step, skip_ncs_timeout_func)
        else:
            timeout_function_token = False

    def stop_function_event(*args):
        global timeout_function_token
        timeout_function_token = False

    # main body
    window = Gtk.Window()
    outside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    inside_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    cancel_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    jump_start_button = Gtk.Button(label="NCS Jump Start")
    jump_stop_button = Gtk.Button(label="Stop")
    cancel_button = Gtk.Button(label="Cancel")
    ms_step = ncs_jumping_time_step
    timeout_function_token = False

    window.set_title("Auto NCS Jumping")
    window.set_child(outside_vbox)
    outside_vbox.append(inside_hbox)
    outside_vbox.append(h_sep)
    outside_vbox.append(cancel_hbox)
    inside_hbox.append(jump_start_button)
    inside_hbox.append(jump_stop_button)
    cancel_hbox.append(cancel_button)

    jump_start_button.connect("clicked", start_function_event)

    jump_stop_button.connect("clicked", stop_function_event)

    cancel_button.connect("clicked", delete_event)

    window.show()


# GUI for ligand superpositioning by graph matching
#
def superpose_ligand_gui():

    def delete_event(*args):
        window.destroy()
        return False

    def combobox_to_molecule_number(combobox):
      imol = -1
      tree_iter = combobox.get_active_iter()
      if tree_iter is not None:
        model = combobox.get_model()
        it = model[tree_iter]
        imol = it[0]
      return imol

    def go_button_function(widget):
        active_mol_no_ref_lig = combobox_to_molecule_number(combobox_ref_mol)
        active_mol_no_mov_lig = combobox_to_molecule_number(combobox_mov_mol)

        chain_id_ref = chain_id_ref_entry.get_text()
        chain_id_mov = chain_id_mov_entry.get_text()
        resno_ref = False
        resno_mov = False
        try:
            resno_ref = int(resno_ref_entry.get_text())
        except:
            print("can't decode reference resno", resno_ref_entry.get_text())

        try:
            resno_mov = int(resno_mov_entry.get_text())
        except:
            print("can't decode moving resno", resno_mov_entry.get_text())

        if (resno_ref and resno_mov):
            coot_utils.overlay_my_ligands(active_mol_no_mov_lig, chain_id_mov, resno_mov,
                                          active_mol_no_ref_lig, chain_id_ref, resno_ref)

        delete_event()

    window = Gtk.Window()
    title = Gtk.Label(label="Superpose Ligands")
    ligands_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    ref_chain_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    chain_id_ref_label = Gtk.Label(label="Ligand Chain ID: ")
    chain_id_ref_entry = Gtk.Entry()
    resno_ref_label = Gtk.Label(label=" Residue Number ")
    resno_ref_entry = Gtk.Entry()

    mov_chain_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    chain_id_mov_label = Gtk.Label(label="Ligand Chain ID: ")
    chain_id_mov_entry = Gtk.Entry()
    resno_mov_label = Gtk.Label(label=" Residue Number ")
    resno_mov_entry = Gtk.Entry()

    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)

    buttons_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

    ok_button = Gtk.Button(label="   Superpose 'em  ")
    cancel_button = Gtk.Button(label="    Cancel    ")

    window.set_child(ligands_vbox)
    ligands_vbox.append(title)
    combobox_ref_mol = generic_molecule_chooser(ligands_vbox, "Model with reference ligand")
    ligands_vbox.append(ref_chain_hbox)

    combobox_mov_mol = generic_molecule_chooser(ligands_vbox, "Model with moving ligand")
    ligands_vbox.append(mov_chain_hbox)

    ligands_vbox.append(h_sep)
    ligands_vbox.append(buttons_hbox)

    buttons_hbox.append(ok_button)
    buttons_hbox.append(cancel_button)

    ref_chain_hbox.append(chain_id_ref_label)
    ref_chain_hbox.append(chain_id_ref_entry)
    ref_chain_hbox.append(resno_ref_label)
    ref_chain_hbox.append(resno_ref_entry)

    mov_chain_hbox.append(chain_id_mov_label)
    mov_chain_hbox.append(chain_id_mov_entry)
    mov_chain_hbox.append(resno_mov_label)
    mov_chain_hbox.append(resno_mov_entry)

#   chain_id_lig_entry.set_size_request(32, -1)
#   chain_id_ref_entry.set_size_request(32, -1)
#   resno_start_entry.set_size_request(50, -1)
#   resno_end_entry.set_size_request(50, -1)
#   chain_id_ref_entry.set_text("A")
#   chain_id_lig_entry.set_text("A")
#   resno_start_entry.set_text("1")

#   tooltips = Gtk.Tooltips()
#   tooltips.set_tip(chain_id_ref_entry, "'A' is a reasonable guess at the NCS master chain id.  " +
#                    "If your ligand (specified below) is NOT bound to the protein's " +
#                    "'A' chain, then you will need to change this chain and also " +
#                    "make sure that the master molecule is specified appropriately " +
#                    "in the Draw->NCS Ghost Control window.")
#   tooltips.set_tip(resno_end_entry, "Leave blank for a single residue")

    ok_button.connect("clicked", go_button_function)

    cancel_button.connect("clicked", delete_event)

    window.show()


def gui_overlap_ligands(imol_ligand, imol_ref, chain_id_ref, res_no_ref):

    # we don't want to overlap-ligands if there is no dictionary
    # for the residue to be matched to.
    #
    res_name = coot.residue_name(imol_ref, chain_id_ref, res_no_ref, "")
    restraints = coot.active_residue_pymonomer_restraints(res_name)
    if (not restraints):
        return False
    else:
        if (not coot_utils.residue_has_hetatms_qm(imol_ref, chain_id_ref, res_no_ref, "")):
            return False
        else:
            print("----------- overlap-ligands %s %s %s %s ------------"
                  % (imol_ligand, imol_ref, chain_id_ref, res_no_ref))
            # this can return the rtop operator or the False (for fail of course).
            coot.match_ligand_torsions(imol_ligand, imol_ref,
                                  chain_id_ref, res_no_ref)
            ret = coot.overlap_ligands(imol_ligand, imol_ref, chain_id_ref, res_no_ref)
            return ret


global std_key_bindings
std_key_bindings = [["^g", "keyboard-go-to-residue"],
                    ["^s", "quick-save-as"],
                    ["^i", "residue info"],
                    ["^z", "undo"],
                    ["^y", "redo"],
                    ["a", "refine with auto-zone"],
                    ["b", "toggle baton swivel"],
                    ["c", "toggle cross-hairs"],
                    ["d", "reduce depth of field"],
                    ["f", "increase depth of field"],
                    ["u", "undo last navigation"],
                    ["i", "toggle spin mode"],
                    ["l", "label closest atom"],
                    ["m", "zoom out"],
                    ["n", "zoom in"],
                    ["o", "other NCS chain"],
                    ["p", "update position to closest atom"],
                    ["s", "update skeleton"],
                    [".", "up in button list"],
                    [",", "down in button list"]]


# for news infos
(
    INSERT_NO_NEWS,
    INSERT_NEWS,
    STATUS,
    NEWS_IS_READY,
    GET_NEWS,
    SET_TEXT,
    STOP,
    NO_NEWS,
) = list(range(8))

global news_status
news_status = NO_NEWS
global news_string_1
global news_string_2
news_string_1 = False
news_string_2 = False

import coot_fitting as fitting

# Cootaneer/sequencing gui modified by BL with ideas from KC
# based on Paul's cootaneer gui and generic_chooser_entry_and_file_selector
#
def cootaneer_gui_bl():

    # unfortunately currently I dont see a way to avoid a global variable here
    # contains flag if file was imported and no of sequences
    global imported_sequence_file_flags
    imported_sequence_file_flags = [False, 0]

    def delete_event(*args):
        window.destroy()
        return False

    def refine_function_event(widget):
        # doesnt need to do anything
        status = refine_check_button.get_active()
        if (status):
            print("INFO:: refinement on")
        else:
            print("INFO:: refinement off")

    def go_function_event(widget):
        print("apply the sequence info here\n")
        print("then cootaneer\n")

        # no active atom won't do.  We need
        # to find the nearest atom in imol to (rotation-centre).
        #
        # if it is too far away, give a
        # warning and do't do anything.
        combo_box = widget
        active_mol_no = get_combobox_active_molecule(combo_box, model_mol_list)
        imol = int(active_mol_no)
        imol_map = coot.imol_refinement_map()

        do_it = assign_sequences_to_mol(imol)

        if (do_it):
            # now cootaneer it
            chain_ls = coot_utils.chain_ids(imol)
            for chain_id in chain_ls:
                res_name = coot.resname_from_serial_number(imol, chain_id, 0)
                res_no = coot.seqnum_from_serial_number(imol, chain_id, 0)
                ins_code = coot.insertion_code_from_serial_number(imol, chain_id, 0)
                alt_conf = ""
                at_name = coot_utils.residue_spec_to_atom_for_centre(
                    imol, chain_id, res_no, ins_code)[0]
                cootaneer_result = coot.cootaneer(imol_map, imol, [chain_id, res_no, ins_code, at_name, alt_conf])
                if (cootaneer_result == 0):
                    s = "Insufficiently confident in alignment to make a fit." + \
                        "\n" + \
                        "Perhaps you could improve or extend this fragment."
                    coot.info_dialog(s)
                refine_qm = refine_check_button.get_active()
            # refine?
            window.hide()
            if (refine_qm):
                fitting.fit_protein(imol)

            delete_event()

    def import_function_event(widget, selector_entry):
        # we import a sequence file and update the cootaneer table
        global imported_sequence_file_flags
        imported_sequence_file_qm = imported_sequence_file_flags[0]
        combo_box = widget
        active_mol_no = get_combobox_active_molecule(combo_box, model_mol_list)
        imol = int(active_mol_no)

        seq_info_ls = []
        seq_file_name = selector_entry.get_text()
        if (seq_file_name):
            # get and set sequence info
            coot.assign_sequence_from_file(imol, str(seq_file_name))
            seq_info_ls = coot.sequence_info(imol)
            no_of_sequences = len(seq_info_ls)

            # remove children if new file
            if not imported_sequence_file_qm:
                table_children = seq_table.get_children()
                for child in table_children:
                    seq_table.remove(child)
                widget_range = list(range(no_of_sequences))
            else:
                # we update the number of sequences
                spin_len = int(spin_button.get_value())
                widget_range = list(range(spin_len, no_of_sequences))

            # make new table
            imported_sequence_file_flags = [True, no_of_sequences]
            spin_button.set_value(no_of_sequences)
            seq_table.resize(no_of_sequences, 1)
            for i in widget_range:
                seq_widget = entry_text_pair_frame_with_button(seq_info_ls[i])
                seq_table.attach(seq_widget[0], 0, 1, i, i+1)
                seq_widget[0].show()
        else:
            print("BL WARNING:: no filename")

    def fill_table_with_sequences(*args):
        # fills the table with sequences if they have been associated with the model imol
        # already
        global imported_sequence_file_flags
        combo_box = False # FIXME - where do I get combo_box from?
        active_mol_no = get_combobox_active_molecule(combo_box, model_mol_list)
        imol = int(active_mol_no)
        seq_info_ls = coot.sequence_info(imol)
        if (seq_info_ls):
            # we have a sequence and fill the table
            no_of_sequences = len(seq_info_ls)
            imported_sequence_file_flags = [True, no_of_sequences]
            spin_button.set_value(no_of_sequences)
            seq_table.resize(no_of_sequences, 1)
            # remove existing children
            table_children = seq_table.get_children()
            for child in table_children:
                seq_table.remove(child)
            widget_range = list(range(no_of_sequences))
            for i in widget_range:
                seq_widget = entry_text_pair_frame_with_button(seq_info_ls[i])
                seq_table.attach(seq_widget[0], 0, 1, i, i+1)
                seq_widget[0].show()
        else:
            # no sequence information, reset the table
            clear_function_event()

    def add_text_to_text_buffer(text_buffer, description):
        start = text_buffer.get_start_iter()
        text_buffer.create_tag("tag", foreground="black", background="#c0e6c0")
        text_buffer.insert_with_tags_by_name(start, description, "tag")

    # return the (entry . textbuffer/box)
    #
    def entry_text_pair_frame_with_button(seq_info):

        def fragment_go_event(widget):
            combo_box = widget
            active_mol_no = get_combobox_active_molecule(combo_box, model_mol_list)
            imol = int(active_mol_no)
            imol_map = coot.imol_refinement_map()
            print("apply the sequence info here\n")
            print("then cootaneer\n")

            # no active atom won't do.  We need
            # to find the nearest atom in imol to (rotation-centre).
            #
            # if it is too far away, give a
            # warning and do't do anything.

            do_it = assign_sequences_to_mol(imol)
            if (do_it):

                n_atom = coot.closest_atom(imol)
                if n_atom:
                    imol = n_atom[0]
                    chain_id = n_atom[1]
                    res_no = n_atom[2]
                    ins_code = n_atom[3]
                    at_name = n_atom[4]
                    alt_conf = n_atom[5]
                    cootaneer_result = coot.cootaneer(imol_map, imol, [chain_id, res_no, ins_code,
                                                                  at_name, alt_conf])
                    if (cootaneer_result == 0):
                        s = "Insufficiently confident in alignment to make a fit." + \
                            "\n" + \
                            "Perhaps you could improve or extend this fragment."
                        coot.info_dialog(s)
                    else:
                        refine_qm = refine_check_button.get_active()
                        if (chain_check_button.get_active()):
                            # we try to change the chain
                            from_chain_id = chain_id
                            to_chain_id = entry.get_text()
                            start_resno = coot.seqnum_from_serial_number(
                                imol, from_chain_id, 0)
                            end_resno = coot.seqnum_from_serial_number(
                                imol, from_chain_id, (coot.chain_n_residues(from_chain_id, imol) - 1))
                            [istat, message] = coot.change_chain_id_with_result_py(
                                imol, from_chain_id, to_chain_id, 1, start_resno, end_resno)
                            if (istat == 1):
                                # renaming ok
                                chain_id = to_chain_id
                            else:
                                # renaming failed
                                if (refine_qm):
                                    message += "\nRefinement proceeded with old=new chain "
                                    message += chain_id
                                coot.info_dialog(message)

                        if (refine_qm):
                            fitting.fit_chain(imol, chain_id)
                else:
                    print("BL WARNING:: no close atom found!")
            else:
                print("BL ERROR:: something went wrong assigning the sequence")

        def chain_toggled(widget):
            # doesnt need to do anything
            status = chain_check_button.get_active()
            if(status):
                print("BL INFO:: assign chain_id too")
            else:
                print("BL INFO:: do not assign chain_id")

        frame = Gtk.Frame()
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        entry = Gtk.Entry()
        textview = Gtk.TextView()
        textview.set_wrap_mode(Gtk.WRAP_WORD_CHAR)
        textview.set_editable(True)
        textview.set_size_request(300, -1)
        # I don't know how to insall pythonic pango
        # textview.modify_font(pango.FontDescription("Courier 11"))
        text_buffer = textview.get_buffer()
        chain_id_label = Gtk.Label(label="Chain ID")
        sequence_label = Gtk.Label(label="Sequence")
        vbox_for_buttons = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        fragment_button = Gtk.Button(label="  Sequence closest fragment  ")
        chain_check_button = Gtk.CheckButton("Assign Chain ID as well?")

        frame.add(hbox)
        vbox.append(chain_id_label)
        vbox.append(entry)
        vbox.append(sequence_label)
        vbox.append(textview)
        add_text_to_text_buffer(text_buffer, seq_info[1])
        entry.set_text(seq_info[0])
        hbox.append(vbox)
        vbox_for_buttons.append(chain_check_button)
        vbox_for_buttons.append(fragment_button)
        hbox.append(vbox_for_buttons)

        fragment_button.connect("clicked", fragment_go_event)
        chain_check_button.connect("toggled", chain_toggled)

        return [frame, entry, text_buffer]

    # redraw the table when spin_button is changed
    def spin_button_changed(widget):
        global imported_sequence_file_flags
        no_of_frames = int(spin_button.get_value())
        imported_sequence_file_qm = imported_sequence_file_flags[0]
        no_of_sequences = imported_sequence_file_flags[1]

        # get table information
        table_children = seq_table.get_children()
        no_of_children = len(table_children)

        # make range for redraw
        if (imported_sequence_file_qm):
            # we only make extra ones
            redraw_range = list(range(no_of_sequences, no_of_frames))
            if (no_of_sequences > no_of_frames):
                child_range = []    # do not remove children
                redraw_range = []   # do not redraw
                spin_button.set_value(no_of_sequences)
                no_of_frames = no_of_sequences
            else:
                if (no_of_children == no_of_sequences):
                    # do not remove any
                    child_range = []
                else:
                    child_range = list(
                        range(0, no_of_children - no_of_sequences))
                    # children seem to be added in the beginning ???????
        else:
            # we make everything new
            redraw_range = list(range(no_of_frames))
            child_range = list(range(no_of_children))

        # lets remove the children
        for j in child_range:
            child = table_children[j]
            seq_table.remove(child)

        # make new cells
        for i in redraw_range:
            make_cell(i)

        # resize the table
        seq_table.resize(no_of_frames, 1)

    # reset the table
    def clear_function_event(widget=None, file_sel_entry=None):
        global imported_sequence_file_flags
        imported_sequence_file_flags = [False, 0]
        seq_table.resize(1, 1)
        # remove children
        table_children = seq_table.get_children()
        for child in table_children:
            seq_table.remove(child)
        # make new
        make_cell(0)
        spin_button.set_value(1)
        # reset the filechooser entry
        if file_sel_entry:
            file_sel_entry.set_text("")

    # make one cell in line with deafult fill
    def make_cell(line):
        seq_widget = entry_text_pair_frame_with_button(["",
                                                        "Cut and Paste Sequence to here or import a sequence file"])
        seq_table.attach(seq_widget[0], 0, 1, line, line + 1)
        seq_widget[0].show()

    # assign the in table given sequences to the model imol
    def assign_sequences_to_mol(imol):
        no_of_seq = int(spin_button.get_value())
        frame_list = seq_table.get_children()
        seq_all = []
        write_sequence = True
        for i in range(no_of_seq):
            fframe = frame_list[i]
            hhbox = fframe.get_children()[0]
            vvbox = hhbox.get_children()[0]
            child_list = vvbox.get_children()
            chain_id = child_list[1].get_text()
            seq_textbuffer = child_list[3].get_buffer()
            startiter, enditer = seq_textbuffer.get_bounds()
            seq_in = seq_textbuffer.get_text(startiter, enditer)
            pair = [chain_id, seq_in]
            if (len(chain_id) == 0) or (
                    "Cut and Paste Sequence to here or import a sequence file") in pair:
                print("ERROR:: the input contains an invalid chain and/or sequence")
                write_sequence = False
            seq_all.append(pair)

        if (write_sequence):
            for element in seq_all:
                chain_id_new = element[0]
                seq = element[1].upper()
                # first check if chain_id is already in mol
                # if so delete it so that it can be replaced by the new sequence
                seq_info = coot.sequence_info(imol)
                if seq_info:
                    for info in seq_info:
                        chain_id_old = info[0]
                        if (chain_id_new == chain_id_old):
                            coot.delete_sequence_by_chain_id(imol, chain_id_old)

                # replace space, eol etc in sequence first
                seq = seq.replace(" ", "")
                seq = seq.replace("\r", "")       # mac?
                seq = seq.replace("\r\n", "")     # win?
                seq = seq.replace("\n", "")       # unix?
                coot.assign_sequence_from_string(imol, chain_id_new, seq)
            return True
        else:
            coot.add_status_bar_text("Invalid chain_id and/or sequence provided")
            return False

    # main body
    imol_map = coot.imol_refinement_map()
    if (imol_map == -1):
        coot.show_select_map_dialog()

    window = Gtk.Window()
    window.set_title("Sequencing GUI")
    #tooltips = Gtk.Tooltips()
    label = Gtk.Label(label="Molecule to be sequenced")
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    option_menu = Gtk.combo_box_new_text()
    model_mol_list = fill_option_menu_with_mol_options(
        option_menu, coot_utils.valid_model_molecule_qm)
    inside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    seq_table = Gtk.Table(1, 1, True)
    hbox_for_spin = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    spin_label = Gtk.Label(label="Number of Sequences:")
    spin_adj = Gtk.Adjustment(1, 1, 10, 1, 4, 0)
    spin_button = Gtk.SpinButton(spin_adj, 0, 0)
    refine_check_button = Gtk.CheckButton("Auto-fit-refine after sequencing?")
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    h_sep2 = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    buttons_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    import_button = Gtk.Button(label="  Import and associate sequence from file  ")
    go_button = Gtk.Button(label="  Sequence all fragments!  ")

    cancel_button = Gtk.Button(label="  Cancel  ")
    clear_button = Gtk.Button(label="  Clear all  ")

    window.set_default_size(400, 200)
    window.set_child(vbox)
    vbox.append(label)
    vbox.append(option_menu)

    hbox_for_spin.append(spin_label)
    hbox_for_spin.append(spin_button)
    hbox_for_spin.pack_end(refine_check_button, False, False, 2)
    vbox.append(hbox_for_spin)

    vbox.append(inside_vbox)
    inside_vbox.add(seq_table)
    make_cell(0)
    fill_table_with_sequences()

    vbox.append(h_sep)
    file_sel_entry = file_chooser_entry(window, vbox, "Select PIR file")
    vbox.append(import_button)

    buttons_hbox.append(go_button)
    buttons_hbox.append(cancel_button)
    buttons_hbox.append(clear_button)

    vbox.append(h_sep2)
    vbox.append(buttons_hbox)

    import_button.connect("clicked", import_function_event, file_sel_entry)

    cancel_button.connect("clicked", delete_event)

    go_button.connect("clicked", go_function_event)

    clear_button.connect("clicked", clear_function_event, file_sel_entry)

    spin_adj.connect("value_changed", spin_button_changed)

    refine_check_button.connect("toggled", refine_function_event)

    option_menu.connect("changed", fill_table_with_sequences)

    window.show()


def generic_check_button(vbox, label_text, handle_check_button_function):
    def check_callback(*args):
        active_state = check_button.get_active()
        set_state = 0
        if (active_state):
            set_state = 1
        handle_check_button_function(set_state)
    check_button = Gtk.CheckButton(label_text)
    vbox.append(check_button)
    check_button.connect("toggled", check_callback)
    return check_button

# a master gui to set all kinds of refinement parameters
#


def refinement_options_gui():

    def set_matrix_func(button, entry):
        text = entry.get_text()
        try:
            t = float(text)
            s = "Matrix set to " + text
            coot.set_matrix(t)
            coot.add_status_bar_text(s)
        except:
            coot.add_status_bar_text("Failed to read a number")

    def delete_event(*rags):
        window.destroy()
        return False

    def go_function_event(*args):
        set_matrix_func('dummy', matrix_entry)
        window.destroy()
        return False

    window = Gtk.Window()
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    h_sep  = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    h_sep2 = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    h_sep3 = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    go_button = Gtk.Button(label="   Ok   ")
    cancel_button = Gtk.Button(label="  Cancel  ")

    window.set_child(vbox)
    # add the matrix entry
    matrix_entry = entry_do_button(vbox, "set matrix: (smaller means better geometry)",
                                   "Set", set_matrix_func)
    matrix_entry.set_text(str(coot.matrix_state()))

    vbox.append(h_sep2)

    # use torsion restrains?
    torsion_restraints_button = generic_check_button(vbox,
                                                     "Use Torsion Restraints?",
                                                     lambda state: coot.set_refine_with_torsion_restraints(state))
    if (coot.refine_with_torsion_restraints_state() == 1):
        torsion_restraints_button.set_active(True)
    else:
        torsion_restraints_button.set_active(False)

    # planar peptide restrains?
    planar_restraints_button = generic_check_button(vbox,
                                                    "Use Planar Peptide Restraints?",
                                                    lambda state: coot.remove_planar_peptide_restraints() if state == 0 else coot.add_planar_peptide_restraints())
    if (coot.planar_peptide_restraints_state() == 1):
        planar_restraints_button.set_active(True)
    else:
        planar_restraints_button.set_active(False)

    # use ramachandran restrains?
    rama_restraints_button = generic_check_button(vbox,
                                                  "Use Ramachandran Restraints?",
                                                  lambda state: coot.set_refine_ramachandran_angles(state))
    if (coot.refine_ramachandran_angles_state() == 1):
        rama_restraints_button.set_active(True)
    else:
        rama_restraints_button.set_active(False)

    vbox.append(h_sep3)

    # add rotamer check button
    rotamer_autofit_button = generic_check_button(vbox,
                                                  "Real Space Refine after Auto-fit Rotamer?",
                                                  lambda state: coot.set_rotamer_auto_fit_do_post_refine(state))
    if (coot.rotamer_auto_fit_do_post_refine_state() == 1):
        rotamer_autofit_button.set_active(True)
    else:
        rotamer_autofit_button.set_active(False)

    # add mutate check button
    mutate_autofit_button = generic_check_button(vbox,
                                                 "Real Space Refine after Mutate and Auto-fit?",
                                                 lambda state: coot.set_mutate_auto_fit_do_post_refine(state))
    if (coot.mutate_auto_fit_do_post_refine_state() == 1):
        mutate_autofit_button.set_active(True)
    else:
        mutate_autofit_button.set_active(False)

    # add terminal residue check button
    terminal_autofit_button = generic_check_button(vbox,
                                                   "Real Space Refine after Add Terminal Residue?",
                                                   lambda state: coot.set_add_terminal_residue_do_post_refine(state))
    if (coot.add_terminal_residue_do_post_refine_state() == 1):
        terminal_autofit_button.set_active(True)
    else:
        terminal_autofit_button.set_active(False)

    # add a b-factor button
    reset_b_factor_button = generic_check_button(vbox,
                                                 "Reset B-Factors to Default Value after Refinement/Move?",
                                                 lambda state: coot.set_reset_b_factor_moved_atoms(state))
    if (coot.get_reset_b_factor_moved_atoms_state() == 1):
        reset_b_factor_button.set_active(True)
    else:
        reset_b_factor_button.set_active(False)

    vbox.append(h_sep)
    vbox.append(hbox)
    hbox.append(go_button)
    hbox.append(cancel_button)

    go_button.connect("clicked", go_function_event)
    cancel_button.connect("clicked", delete_event)
    window.show()


def map_sharpening_gui(imol):

    window = Gtk.Window()
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    adj = Gtk.Adjustment(0.0, -30, 60, 0.05, 2, 30.1)
    slider = Gtk.HScale(adj)
    label = Gtk.Label(label="\nSharpen Map:")
    lab2 = Gtk.Label(label="Add B-factor: ")

    vbox.append(label)
    vbox.append(hbox)
    hbox.append(lab2)
    hbox.append(slider)
    window.set_child(vbox)
    window.set_size_request(500, 100)
    # slider.add_mark(-30, -30, 0) # not yet, needs updated pygtk

    adj.connect("value_changed", lambda func: coot.sharpen(imol, adj.value))

    window.show()


# Associate the contents of a sequence file with a chain.
# Select file from a GUI.
# File format can be Fasta (default) or PIR
#
# added checkbox to assign for all protein chains
#
def associate_sequence_with_chain_gui(sequence_format="FASTA", do_alignment=False):

    def associate_func(imol, chain_id_in, pir_file_name,
                       use_all_chains=False):
        # print "assoc seq:", imol, chain_id, pir_file_name
        all_chains = chain_id_in
        if use_all_chains:
            all_chains = [chain for chain in coot_utils.chain_ids(
                imol) if coot_utils.is_protein_chain_qm(imol, chain)]
        for chain_id in all_chains:
            if (sequence_format == "FASTA"):
                coot_utils.associate_fasta_file(imol, chain_id, pir_file_name)
            elif (sequence_format == "PIR"):
                coot_utils.associate_pir_file(imol, chain_id, pir_file_name)
            else:
                coot.info_dialog("BL INFO:: wrong sequence input format.")
                return
        if do_alignment:
            alignment_mismatches_gui(imol)

    generic_chooser_entry_and_file_selector(
        "Associate Sequence with Chain: ",
        coot_utils.valid_model_molecule_qm,
        "Chain ID",
        "",
        "Select " + sequence_format + " file",
        lambda imol, chain_id, pir_file_name:
        associate_func(imol, chain_id, pir_file_name),
        use_check_button=True,
        check_button_label="Assign sequence to all protein chains (ignoring the chain specified above)",
        alternative_callback_function=(lambda imol, chain_id, pir_file_name:
                                       associate_func(imol, chain_id, pir_file_name,
                                                      use_all_chains=True)))


# Make a box-of-buttons GUI for the various modifications that need
# to be made to match the model sequence to the assigned sequence(s).
#
# Call this when the associated sequence(s) have been read in already.
#
def alignment_mismatches_gui(imol):

   # Return CA if there is such an atom in the residue, else return
   # the first atom in the residue.
   #
   def get_sensible_atom_name(res_info):
      chain_id = res_info[2]
      res_no   = res_info[3]
      ins_code = res_info[4]
      residue_atoms = coot.residue_info(imol, chain_id, res_no, ins_code)
      if not residue_atoms:
         return " CA "  # wont work of course
      else:
         for atoms in residue_atoms:
            if (atoms[0][0] == " CA "):
               return " CA "
         return residue_atoms[0][0][0]

   # main line
   am = coot.alignment_mismatches(imol)


   if am == []:
      coot.info_dialog("No sequence mismatches")
   else:
      if not am:
         coot.info_dialog("Sequence not associated - no alignment")
      else:
         #print "mutations", am[0]
         #print "deletions", am[1]
         #print "insertions", am[2]

         # a button is a list [button_label, button_action]
         def mutate_buttons():
            ret_buttons = []
            for res_info in am[0]:
               chain_id = res_info[2]
               res_no   = res_info[3]
               ins_code = res_info[4]
               button_1_label = "Mutate " + chain_id + \
                                " " + str(res_no) + \
                                " " + coot.residue_name(imol, chain_id, res_no, ins_code) + " to " + res_info[0]

               button_1_action = ["set_go_to_atom_molecule(" + str(imol) + ")",
                                  "set_go_to_atom_chain_residue_atom_name(\'" + \
                                  chain_id + "\', " + str(res_no) + ", " + \
                                  "\'" + get_sensible_atom_name(res_info) + "\')"]
               ret_buttons.append([button_1_label, button_1_action])
            return ret_buttons

         def delete_buttons():
            ret_buttons = []
            for res_info in am[1]:
               chain_id = res_info[2]
               res_no   = res_info[3]
               ins_code = res_info[4]
               button_1_label = "Delete " + chain_id + " " + str(res_no)
               button_1_action = ["set_go_to_atom_molecule(" + str(imol) + ")",
                                  "set_go_to_atom_chain_residue_atom_name(\'" + \
                                  chain_id + "\', " + \
                                  str(res_no) + ", " + \
                                  "\'" + get_sensible_atom_name(res_info) + "\')"]
               ret_buttons.append([button_1_label, button_1_action])
            return ret_buttons

         def insert_buttons():
            ret_buttons = []
            for res_info in am[2]:
               chain_id = res_info[2]
               res_no   = res_info[3]
               ins_code = res_info[4]
               button_1_label = "Insert " + chain_id + \
                                " " + str(res_no)
               #button_1_action = "info_dialog(" + button_1_label + ")"
               # oh dear, will that work? I dont think I can pass asignments
               # here. Need to rethink this! FIXME
               # messy but should work (without too much hazzle)
               button_1_action = ["info_dialog(\'" + button_1_label + "\')",
                                  "set_go_to_atom_chain_residue_atom_name(\'" + \
                                  chain_id + "\', " + \
                                  "nearest_residue_by_sequence(" + \
                                  str(imol) + ", \'" + \
                                  chain_id + "\', " + \
                                  str(res_no) + ", " + \
                                  "\'" + ins_code + "\')[2], " + \
                                  "\' CA \')"]
               ret_buttons.append([button_1_label, button_1_action])
            return ret_buttons

         buttons  = delete_buttons()
         buttons += mutate_buttons()
         buttons += insert_buttons()
         if (len(am) > 3):
            # we have alignment text for info box
            # protected for compatibiity reasons
            alignments_as_text_list = am[3]
            for alignment_text in alignments_as_text_list:
               coot.info_dialog_with_markup(alignment_text)

         dialog_box_of_buttons("Residue mismatches", [300, 300], buttons, "  Close  ")

# Wrapper in that we test if there have been sequence(s) assigned to
# imol before we look for the sequence mismatches
#


def wrapper_alignment_mismatches_gui(imol):

    seq_info = coot.sequence_info_py(imol)
    print("BL DEBUG:: sequence_info", seq_info)
    if seq_info:
        alignment_mismatches_gui(imol)
    else:
        associate_sequence_with_chain_gui(do_alignment=True)


# Multiple residue ranges gui
#
# Create a new top level window that contains a residue-range-vbox
# which contains a set of hboxes that contain (or allow the user to
# enter) a residue range (chain-id resno-start resno-end).
#
# The '+' and '-' buttons on the right allow the addition of extra
# residue ranges (and remove them of course).  The residue ranges are
# added to residue-range-widgets in a somewhat ugly manner.  Note
# also that fill-residue-range-widgets-previous-data generates
# residue range widgets and adds them to residue-range-widgets.
#
# The interesting function is make-residue-range-frame which returns
# the outside vbox (that contains the frame and + and - buttons, so
# it is not a great name for the function) and each of the entries -
# so that they can be decoded (gtk-entry-get-text) when the "Go"
# button is pressed.
#
# Using the variable saved-residue-ranges, the GUI can restore itself
# from previous (saved) residue ranges.
#
# (Notice that we are not dealing with insertion codes).
#
global saved_residue_ranges
saved_residue_ranges = []


def residue_range_gui(func, function_text, go_button_label):

    global saved_residue_ranges
    residue_range_widgets = []
    #

    def n_residue_range_vboxes(residue_range_widgets_vbox):
        ls = residue_range_widgets_vbox.get_children()
        length = len(ls)
        return length

    # Remove widget from residue-range-widgets (on '-' button
    # pressed)
    def remove_from_residue_range_widget(widget):
        for ls in residue_range_widgets:
            if (widget == ls[0]):
                rem = ls
                break
        residue_range_widgets.remove(rem)

    #
    def make_residue_range_frame(residue_range_vbox):

        def plus_button_cb(*args):
            # we need to add a new residue-range
            # outside-hbox into the residue-range-widgets-vbox
            rr_frame = make_residue_range_frame(residue_range_vbox)
            residue_range_vbox.append(rr_frame[0])
            rr_frame[0].show()
            residue_range_widgets.append(rr_frame)

        def minus_button_cb(*args):
            n = n_residue_range_vboxes(residue_range_vbox)
            if (n > 1):
                remove_from_residue_range_widget(outside_hbox)
                outside_hbox.destroy()

        frame = Gtk.Frame()
        outside_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        text_1 = Gtk.Label(label="  Chain-ID: ")
        text_2 = Gtk.Label(label="  Resno Start: ")
        text_3 = Gtk.Label(label="  Resno End: ")
        entry_1 = Gtk.Entry()
        entry_2 = Gtk.Entry()
        entry_3 = Gtk.Entry()
        plus_button = Gtk.Button(label="+")
        minus_button = Gtk.Button(label=" - ")

        hbox.append(text_1)
        hbox.append(entry_1)
        hbox.append(text_2)
        hbox.append(entry_2)
        hbox.append(text_3)
        hbox.append(entry_3)

        outside_hbox.append(frame)
        frame.set_child(hbox)
        outside_hbox.append(plus_button)
        outside_hbox.append(minus_button)

        plus_button.connect("clicked", plus_button_cb)

        minus_button.connect("clicked", minus_button_cb)

        list(map(lambda x: x.show(), [frame, outside_hbox, hbox, text_1, text_2, text_3,
                                      entry_1, entry_2, entry_3, plus_button, minus_button]))

        # return the thing that we need to pack and the entries we
        # need to read.
        return [outside_hbox, entry_1, entry_2, entry_3]

    #
    def make_residue_ranges():
        ls = list(map(make_residue_range, residue_range_widgets))
        return ls

    # Return a list ["A", 2, 3] or False on failure to decose entries
    #
    def make_residue_range(residue_range_widget):
        # print "make a residue range using", residue_range_widget
        entry_1 = residue_range_widget[1]
        entry_2 = residue_range_widget[2]
        entry_3 = residue_range_widget[3]
        chain_id = entry_1.get_text()
        res_no_1_txt = entry_2.get_text()
        res_no_2_txt = entry_3.get_text()
        try:
            res_no_1 = int(res_no_1_txt)
            res_no_2 = int(res_no_2_txt)
            return [chain_id, res_no_1, res_no_2]
        except:
            print("did not understand %s and %s as numbers - fail residue range" %
                  (res_no_1_txt, res_no_2_txt))
            return False

    #
    def save_ranges(residue_range_widgets):
        global saved_residue_ranges
        residue_ranges = []
        for residue_range_widget in residue_range_widgets:
            ls = make_residue_range(residue_range_widget)
            residue_ranges.append(ls)
        saved_residue_ranges = residue_ranges

    # range_info is list [chain_id, res_no_1, res_no_2]
    #
    def fill_with_previous_range(range_info, vbox_info):
        print("fill_with_previous_range using", range_info)
        entry_1 =  vbox_info[1]
        entry_2  = vbox_info[2]
        entry_3  = vbox_info[3]
        chain_id = range_info[0]
        resno_1  = range_info[1]
        resno_2  = range_info[2]

        entry_1.set_text(chain_id)
        entry_2.set_text(str(resno_1))
        entry_3.set_text(str(resno_2))

    #
    def fill_residue_range_widgets_previous_data(previous_ranges,
                                                 first_vbox_info,
                                                 residue_range_vbox):
        print("first one", previous_ranges[0])
        if previous_ranges:
            if previous_ranges[0]:
                fill_with_previous_range(previous_ranges[0], first_vbox_info)
        if (len(previous_ranges) > 1):
            for rang in previous_ranges[1:]:
                if rang:
                    vbox_info = make_residue_range_frame(residue_range_vbox)
                    residue_range_vbox.pack_start(
                        vbox_info[0], False, False, 2)
                    print("next one", rang)
                    residue_range_widgets.append(vbox_info)
                    fill_with_previous_range(rang, vbox_info)

    # main line
    #
    def cancel_button_cb(*args):
        save_ranges(residue_range_widgets)
        window.destroy()
        return False

    def combobox_to_molecule_number(combobox):
        imol = -1
        tree_iter = combobox.get_active_iter()
        if tree_iter is not None:
            model = combobox.get_model()
            it = model[tree_iter]
            imol = it[0]
        return imol

    def go_button_cb(*args):

        save_ranges(residue_range_widgets)
        residue_ranges = make_residue_ranges()
        imol = combobox_to_molecule_number(combobox)
        try:
            func(imol, residue_ranges)
        except KeyError as e:
            print("ERROR:: something was amiss")
            print("ERROR::", e)
        window.destroy()
        return False

    window = Gtk.Window()
    window.set_title("Coot: Rigid Body Refine Residue Ranges")
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    residue_range_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    residue_range_widget_info = make_residue_range_frame(residue_range_vbox)
    hbox_buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    function_label = Gtk.Label(label=function_text)
    cancel_button = Gtk.Button(label="  Cancel  ")
    go_button = Gtk.Button(label=go_button_label)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    h_sep.set_margin_top(6)
    h_sep.set_margin_bottom(6)
    # the first residue range
    outside_vbox_residue_range = residue_range_widget_info[0]

    residue_range_widgets = [residue_range_widget_info]  # ?

    # buttons
    hbox_buttons.append(cancel_button)
    hbox_buttons.append(go_button)
    hbox_buttons.set_margin_start(8)
    hbox_buttons.set_margin_end(8)
    hbox_buttons.set_margin_top(6)
    hbox_buttons.set_margin_bottom(6)
    for w in cancel_button, go_button:
        w.set_margin_start(8)
        w.set_margin_end(8)
        w.set_margin_top(2)
        w.set_margin_bottom(2)

    # the vbox of residue ranges
    residue_range_vbox.append(outside_vbox_residue_range)

    # main vbox
    vbox.append(function_label)
    combobox = generic_molecule_chooser(vbox, "Molecule for Ranges:")
    combobox.set_margin_top(6)
    combobox.set_margin_bottom(6)
    combobox.set_margin_start(6)
    combobox.set_margin_end(6)
    vbox.append(residue_range_vbox)
    vbox.append(h_sep)
    vbox.append(hbox_buttons)

    if saved_residue_ranges:
        fill_residue_range_widgets_previous_data(saved_residue_ranges,
                                                 residue_range_widget_info,
                                                 residue_range_vbox)
    else:
        imol = combobox_to_molecule_number(combobox)
        ch_ids = coot_utils.chain_ids(imol)
        if ch_ids:
            ch_id_0 = ch_ids[0]
            rn_1 = coot.min_resno_in_chain(imol, ch_id_0)
            rn_2 = coot.max_resno_in_chain(imol, ch_id_0)
            range_info = [ch_id_0, rn_1, rn_2]
            fill_with_previous_range(range_info, residue_range_widget_info)

    window.set_child(vbox)
    # vbox.set_border_width(6)

    cancel_button.connect("clicked", cancel_button_cb)

    go_button.connect("clicked", go_button_cb)

    window.show()


global additional_solvent_ligands
additional_solvent_ligands = []

global random_jiggle_n_trials
random_jiggle_n_trials = 50


def solvent_ligand_list():
    global additional_solvent_ligands
    return (additional_solvent_ligands +
            ["EDO", "GOL", "DMS", "ACT", "MPD", "CIT", "SO4", "PO4", "TRS",
             "TAM", "PEG", "PG4", "PE8", "EBE", "BTB"])

# add solvent molecules
#
# Change the coot_utils.translation jiggle-factor to 1.0, so the ligand doesn't
# move so far and get sucked into protein density (this is just a
# temporary hack, it would be better to mask the enviroment of the
# ligand by the surrounding atoms of the molecule to which the ligand
# is added - that is much harder).
#


def solvent_ligands_gui():

    global random_jiggle_n_trials
    #

    def add_ligand_func(imol, tlc):
        print("Add a %s to molecule %s here" % (tlc, imol))
        imol_ligand = coot.get_monomer(tlc)
        if (coot_utils.valid_model_molecule_qm(imol_ligand)):
            # delete hydrogens from the ligand if the master molecule
            # does not have hydrogens.
            if coot_utils.valid_model_molecule_qm(imol):
                if not coot_utils.molecule_has_hydrogens(imol):
                    coot.delete_residue_hydrogens(imol_ligand, "A", 1, "", "")
            if (coot_utils.valid_map_molecule_qm(coot.imol_refinement_map())):

                coot.merge_molecules_py([imol_ligand], imol)

                # We no longer do this: because we now mask the map by the neighbours
                # of the jiggling ligand and for that we need to use molecule imol
                #
                # coot.fit_to_map_by_random_jiggle(imol_ligand, "A", 1, "",
                #                             random_jiggle_n_trials, 1.0)
                # coot_utils.with_auto_accept([refine_zone, imol_ligand, "A", 1, 1, ""])

                # we presume that the active residue is the jiggling residue!
                # (we'd like to know what imol_ligand: "A" 1 moves to on merging
                # but we don't)
                #
                active_atom = coot.active_residue_py()
                aa_chain_id = active_atom[1]
                aa_res_no   = active_atom[2]
                coot.fit_to_map_by_random_jiggle(imol, aa_chain_id, aa_res_no, "", random_jiggle_n_trials, 1.0)
                coot.close_molecule(imol_ligand)

                # if we use refine_residues, that will take note of residues
                # near this residue and make non-bonded contacts
                # (whereas refine_zone will not).
                #
                # coot_utils.with_auto_accept([refine_zone, imol, aa_chain_id, aa_res_no, 1, ""])
                coot_utils.with_auto_accept([coot.refine_residues_py, imol, [[aa_chain_id, aa_res_no, ""]]])


    # add a button for a 3-letter-code to the scrolled vbox that runs
    # add-ligand-func when clicked.
    #
    def add_solvent_button(comp_id, button_label, inside_vbox, combobox):

        def combobox_to_molecule_number(combobox):
            imol = -1
            tree_iter = combobox.get_active_iter()
            if tree_iter is not None:
                model = combobox.get_model()
                it = model[tree_iter]
                imol = it[0]
            return imol

        def button_cb(*args):
            imol = combobox_to_molecule_number(combobox)
            add_ligand_func(imol, comp_id)

        button = Gtk.Button(label=button_label)
        button.set_margin_start(6)
        button.set_margin_end(6)
        # inside_vbox.append(button)
        inside_vbox.append(button)
        button.show()
        button.connect("clicked", button_cb)

    def delete_event(*args):
        window.destroy()
        return False

    def add_new_button_cb(*args):
        global additional_solvent_ligands

        def add_button_func(txt):
            additional_solvent_ligands.append(txt)
            add_solvent_button(txt, comp_id_to_button_label(txt), inside_vbox, combobox)

        generic_single_entry("Add new 3-letter-code/comp-id", "", "  Add  ",
                             lambda txt: add_button_func(txt))

    def comp_id_to_button_label(comp_id):
        coot.auto_load_dictionary(comp_id)
        comp_id_name = coot.comp_id_to_name_py(comp_id)
        label = (comp_id + ": " + comp_id_name) if comp_id_name else comp_id
        return label

    # main
    window = Gtk.Window()
    scrolled_win = Gtk.ScrolledWindow()
    outside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    inside_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    label = Gtk.Label(label="\nSolvent molecules added to molecule: ")
    frame_for_combobox = Gtk.Frame()
    vbox_for_combobox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    # molecule_option_menu = Gtk.combo_box_new_text()

    combobox_items = make_store_for_model_molecule_combobox()
    combobox = Gtk.ComboBox.new_with_model(combobox_items)
    renderer_text = Gtk.CellRendererText()
    if len(combobox_items) > 0:
        combobox.set_active(0)
    combobox.set_entry_text_column(1) # Sets the model column which combo_box
                                      # should use to get strings from to be text_column
    combobox.pack_start(renderer_text, True)
    combobox.add_attribute(renderer_text, "text", 1)

    add_new_button = Gtk.Button(label="  Add a new Residue Type...")
    add_new_button.set_margin_start(6)
    add_new_button.set_margin_end(6)
    add_new_button.set_margin_top(6)
    add_new_button.set_margin_bottom(6)
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    close_button = Gtk.Button(label="  Close  ")
    close_button.set_margin_start(6)
    close_button.set_margin_end(6)
    close_button.set_margin_top(6)
    close_button.set_margin_bottom(6)

    window.set_default_size(250, 500)
    window.set_title("Solvent Ligands")
    # window.set_border_width(8)
    window.set_child(outside_vbox)
    # outside_vbox.append(label)
    outside_vbox.append(label)
    frame_for_combobox.set_child(vbox_for_combobox)
    # vbox_for_combobox.pack_start(combobox, False, False, 8)
    vbox_for_combobox.append(combobox)
    # frame_for_combobox.set_border_width(6)
    # outside_vbox.append(frame_for_option_menu)
    #  outside_vbox.append(scrolled_win)
    outside_vbox.set_spacing(4)
    outside_vbox.append(frame_for_combobox)
    outside_vbox.append(scrolled_win)
    # scrolled_win.add_with_viewport(inside_vbox)
    inside_vbox.set_spacing(4)
    scrolled_win.set_child(inside_vbox)
    scrolled_win.set_vexpand(True)
    # scrolled_win.set_policy(Gtk.POLICY_AUTOMATIC, Gtk.POLICY_ALWAYS)
    # outside_vbox.append(add_new_button)
    # outside_vbox.append(h_sep)
    # outside_vbox.append(close_button)
    outside_vbox.append(add_new_button)
    outside_vbox.append(h_sep)
    outside_vbox.append(close_button)

    for comp_id in solvent_ligand_list():
        button_label = comp_id_to_button_label(comp_id)
        add_solvent_button(comp_id, button_label, inside_vbox, combobox)

    add_new_button.connect("clicked", add_new_button_cb)
    close_button.connect("clicked", delete_event)

    # window.show_all()
    window.show()

def rigid_body_refine_residue_ranges_gui():
    residue_range_gui(lambda imol, ls: coot.rigid_body_refine_by_residue_ranges_py(imol, ls), "Rigid Body Refine", "  Fit  ")

# USER MODS gui
#
def user_mods_gui(imol, pdb_file_name):

    # no alt conf, no inscode
    def atom_spec_to_string(atom_spec):
        chain_id = atom_spec[1]
        res_no = atom_spec[2]
        ins_code = atom_spec[3]
        atom_name = atom_spec[4]
        alt_conf = atom_spec[5]
        return chain_id + str(res_no) + atom_name

    #
    def make_flip_buttons(flip_list):
        ret = []
        for flip in flip_list:
            atom_spec = flip[0]
            residue_type = flip[1]
            info_string = flip[2]
            set_string = flip[3]
            score = flip[4]
            chain_id = atom_spec[1]
            res_no = atom_spec[2]
            ins_code = atom_spec[3]
            atom_name = atom_spec[4]
            alt_conf = atom_spec[5]
            label = set_string + " " + \
                chain_id + " " + str(res_no) + \
                atom_name + " : " + \
                info_string + " " + \
                " score %2.2f" % score
            # func = [cmd2str(coot.set_go_to_atom_molecule, imol), coot_utils.cmd2str(coot.set_go_to_atom_chain_residue_atom_name, chain_id, res_no, atom_name)]
            func = "FIXME - Make me a function"
            ret.append([label, func])
        return ret

    #
    def make_no_adj_buttons(no_flip_list):
        ret = []
        for no_flip_item in no_flip_list:
            specs = no_flip_item[0]
            info_string = no_flip_item[1]
            label = "No Adjustment " + \
                    " ".join(map(atom_spec_to_string, specs)) + \
                    " " + info_string
            atom_spec = specs[0]
            chain_id = atom_spec[1]
            res_no = atom_spec[2]
            ins_code = atom_spec[3]
            atom_name = atom_spec[4]
            alt_conf = atom_spec[5]
            # func = [cmd2str(coot.set_go_to_atom_molecule, imol),
            #         coot_utils.cmd2str(set_go_to_atom_chain_residue_atom_name,
            #                            chain_id, res_no, atom_name)]
            func = "FIXME - make me a function"
            ret.append([label, func])
        return ret

    # Return a list of buttons that are (in this case, (only) clashes,
    # unknown/problems and flips.
    #
    def filter_buttons(flip_list):
        ret = []
        for flip in flip_list:
            atom_spec = flip[0]
            residue_type = flip[1]
            info_string = flip[2]
            set_string = flip[3]
            score = flip[4]
            if len(info_string) < 3:
                pass
            else:
                # keep-letter: K is for keep,
                # C is clash, X is "not sure"
                # F is flip.
                keep_letter = info_string[2:3]
                if keep_letter in "XFC":
                    ret.append(flip)
        return ret

    # filter flag is True or False
    def clear_and_add_back(vbox, flip_list, no_adj_list, filter_flag):
        # clear
        children = vbox.get_children()
        list(map(lambda c: c.destroy(), children))
        # add back
        if not filter_flag:
            buttons = make_no_adj_buttons(no_adj_list) + \
                make_flip_buttons(flip_list)
        else:
            # filter
            buttons = make_flip_buttons(filter_buttons(flip_list))
        list(map(lambda button_info: add_button_info_to_box_of_buttons_vbox(button_info, vbox),
                 buttons))

    # main line
    #
    # user mods will return a pair of lists.
    if coot_utils.using_gui():
        flips = coot.user_mods(pdb_file_name)
        flip_buttons = make_flip_buttons(flips[0])
        no_adj_buttons = make_no_adj_buttons(flips[1])
        all_buttons = no_adj_buttons + flip_buttons
        dialog_box_of_buttons_with_check_button(" Flips ", [300, 300], all_buttons, "  Close  ",
                                                "Clashes, Problems and Flips only",
                                                lambda check_button, vbox: clear_and_add_back(
                                                    vbox, flips[0], flips[1], True)
                                                if check_button.get_active() else
                                                clear_and_add_back(vbox, flips[0], flips[1], False),
                                                False)


def rename_residue_gui_simple():
    active_atom = coot.active_residue_py()
    if not active_atom:
        coot.info_dialog("INFO:: No Residue Here")
    else:
        print(active_atom)
        generic_single_entry("Rename this residue", "ALA", "Rename",
                             lambda text: coot_utils.using_active_atom(coot.set_residue_name,
                                                                       "aa_imol", "aa_chain_id", "aa_res_no", "aa_ins_code",
                                                                       text))
#                           lambda text: coot_utils.using_active_atom([[set_residue_name,
#                                                            ["aa_imol", "aa_chain_id", "aa_res_no", "aa_ins_code"],
#                                                            [text]]]))


def average_map_gui():

    # mav-widgets (mav is "map average") is something like a
    # (local-to-the-function) "static" - it can be refered to in the
    # call-backs.  Presumably, if you refactor this as a class, it can
    # be a class data item.
    #
    # BL syas:  ok, lets make a class, just for the sake of it
    class mav:
        def __init__(self):
            self.mav_widgets = []

        # On pressing the - button, delete the widget from the
        # mav-widgets store.  The widget is actually gtk-widget-deleted
        # elsewhere.
        #
        def remove_from_mav_widgets(self, widget):
            to_be_removed = False
            for item in self.mav_widgets:
                if (item[0] == widget):
                    to_be_removed = item
                    break
            if to_be_removed:
                self.mav_widgets.remove(to_be_removed)

        # Return a list of the hbox the optionmenu the model-mol-list
        # and the entry
        def add_average_molecule_widget(self, maps_vbox):

            def plus_button_cb(*args):
                mav_bits = self.add_average_molecule_widget(maps_vbox)
                mav_bits[0].show()
                self.mav_widgets.append(mav_bits)

            def minus_button_cb(*args):
                if len(self.mav_widgets) > 1:
                    self.remove_from_mav_widgets(hbox)
                    hbox.destroy()

            frame = Gtk.Frame()
            hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
            label = Gtk.Label(label="Weight:  ")
            entry = Gtk.Entry()
            combobox_items = make_store_for_molecule_combobox(coot.is_valid_map_molecule)
            combobox = Gtk.ComboBox.new_with_model(combobox_items)
            renderer_text = Gtk.CellRendererText()
            if len(combobox_items) > 0:
                combobox.set_active(0)
            combobox.set_entry_text_column(1) # Sets the model column which combo_box
                                              # should use to get strings from to be text_column
            combobox.pack_start(renderer_text, True)
            combobox.add_attribute(renderer_text, "text", 1)

            map_mol_list = coot_utils.map_molecule_list()
            plus_button = Gtk.Button(label="+")
            minus_button = Gtk.Button(label=" - ")
            hbox.append(combobox)
            hbox.append(label)
            hbox.append(entry)
            hbox.append(plus_button)
            hbox.append(minus_button)
            entry.set_size_request(40, -1)
            entry.set_text("1.0")

            plus_button.connect("clicked", plus_button_cb)

            # when the - button is clicked, delete the hbox and
            # everything in it.  Except if it was the only hbox/line,
            # and in that case, don't do anything.
            minus_button.connect("clicked", minus_button_cb)

            maps_vbox.append(hbox)
            # show everything we just created
            list(map(lambda x: x.show(), [frame, hbox, label, entry, combobox, plus_button, minus_button]))

            # print "saving map_mol_list", map_mol_list
            return [hbox, combobox, map_mol_list, entry]

        # main line
        #
        # create the usual outside vbox for everything, and the
        # inner-vbox which is for the map hboxes.
        #
        def main_line(self):

            def cancel_button_cb(*args):
                window.destroy()
                return False

            def ok_button_cb(*args):
                maps_to_average_list = []
                for mav_bits in self.mav_widgets:
                    combobox = mav_bits[1]
                    map_mol_list = mav_bits[2]
                    entry = mav_bits[3]
                    # map_selected = get_option_menu_active_molecule(option_menu, map_mol_list)

                    map_selected = -1
                    tree_iter = combobox.get_active_iter()
                    if tree_iter is not None:
                        model = combobox.get_model()
                        it = model[tree_iter]
                        map_selected = it[0]

                    text = entry.get_text()
                    weight = float(text)   # try?! FIXME
                    maps_to_average_list.append([map_selected, weight])
                print("maps to average", maps_to_average_list)
                coot.average_map_py(maps_to_average_list)
                window.destroy()
                return False

            window = Gtk.Window()
            outer_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
            inner_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
            title = Gtk.Label(label="Average Maps")
            h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
            buttons_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
            mav_widget = self.add_average_molecule_widget(inner_vbox)
            cancel_button = Gtk.Button(label="  Cancel  ")
            ok_button = Gtk.Button(label="  Average Maps  ")

            window.set_child(outer_vbox)
            outer_vbox.append(title)
            outer_vbox.append(inner_vbox)
            outer_vbox.append(h_sep)
            outer_vbox.append(buttons_hbox)
            buttons_hbox.pack_end(ok_button, False, False, 6)
            buttons_hbox.pack_end(cancel_button, False, False, 6)

            # reset mav-widget when we start a new dialog (otherwise, it
            # retains the old mav-widgets, which is confusing/wrong.
            #
            self.mav_widgets = [mav_widget]

            cancel_button.connect("clicked", cancel_button_cb)

            # On clicking "Average Maps", we get a list of maps to
            # average by looking at the widgets (the option menu and the
            # entry) for each mav-bits (i.e. each widget list that is
            # returned by add-average-molecule-widget).
            #
            ok_button.connect("clicked", ok_button_cb)
            window.show()

    gui = mav()
    gui.main_line()


# simple rename residue GUI
#
def rename_residue_gui():
    active_atom = coot.active_residue_py()
    if not active_atom:
        coot.info_dialog("No Residue Here")
    else:
        aa_imol     = active_atom[0]
        aa_chain_id = active_atom[1]
        aa_res_no   = active_atom[2]
        aa_ins_code = active_atom[3]
        label = "Rename Residue [in molecule " + str(aa_imol) + "]: " + \
                aa_chain_id + str(aa_res_no) + aa_ins_code + " to: "
        generic_single_entry(label, "ALA", "Rename Residue",
                             lambda text: coot.set_residue_name(aa_imol, aa_chain_id,
                                                           aa_res_no, aa_ins_code, text))


# molecule chooser
#
# coordination number chooser
#
# Max dist entry
#
# results vbox
#    containing buttons with atom-spec labels
#
# h-sep
#
#      close-button
#
def water_coordination_gui():

    def delete_event(*args):
        window.destroy()
        return False

    def apply_cb(*args):
        n = get_number()
        imol = get_molecule()
        d = get_distance()
        if d:
            print("now call update_water_results() with imol", imol, "coordination number", n, "imol", imol)
            update_water_results(imol, n, d)

    def key_press_event(widget, event):
        if (event.keyval == 65293):  # GDK_return
            n = get_number()
            imol = get_molecule()
            d = get_distance()
            if d:
                update_water_results(imol, n, d)

    def entry_activate_event(entry, user_data):
        n = get_number()
        imol = get_molecule()
        d = get_distance()
        if d:
            update_water_results(imol, n, d)

    def atom_spec_to_text(atom_spec):
        # remove the leading element (user_int, I think)
        # return " ".join(map(str, atom_spec))
        remains = atom_spec[1:]
        return " ".join(map(str, remains))

    def get_ele(imol, atom_spec):
        # print("debug:: get_ele() with imol", imol, " atom_spec", atom_spec)
        atoms = coot.residue_info_py(imol, atom_spec[1], atom_spec[2], atom_spec[3])
        # print("debug:: get_ele() with atoms", atoms)
        input_atom_name = atom_spec[4]
        try:
            for atom in atoms:
                if atom[0][0] == input_atom_name:
                    return atom[1][2]
        except KeyError as e:
            print(e)
        return False

    # add info about bumps (to non-H-bonding atoms or so).  given a
    # water info (a central atom spec and a list of its contacts).
    #
    def make_bump_text(imol, water_info):
        # print("debug:: in make_bump_text with imol", imol, "water_info", water_info)
        central_atom = water_info[0]
        contact_list = water_info[1]
        rv = ""
        for contact in contact_list:
            ele = get_ele(imol, contact)
            if (ele == " C"):
                rv = " Bump"
        return rv

    def is_a_metal_site_too_qm(atom_spec, metal_results):
        # print "   checking if %s is in %s... result: %s" %(atom_spec, metal_results, atom_spec in metal_results)
        return atom_spec in metal_results

    def make_store(number_list):
        name_store = Gtk.ListStore(int, str)
        for i in number_list:
            label_str = str(i)
            name_store.append([i, label_str])
        return name_store

    window = Gtk.Window()
    window.set_title("Coot: Highly-Coordinated Waters")
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    results_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    water_results_label = Gtk.Label(label="Other Coordinated Waters")
    metal_results_frame = Gtk.Frame()
    metal_results_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    metal_results_label = Gtk.Label(label="Potential Metals: ")
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    hint_text = "Molecule: "
    hbox_chooser = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    hbox_max_dist = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    hbox_number_chooser = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    number_text = Gtk.Label(label="Coordination Number: ")
    # molecule_chooser_option_menu_and_model_list = generic_molecule_chooser(hbox_chooser, hint_text)
    # molecule_chooser_option_menu = molecule_chooser_option_menu_and_model_list[0]

    combobox_molecule = Gtk.ComboBox()
    combobox_mol_items = make_store_for_model_molecule_combobox()
    combobox_molecule.set_model(combobox_mol_items)

    renderer_text = Gtk.CellRendererText()
    if len(combobox_mol_items) > 0:
        combobox_molecule.set_active(0)
    combobox_molecule.set_entry_text_column(1) # Sets the model column which combo_box
                                      # should use to get strings from to be text_column
    combobox_molecule.pack_start(renderer_text, True)
    combobox_molecule.add_attribute(renderer_text, "text", 1)
    combobox_molecule.set_margin_start(6)
    combobox_molecule.set_margin_end(6)
    combobox_molecule.set_margin_top(4)
    combobox_molecule.set_margin_bottom(4)

    print("debug:: water_coordination_gui(): combobox_mol_items:", combobox_mol_items)
    print("debug:: water_coordination_gui(): combobox_molecule:",  combobox_molecule)
    # print("debug:: water_coordination_gui(): something:", something)

    combobox_molecule.set_active(0)

    # model_list = molecule_chooser_option_menu_and_model_list[1]
    scrolled_win = Gtk.ScrolledWindow()
    metal_results_scrolled_win = Gtk.ScrolledWindow()

    # https://python-gtk-3-tutorial.readthedocs.io/en/latest/combobox.html

    # coordination number combobox
    combobox_coordination = Gtk.ComboBoxText.new()
    for i in range(3,10):
        combobox_coordination.append_text(str(i))

    combobox_coordination.set_active(2)
    combobox_coordination.set_margin_start(6)
    combobox_coordination.set_margin_end(6)
    combobox_coordination.set_margin_top(4)
    combobox_coordination.set_margin_bottom(4)

    dist_label = Gtk.Label(label="Max Dist: ")
    dist_entry = Gtk.Entry()
    close_button = Gtk.Button(label="  Close  ")
    apply_button = Gtk.Button(label="  Apply  ")
    hbox_buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    apply_button.set_margin_start(6)
    apply_button.set_margin_end(6)
    apply_button.set_margin_top(4)
    apply_button.set_margin_bottom(4)
    close_button.set_margin_start(6)
    close_button.set_margin_end(6)
    close_button.set_margin_top(4)
    close_button.set_margin_bottom(4)
    hbox_buttons.set_margin_start(6)
    hbox_buttons.set_margin_end(6)
    hbox_buttons.set_margin_top(4)
    hbox_buttons.set_margin_bottom(4)

    def get_molecule():
        tree_iter = combobox_molecule.get_active_iter()
        imol = -1
        if tree_iter is not None:
            model = combobox_molecule.get_model()
            it = model[tree_iter]
            imol = it[0]
        return imol

    def get_number():
        at = combobox_coordination.get_active_text()
        n = int(at)
        return n

    def get_distance():
        t = dist_entry.get_text()
        try:
            ret = float(t)
        except:
            ret = False
        return ret

    def clear_previous_results():
        for this_vbox in [results_vbox, metal_results_vbox]:
            child = this_vbox.get_first_child()
            while child is not None:
                next_child = child.get_next_sibling()
                this_vbox.remove(child)
                child = next_child


    def update_water_results(imol, n, d):
        results = coot.highly_coordinated_waters_py(imol, n, d)
        clear_previous_results()
        import time
        time.sleep(2)
        if results:
            coordination_results = results[1]
            metal_results = results[0]
            for water_info in coordination_results:
                # a water spec is a central-atom spec and a list
                # of its neighbours.
                atom_spec = water_info[0]
                t = atom_spec_to_text(atom_spec)
                bump_text = make_bump_text(imol, water_info)
                button = Gtk.Button(label=t + bump_text)
                if not is_a_metal_site_too_qm(atom_spec, metal_results):
                    results_vbox.append(button)
                    button.show()

                    def water_func(widget, imol, water_info):
                        water_spec = water_info[0]
                        chain_id = water_spec[1]
                        res_no = water_spec[2]
                        atom_name = water_spec[4]
                        coot.set_go_to_atom_molecule(imol)
                        coot.set_go_to_atom_chain_residue_atom_name(chain_id, res_no, atom_name)
                    button.connect("clicked", water_func, imol, water_info)

            # now handle metal results
            for metal_site in metal_results:
                metal_text = metal_site[1]
                t = atom_spec_to_text(metal_site[0])
                button_text = t + " Potential " + metal_text
                button = Gtk.Button(label=button_text)
                metal_results_vbox.append(button)
                button.show()

                def metal_func(widget, imol, metal_site):
                    metal_spec = metal_site[0]
                    chain_id = metal_spec[1]
                    res_no = metal_spec[2]
                    atom_name = metal_spec[4]
                    coot.set_go_to_atom_molecule(imol)
                    coot.set_go_to_atom_chain_residue_atom_name(
                        chain_id, res_no, atom_name)
                button.connect("clicked", metal_func, imol, metal_site)

    window.set_child(vbox)

    # fill_option_menu_with_number_options(number_menu, coot_utils.number_list, 5)

    # 20230520-PE old scrolled_win.add_with_viewport(results_vbox)
    scrolled_win.set_child(results_vbox)

    metal_results_scrolled_win.set_child(metal_results_frame)
    # metal_results_frame.add(metal_results_vbox)
    metal_results_frame.set_child(metal_results_vbox)
    # metal_results_scrolled_win.add_with_viewport(metal_results_vbox)

    vbox.append(combobox_molecule)

    hbox_max_dist.append(dist_label)
    hbox_max_dist.append(dist_entry)

    vbox.append(hbox_chooser)

    hbox_number_chooser.append(number_text)
    # hbox_number_chooser.append(number_menu)
    hbox_number_chooser.append(combobox_coordination)

    vbox.append(hbox_number_chooser)

    vbox.append(hbox_max_dist)

    # metal sites
    vbox.append(metal_results_label)
    vbox.append(metal_results_scrolled_win)

    # interesting water sites
    vbox.append(water_results_label)
    vbox.append(scrolled_win)
    vbox.append(h_sep)
    hbox_buttons.append(close_button)
    hbox_buttons.append(apply_button)
    vbox.append(hbox_buttons)

    # From the Nayal and Di Cera (1996) paper, it seems that 2.7
    # and at least 4 oxygens is a good test for Na+ or other
    # interesting things
    #
    dist_entry.set_text("2.7")
    dist_entry.set_width_chars(5)

    close_button.connect("clicked", delete_event)

    # dist_entry.connect("key_press_event", key_press_event)

    dist_entry.connect("activate", entry_activate_event)

    apply_button.connect("clicked", apply_cb)

    window.show()

# return a list, or False (e.g. if not in same chain and molecule)
#


def min_max_residues_from_atom_specs(specs):

    print(specs)

    min_res_no = False
    max_res_no = False
    chain_id = False

    for spec in specs:
        spec_model = spec[1]
        spec_chain = spec[2]
        res_no = spec[3]

        if isinstance(chain_id, str):
            if (chain_id != spec_chain):
                return False  # chain mismatch
        else:
            chain_id = spec_chain

        if not min_res_no:  # maybe check for number as well
            min_res_no = res_no
        else:
            if (res_no < min_res_no):
                min_res_no = res_no
        if not max_res_no:  # maybe check for number as well
            max_res_no = res_no
        else:
            if (res_no > max_res_no):
                max_res_no = res_no

    if (min_res_no and max_res_no and chain_id):
        return [min_res_no, max_res_no, chain_id]
    else:
        return False


# by default, rename loop residues to UNK.  If python True, then
# leave them as the residue names found in the database.
global db_loop_preserve_residue_names
db_loop_preserve_residue_names = False


# Note to self - using a python function to call a swigged function that calls a python function
# is completely painful (exceptions get lost (although not so much now that I've tried to fix that)).
# Never do this again - it was miserable trying to fix this.
#
def click_protein_db_loop_gui():

    print("DEBUG:: coot_utils:: click_protein_db_loop_gui() --- start ---")

    global db_loop_preserve_residue_names

    def pick_loop_func(n_clicks):

        print("DEBUG:: coot_utils:: click_protein_db_loop_gui() pick_loop_func() --- start ---")

        def atom_pick_func(*atom_specs):
            # residue_specs = list(map(coot_utils.atom_spec_to_residue_spec, atom_specs))
            for spec in atom_specs:
                print("debug: atom spec:", spec)
            residue_specs = [coot_utils.atom_spec_to_residue_spec(spec) for spec in atom_specs]
            imol = atom_specs[0][1]
            ch_id = atom_specs[0][2] # is that right?
            min_max_and_chain_id = min_max_residues_from_atom_specs(atom_specs)
            if not isinstance(min_max_and_chain_id, list):
                coot.info_dialog("Picked atoms not in same molecule and chain")
            else:
                loop_mols = coot.protein_db_loops_py(imol, residue_specs, coot.imol_refinement_map(),
                                                     10, db_loop_preserve_residue_names)
                imol_loop_orig = loop_mols[0][0]
                imol_loops_consolidated = loop_mols[0][1]
                loop_mols = loop_mols[1]
                min_resno = min_max_and_chain_id[0]
                max_resno = min_max_and_chain_id[1]
                ch_id = min_max_and_chain_id[2]

                def my_copy_function(imol, ch_id, loop_mol, min_resno, max_resno):
                    coot.copy_residue_range(imol, ch_id, loop_mol, ch_id, min_resno, max_resno)

                coot.set_mol_active(imol_loops_consolidated, 1)
                if coot_utils.valid_model_molecule_qm(imol_loop_orig):
                    if len(loop_mols) > 0:
                        # ninja python skills (thank you stackoverflow)
                        buttons = [["Insert " + str(j_mol) + " " + coot.molecule_name(j_mol), lambda button, j_mol=j_mol: my_copy_function(imol, ch_id, j_mol, min_resno, max_resno)]
                                   for j_mol in loop_mols]

                        loop_mols.append(imol_loops_consolidated)

                        def toggle_func(imol):
                            coot_utils.toggle_active_mol(imol)
                            coot_utils.toggle_display_mol(imol)

                        all_buttons = [["Original loop", lambda func: coot.copy_residue_range(imol, ch_id,
                                                                                              imol_loop_orig, ch_id,
                                                                                              min_resno, max_resno)],
                                       ["Toggle Display All Candidate Loops", lambda func: toggle_func(imol_loops_consolidated)]
                                      ] + buttons

                        dialog_box_of_buttons("Loop Candidates", [360, 200], all_buttons, " Close ",
                                               lambda: [(coot.set_mol_displayed(im, 0), coot.set_mol_active(im, 0)) for im in loop_mols])


        coot.user_defined_click_py(n_clicks, atom_pick_func)

    print("DEBUG:: coot_utils:: click_protein_db_loop_gui() --- calling generic_number_chooser() ---")
    # this is wrong! The 4th element has a label "6" (all are offset by 2)
    generic_number_chooser(list(range(2, 10)), 4,
                           "Number of residues for basis",
                           "Pick Atoms...",
                           lambda n_clicks: pick_loop_func(n_clicks))


def refmac_multi_sharpen_gui():

    def delete_event(*args):
        window.destroy()
        return False

    def sharpen_cb(widget, *args):

        # get max_band n_levels and map file name
        max_b = int(get_option_menu_active_item(combobox_b_factor, b_factor_list))
        n_levels = int(get_option_menu_active_item(combobox_n_levels, n_levels_list))
        active_item_imol = get_combobox_active_molecule(combo_box_map, coot_utils.map_molecule_list)


        # There is no function to get a map file name from a molecule
        # It is not stored. So we make/guess it...
        map_file_name = coot.molecule_name(active_item_imol)
        if (map_file_name.find(" ") > 0):
            # we have map coeffs - but then sharpen as here wont work anyway
            map_file_name = map_file_name[:map_file_name.find(" ")]
        map_file_name_stub = coot_utils.strip_path(
            coot_utils.file_name_sans_extension(map_file_name))
        refmac_output_mtz_file_name = "starting_map-" + map_file_name_stub + ".mtz"
        log_file_name = "refmac-multisharp-" + map_file_name_stub + ".log"
        if not os.path.isfile(map_file_name):
            coot.info_dialog("WARNING:: file not found %s" % map_file_name)
        else:
            if not coot_utils.directory_is_modifiable_qm(os.getcwd()):
                m = "ERROR:: Current directory " + os.getcwd() + " is not writable"
                coot.info_dialog(m)
                return
            print("active_item_imol", active_item_imol)
            step_size = max_b/n_levels
            numbers_string = ' '.join(str(i+1) for i in range(n_levels))
            blur_string = "SFCALC BLUR  " + numbers_string
            sharp_string = "SFCALC SHARP " + numbers_string

            cmd_line_args = ["MAPIN", map_file_name]
            data_lines = ["MODE SFCALC",
                          blur_string,
                          sharp_string,
                          "END"]
            this_dir = os.getcwd()
            if not coot_utils.directory_is_modifiable_qm(this_dir):
                coot.info_dialog("WARNING:: Current directory is not writable")
            else:
                refmac_execfile = coot_utils.find_exe(
                    "refmac5", "CBIN", "CCP4_BIN", "PATH")
                s = coot_utils.popen_command(refmac_execfile,
                                             cmd_line_args,
                                             data_lines,
                                             log_file_name,
                                             False)

                try:
                    if s != 0:
                        coot.info_dialog("WARNING:: refmac5 failed")
                    else:
                        # Happy path
                        print("BL DEBUG:: s", s)
                        if os.path.isfile("starting_map.mtz"):
                            os.rename("starting_map.mtz",
                                      refmac_output_mtz_file_name)
                            # offer a read-mtz dialog
                            coot.manage_column_selector(refmac_output_mtz_file_name)

                except:
                    print("BL DEBUG:: tried to rename starting-map.mtz but failed.")
                    pass
            delete_event(widget)

    window = Gtk.Window()
    # boxes
    vbox   = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,spacing=10)
    vbox.set_margin_start(10)
    vbox.set_margin_end(10)
    vbox.set_margin_top(10)
    vbox.set_margin_bottom(10)
    hbox_1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,spacing=5)
    hbox_2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,spacing=5)
    hbox_3 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,spacing=5)
    hbox_3.set_halign(Gtk.Align.END)
    hbox_3.set_homogeneous(True)
    # menus
    combo_box_map     = Gtk.ComboBoxText()
    combobox_b_factor = Gtk.ComboBoxText()
    combobox_n_levels = Gtk.ComboBoxText()

    # labels
    map_label    = Gtk.Label(label="Map ")
    sb_label     = Gtk.Label(label="Sharpen & Blur in ")
    levels_label = Gtk.Label(label=" levels up to ")
    A_label      = Gtk.Label(label=" A*A")
    # separate
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
    # buttons
    ok_button = Gtk.Button(label="OK")
    cancel_button = Gtk.Button(label=" Cancel ")
    n_levels_list = [1, 2, 3, 4, 5, 6]
    b_factor_list = [50, 100, 200, 400, 800, 2000]

    combobox_map_items = make_store_for_map_molecule_combobox()
    combobox_map = Gtk.ComboBox.new_with_model(combobox_map_items)
    renderer_text = Gtk.CellRendererText()
    if len(combobox_map_items) > 0:
        combobox_map.set_active(0)
    combobox_map.set_entry_text_column(1)
    combobox_map.pack_start(renderer_text, True)
    combobox_map.add_attribute(renderer_text, "text", 1)
    combobox_map.set_halign(Gtk.Align.END)
    combobox_map.set_hexpand(True)

    renderer_text = Gtk.CellRendererText()
    combobox_n_levels_items = Gtk.ListStore(int)
    for ii in n_levels_list:  combobox_n_levels_items.append([ii])
    combobox_n_levels = Gtk.ComboBox.new_with_model(combobox_n_levels_items)
    combobox_n_levels.set_active(0)
    combobox_n_levels.set_entry_text_column(0)
    combobox_n_levels.pack_start(renderer_text, True)
    combobox_n_levels.add_attribute(renderer_text, "text", 0)

    renderer_text = Gtk.CellRendererText()
    combobox_b_factor_items = Gtk.ListStore(int)
    for ii in b_factor_list:  combobox_b_factor_items.append([ii])
    combobox_b_factor = Gtk.ComboBox.new_with_model(combobox_b_factor_items)
    combobox_b_factor.set_active(0)
    combobox_b_factor.set_entry_text_column(0)
    combobox_b_factor.pack_start(renderer_text, True)
    combobox_b_factor.add_attribute(renderer_text, "text", 0)

    window.set_title("Coot: Use Refmac for Sharpening & Blurring")
    hbox_1.append(map_label)
    hbox_1.append(combobox_map)
    hbox_2.append(sb_label)
    hbox_2.append(combobox_n_levels)
    hbox_2.append(levels_label)
    hbox_2.append(combobox_b_factor)
    hbox_3.append(cancel_button)
    hbox_3.append(ok_button)

    vbox.append(hbox_1)
    vbox.append(hbox_2)
    vbox.append(h_sep)
    vbox.append(hbox_3)

    cancel_button.connect("clicked", delete_event)

    ok_button.connect("clicked", sharpen_cb, combobox_b_factor, b_factor_list,
                      combobox_n_levels, n_levels_list,
                      combobox_map, coot_utils.map_molecule_list)

    window.set_child(vbox)
    window.show()


def auto_assign_sequence_from_map():

    active_atom = coot.active_residue_py()
    # get these from the current fragment
    imol  = active_atom[0]
    ch_id = active_atom[1]
    res_no = active_atom[2]
    res_spec = [ch_id, res_no, ""]
    imol_map = coot.imol_refinement_map()
    fragment_residues = coot.linked_residues_py(res_spec, imol, 1.7)
    residue_number_list = [spec[2] for spec in fragment_residues] # bleugh. Should be spec[1]
    resno_start = min(residue_number_list)
    resno_end   = max(residue_number_list)
    new_sequence = coot.sequence_from_map(imol, ch_id, resno_start, resno_end, imol_map)
    coot.set_rotamer_search_mode(coot.ROTAMERSEARCHLOWRES)
    coot.mutate_residue_range(imol, ch_id, resno_start, resno_end, new_sequence)
    fitting.backrub_rotamers_for_chain(imol, ch_id)
    coot.refine_residues_py(imol, fragment_residues)  # 20230501-PE should this be refine_residues_py()?


# ;; Associate the contents of a PIR file with a molecule.  Select file from a GUI.
# ;;
# (define (associate-pir-with-molecule-gui do-alignment?)

#   (format #t "in associate-pir-with-molecule-gui~%")
#   (generic-chooser-entry-and-file-selector
#    "Associate PIR Sequence to Model: "
#    valid-model-molecule?
#    "Chain ID"
#    ""
#    "Select PIR Alignment file"
#    (lambda (imol chain-id file-name)
#      (associate-pir-file imol chain-id file-name)
#      (if do-alignment?
#         (alignment-mismatches-gui imol)))
#     *generic-chooser-entry-and-file-selector-file-entry-default-text*))


def associate_pir_wih_molecule_gui(do_alignment_flag):

    def lambda_fn(imol, ch_id, file_name):
        coot_utils.associate_pir_file(imol, ch_id, file_name)
        if do_alignment_flag:
            alignment_mismatches_gui(imol)

    generic_chooser_entry_and_file_selector("Associate PIR Sequence to Model",
                                            coot_utils.valid_model_molecule_qm, "Chain ID", "", " PIR Alignment File: ",
                                            lambda imol, ch_id, file_name: lambda_fn(imol, ch_id, file_name))


def attach_module_menu_button(module_name: str) -> Gio.Menu:
    """
    Creates a new MenuButton and attaches it to the main toolbar.

    To be used with extension modules.

    Returns the button's Gio.Menu
    """
    menu = Gio.Menu.new()
    popover = Gtk.PopoverMenu()
    popover.set_menu_model(menu)
    module_menu_button = Gtk.MenuButton(label=module_name)
    module_menu_button.set_popover(popover)

    coot_gui_api.main_toolbar().append(module_menu_button)
    return menu


def add_module_cryo_em():
    if coot_gui_api.main_menumodel():
        add_module_cryo_em_gui()


def add_module_ccp4():
    if coot_gui_api.main_menumodel():
        add_module_ccp4_gui()

def add_module_ligand():
    if coot_gui_api.main_menumodel():
        add_module_ligand_gui()

def add_module_pdbe():
   if coot_gui_api.main_menumodel():
      # where is this function defined now?
      add_module_pdbe_gui()

def add_module_cryo_em_gui():

    def solidify_maps(w):
        for imol in range(coot.graphics_n_molecules()):
            if coot.is_valid_map_molecule(imol):
                coot.set_draw_solid_density_surface(imol, 1)

    def unsolidify_maps(w):
        for imol in range(coot.graphics_n_molecules()):
            if coot.is_valid_map_molecule(imol):
                coot.set_draw_solid_density_surface(imol, 0)

    def add_mol_sym_mtrix():
         with coot.UsingActiveAtom(True) as [aa_imol, aa_chain_id, aa_res_no,
                                        aa_ins_code, aa_atom_name,
                                        aa_alt_conf, aa_res_spec]:
            coot.add_molecular_symmetry_from_mtrix_from_self_file(aa_imol)
            coot.set_show_symmetry_master(1)

    def go_to_box_middle():
        m_list = coot_utils.map_molecule_list()
        if len(m_list) > 0:
            m = m_list[-1]
            c = coot.cell(m)
            coot.set_rotation_centre(0.5 * c[0], 0.5 * c[1], 0.5 * c[2])

    def flip_hand_local_func():
        map_molecule_chooser_gui("Coot Flip Select Map", lambda imol: coot.flip_hand(imol))

    def make_masked_maps_using_active_atom():
        active_atom = coot.active_residue_py()
        print("active_atom:", active_atom)
        if active_atom:
            imol = active_atom[0]
            coot.make_masked_maps_split_by_chain(imol, coot.imol_refinement_map())

    def make_partitioned_maps():
        coot.show_map_partition_by_chain_dialog()
        # C++ takes control

    def go_to_box_middle():
        m_list = coot_utils.map_molecule_list()
        if len(m_list) > 0:
            m = m_list[-1]
            c = rf.cell(m)
            coot.set_rotation_centre(0.5 * c[0], 0.5 * c[1], 0.5 * c[2])

    if coot_gui_api.main_menumodel():

        def ass_seq_assoc_seq():
            coot.assign_sequence_to_active_fragment()

        def interactive_nudge_func():
            with coot_utils.UsingActiveAtom(True) as [aa_imol, aa_chain_id, aa_res_no,
                                                      aa_ins_code, aa_atom_name,
                                                      aa_alt_conf, aa_res_spec]:
                interactive_nudge_residues.nudge_residues_gui(aa_imol, aa_res_spec)

        def jiggle_fit_chain_simple_wrapper(_simple_action, _arg2):
            active_atom = coot.active_residue_py()
            if active_atom:
                imol  = active_atom[0]
                ch_id = active_atom[1]
                n_trials = 20000
                coot.fit_chain_to_map_by_random_jiggle(imol, ch_id, n_trials, 5)

        def jiggle_fit_molecule_simple_wrapper(_simple_action, _arg2):
            active_atom = coot.active_residue_py()
            if active_atom:
                imol  = active_atom[0]
                n_trials = 20000
                coot.fit_molecule_to_map_by_random_jiggle(imol, n_trials, 2)

        def jiggle_fit_chain_with_fourier_filtering_wrapper(_simple_action, _arg2):
            active_atom = coot.active_residue_py()
            if active_atom:
                imol  = active_atom[0]
                ch_id = active_atom[1]
                n_trials = 5000
                coot.fit_chain_to_map_by_random_jiggle_and_blur(imol, ch_id, n_trials, 3.2, 320)

        def jiggle_fit_molecule_with_fourier_filtering_wrapper(_simple_action, _arg2):
            active_atom = coot.active_residue_py()
            if active_atom:
                imol  = active_atom[0]
                n_trials = 5000
                coot.fit_molecule_to_map_by_random_jiggle_and_blur(imol, n_trials, 3.2, 320)

        def sharpen_blur_map_gui_wrapper(_simple_action, _arg2):
            coot_sharpen_blur.sharpen_blur_map_gui()

        def multi_sharpen_map_gui_wrapper(_simple_action, _arg2):
            refmac_multi_sharpen_gui()

        def mask_map_by_chains_wrapper(_simple_action, _arg2):
            make_masked_maps_using_active_atom()

        def partition_map_by_chains_wrapper(_simple_action, _arg2):
            make_partitioned_maps()

        def go_to_map_molecule_centre_wrapper(_simple_action, _arg2):
            imol_map = coot.imol_refinement_map()
            coot.go_to_map_molecule_centre(imol_map)

        def add_mol_sym_mtrix_wrapper(_simple_action, _arg2):
            # the internals of add_mol_sym_mtrix() can go here - we don't need this
            # extra function call.
            add_mol_sym_mtrix()

        def go_to_map_box_middle_wrapper(_simple_action, _arg2):
            go_to_box_middle()

        def flip_map_hand_wrapper(_simple_action, _arg2):
            flip_hand_local_func()

        def align_and_mutate_using_clustalw2_wrapper(_simple_action, _arg2):
            generic_chooser_entry_and_file_selector(
                "Align Sequence to Model: ",
                coot_utils.valid_model_molecule_qm,
                "Chain ID",
                "",
                "Select PIR Alignment file",
                lambda imol, chain_id, target_sequence_pif_file:
                coot.run_clustalw_alignment(imol, chain_id, target_sequence_pif_file))

        menu = attach_module_menu_button("Cryo-EM")

        def add_action(displayed_name,action_name,on_activate_callback):
            add_simple_action_to_menu(menu,displayed_name,action_name,on_activate_callback)

        add_action("Sharpen/Blur/Resample...",  "sharpen_blur_map_gui", sharpen_blur_map_gui_wrapper)
        add_action("Multi-sharpen",             "multi_sharpen_map_gui", multi_sharpen_map_gui_wrapper)
        add_action("Mask Map by Chains",        "mask_map_by_chains", mask_map_by_chains_wrapper)
        add_action("Partition Map by Chains",   "partition_map_by_chains", partition_map_by_chains_wrapper)
        add_action("Go To Map Molecule Middle", "go_to_map_molecule_centre", go_to_map_molecule_centre_wrapper)
        add_action("Map Box Middle",            "go_to_map_box_middle", go_to_map_box_middle_wrapper)
        add_action("Flip Map Hand",             "flip_map_hand", flip_map_hand_wrapper)

        # where does this one belong?

        # 20231029-PE remove this for now - restore later
        # add_action("Interactive Nudge Residues...",
        #     "interactive_nudge",
        #    lambda _simple_action, _arg2: interactive_nudge_func())

        add_action("Jiggle-fit This Chain - Simple", "jiggle_fit_chain_simple",
                   jiggle_fit_chain_simple_wrapper)

        add_action("Jiggle-fit This Molecule - Simple ", "jiggle_fit_molecule_simple",
                   jiggle_fit_molecule_simple_wrapper)

        add_action("Jiggle-fit This Chain with Fourier Filtering", "jiggle_fit_chain_with_fourier_filtering",
                   jiggle_fit_chain_with_fourier_filtering_wrapper)

        add_action("Jiggle-fit This Molecule with Fourier Filtering", "jiggle_fit_molecule_with_fourier_filtering",
                   jiggle_fit_molecule_with_fourier_filtering_wrapper)
        # belongs in Modelling

        add_action("Add molecular symmetry using MTRIX",
            "add_mol_sym_mtrix",
            add_mol_sym_mtrix_wrapper)
        add_action("Align and Mutate using ClustalW2",
            "align_and_mutate_using_clustalw2",
            align_and_mutate_using_clustalw2_wrapper)
        add_action("Assign Sequence Based on Associated Sequence",
            "ass_seq_assoc_seq",
            lambda _simple_action, _arg2: ass_seq_assoc_seq())
        add_action("Auto-assign Sequence Based on Map",
            "auto_assign_sequence_from_map",
            lambda _simple_action, _arg2: auto_assign_sequence_from_map())

        # belongs in Preferences

        add_action("No Auto-Recontour Map Mode",
            "set_no_auto_recontour_map",
            lambda _simple_action, _arg2: coot.set_auto_recontour_map(0))
        add_action("Enable Auto-Recontour Map Mode",
            "set_auto_recontour_map",
            lambda _simple_action, _arg2: coot.set_auto_recontour_map(1))
        add_action("Solidify Maps",
                   "solidify_maps",
                   lambda _simple_action, _arg2: solidify_maps("all"))


def add_module_ccp4_gui():
    if coot_gui_api.main_menumodel():
        menu = attach_module_menu_button("CCP4")

        add_simple_action_to_menu(menu,"Make LINK via Acedrg","make_link_acedrg",lambda _one, _two: coot_acedrg_link.acedrg_link_generation_control_window())

def show_chem_func():
    with coot_utils.UsingActiveAtom() as [aa_imol, aa_chain_id, aa_res_no, aa_ins_code, aa_atom_name, aa_alt_conf]:
        coot.show_feats(aa_imol, aa_chain_id, aa_res_no, aa_ins_code)

# for quick-ligand-validate:
import coot_ligand_check

def add_module_ligand_gui():

    def jiggle_fit_active_residue():
        with coot_utils.UsingActiveAtom() as [aa_imol, aa_chain_id, aa_res_no,
                                              aa_ins_code, aa_atom_name, aa_alt_conf]:
            coot.fit_to_map_by_random_jiggle(aa_imol, aa_chain_id, aa_res_no, aa_ins_code, 100, 1.0)
    # from contact_score_isolated_ligand.py (hmm)
    def coot_contact_dots_ligand_func():
        with coot_utils.UsingActiveAtom() as [aa_imol, aa_chain_id, aa_res_no,
                               aa_ins_code, aa_atom_name, aa_alt_conf]:
            coot.coot_contact_dots_for_ligand_py(aa_imol, [aa_chain_id, aa_res_no, aa_ins_code])

    # from enhanced_ligand.py (hmm)
    def display_ligand_distortions_func():
         with coot_utils.UsingActiveAtom() as [aa_imol, aa_chain_id, aa_res_no,
                                    aa_ins_code, aa_atom_name, aa_alt_conf]:
             coot.display_residue_distortions(aa_imol, aa_chain_id, aa_res_no, aa_ins_code)

    # from enhanced_ligand.py
    def probe_ligand_func():
        global probe_command
        with coot_utils.UsingActiveAtom() as [aa_imol, aa_chain_id, aa_res_no,
                            aa_ins_code, aa_atom_name, aa_alt_conf]:
            ss = "//" + aa_chain_id + "/" + str(aa_res_no)
            imol_selection = coot.new_molecule_by_atom_selection(aa_imol, ss)
            work_dir = coot_utils.get_directory("coot-molprobity")
            tmp_selected_ligand_for_probe_pdb = os.path.join(work_dir, "tmp-selected-ligand-for-probe.pdb")
            tmp_protein_for_probe_pdb         = os.path.join(work_dir, "tmp-protein-for-probe.pdb")
            probe_dots_file_name              = os.path.join(work_dir, "probe.dots")

            coot.set_mol_displayed(imol_selection, 0)
            coot.set_mol_active(imol_selection, 0)
            # BL comment: we assume H and view is correct.
            #set_go_to_atom_molecule(imol)
            #rc = residue_centre(imol, chain_id, res_no, ins_code)
            #set_rotation_centre(*rc)
            #hydrogenate_region(6)
            coot.write_pdb_file(imol_selection, tmp_selected_ligand_for_probe_pdb)
            coot.write_pdb_file(aa_imol, tmp_protein_for_probe_pdb)
            coot_utils.popen_command(probe_command, ["-u", "-once", str(aa_res_no), # -once or -both
                                             "not " + str(aa_res_no),
                                             "-density40",
                                             tmp_selected_ligand_for_probe_pdb,
                                             tmp_protein_for_probe_pdb],
                                             [], probe_dots_file_name, False)
            coot.handle_read_draw_probe_dots_unformatted(probe_dots_file_name, aa_imol, 0)
            coot.graphics_draw()

    def make_link_ext_func(*args):
        # not used yet - see comment below
        m_spec_1 = args[0]
        m_spec_2 = args[1]
        imol_1 = coot_utils.atom_spec_to_imol(m_spec_1)
        imol_2 = coot_utils.atom_spec_to_imol(m_spec_2)
        spec_1 = m_spec_1[2:]
        spec_2 = m_spec_2[2:]
        if not (imol_1 == imol_2):
            print("Mismatch molecules")
        else:
            coot.make_link_py(imol_1, spec_1, spec_2, "dummy", 0.1)

    if coot_gui_api.main_menumodel():
        menu = attach_module_menu_button("Ligand")
        add_simple_action_to_menu(menu, "Find Ligands", "find_ligands", lambda _one, _two: coot.do_find_ligands_dialog())
        add_simple_action_to_menu(menu, "Jiggle-fit Ligands", "jiggle_fit_ligands", lambda _one, _two: jiggle_fit_active_residue())
        add_simple_action_to_menu(menu, "Hydrogenate Region", "hydrogenate_region", lambda _one, _two: coot.hydrogenate_region(6))
        add_simple_action_to_menu(menu, "Contact Dots for Ligand", "contact_dots_for_ligand", lambda _one, _two: coot_contact_dots_ligand_func())
        add_simple_action_to_menu(menu, "SMILES -> Simple 3D", "smiles_to_simple_3d", lambda _one, _two: coot.do_smiles_to_simple_3d_overlay_frame())
        add_simple_action_to_menu(menu, "Show Chemical Features", "show_chemical_features", lambda _one, _two: show_chem_func())
        add_simple_action_to_menu(menu, "Display Ligand Distortions", "display_ligand_distortions", lambda _one, _two: display_ligand_distortions_func())
        add_simple_action_to_menu(menu, "Quick Ligand Validate", "quick_ligand_validate", lambda _one, _two: coot_ligand_check.gui_ligand_check_dialog_active_residue())
        add_simple_action_to_menu(menu, "Isolated Molprobity Dots for ligand", "isolated_molprobity_dots_for_ligand", lambda _one, _two: probe_ligand_func())
        # 20230915-PE this is commented out for now because although user_defined_click_py() runs as before, the no longer a check for
        # in_user_defined_define reaching zero and then running the specified function. There should be of course.
        # add_simple_action_to_menu(menu, "Add Link to Header...", "make_link_trivia", lambda _one, _two: coot.user_defined_click_py(2, make_link_ext_func))

def add_module_pdbe_gui():
   if coot_gui_api.main_menumodel():
      menu = coot_menubar_menu("PDBe")

      # ---------------------------------------------------------------------
      #     Recent structures from the PDBe
      # ---------------------------------------------------------------------
      #
      #   add_simple_coot_menu_menuitem(
      #      menu, "PDBe recent structures...",
      #      lambda func: get_recent_pdbe.pdbe_latest_releases_gui())

      # we do test for refmac at startup not runtime (for simplicity)
      if coot_utils.command_in_path_qm("refmac5"):
         mess = " Get it "
      else:
         mess = "\n  WARNING::refmac5 not in the path - SF calculation will fail  \n\n"

      #   add_simple_coot_menu_menuitem(
      #      menu, "Get from PDBe...",
      #      lambda func: generic_single_entry("Get PDBe accession code",
      #                                        "", " Get it ",
      #                                        lambda text:
      #                                        get_recent_pdbe.pdbe_get_pdb_and_sfs_cif("include-sfs", text.rstrip().lstrip())))



def add_module_refine():

    if coot_gui_api.main_menumodel():

        # menu = attach_module_menu_button("Refine")

        # add_simple_action_to_menu(menu, "Intermediate Atom Contact Dots On","contact_dots_on",   lambda _simple_action, _arg2: coot.set_do_coot_probe_dots_during_refine(1))
        # add_simple_action_to_menu(menu, "Intermediate Atom Contact Dots Off","contact_dots_off", lambda _simple_action, _arg2: coot.set_do_coot_probe_dots_during_refine(0))

        # # they get turned on but are not active - they currently need to be turn off by the user using the Generic Display dialog
        # add_simple_action_to_menu(menu, "Intermediate Atom Restraints On","intermediate_atom_restraints_on",   lambda _simple_action, _arg2: coot.set_draw_moving_atoms_restraints(1))
        # add_simple_action_to_menu(menu, "Intermediate Atom Restraints Off","intermediate_atom_restraints_off", lambda _simple_action, _arg2: coot.set_draw_moving_atoms_restraints(0))

        # add_simple_action_to_menu(menu, "Rama Goodness Dodecs On","rama_goodness_dodecs_on",  lambda _simple_action, _arg2: coot.set_show_intermediate_atoms_rota_markup(1))
        # add_simple_action_to_menu(menu, "Rama Goodness Dodecs Off","rama_goodness_dodecs_off", lambda _simple_action, _arg2: coot.set_show_intermediate_atoms_rota_markup(0))

        def switch_rama_switched(switch, thing_b, thing_c):
            print("thing_b", thing_b)
            print("thing_c", thing_c)
            if switch.get_active():
                coot.set_draw_moving_atoms_rama_markup(1)
            else:
                coot.set_draw_moving_atoms_rama_markup(0)

        def switch_rota_switched(switch, thing_b, thing_c):
            print("thing_b", thing_b)
            print("thing_c", thing_c)
            if switch.get_active():
                coot.set_draw_moving_atoms_rota_markup(1)
            else:
                coot.set_draw_moving_atoms_rota_markup(0)

        def switch_contact_dots_switched(switch, thing_b, thing_c):
            print("thing_b", thing_b)
            print("thing_c", thing_c)
            if switch.get_active():
                coot.set_do_coot_probe_dots_during_refine(1)
            else:
                coot.set_do_coot_probe_dots_during_refine(0)

        def switch_GM_restraints_switched(switch, thing_b, thing_c):
            print("thing_b", thing_b)
            print("thing_c", thing_c)
            if switch.get_active():
                coot.set_draw_moving_atoms_restraints(1)
            else:
                coot.set_draw_moving_atoms_restraints(0)

        popover = Gtk.PopoverMenu()
        scrolled_win = Gtk.ScrolledWindow()

        menu_button = Gtk.MenuButton(label="Refine")
        menu_button.set_popover(popover)
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        scrolled_win.set_child(box)

        switch_1_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        switch_2_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        switch_3_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        switch_4_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        switch_contact_dots  = Gtk.Switch()
        switch_GM_restraints = Gtk.Switch()
        switch_rama          = Gtk.Switch()
        switch_rota          = Gtk.Switch()
        switch_contact_dots.connect( "state_set", switch_contact_dots_switched, 1)
        switch_GM_restraints.connect("state_set", switch_GM_restraints_switched, 2)
        switch_rama.connect("state_set", switch_rama_switched, 3)
        switch_rota.connect("state_set", switch_rota_switched, 4)
        switch_contact_dots_label  = Gtk.Label(label="Intermediate Atom Contact Dots")
        switch_GM_restraints_label = Gtk.Label(label="Intermediate Atom GM Restraints")
        switch_rama_label          = Gtk.Label(label="Ramachandran Probability Spheres")
        switch_rota_label          = Gtk.Label(label="Rotamer Probability Dodecahedra")
        switch_contact_dots_label.set_xalign(0)
        switch_GM_restraints_label.set_xalign(0)
        switch_rama_label.set_xalign(0)
        switch_rota_label.set_xalign(0)

        if coot.get_draw_moving_atoms_rama_markup_state() == 1: switch_rama.set_active(True)
        if coot.get_draw_moving_atoms_rama_markup_state() == 1: switch_rota.set_active(True)
        if coot.get_do_coot_probe_dots_during_refine() == 1:    switch_contact_dots.set_active(True)
        if coot.get_draw_moving_atoms_restraints() == 1:        switch_GM_restraints.set_active(True)

        grid = Gtk.Grid()
        grid.set_column_spacing(8)
        grid.set_row_spacing(8)
        grid.attach(switch_rama_label,          0, 0, 1, 1)
        grid.attach(switch_rota_label,          0, 1, 1, 1)
        grid.attach(switch_contact_dots_label,  0, 2, 1, 1)
        grid.attach(switch_GM_restraints_label, 0, 3, 1, 1)
        grid.attach(switch_rama,                1, 0, 1, 1)
        grid.attach(switch_rota,                1, 1, 1, 1)
        grid.attach(switch_contact_dots,        1, 2, 1, 1)
        grid.attach(switch_GM_restraints,       1, 3, 1, 1)

        box.append(grid)
        box.set_margin_top(6)
        box.set_margin_start(6)
        popover.set_size_request(300, 160)

        popover.set_child(scrolled_win) # the child of popover is always a scrolled window

        coot_gui_api.main_toolbar().append(menu_button)

def scale_alt_conf_occ_gui(imol, chain_id, res_no, ins_code):

    alt_confs = coot_utils.residue_alt_confs(imol, chain_id, res_no, ins_code)
    try:
        # remove no alt conf, i.e. '', from list if present
        alt_confs.remove('')
    except:
        pass

    if (len(alt_confs) != 2):
        print("INFO:: no (or too many) alt confs, no gui!")
    else:
        # only do if 2 alt confs (plus no)
        res_info = coot.residue_info_py(imol, chain_id, res_no, ins_code)
        alt_conf = alt_confs[0]

        def get_occ_for_alt_conf(atom_ls, alt_conf):
            # should check that they are consistent!!
            for i in range(len(atom_ls)):
                alt_conf_str = atom_ls[i][0][1]
                if (alt_conf_str == alt_conf):
                    occ = atom_ls[i][1][0]
                    return occ

        occ_start = get_occ_for_alt_conf(res_info, alt_conf)

        def delete_event(*args):
            window.destroy()
            return False

        def go_function_event(widget, occ_adjust,
                              imol, chain_id, res_no, ins_code,
                              alt_confs):
            new_occ = occ_adjust.value
            print("BL INFO:: setting new occupancy ", new_occ)
            alt_conf_list = [[alt_confs[0], new_occ],
                             [alt_confs[1], 1 - new_occ]]
            coot_utils.set_alt_conf_occ(
                imol, chain_id, res_no, ins_code, alt_conf_list)
            delete_event()

        def change_occ(*args):
            # needed?!
            # print "change occ slider?!"
            pass

        window = Gtk.Window()
        title = Gtk.Label(label="Adjust alt conf occupancies")
        occ_label = Gtk.Label(label="Occupancy")
        alt_conf_label = Gtk.Label(label="Alt Conf: " + alt_conf)
        occ_adj = Gtk.Adjustment(occ_start, 0.1, 0.99, 0.01, 0.1, 0.1)
        occ_scale = Gtk.HScale(occ_adj)
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        scale_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        scale_hbox.append(alt_conf_label)
        scale_hbox.append(occ_scale)
        vbox.append(occ_label)
        vbox.append(scale_hbox)

        occ_adj.connect("value_changed", change_occ)

        window.set_child(vbox)

        h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
        buttons_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        ok_button = Gtk.Button(label="   OK   ")
        cancel_button = Gtk.Button(label=" Cancel ")

        buttons_hbox.append(ok_button)
        buttons_hbox.append(cancel_button)

        vbox.append(h_sep)
        vbox.append(buttons_hbox)

        ok_button.connect("clicked", go_function_event, occ_adj,
                          imol, chain_id, res_no, ins_code, alt_confs)

        cancel_button.connect("clicked", delete_event)

        window.show()


def select_atom_alt_conf_occ_gui():

    def helper_function(*args):
        imol = args[0][1]
        chain_id = args[0][2]
        res_no = args[0][3]
        ins_code = args[0][4]
        scale_alt_conf_occ_gui(imol, chain_id, res_no, ins_code)
    coot.user_defined_click_py(1, helper_function)


def toggle_backrub_rotamers(widget=None):
    """Toggle function to swtich on and off backrub rotamer fitting.

    Keyword arguments:
    widget -- can be passed from the toolbutton

    """

    if widget:
        if widget.get_active():
            # the button is toggled on
            coot.set_rotamer_search_mode(coot.ROTAMERSEARCHLOWRES)
            print("INFO:: Using Backrub rotamers now")
        else:
            coot.set_rotamer_search_mode(coot.ROTAMERSEARCHHIGHRES)
            print("INFO:: No longer using Backrub rotamers")

    else:
        # non graphical - but wont be able to run if this is not loaded.
        mode = coot.rotamer_search_mode_state()
        if (mode == coot.ROTAMERSEARCHLOWRES):
            coot.set_rotamer_search_mode(coot.ROTAMERSEARCHHIGHRES)
            print("INFO:: No longer using Backrub rotamers")
        if (mode == coot.ROTAMERSEARCHHIGHRES or
                mode == coot.ROTAMERSEARCHAUTOMATIC):
            coot.set_rotamer_search_mode(coot.ROTAMERSEARCHLOWRES)
            print("INFO:: Using Backrub rotamers")

        # no alternative for now
        # need to be able to get the state of search mode.
        # easily added. FIXME
        print("BL WARNING:: no widget")

def atom_overlaps_for_this_model():
   """Display Atom overlaps for active atom"""
   active_atom = coot.active_residue_py()
   if active_atom:
      aa_imol = active_atom[0]
      coot.coot_all_atom_contact_dots(aa_imol)


def toggle_hydrogen_display(widget=None):
    """Toggle function to display all hydrogens or not.

    Keyword arguments:
    widget -- can be passed from the toolbutton

    """

    if widget:
        if widget.get_active():
            # the button is toggled on
            coot_utils.hide_all_hydrogens()
        else:
            coot_utils.show_all_hydrogens()

    else:
        # non graphical - but wont be able to run if this is not loaded.
        print("BL INFO:: No display, so I dont care about the hydrogens.")
        print("BL WARNING:: no widget")


# Simple minded dialog, search disk or not?
# Could/should be expaded to browse for exe and to select which
# disks to search for.
#


def search_disk_dialog(program_name, path_ls):

    # graphics
    ret = False
    label_text = "Couldn't find %s in default path" % (program_name)
    for path in path_ls:
        label_text += " and "
        label_text += path
    label_text += "\n\nShall we search the whole disk?\n"

    try:
        ret = yes_no_dialog(label_text, "Search whole disk dialog")
    except:
        # no graphics
        label_text += "[y/N] >"
        result = ""
        while result.lower() not in ['y', 'yes', 'n', 'no']:
            result = input(label_text)
        if result.lower() in ['y', 'yes']:
            ret = True
        else:
            ret = False

    return ret


def duplicate_range_by_atom_pick():
    """Pick two atoms and duplicate range in between."""

    def pick_range_func(*atom_specs):

        residue_specs = list(
            map(coot_utils.atom_spec_to_residue_spec, coot_utils.atom_specs))
        imol_1 = coot_utils.atom_specs[0][1]
        imol_2 = coot_utils.atom_specs[1][1]
        chain_id1 = coot_utils.atom_specs[0][2]
        chain_id2 = coot_utils.atom_specs[1][2]
        res_no_1 = coot_utils.atom_specs[0][3]
        res_no_2 = coot_utils.atom_specs[1][3]

        # some sanity check
        if not (imol_1 == imol_2):
            msg = (
                "WARNING:: not the same imols. \n"
                "imol %i and %i were selected" % (imol_1, imol_2))
            coot.info_dialog_and_text(msg)
            return
        else:
            # imol ok
            if (not chain_id1 == chain_id2):
                msg = (
                    "BL WARNING:: not the same chains. \n"
                    "Chains %s and %s were selected" % (chain_id1, chain_id2))
                coot.info_dialog_and_text(msg)
                return
            else:
                # chain ok

                # only allow duplication of 30 res for now (hardcode)
                # as to avoid strangeness if an atom is not selected
                # properly. And swap start, stop res if required
                res_diff = res_no_1 - res_no_2
                if (abs(res_diff) > 30):
                    msg = (
                        "BL WARNING:: too many residues. \n"
                        "%i residues deExceeds the limit of 30 residues"
                        % (abs(res_diff)))
                    coot.info_dialog_and_text(msg)
                    return
                elif (abs(res_diff) < 0):
                    msg = (
                        "BL WARNING::  No residue selected.")
                    coot.info_dialog_and_text(msg)
                    return
                if (res_no_1 > res_no_2):
                    # need to swap
                    res_no_1, res_no_2 = res_no_2, res_no_1

                # main line
                # NB: no occupancy setting here
                coot_utils.duplicate_residue_range(
                    imol_1, chain_id1, res_no_1, res_no_2)

    coot.add_status_bar_text("Pick two atoms")
    coot.user_defined_click_py(2, pick_range_func)

# A simple modal dialog to accept or reject something. Pass a question
# to be asked as string.
#


def yes_no_dialog(label_text, title_text=None):
    """A simple modal dialog to accept or reject something. Pass a question
    to be asked as string.

    Args:
       label_text: the text/question to be displayed/asked in the dialog.

    Keyword args:
       title_text: title of the dialog window

    Returns:
       bool of answer.
    """

    dialog = Gtk.Dialog(title_text, None,
                        Gtk.DIALOG_MODAL | Gtk.DIALOG_NO_SEPARATOR,
                        (Gtk.STOCK_YES, Gtk.RESPONSE_ACCEPT,
                         Gtk.STOCK_NO, Gtk.RESPONSE_REJECT))
    ifont = Gtk.gdk.Font("fixed")
    label = Gtk.Label(label=label_text)
    dialog.vbox.pack_end(label, True, True, 0)
    dialog.show()
    result = dialog.run()
    if result == Gtk.RESPONSE_ACCEPT:
        ret = True
    else:
        ret = False
    dialog.destroy()

    return ret

# Function based on Davis et al. (2007) Molprobity: all atom contacts
# and structure validation for proteins and nucleic acids, Nucleic
# Acids Research 35, W375-W383.
#
#    "RNA sugar puckers (C3'endo or C2'endo) is strongly correlated
#    to the perpendicular distance between the following (3')
#    phosphate and either the plane of the base or the C1'-N1/9
#    glycosidic bond vector. [] .. a sugar pucker is very difficult
#    to determine directly from the electron density at resolutions
#    typical for RNAs."
#
# To paraphrase:
# The distance of the plane of the base to the following phosphate
# is highly correlated to the pucker of the ribose.
#
# An analysis of the structures in RNADB2005 shows that a critical
# distance of 3.3A provides a partition function to separate C2' from
# C3' endo puckering.  Not all ribose follow this rule.  There may be
# some errors in the models comprising RNADB2005. So we check the
# distance of the following phosphate to the plane of the ribose and
# record the riboses that are inconsitent.  We also report puckers
# that are not C2' or C3'.  The puckers are determined by the most
# out-of-plane atom of the ribose (the rms deviation of the 4 atoms
# in the plane is calculated, but not used to determine the
# puckering atom).
#
def pukka_puckers_qm(imol):

    import types

    residue_list = []
    crit_d = 3.0  # Richardson's group value to partition C2'-endo from C3'-endo

    def add_questionable(r):
        residue_list.append(r)

    def get_ribose_residue_atom_name(imol, residue_spec, pucker_atom):
        r_info = coot.residue_info_py(imol, residue_spec[0], residue_spec[1], residue_spec[2])
        t_pucker_atom = pucker_atom[0:3] + "*"
        if (pucker_atom in [at[0][0] for at in r_info]):
            return pucker_atom
        else:
            return t_pucker_atom

    # main line
    for chain_id in coot_utils.chain_ids(imol):
        if (not coot_utils.is_solvent_chain_qm(imol, chain_id)):
            n_residues = coot.chain_n_residues(chain_id, imol)

            for serial_number in range(n_residues):

                res_name = coot.resname_from_serial_number(imol, chain_id, serial_number)
                res_no = coot.seqnum_from_serial_number(imol, chain_id, serial_number)
                ins_code = coot.insertion_code_from_serial_number(imol, chain_id, serial_number)

                if (not res_name == "HOH"):

                    residue_spec = [chain_id, res_no, ins_code]
                    pi = coot.pucker_info_py(imol, residue_spec, 1)
                    if pi:
                        try:
                            if len(pi) == 4:
                                pucker_atom = pi[1]
                                if ((abs(pi[0]) > crit_d) and (pucker_atom == " C2'")):
                                    add_questionable([pucker_atom, residue_spec, "Inconsistent phosphate distance for C2' pucker"])
                                if ((abs(pi[0]) < crit_d) and (pucker_atom == " C3'")):
                                    add_questionable([pucker_atom, residue_spec, "Inconsistent phosphate distance for C3' pucker"])
                                if not ((pucker_atom == " C2'") or (pucker_atom == " C3'")):
                                    add_questionable([pucker_atom, residue_spec, "puckered atom:" + pucker_atom])
                        except NameError as e:
                            print(e)
                        except TypeError as e:
                            print(e)

    def go(imol, residue_spec, at_name):
        ch_id  = coot_utils.residue_spec_to_chain_id(residue_spec)
        res_no = coot_utils.residue_spec_to_res_no(residue_spec)
        coot.set_go_to_atom_molecule(imol)
        coot.set_go_to_atom_chain_residue_atom_name(ch_id, res_no, at_name)

    def generator(imol, residue_spec, at_name):
        func = lambda imol_c = imol, residue_spec_c = residue_spec, at_name_c = at_name : go(imol_c, residue_spec_c, at_name_c)
        def action(arg):
            func(imol, residue_spec, at_name)
        return action

    if len(residue_list) == 0:
        coot.info_dialog("No bad puckers.")
    else:
        buttons = []
        for residue in residue_list:
            residue_spec = residue[1]
            pucker_atom  = residue[0]
            info_string  = residue[2]
            at_name = get_ribose_residue_atom_name(imol, residue_spec, pucker_atom)
            label = residue_spec[0] + " " + str(residue_spec[1]) + residue_spec[2] + ": " + info_string
            func = generator(imol, residue_spec, at_name)
            ls = [label, func]
            buttons.append(ls)
        dialog_box_of_buttons("Non-pukka puckers", [370, 250], buttons, "  Close  ")

# A gui to list Ramachandran outliers etc.
# May become more sophisticated at some point
#
def rama_outlier_gui():

    """
    A gui to list Ramachandran outliers etc.
    A first draft, may become more sophisticated at some point
    """

    def list_rama_outliers(imol):

        r = coot.all_molecule_ramachandran_region_py(imol)
        for res in r:
            if res[1] == 0:
                outliers.append(res[0])
            if res[1] == 1:
                allowed.append(res[0])

    def make_buttons_old(res_list, label_string):

         ret = []
         for res_spec in res_list:
            chain_id = res_spec[1]
            res_no = res_spec[2]
            label = label_string + ": " + \
                    chain_id + " " + str(res_no)
            # func = [cmd2str(coot.set_go_to_atom_molecule, imol),
            #         cmd2str(coot.set_go_to_atom_from_res_spec, res_spec)]
            func = "FIXME in make_buttons_old"
            ret.append([label, func])

         return ret

    def go_to_residue(res_spec):
        print("Here in go_to_residue() with res_spec", res_spec)

    def generator(res_spec):
        func = lambda res_spec_c=res_spec : go_to_residue(res_spec_c)
        def action(arg):
            func(res_spec)
        return action

    def make_buttons(res_list, label_prefix):

        button_list = []
        for res_spec in res_list:
            chain_id = res_spec[1]
            res_no   = res_spec[2]
            ins_code = res_spec[3]
            label = label_prefix + ": " + chain_id + " " + str(res_no)
            if ins_code:
                label += " " + ins_code
            func = generator(res_spec)
            button_list.append([label, func])

        return button_list

    outlier_buttons = make_buttons(outliers, "Outlier")
    allowed_buttons = make_buttons(allowed, "Allowed")
    all_buttons = outlier_buttons + allowed_buttons

    def clear_and_add_back(vbox, outliers_list, allowed_list, filter_flag):
         # clear
         children = vbox.get_children()
         map(lambda c: c.destroy(), children)
         # add back
         if not filter_flag:
            buttons = outliers_list + allowed_list
         else:
            # filter
            buttons = outliers_list
         map(lambda button_info: add_button_info_to_box_of_buttons_vbox(button_info, vbox),
             buttons)

    dialog_box_of_buttons_with_check_button(
          " Ramachandran issues ", [300, 300], [], "  Close  ",
          "Outliers only",
          lambda check_button, vbox: clear_and_add_back(vbox, outlier_buttons, allowed_buttons, True)
          if check_button.get_active() else
          clear_and_add_back(vbox, outlier_buttons, allowed_buttons, False),
          False)

    outliers = []
    allowed = []
    molecule_chooser_gui("List Rama outliers for which molecule?", lambda imol: list_rama_outliers(imol))

def model_map_diff_map_molecule_chooser_gui(callback_function):

    def delete_event(*args):
       window.destroy()
       return False

    def combobox_to_molecule_number(combobox):
        imol = -1
        tree_iter = combobox.get_active_iter()
        if tree_iter is not None:
            model = combobox.get_model()
            it = model[tree_iter]
            imol = it[0]
        return imol

    def on_ok_clicked(*args):
        active_mol_no_model    = combobox_to_molecule_number(combobox_model)
        active_mol_no_map      = combobox_to_molecule_number(combobox_map)
        active_mol_no_diff_map = combobox_to_molecule_number(combobox_diff_map)
        try:
           active_mol_no_model    = int(active_mol_no_model)
           active_mol_no_map      = int(active_mol_no_map)
           active_mol_no_diff_map = int(active_mol_no_diff_map)
           print("INFO: operating on molecule numbers ", active_mol_no_model, active_mol_no_map, active_mol_no_diff_map)
           try:
               auto_button_state = auto_update_checkbutton.get_active()
               callback_function(active_mol_no_model, active_mol_no_map, active_mol_no_diff_map, auto_button_state)
           except TypeError as e:
               print(e)
               print("BL INFO:: problem in callback_function", callback_function.func_name)
           delete_event()
        except TypeError as e:
            print(e)
            print( "Failed to get a (molecule) number")

    window = Gtk.Window(title="Coot: Map Molecule Chooser")
    model_chooser_label = "Model"
    map_chooser_label   = "Map (with data info attached)"
    diff_map_chooser_label   = "Difference Map"
    label_for_map      = Gtk.Label(label=map_chooser_label)
    label_for_diff_map = Gtk.Label(label=diff_map_chooser_label)
    label_for_model    = Gtk.Label(label=model_chooser_label)
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
    vbox.set_margin_top(6)
    vbox.set_margin_bottom(6)
    vbox.set_margin_start(12)
    vbox.set_margin_end(12)
    label_for_model.set_margin_top(4)
    label_for_map.set_margin_top(4)
    label_for_diff_map.set_margin_top(4)

    hbox_buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    hbox_buttons.set_homogeneous(True)
    hbox_buttons.set_hexpand(False)

    # 20220326-PE
    # combobox_model    = Gtk.combo_box_new_text()
    # combobox_diff_map = Gtk.combo_box_new_text()
    # combobox_map      = Gtk.combo_box_new_text()

    combobox_diff_map = Gtk.ComboBox()

    combobox_mol_items = make_store_for_model_molecule_combobox()
    combobox_model = Gtk.ComboBox.new_with_model(combobox_mol_items)

    renderer_text_for_model = Gtk.CellRendererText()
    if len(combobox_mol_items) > 0:
        combobox_model.set_active(0)
    combobox_model.set_entry_text_column(1) # Sets the model column which combo_box
                                      # should use to get strings from to be text_column
    combobox_model.pack_start(renderer_text_for_model, True)
    combobox_model.add_attribute(renderer_text_for_model, "text", 1)

    combobox_map_items = make_store_for_map_molecule_combobox()
    combobox_map = Gtk.ComboBox.new_with_model(combobox_map_items)

    renderer_text_for_map = Gtk.CellRendererText()
    if len(combobox_map_items) > 0:
        combobox_map.set_active(0)
    combobox_map.set_entry_text_column(1) # Sets the model column which combo_box
                                      # should use to get strings from to be text_column
    combobox_map.pack_start(renderer_text_for_map, True)
    combobox_map.add_attribute(renderer_text_for_map, "text", 1)

    combobox_diff_map_items = make_store_for_diff_map_molecule_combobox()
    combobox_diff_map = Gtk.ComboBox.new_with_model(combobox_diff_map_items)

    renderer_text_for_diff_map = Gtk.CellRendererText()
    if len(combobox_diff_map_items) > 0:
        combobox_diff_map.set_active(0)
    combobox_diff_map.set_entry_text_column(1) # Sets the model column which combo_box
                                               # should use to get strings from to be text_column
    combobox_diff_map.pack_start(renderer_text_for_diff_map, True)
    combobox_diff_map.add_attribute(renderer_text_for_diff_map, "text", 1)

    ok_button = Gtk.Button(label="  OK  ")
    cancel_button = Gtk.Button(label=" Cancel ")
    h_sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)

    # "auto" button
    auto_update_checkbutton = Gtk.CheckButton(label="Auto Update")
    auto_update_checkbutton.set_margin_top(4)
    auto_update_checkbutton.set_margin_bottom(4)

    window.set_default_size(370,100)
    window.set_child(vbox)
    vbox.append(label_for_model)
    vbox.append(combobox_model)
    vbox.append(label_for_map)
    vbox.append(combobox_map)
    vbox.append(label_for_diff_map)
    vbox.append(combobox_diff_map)
    vbox.append(auto_update_checkbutton)
    vbox.append(h_sep)
    vbox.append(hbox_buttons)
    hbox_buttons.append(cancel_button)
    hbox_buttons.append(    ok_button)

    for b in [cancel_button, ok_button]:
        b.set_margin_top(4)
        b.set_margin_bottom(4)
        b.set_margin_start(6)
        b.set_margin_end(6)

    # button callbacks:
    ok_button.connect("clicked", on_ok_clicked)
    cancel_button.connect("clicked", delete_event)

    window.show()

def show_updating_maps_chooser():

    def update_maps_func(toolbutton):
        # the R-factor is added to the status bar
        stats_result = coot.calculate_maps_and_stats_py(imol, imol_map, imol_map, imol_diff_map)

    def generator_update_maps_func_wrap_for_capture(imol, imol_map, imol_diff_map):
        func = lambda imol_c=imol, imol_map_c=imol_map, imol_diff_map_c=imol_diff_map : coot.calculate_maps_and_stats_py(imol, imol_map, imol_map, imol_diff_map)
        def action(arg):
           func(imol, imol_map, imol_diff_map)
        return action

    # this needs  the same generator work-around but I've run out of energy.
    def shiftfield_func():
        imol = 0
        coot.shiftfield_b_factor_refinement(imol)

    def ok_button_function(imol, imol_map, imol_diff_map, use_auto_update_mode):
        # print("imol for coords", imol, "imol_for_map", imol_map, "use_auto_update_mode", use_auto_update_mode)
        if coot.is_valid_map_molecule(imol_map):
            if use_auto_update_mode:
                coot.set_auto_updating_sfcalc_genmap(imol, imol_map, imol_diff_map)
            else:
                print("================================= calculate_maps_and_stats_py()", imol, imol_map, imol_diff_map)
                coot.calculate_maps_and_stats_py(imol, imol_map, imol_map, imol_diff_map)
            menu_bar_callback_func = generator_update_maps_func_wrap_for_capture(imol, imol_map, imol_diff_map)
            coot_toolbar_button("Update Maps", menu_bar_callback_func, use_button_flag=True)
            coot_toolbar_button("Shiftfield B", shiftfield_func)

    model_map_diff_map_molecule_chooser_gui(ok_button_function)



# let the c++ part of mapview know that this file was loaded:

# print "From coot_gui.py calling coot.set_found_coot_python_gui()" - called from rcrane loader
# too (I think)
coot.set_found_coot_python_gui()