cl-dormouse / dormouse.lisp

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
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; coding: utf-8-unix -*- ;;;;;;;;80
;;;;
;;;;    This file is part of DORMOUSE, by Paul Sexton
;;;;    Released under the Gnu Public License version 3
;;;;
;;;;    DORMOUSE 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.
;;;;
;;;;    DORMOUSE 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 DORMOUSE.  If not, see <http://www.gnu.org/licenses/>.
;;;;
;;;;
;;;; DORMOUSE
;;;; "Graphical" user interface for the libtcod console library.
;;;;
;;;; TODO
;;;; Finish assertions for all tcod wrapper functions.
;;;; Colours don't return to default in log windows.
;;;; REPL.
;;;; Finish documentation.
;;;;
;;;; Table of contents
;;;; =================
;;;;
;;;; (Emacs users: org-mode will allow you to navigate using these
;;;; hyperlinks)
;;;;
;;;; [[Package definition]]
;;;; (@> "Utility functions")
;;;; (@> "Constants")
;;;; (@> "Global variables")
;;;; [[Keys]]
;;;; (@> "Colourising strings")

;;;; - [[Window class]]
;;;;      - [[List Window]]
;;;;           - [[Filtered Window]]
;;;;           - [[Menu Window]]
;;;;           - [[Log Window]]
;;;;             - [[Terminal Window]]
;;;;               - [[Simple Prompt Window]]
;;;;           - [[Pager Window]]
;;;;           - [[Hypertext Window]]
;;;;           - [[Terminal Window]]
;;;;      - [[Modal Window]]
;;;;           - [[Alert Window]]
;;;;           - [[Yes/No Window]]
;;;;      - [[Dialog Window]]
;;;;           - [[Tooltip Window]]
;;;;                uses [[Floating Window]]
;;;;      - [[Background window]]
;;;;      - [[Meter Window]]
;;;;      - (@> "Ghost-Window")
;;;;      - [[Window With Context Menu]]
;;;;      - (@> "Viewport")
;;;; - [[Window Themes]]
;;;;
;;;; - [[Events]]
;;;;
;;;; The documentation for this package is generated using the CLOD library.
;;;;
;;;; The following command is used: (dormouse and clod systems must be
;;;; loaded into the running lisp image first)
;;;;

#+nil
(clod:document-package :dormouse "doc/dormouse.org"
                       :title "The Dormouse Library"
                       :internal-symbols? nil
                       :brief-methods t
                       :author "Paul Sexton"
                       :email "eeeickythump@gmail.com")


;;; <<Package definition>> ====================================================

(in-package :cl-user)

(declaim (optimize (speed 0) (safety 3) (debug 3)))

(defpackage :dormouse
  (:nicknames :dormouse :tcod-gui :tcod.gui)
  (:use :cl :tcod ;;:util
        :iterate)
  (:documentation
"DORMOUSE is a windowing `graphical' user interface library, built on top of
the [[http://doryen.eptalys.net/libtcod/][Doryen Library]] (libtcod).

* What is the Doryen Library?

The Doryen Library, or /libtcod/, is a library that implements a truecolour
console. It can be thought of as a souped-up alternative to
[[http://en.wikipedia.org/wiki/Curses_(programming_library)][Curses]]. The
console can be of any size that fits on the screen. Both keyboard and mouse
events are handled. There is support for artibrarily large character sets, and
font antialiasing. BMP and PNG images can be displayed alongside text.

While libtcod is well-suited for any application where a console-based
interface is desired, the author's motivation is to support the development of
roguelike games (see [[http://en.wikipedia.org/wiki/Roguelike_game]]). As such,
libtcod also provides line-of-sight calculations, pathfinding, perlin noise,
height maps, BSP, parsing of configuration files, and other features useful
to game developers.

Libtcod is written in C and C++. Bindings for libtcod are currently available
for the python, C#, D, and
[[http://bitbucket.org/eeeickythump/cl-tcod/][Common Lisp]] languages.

* What is DORMOUSE?

Dormouse ('Doryen' + 'Mouse', groan) is a windowing `graphical' user interface
built on top of libtcod. The programmer creates Window objects which are
displayed on the root console. The mouse can be used to move, resize, and close
windows. Keyboard and mouse events are sent to whichever window object has the
focus.

* Features

- Full mouse support, including drag and drop events from one window to another,
  moving and resizing windows with the mouse.
- Each window's foreground, background, and text can be displayed in any 32-bit
  colour.
- Text strings can contain formatting directives, similar to HTML, which can:
  -  instruct the library about the colours in which parts of the string should
     be displayed
  -  compose accented characters
  -  define 'live' areas of the string which generate special events when
     clicked with the mouse (acting like dialog buttons).
- Many subclasses of the base 'Window' class with specialised behaviour,
  including:
  - Viewports: windows which provide a view onto an underlying map (array),
    which may be much larger. Dragging with the mouse moves the viewport around
    the map. Intended for the main display area in roguelike games.
  - List windows: browse and select from a list of values. Items can have
    'hotkeys' defined for quick selection.
  - Filtered windows: list windows that allow the user to type a 'filter
    string', only displaying items which contain the string.
  - Menu windows: simplified list window where a single mouse click selects and
    closes the window.
  - Log windows: a scrolling 'buffer' of text, with new messages added at the
    bottom.
  - Modal windows: prevent access to other windows, forcing the user to respond
    to a message or dialog.
  - Ghost windows: cannot be interacted with, useful for simply displaying some
    information in an area of the screen.
  - Dialog windows: present strings containing 'dialog buttons' to the user.
  - Tooltip windows: display a message when the mouse hovers over items within
    the window.
  - Context windows: window in which right-clicking on an item brings up a list
    of commands which can be applied to the item, where the commands presented
    will vary according to the characteristics of the right-clicked item.
  - And any combination of the above, using multiple inheritance...
- Windows can be created as 'children' of other windows, allowing hiding,
  showing, creation and destruction of a complex group of windows as a unit

The latest version of DORMOUSE can be found at:
- [[http://bitbucket.org/eeeickythump/cl-dormouse/]]

* Dependencies

- The Doryen library, which can be found at http://doryen.eptalys.net/libtcod/]
- CL-TCOD: http://bitbucket.org/eeeickythump/cl-tcod/
- ITERATE: http://common-lisp.net/project/iterate/
- ASDF

* Installation

- Install all dependencies (see above).
- Download =DORMOUSE= from its
  [[http://bitbucket.org/eeeickythump/cl-dormouse/][repository.]]
- Run your lisp and make sure you can load asdf, and asdf can load
  =CL-TCOD= and =DORMOUSE=.
- The following is a minimal 'hello world' application:
;;; (in-package :cl-user)
;;; (defpackage :mypkg
;;;  (:use :cl :tcod :dormouse)
;;;  (:export #:my-test))
;;;
;;; (in-package :mypkg)
;;;
;;; (defun my-test ()
;;;    (let ((msgwin nil))
;;;      (dormouse:start-gui :title \"Testing\")
;;;      (setf msgwin
;;;        (make-instance '<Log-Window> :tlx 30 :tly 10 :width 20 :height 6
;;;                      :title \"log\" :foreground :cornsilk
;;;                      :background :dark-blue))
;;;      (add-message msgwin \"Press control-F1 or control-Esc to quit\")
;;;      (main-gui-loop)))
- Save it in a file, load it, and run (mypkg:my-test) at the lisp prompt
  to try it.
")
  (:export #:start-gui
           #:main-gui-loop
           #:resume-gui
           #:*shift*
           #:*ctrl*
           #:*alt*
           #:*exit-gui?*
           #:+OPAQUE+
           #:+INVISIBLE+
           #:+DIMMED+
           #:screen-width
           #:screen-height
           #:legal-window-coordinates?
           #:with-no-redraw
           #:with-window-unchanged
           #:colour
           #:destroy-window
           #:destroy-all-windows
           #:copy-windows-to-console
           #:prepare-window
           #:process-window
           #:redraw-window
           #:redraw-window-area
           #:redraw-all-windows
           #:prepare-windows-by-type
           #:do-for-windows-by-type
           #:save-interface-state
           #:restore-interface-state
           #:destroy-interface-state
           #:hide-window
           #:hide-all-windows
           #:raise-window
           #:dirty-window
           #:move-window
           #:resize-window
           #:*window-stack*
           #:all-windows
           #:*mouse-x*
           #:*mouse-y*
           #:move-mouse-to-window
           ;; === events ===
           #:send-to-window
           #:send-key-to-window
           #:<GUI-Event>
           #:<Key-Event>
           #:<Mouse-Event>
           #:<Mouse-Hover-Event>
           #:<Mouse-Double-Click-Event>
           #:<GUI-Dialog-Event>
           #:<GUI-Select-Event>
           #:<GUI-Mouse-Drag-Event>
           #:gui-event-winx
           #:gui-event-winy
           #:gui-event-keypress
           #:gui-event-mouse-state
           #:gui-event-focus
           #:gui-event-string
           #:key-pressed-event?
           #:mouse-drag
           #:key->string
           #:<Window-Theme>
           #:*window-theme*
           #:<Window>
           #:<Modal-Window>
           #:<Ghost-Window>
           #:<Background-Window>
           #:<Meter-Window>
           #:<List-Window>
           #:<Menu-Window>
           #:<Alert-Window>
           #:<Yes/No-Window>
           #:<Tooltip-Window>
           #:<Filtered-Window>
           #:filter-string
           #:clear-filter
           #:binding->key
           #:character->vk
           #:character->shift
           #:<Window-With-Context-Menu>
           #:get-menu-items-for-context
           #:command-from-context-menu
           #:tooltip-text
           #:calculate-floating-window-width
           #:<Dialog-Window>
           #:button
           #:window-cursor
           #:move-cursor-to  ;;
           #:cursor-moved-to-item
           #:window-offset
           #:wrap-coloured-text
           #:coloured-string-length
           #:colourise
           #:window-draw-char-at  ;;
           #:draw-string-at  ;;
           #:format-at  ;;
           #:add-item  ;;
           #:window-items
           #:window-items-lines
           #:clear-items  ;;
           #:list-item
           #:list-item-item
           #:list-item-hotkey
           #:list-item-p
           #:move-cursor-to-end  ;;
           #:window-show-tail-by-default?
           #:window-fades-when-unfocussed?
           #:window-can-close?
           #:window-can-drag?
           #:window-can-resize?
           #:window-item-at-cursor
           ;; Log window
           #:<Log-Window>
           #:clear-messages   ;;
           #:add-message   ;;
           #:add-message-and-redraw  ;;
           #:bottom-message  ;;
           ;; Pager window
           #:<Pager-Window>
           #:add-browser-line   ;;
           #:clear-browser-lines   ;;
           ;; [[Hypertext window]] ============================================
           #:<Hypertext-Window>
           #:make-autolinks-in-hypertext-database
           #:hyperlink-foreground-colour
           #:open-hypertext-topic   ;;
           ;; Terminal window
           #:<Terminal-Window>
           #:window-input-function
           #:window-echo-input?
           #:window-input-active?
           #:window-input-history
           #:<Simple-Prompt-Window>
           ;; Viewports
           #:<Viewport>
           #:clear-map   ;;
           #:share-map
           #:unshare-map
           #:map-xdim
           #:map-ydim
           #:map-draw-char-at   ;; if visible
           #:map-char-at
           #:map-set-foreground-at   ;; if visible
           #:map-set-background-at   ;; if visible
           #:in-view?
           #:centre-viewport-on   ;;
           #:window-foreground
           #:window-background
           #:window-width
           #:window-height
           #:window-tlx
           #:window-tly
           #:window-brx
           #:window-bry
           #:window-framed?
           #:window-children
           #:window-raise-children-with-parent?
           #:window-hidden?
           #:window-changed?
           #:window-changed!
           #:window-auto-redraw?
           #:view-tlx
           #:view-tly
           #:view-brx
           #:view-bry
           #:viewport-width
           #:viewport-height
           #:in-view?
           #:in-viewport-map?
           #:winx->mapx
           #:winy->mapy
           #:winx->rootx
           #:winy->rooty
           #:rootx->winx
           #:rooty->winy
           #:bar-chart
           ))

(in-package :dormouse)

(defgeneric destroy-window (win)
  (:documentation
   "* Arguments
- WIN :: a [[<Window>]]
* Returns
Ignored.
* Description
Destroy the window object =WIN=, hiding it first if it is not
already hidden."))
(defgeneric touch-windows (win)
  (:documentation
   "* Arguments
- WIN :: a [[<Window>]]
* Returns
None.
* Description
Internal function. Makes =WIN= refresh its list of all other windows it is
touching, i.e. overlapping."))
(defgeneric untouch-windows (win)
  (:documentation "TODO document."))
(defgeneric dirty-window (win))
(defgeneric move-window (win tlx tly)
  (:documentation
   "* Arguments
- WIN :: a [[<Window>]]
- TLX, TLY :: coordinates on the screen where the top left corner of =WIN=
  is to be moved to.
* Returns
None.
* Description
Move the window =WIN= so that its top left corner is located
at =(TLX, TLY)= relative to the top left corner of the screen."))
(defgeneric window-touches-spot? (win x y)
  (:documentation
     "* Arguments
- WIN :: a [[<Window>]]
- X, Y :: Integer coordinates of a point on the root console.
* Returns
Boolean.
* Description
Predicate. Does this window overlap the spot at =(X, Y)= ?"))
(defgeneric windows-touching? (win other)
  (:documentation
     "* Arguments
- WIN :: a [[<Window>]]
- OTHER :: a [[<Window>]]
* Returns
Boolean.
* Description
Predicate. Do these two windows overlap somewhere?"))
(defgeneric window-parent (win)
  (:documentation "* Arguments
- WIN :: a [[<Window>]]
* Returns
A [[<Window>]] or nil.
* Description
Finds and returns the parent window of =WIN=, if it has one."))
(defgeneric windows-below (win)
  (:documentation
     "* Arguments
- WIN :: a [[<Window>]]
* Returns
A list of [[<Window>]] objects, or nil.
* Description
Returns list of all windows 'under' =WIN= in the window stack."))
(defgeneric windows-above (win)
  (:documentation
     "* Arguments
- WIN :: a [[<Window>]]
* Returns
A list of [[<Window>]] objects, or nil.
* Description
Returns list of all windows 'above' =WIN= in the window stack."))
(defgeneric windows-overlying (win)
  (:documentation
     "* Arguments
- WIN :: a [[<Window>]]
* Returns
A list of [[<Window>]] objects, or nil.
* Description
List of all windows that both overlap with WIN and are above it in
the stack."))
(defgeneric windows-underlying (win)
  (:documentation
     "* Arguments
- WIN :: a [[<Window>]]
* Returns
A list of [[<Window>]] objects, or nil.
* Description
List of all windows that both overlap with WIN and are below it in
the stack."))
(defgeneric copy-window-to-console (win con)
  (:documentation "* Arguments
- WIN :: a [[<Window>]]
- CON :: a [[console]]
* Returns
Ignored.
* Description
Copies the contents of =(window-console WIN)= onto another console, =CON=."))
(defgeneric redraw-window (win)
  (:documentation   "* Arguments
- WIN :: a [[<Window>]]
* Returns
Ignored.
* Description
Force =WIN= to copy itself onto the root console."))
(defgeneric window-redraw-at (win rootx rooty)
  (:documentation "* Arguments
- WIN :: a [[<Window>]]
- ROOTX, ROOTY :: Coordinates.
* Returns
Ignored.
* Description
Force =WIN= to copy itself into a rectangle on the root console.
The top left corner of the rectangle is at =(ROOTX, ROOTY)=."))
(defgeneric redraw-window-in-area (win x1 y1 x2 y2 &key fade)
  (:documentation "* Arguments
- WIN :: a [[<Window>]]
- X1, Y1 :: Coordinates.
- X2, Y2 :: Coordinates.
- FADE :: A float between 0.0 and 1.0, or nil.
* Returns
Ignored.
* Description
Force =WIN= to copy itself into a rectangle on the root console,
bounded by =(X1, Y1)= and =(X2, Y2)=."))
(defgeneric redraw-window-intersection (win1 win2 &key fade)
  (:documentation "* Arguments
- WIN1 :: a [[<Window>]]
- WIN2 :: a [[<Window>]]
- FADE :: A float between 0.0 and 1.0, or nil.
* Returns
Ignored.
* Description
Force =WIN1= and =WIN2= to each redraw the area where they overlap with
each other, onto the root console."))
(defgeneric redraw-intersecting-windows-below (win)
  (:documentation "TODO document."))
(defgeneric redraw-intersecting-windows-above (win)
  (:documentation "TODO document."))
(defgeneric window-auto-redraw? (win))
(defgeneric prepare-window (win)
  (:documentation
     "Redraw window contents, but don't actually copy the window console
anywhere."))
(defgeneric process-window (win)
  (:documentation "TODO document."))
(defgeneric resize-window (win width height)
  (:documentation "TODO document."))
(defgeneric mouse-drag-window (win rodent)
  (:documentation
   "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
- RODENT: a mouse object.
* Returns: None.
* Description: Internal function, called by {defun dormouse:main-gui-loop}
when the user uses the mouse to move a window across the screen."))
(defgeneric mouse-resize-window (win rodent)
  (:documentation
   "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
- RODENT: a mouse object.
* Returns: None.
* Description: Internal function, called by {defun dormouse:main-gui-loop}
when the user uses the mouse to resize a window."))
(defgeneric raise-window (win &key redraw &allow-other-keys)
  (:documentation
   "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
- REDRAW: boolean value indicating whether the area of the screen occupied
by the window should be redrawn.
* Returns: None.
* Description: Put the window WIN at the top of the window stack, so that
it is displayed as overlying any other overlapping windows.
* Examples:
* See Also: "))
(defgeneric hide-window (win &key redraw &allow-other-keys)
  (:documentation
   "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
- REDRAW: boolean value indicating whether the area of the screen occupied
by the window should be redrawn.
* Returns: None.
* Description: Hide the window WIN, making it invisible and unable to
receive events. The window is not destroyed.
* Examples:
;;; (hide-window mywin :redraw t)
* See Also: "))
(defgeneric send-to-window (win event)
  (:documentation "* Arguments:
- WIN: an instance of [[<Window>]]
- EVENT :: an instance of [[<GUI-Event>]]
* Returns: Non-nil if the event is handled, nil otherwise.
* Description: Send an event to the window WIN. The event is described by EVENT.
* Examples:
;;; (send-to-window mywin (make-instance '<GUI-Mouse-Event>
;;;                 :mouse-state (get-mouse-state))
* See Also: "))
(defgeneric on-border? (win x y)
  (:documentation
   "* Arguments:
- WIN:
- X, Y: Coordinates.
* Returns:
* Description:
* Examples:
* See Also: "))
(defgeneric on-lower-window-border? (win x y)
  (:documentation "TODO document."))
(defgeneric on-upper-window-border? (win x y)
  (:documentation "TODO document."))
(defgeneric window-draw-char-at (win ch winx winy
                                &key background-flag fg bg redraw
                                &allow-other-keys)
  (:documentation "TODO document."))
(defgeneric console-draw-char-at (con ch winx winy
                             &key background-flag fg bg &allow-other-keys)
  (:documentation "TODO document."))
(defgeneric draw-string-at (win str x y
                           &key fg bg redraw align &allow-other-keys)
  (:documentation
   "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
- STR: A string, which may contain formatting directives (see below).
- X, Y: coordinates where the string should be printed, relative to
the top left corner of WIN. If the coordinates are negative then they are
taken as relative to the bottom right corner of WIN. If the coordinates
are :CENTRE then the start of the string is taken as the centre of the
window.
- FG, BG: foreground and background colours for the string.
- ALIGN: one of :LEFT, :RIGHT or :CENTRE. If alignment is :RIGHT,
the string is drawn so that its last character is located at X, Y; if
:CENTRE, so that the middle character is at X, Y.
- REDRAW: Boolean.
* Returns: None.
* Description: Draw the string STR on the window object WIN at
position X,Y. The string STR can contain colour-changing directives - see the
documentation for {defun dormouse:make-coloured-string} for details.
* Examples:
;;; (draw-string-at mywin ``Hello, {blue}world!{/}'' 1 1 :fg :green)
* See Also:
- {defun dormouse:make-coloured-string}"))
(defgeneric colour->control-string (col background? &optional win)
  (:documentation
   "* Arguments:
- COL :: A colour specifier (keyword, number, or string.)
- BACKGROUND? :: Boolean.
- WIN :: Optional. The window on which the colour control string will
  be printed.

* Description:
Given a colour, returns a string of control codes which will change a
console's foreground colour (or background colour if BACKGROUND? is
non-nil) to the specified colour, when printed to the console."))
(defgeneric window-item-lines (win item)
  (:documentation   "Returns the number of lines that the item ITEM takes up in
the displayed list. Most items take up only 1 line."))
(defgeneric window-items-lines (win)
  (:documentation   "Returns the total number of lines needed to display all
the items in the window's list."))
(defgeneric add-item (win item str &optional k)
  (:documentation   "Add an item to the end of the window's list.  ITEM is the
'value' of the item itself. It can be any lisp value.  STR is a string
representing ITEM, which is what is displayed in the window.  HOTKEY is an
optional hotkey which quickly selects the item."))
(defgeneric clear-items (win)
  (:documentation   "Delete all items in the list belonging to WIN."))
(defgeneric draw-item-at (win item x y cursor?)
  (:documentation   "Draw list-item ITEM at WINX,WINY in the window WIN.  If
CURSOR? is non-nil, make it visually apparent that the cursor is currently
positioned over this item."))
(defgeneric window-item-at-cursor (win)
  (:documentation   "Return the list-item that is at the current cursor
position in this window (the 'cursor' moves up and down the list and always
points to one of the items in the list)."))
(defgeneric move-cursor-to-end (win)
  (:documentation "TODO document."))
(defgeneric wrap-items (win)
  (:documentation "TODO document."))
(defgeneric add-message (win fmt &rest args)
  (:documentation   "Adds the string produced by calling (APPLY #'FORMAT nil
FMT ARGS) to the end of the message list, and moves the display so that the
tail of the list is visible (including the new message)."))
(defgeneric add-message-and-redraw (win fmt &rest args)
  (:documentation   "Calls ADD-MESSAGE, then forces a redraw of WIN so
that the message is immediately visible."))
(defgeneric clear-messages (win)
  (:documentation "TODO document."))
(defgeneric clear-filter (win))
(defgeneric calculate-floating-window-width (win)
  (:documentation "TODO document."))
(defgeneric tooltip-text (win datum winx winy)
  (:documentation   "Accepts an arbitrary value. Returns nil if the datum
should not be associated with a tooltip for this window. Otherwise returns a
list of strings, which can contain colour fields.  Each string can be an
arbitrary length, as they are treated as separate messages by the floating
window."))
(defgeneric copy-map-to-viewport (win)
  (:documentation "TODO document."))
(defgeneric clear-map (win &key redraw &allow-other-keys)
  (:documentation "TODO document."))
(defgeneric centre-viewport-on (win mapx mapy)
  (:documentation "TODO document."))
(defgeneric share-map (receiver giver tlx tly)
  (:documentation "TODO document."))
(defgeneric unshare-map (receiver giver)
  (:documentation "TODO document."))
(defgeneric map-draw-char-at (win ch x y
                                &key background-flag fg bg redraw
                             &allow-other-keys)
  (:documentation   "Draw character with ASCII code CH at position MAPX, MAPY
on the map console of WIN."))
(defgeneric map-char-at (win mapx mapy)
  (:documentation
  "* Arguments:
- WIN:
- MAPX, MAPY: Coordinates on the map associated with WIN.
* Returns: A character.
* Description: Returns the character stored at (MAPX, MAPY) on the
map that is 'viewed' by the viewport WIN."))
(defgeneric get-context-at (win winx winy)
  (:documentation "TODO document."))
(defgeneric get-menu-items-for-context (win context-item)
  (:documentation "TODO document."))
(defgeneric command-from-context-menu (win command context-item)
  (:documentation "TODO document."))
(defgeneric mouse-drag (from-win to-win wfromx wfromy wtox wtoy)
  (:method ((from-win t) (to-win t) wfromx wfromy wtox wtoy)
    (declare (ignore wfromx wfromy wtox wtoy))
    nil)
  (:documentation "TODO document."))
(defgeneric windows-overlapping (win &key)
  (:documentation "TODO document."))
(defgeneric window-item-at (win winx winy)
  (:documentation   "Return the list-item that would be selected if the user
clicked on position WINX, WINY in window WIN."))
(defgeneric move-cursor-to (win cursor)
  (:documentation   "Move cursor to point to item number CURSOR in the list."))
(defgeneric cursor-moved-to-item (win item)
  (:documentation "TODO document."))
(defgeneric move-cursor-by (win increment)
  (:documentation   "Move cursor by INCREMENT items in the list. A positive
number moves further down the list, a negative number moves up."))
(defgeneric item-matches-filter-string? (win item)
  (:documentation "TODO document."))
(defgeneric ok-to-show-tooltip? (win)
  (:documentation "TODO document.")
  (:method ((win t)) nil))
(defgeneric window-page-length (win)
  (:documentation "TODO document."))
(defgeneric make-context-menu (win)
  (:documentation "TODO document."))
(defgeneric fill-to-end-of-window (win)
  (:documentation "TODO document."))
(defgeneric add-browser-line (win line)
  (:documentation "TODO document."))
(defgeneric clear-browser-lines (win)
  (:documentation "TODO document."))
(defgeneric hypertext-current-topic (win))
(defgeneric open-hypertext-topic (win topic))
(defgeneric render-input-string (win))
(defgeneric send-string-to-terminal (win &optional str))
(defgeneric window-insert-character (win ch))
(defgeneric window-delete-character (win))
(defgeneric window-backspace-character (win))
(defgeneric map-set-background-at (win colour mapx mapy &key redraw))
(defgeneric map-set-foreground-at (win colour mapx mapy &key redraw))
(defgeneric window-prompt-foreground (win/theme))
(defgeneric window-prompt-background (win/theme))
(defgeneric window-input-foreground (win/theme))
(defgeneric window-input-background (win/theme))
(defgeneric key-pressed-event? (event))


;;;; <<User-defined types>> ===================================================


(deftype =positive-integer= ()
  "Type consisting of all positive integers."
  `(integer 1))
(deftype =accent-specifier= ()
  "Type consisting of characters which are able to specify composition
of accented characters within strings."
  `(member #\^ #\: #\` #\' #\0))
;; (deftype =window-event-type= ()
;;   "Type for the =DATA= argument to [[SEND-TO-WINDOW]]."
;;   `(or (member :left :right :middle :wheel-up :wheel-down :select
;;                :dialog)
;;        tcod:key))


;;;; <<Constants>> ============================================================


(defconstant +OPAQUE+ 0
  "Value of =WINDOW-TRANSPARENCY= for a window that is not at all
transparent.")
(defconstant +INVISIBLE+ 100
  "Value of =WINDOW-TRANSPARENCY= for a window that is completely
transparent (invisible).")
(defconstant +DIMMED+ 75
  "Value of =WINDOW-TRANSPARENCY= for a window that is dimmed.")
(defconstant +BOLD-FACTOR+ 1.4
  "Scalar (number) by which a colour is multiplied to produce a 'bold'
version of that colour.")


;;;; <<Global variables>> =====================================================


;;;; Information about the default font file.
(defparameter *default-font-file*  "MDA9x14.png"
  "Filename of the default font file to be used by libtcod.")
;; (defparameter *default-font-file-chars-in-columns?* t
;;   "TODO document.")
;; (defparameter *default-font-file-background-colour* :true-pink
;;   "TODO document.")
(defparameter *default-font-layout*  :font-layout-ascii-in-row
  "Argument to pass to =TCOD:CONSOLE-SET-CUSTOM-FONT=, that describes the
layout of the [[*default font file*]]. Can be either a single keyword, or a
list of keywords.")

(defvar *window-stack* (list)
  "Stack (list) of all existing non-hidden windows. The 'topmost' window is at
the top of the stack.")
(defvar *hidden-windows* (list)
  "Stack (list) of all existing hidden windows. The 'topmost' window is at the
top of the stack.")
(defvar *scratch* nil
  "TCOD console used as a 'scratch' buffer.")
(defvar *temp-con* nil
  "TCOD console used as a 'scratch' buffer.")
(defvar *shift* nil
  "Global variable which is set to =T= while the shift key is being pressed,
and =NIL= while it is released.")
(defvar *ctrl* nil
  "Global variable which is set to =T= while the ctrl key is being pressed,
and =NIL= while it is released.")
(defvar *alt* nil
  "Global variable which is set to =T= while the alt/meta key is being pressed,
and =NIL= when it is released.")
(defvar *mouse-x* 0
  "Global variable set to the current absolute X-coordinate of the mouse
cursor, relative to the top left corner of the root console.")
(defvar *mouse-y* 0
  "Global variable set to the current absolute Y-coordinate of the mouse
cursor, relative to the top left corner of the root console.")
(defvar *auto-redraw* t
  "Do operations such as [[RAISE-WINDOW]] automatically copy the new window
appearance to [[*ROOT*]]?")
(defvar *drag-delay* 400
  "Delay before a down-LMB becomes a drag, in milliseconds.")
(defvar *text-format-start-char* #\{
  "Character which, when found in a string that is an argument to [[draw-string]],
heralds the beginning of a formatting instruction. The end of the instruction
is signalled by a second such character. The string between the characters must
be the name of a colour, or two colours separated by a comma.")
(defvar *text-format-end-char* #\}
  "Character which, when found in a string that is an argument to [[draw-string]],
heralds the end of an instruction that began with [[*TEXT-FORMAT-START-CHAR*]].")
(defvar *exit-gui?* nil
  "Setting this to non-nil will cause the GUI event-handling
loop to exit, and control to return to wherever the event-handling loop was
originally called from.")
(defvar *focus-changed?* nil
  "Transiently set to true when a new window has taken over the focus.")
(defvar *focus-fade-mode* :together
  "Option that controls fading behaviour of non-focussed windows.

=:TOGETHER= means that all non-background windows gain and lose opacity
together. When one of these windows has focus, all the others also become
more visible.

=:SEPARATE= means that windows gain and lose transparency individually. When
a window gains focus, /it/ becomes more opaque, but other windows do not.")


;;; <<Utility functions>> =====================================================


(defmacro translate-negative-coordinates (x y &optional win)
  "* Usage
: (translate-negative-coordinates X Y)
* Arguments
- X, Y :: Coordinates.
- WIN :: a window (optional)
* Description
=X= and =Y= are PLACES holding X and Y screen coordinates. If
either of them is negative, assume they are specified relative to the bottom
right corner of the screen rather than the top left corner as is usual, and
change the coordinates stored there into normal coordinates specified relative
to the top left corner.
If WIN is supplied, then negative coordinates are assumed to be relative to the
bottom right corner of that window, rather than the screen."
  (let ((winvar (gensym)))
    `(let ((,winvar ,win))
       (assert (plusp (screen-width)))
       (progn
         (if (member ,x '(:centre :centred :center :centered))
             (setf ,x (floor (if ,winvar (window-width ,winvar)
                                 (screen-width)) 2)))
         (if (member ,y '(:centre :centred :center :centered))
             (setf ,y (floor (if ,winvar (window-height ,winvar)
                                 (screen-height)) 2)))
         (if (< ,x 0)
             (incf ,x (if ,winvar (window-width ,winvar)
                          (screen-width))))
         (if (< ,y 0)
             (incf ,y (if ,winvar (window-height ,winvar)
                          (screen-height))))))))


(defmacro do-for-windows-by-type ((winvar wtype &key (include-hidden? nil))
                                  &body body)
  "* Usage
: (do-for-windows-by-type (WIN WTYPE &key INCLUDE-HIDDEN?)
:     ...body...)
* Arguments
- WINVAR :: a symbol.
- WTYPE :: symbol naming a subclass of [[<Window>]]
- include-hidden? :: boolean.
* Description
Iterate through all existing windows that are of type =WTYPE=,
which must be a non-quoted symbol naming a class. If =INCLUDE-HIDDEN?= is true,
iterate through hidden as well as visible windows.

Within the body of the iteration, the symbol given as =WINVAR= is bound to each
successive window.

* Example
;;; (do-for-windows-by-type (win <Message-Window>)
;;;   (draw-string-at win 1 1 ``Here is a message.''))"
  `(dolist (,winvar (if ,include-hidden? (all-windows) *window-stack*))
     (when (typep ,winvar ',wtype)
       ,@body)))



(defmacro push-end (item list-place)
  "* Usage
: (push-end ITEM LIST-PLACE)
* Arguments
- ITEM :: a value.
- LIST-PLACE :: a setf-able place, containing a list.
* Returns
A list.
* Description
Destructively appends =ITEM= to the end of the list stored in =LIST-PLACE=.
In other words, like =PUSH=, but adds to the end of the list rather than
the start."
    `(setf ,list-place (append ,list-place (list ,item))))



(defun constrain (n lower-limit upper-limit)
  "* Arguments:
- N: a number.
- LOWER-LIMIT: a number which is the lowest value that the function will return.
- UPPER-LIMIT: a number which is the highest value that the function will return.

* Description: Given a number N, Return N if the number is between LOWER-LIMIT
and UPPER-LIMIT inclusive, otherwise return whichever of LOWER-LIMIT or
UPPER-LIMIT is nearest to N.
* See Also: {defmacro dormouse:constrain!}"
  (cond
    ((< n lower-limit)
     lower-limit)
    ((> n upper-limit)
     upper-limit)
    (t n)))



(defmacro constrain! (place lower-limit upper-limit)
  "* Arguments:
- PLACE: a setf-able place that contains a number.
- LOWER-LIMIT: a number which is the lowest value that the function will return.
- UPPER-LIMIT: a number which is the highest value that the function will return.

* Description: Destructively modifies PLACE, replacing its value with
the value returned by (CONSTRAIN PLACE LOWER-LIMIT UPPER-LIMIT).
* See Also: {defun dormouse:constrain}"
  `(setf ,place (constrain ,place ,lower-limit ,upper-limit)))



(defun keyword->string (kwd)
  "Given :MY-KEYWORD, returns the string 'MY-KEYWORD'."
  (string-trim '(#\:) (format nil "~A" kwd)))


 (defun make-keyword (&rest parts)
    "Concatenate the parts and intern as a symbol in the KEYWORD package,
creating a keyword called :SYMBOL."
    (intern (string-upcase (format nil "~{~A~}" parts)) :keyword))


(defun string-tokenise (bag str)
  "* Arguments:
- BAG: list of characters.
- STR: A string

* Returns: A list of strings.

* Description: Divides the string STR wherever any of the characters
in BAG occur within it. The resulting substrings will not contain the
characters in BAG. Returns the resulting list of substrings."
  (let ((tokens nil)
        (found-pos nil))
    (check-type str string)
    (setf str (string-trim bag str))
    (iterate
      (while (> (length str) 0))
      (setf found-pos
            (car
             (sort
              (remove nil
                      (mapcar #'(lambda (c) (position c str)) bag))
              #'<)))
      (when found-pos
        (push (subseq str 0 found-pos) tokens)
                                        ;(setf found-ch t)
        (setf str (string-left-trim bag
                                    (subseq str found-pos nil))))
      (unless (or found-pos
                  (= 0 (length str)))
        (push str tokens)
        (setf str "")))
    (nreverse tokens)))



(defun spaces (n)
  "* Arguments:
- N: a positive integer.
* Returns: A string of N spaces.
* Description: Given an integer N, return a string of spaces N characters
  long."
  (make-sequence 'string n :initial-element #\space))


(defun centre-string (str width)
  "Returns string =STR= padded by spaces on either side, so that the length
of the returned string is at least =WIDTH=."
  (check-type str string)
  (check-type width (integer 0))
  (cond
    ((>= (length str) width)
     str)
    (t
     (concatenate 'string
                  (spaces (floor (- width (length str)) 2))
                  str
                  (spaces (ceiling (- width (length str)) 2))))))




(defun word-wrap (text &key (width 80) respect-newlines respect-hyphens
                  exclude-start-char exclude-end-char)
  "* Usage
: (word-wrap TEXT &key WIDTH RESPECT-NEWLINES RESPECT-HYPHENS
:    EXCLUDE-START-CHAR EXCLUDE-END-CHAR)
* Arguments
- TEXT :: A string.
- WIDTH :: An integer. The maximum length of lines once TEXT is wrapped.
Default is 80.
- RESPECT-NEWLINES :: Boolean. Should newline characters within the string
be treated as unbreakable? (=NIL=)
- RESPECT-HYPHENS :: Boolean. Should we refrain from breaking hyphenated
words? (=NIL=)
- EXCLUDE-START-CHAR :: A character, or nil.
- EXCLUDE-END-CHAR :: A character, or nil.

* Return Value
A list of strings.

* Description
Given a string =TEXT=, breaks the string into a series of
smaller strings, none of which is longer than =WIDTH=. Returns the list of
strings.

If =EXCLUDE-START-CHAR= and =EXCLUDE-END-CHAR= are supplied, those characters
will be treated as demarcating sections of the string whose length is to
be ignored (treated as zero)."
  (iterate
    (with counted = 0)
    (with breakpoint = nil)
    (with skipping = nil)
    (for c :in-string text)
    (for actual :upfrom 0)
    (cond
      ((eql c exclude-start-char)
       (setf skipping t))
      ((eql c exclude-end-char)
       (setf skipping nil)))
    (when (not skipping)
      (incf counted)
      (if (or (eql c #\space) (eql c #\tab)
              (and (eql c #\Newline) (not respect-newlines))
              (and (eql c #\-) (not respect-hyphens)))
          (setf breakpoint actual))
      (when (and (eql c #\Newline) respect-newlines)
        (setf breakpoint actual)
        (setf counted (1+ width))))
    (when (>= counted width)
      (return (cons (substitute-if #\space
                                   #'(lambda (ch)
                                       (or (eql ch #\tab)
                                           (eql ch #\newline)))
                                   (subseq text 0
                                           (or breakpoint actual)))
                    (word-wrap (subseq text (if breakpoint
                                                (1+ breakpoint)
                                                actual))
                               :width width
                               :respect-newlines respect-newlines
                               :respect-hyphens respect-hyphens
                               :exclude-start-char exclude-start-char
                               :exclude-end-char exclude-end-char))))
    (finally (return (list text)))))


(defun all-hashtable-keys (hashtable)
  "Return a list of every key in HASHTABLE."
  (iterate
    (for (key nil) in-hashtable hashtable)
    (collect key)))


(defmacro with-no-redraw (win &body body)
  "Execute BODY, and return its value as if it were a PROGN. Turn off all
automatic redrawing of windows while the body is executing."
  (let ((winvar (gensym "WIN"))
        (redraw (gensym "REDRAW")))
    `(let* ((,winvar ,win)
            (*auto-redraw* nil)
            (,redraw (if (slot-boundp ,winvar 'window-auto-redraw?)
                         (slot-value ,winvar 'window-auto-redraw?))))
       (if ,redraw (setf (window-auto-redraw? ,winvar) nil))
       (prog1 (progn ,@body)
         (if ,redraw (setf (window-auto-redraw? ,winvar) ,redraw))))))



(defmacro with-window-unchanged (win &body body)
  "Execute BODY, and return its value as if it were a PROGN. Before returning,
force (WINDOW-CHANGED? WIN) to be NIL."
  `(prog1 (progn ,@body)
     (setf (window-changed? ,win) nil)))


;;; <<Events>> ================================================================


(defclass <GUI-Event> ()
  ((gui-event-type :accessor gui-event-type :initform nil :initarg :event-type)
   (gui-event-window :accessor gui-event-window :initform nil :initarg :window)
   (gui-event-winx :accessor gui-event-winx :initform nil :initarg :winx)
   (gui-event-winy :accessor gui-event-winy :initform nil :initarg :winy)
   (gui-event-time :reader gui-event-time :initform (tcod:sys-elapsed-milli))))


(defmethod print-object ((event <GUI-Event>) strm)
  (print-unreadable-object (event strm :type t)
    (format strm "at (~A, ~A)" (gui-event-winx event) (gui-event-winy event))))


(defclass <Key-Event> (<GUI-Event>)
  ((gui-event-type :initform :keypress)
   (gui-event-keypress :accessor gui-event-keypress
                       :type (or null tcod:key) :initform nil
                       :initarg :keypress)))


(defmethod key-pressed-event? ((event <GUI-Event>))
  (and (typep event '<Key-Event>)
       (key-pressed (gui-event-keypress event))))


(defmethod print-object ((event <Key-Event>) strm)
  (print-unreadable-object (event strm :type t)
    (format strm "~A at (~A, ~A)" (gui-event-keypress event)
            (gui-event-winx event) (gui-event-winy event))))


(defclass <Mouse-Event> (<GUI-Event>)
  ((gui-event-type :initform :mouse)
   (gui-event-mouse-state :accessor gui-event-mouse-state
                          :initform nil :initarg :mouse-state)))


(defmethod print-object ((event <Mouse-Event>) strm)
  (print-unreadable-object (event strm :type t)
    (format strm "~A at (~A, ~A)" (gui-event-mouse-state event)
            (gui-event-winx event) (gui-event-winy event))))


(defclass <Mouse-Double-Click-Event> (<Mouse-Event>)
  ((gui-event-type :initform :mouse-double-click)))


(defclass <GUI-Mouse-Drag-Event> (<Mouse-Event>)
  ((gui-event-type :initform :mouse-drag)))


(defclass <Mouse-Hover-Event> (<Mouse-Event>)
  ((gui-event-type :initform :mouse-hover)
   (gui-event-focus :initform nil :accessor gui-event-focus :initarg :focus
                    :documentation "If the mouse is hovering over some particular
item or value, it can be stored here.")))


(defclass <GUI-Dialog-Event> (<GUI-Event>)
  ((gui-event-type :initform :dialog)
   (gui-event-string :initform nil :accessor gui-event-string :initarg :string)))


(defmethod print-object ((event <GUI-Dialog-Event>) strm)
  (print-unreadable-object (event strm :type t)
    (format strm "~S at (~A, ~A)" (gui-event-string event)
            (gui-event-winx event) (gui-event-winy event))))


(defclass <GUI-Select-Event> (<GUI-Event>)
  ((gui-event-type :initform :select)
   (gui-event-focus :initform nil :accessor gui-event-focus :initarg :focus)))


(defmethod print-object ((event <GUI-Select-Event>) strm)
  (print-unreadable-object (event strm :type t)
    (format strm "~S at (~A, ~A)" (gui-event-focus event)
            (gui-event-winx event) (gui-event-winy event))))


;;; <<Keys>> ==================================================================


(defun character->vk (ch)
  "Given a character =CH=, return the value of the 'VK' field that is expected
when the key for that character is pressed by the user."
  (case ch
    (#\space
     :space)
    ((#\1 #\!)
     :key-1)
    ((#\2 #\@)
     :key-2)
    ((#\3 #\#)
     :key-3)
    ((#\4 #\$)
     :key-4)
    ((#\5 #\%)
     :key-5)
    ((#\6 #\^)
     :key-6)
    ((#\7 #\&)
     :key-7)
    ((#\8 #\*)
     :key-8)
    ((#\9 #\()
     :key-9)
    ((#\0 #\))
     :key-0)
    (otherwise
     :char)))


(defun character->shift (ch)
  "Given a character CH, return the value of the 'SHIFT' field that is expected
when the key for that character is pressed by the user."
  (if (or (upper-case-p ch)
          (find ch '(#\~ #\! #\@ #\# #\$ #\% #\^ #\& #\*
                     #\( #\) #\_ #\+ #\{ #\} #\| #\: #\"
                     #\< #\> #\?)))

      t nil))


(defun binding->key (binding)
  "BINDING is a list of the form:
  (KEYCODE [:ctrl CTRL] [:alt ALT] [:shift SHIFT])
Where:
  -- KEYCODE is a character or a VK code
  -- SHIFT, CTRL and ALT are boolean values
Return the TCOD key structure that we expect to be produced when the key
combination described by BINDING is pressed."
  (destructuring-bind (keycode &key ctrl shift alt) binding
      (tcod:make-key
       :vk (if (characterp keycode)
               (character->vk keycode)
               keycode)
       :c (if (characterp keycode)
              keycode
              #\null)
       :pressed t
       :shift (if (not (characterp keycode))
                  shift
                  (character->shift keycode ))
       :lctrl ctrl :rctrl ctrl :lalt alt :ralt alt)))


(defun key->string (k)
  "Return a string that describes the key combination represented by the TCOD
key structure, K, in human-readable form."
  (check-type k key)
  (concatenate 'string
               (format nil "~A~A~A"
                       (if (key-shift k) "shift-" "")
                       (if (or (key-rctrl k) (key-lctrl k)) "ctrl-" "")
                       (if (or (key-ralt k) (key-lalt k)) "alt-" ""))
               (case (key-vk k)
                 (:key-0 "0")
                 (:key-1 "1")
                 (:key-2 "2")
                 (:key-3 "3")
                 (:key-4 "4")
                 (:key-5 "5")
                 (:key-6 "6")
                 (:key-7 "7")
                 (:key-8 "8")
                 (:key-9 "9")
                 (:char
                  (format nil "~C" (key-c k)))
                 (otherwise
                  (format nil "~A" (key-vk k))))))


(let ((key-event nil))
  (defun send-key-to-window (win key winx winy)
    "Return non-nil if the key is handled, nil if not handled."
    (unless key-event
      (setf key-event (make-instance '<Key-Event>)))
    (setf (gui-event-keypress key-event) key
          (gui-event-winx key-event) winx
          (gui-event-winy key-event) winy
          (gui-event-window key-event) win)
    (send-to-window win key-event)))


;;; <<Colourising strings>> ===================================================


(defun make-coloured-string (str &key (dialog? nil) (win nil))
  "* Usage
: (make-coloured-string STR &key DIALOG? WIN)
* Arguments
- STR :: A string.
- DIALOG? :: boolean.
- WIN :: a [[<Window>]] or nil.
* Returns
A string.
* Description

=STR= is a string that may contain formatting directives. Each directive is
enclosed within pairs of the characters [[*TEXT-FORMAT-START-CHAR*]] and
[[*TEXT-FORMAT-END-CHAR*]] (these are `{'and `}' by
default.). =MAKE-COLOURED-STRING= returns a string that is the same as =STR=,
except that formatting directives have been replaced with control characters
that libtcod will understand.

The directives can be used to change the colour in which the string is printed.
: {COLOURNAME} -- set foreground colour to COLOURNAME.
: {bg:COLOURNAME} -- set background colour to COLOURNAME.
: {fg:COLOURNAME,bg:COLOURNAME} -- change foreground and background colours.

Examples of colour directives:
: {green} -- change foreground colour to :GREEN
: {fg:green,bg:dark-blue} -- change foreground to :GREEN and background to
:                            :DARK-BLUE
: {bg:yellow} -- change background to :YELLOW

The delimiters can also be used to 'compose' accented characters:
: {:a} - output a lowercase a with diaeresis.
: {'a} - output a lowercase a with acute accent.
: {`a} - output a lowercase a with grave accent.
: {^a} - output a lowercase a with circumflex accent.
: {0a} - output a lowercase a with 'o' accent.

The directives can be used to mark parts of the string as 'clickable', like
dialog buttons:
: {click:MYLABEL}Click me!{/}

Finally:
: {/} - return to default foreground and background colours for this window.
: {{ - output a single `{'.
: }} - output a single `}'.

* Examples
;;;   \"Lisp is the {red}red{/} pill.\"
;;;   \"G{'i}mli, son of Glo{'i}n\"
"
  (let ((pos@ nil)
        (pos@@ 0))
    (setf pos@ (position *text-format-start-char* str))
    (cond
      ((null pos@)
       str)
      ((and (> (length str) 1)
            (member (char str 0) (list *text-format-start-char*
                                       *text-format-end-char*))
            (eql (char str 0) (char str 1)))
       (format nil "~C~A" (char str 0)
               (make-coloured-string (subseq str 2)
                                     :dialog? dialog? :win win)))
      ((> pos@ 0)
       (concatenate 'string (subseq str 0 pos@)
                    (make-coloured-string (subseq str pos@)
                                          :dialog? dialog? :win win)))
      ((null (setf pos@@ (position *text-format-end-char*
                                   (subseq str 1))))
       (warn "Missing format-end character `~C' in string ~s"
             *text-format-end-char* str)
       str)
      (t
       (incf pos@@)
       (concatenate 'string
                    (if dialog?
                        (string->dialog-codes (subseq str 1 pos@@))
                        ;; else
                        (string->tcod-colour-codes (subseq str 1 pos@@)
                                                   win))
                    (if (>= pos@@ (length str))
                        ""
                        (make-coloured-string
                         (subseq str (+ 1 pos@@)) :dialog? dialog?
                         :win win)))))))


(defmethod colour->control-string ((col integer) background?
                                   &optional win)
  (declare (ignore win))
  (multiple-value-bind (r g b) (decompose-colour col)
    (format nil "~C~C~C~C"
            (colctrl->char (if background? :COLCTRL-BACK-RGB :COLCTRL-FORE-RGB))
            (code-char (max r 1))
            (code-char (max g 1))
            (code-char (max b 1)))))


(defmethod colour->control-string ((col symbol) background?
                                   &optional win)
  (colour->control-string (colour col) background? win))


(defmethod colour->control-string ((col string) background?
                                   &optional win)
  (cond
    ((and win
          (find (string-upcase col) '("B" "BOLD") :test #'string=))
     (colour->control-string
      (tcod:colour-multiply-scalar
       (tcod:colour (if background? (window-background win)
                        (window-foreground win)))
       +BOLD-FACTOR+) background? win))
    (t
     (colour->control-string (string->colournum col) background? win))))


(defun string->tcod-colour-codes (str &optional win)
  "Given the contents of a formatting directive STR (a string), return the TCOD
control codes that are needed to use the colours specified in the string.

A formatting directive is a series of terms separated by commas. Each term is
either the single character '/', or the name of a colour, or the name of a
colour prefixed by one of the labels FOREGROUND:, BACKGROUND:, FG:, or BG:."
  (with-output-to-string (s)
    (cond
      ((string= str "/")
       (cond
         (win
         ;; Just outputting COLCTRL-STOP seems not to work if the stop code
         ;; is a different function call from the original colour-changing
         ;; codes. It seems that if the colours are changed within a string
         ;; and not changed back, then the new colours become the new default
         ;; colours for the console.
         ;; Therefore, if WIN is supplied, reset the console colours to the
         ;; remembered default colours for the window object, prior to
         ;; outputting COLCTRL-STOP.
          (format s (colour->control-string (window-foreground win) nil win))
          (format s (colour->control-string (window-background win) t win)))
         (t
          (format s "~C" (colctrl->char :COLCTRL-STOP)))))
       ;;   (console-set-foreground-colour (window-console win)
       ;;                                  (colour (window-foreground win)))
       ;;   (console-set-background-colour (window-console win)
       ;;                                  (colour (window-background win))))
       ;; (format s "~C" (colctrl->char :COLCTRL-STOP)))
      ((and (= 2 (length str))
            (member (char str 0) '(#\^ #\: #\' #\`))
            (member (char str 1) '(#\A #\E #\I #\O #\U #\a #\e #\i #\o #\u)))
       (format s "~C" (compose-accented-char (char str 1) (char str 0))))
      (t
       (let* ((props (string->properties str :foreground))
              (foreground (or (getf props :foreground)
                              (getf props :fg)))
              (background (or (getf props :background)
                              (getf props :bg))))
         (when foreground
           (format s (colour->control-string foreground nil win)))
           ;; (multiple-value-bind
           ;;       (fr fg fb) (decompose-colour (string->colournum foreground))
           ;;   (format s "~C~C~C~C"
           ;;           (colctrl->char :COLCTRL-FORE-RGB)
           ;;           (code-char (max fr 1))
           ;;           (code-char (max fg 1))
           ;;           (code-char (max fb 1)))))
         (when background
           (format s (colour->control-string background t win))))))))
           ;; (multiple-value-bind
           ;;       (br bg bb) (decompose-colour (string->colournum background))
           ;;   (format s "~C~C~C~C"
           ;;           (colctrl->char :COLCTRL-BACK-RGB)
           ;;           (code-char (max br 1))
           ;;           (code-char (max bg 1))
           ;;           (code-char (max bb 1))))))))))


(defun compose-accented-char (ch accent)
  "* Arguments:
- CH -- an alphabetic character.
- ACCENT -- another character which must be a member of the set #\^, #\:, #\`,
#\', #\0.
-- #\^ -- circumflex
-- #\: -- diaeresis
-- #\` -- grave
-- #\' -- acute
-- #\0 -- ring (small 'o' as seen above Scandinavian 'a')

* Returns:
The ASCII character for CH accented according to ACCENT.

* Examples:
;;; (compose-accented-char #\a #\')  ; returns a with acute accent (ASCII 160)."
  (declare (character ch) (type =accent-specifier= accent))
  ;; todo this may break with some other character sets.
  (case accent
    (#\^
     ;; ^a 131 ^e 136 ^i 140 :A 142 ^o 147 ^u 150
     (case ch
       (#\a (code-char 131))
       (#\e (code-char 136))
       (#\i (code-char 140))
       (#\o (code-char 147))
       (#\u (code-char 150))
       (#\A (code-char 142))
       (otherwise ch)))
    (#\:
     ;; :u 129 :a 132 :e 137 :i 139 :o 148 :O 153 :U 154
     (case ch
       (#\a (code-char 132))
       (#\e (code-char 137))
       (#\i (code-char 139))
       (#\o (code-char 148))
       (#\u (code-char 129))
       (#\O (code-char 153))
       (#\U (code-char 154))
       (otherwise ch)))
    (#\`  ;; \
     ;; `a 133 `e 138 `i 141 `o 149 `u 151
     (case ch
       (#\a (code-char 133))
       (#\e (code-char 138))
       (#\i (code-char 141))
       (#\o (code-char 149))
       (#\u (code-char 151))
       (otherwise ch)))
    (#\'  ;; /
     ;; 'e 130 'E 144 'a 160 'i 161 'o 162 'u 163
     (case ch
       (#\a (code-char 160))
       (#\e (code-char 130))
       (#\i (code-char 161))
       (#\o (code-char 162))
       (#\u (code-char 163))
       (#\E (code-char 144))
       (otherwise ch)))
    (#\0
     ;; 0a 134 0A 143
     (case ch
       (#\a (code-char 134))
       (#\A (code-char 143))
       (otherwise ch)))
    (otherwise
     ch)))


(defun string->dialog-codes (str)
  "Similar to [[string->tcod-colour-codes]], but deals only with
the directives that create clickable 'dialog buttons' within a string.

STR is a string containing a series of terms separated by commas. Each term
is either the single character '/', or the name of a colour, or the name of a
colour prefixed by one of the labels FOREGROUND:, BACKGROUND:, FG:, or BG:, or
a label prefixed by one of the labels BUTTON:, BTN: or CLICK:."
  (with-output-to-string (s)
    (cond
      ((string= str "/")
       (format s "~C" (colctrl->char :COLCTRL-STOP)))
      (t
       (let* ((props (string->properties str :foreground))
              (click-label (or (getf props :button)
                               (getf props :btn)
                               (getf props :click))))
         (when click-label
           (multiple-value-bind
                 (fr fg fb) (decompose-colour
                             (string->dialog-colour click-label))
             (format s "~C~C~C~C"
                     (colctrl->char :COLCTRL-FORE-RGB)
                     (code-char (max fr 1))
                     (code-char (max fg 1))
                     (code-char (max fb 1))))))))))


(defun string->properties (str &optional (default-label :unlabelled))
  "Given a string found within a pair of TEXT-FORMAT-CHARs, break it
down into a property list.
The string is considered to be a list of terms separated by commas.
Each term may be prefixed with a label and ':', in which case the label
becomes the keyword associated with the rest of the term in the returned
property list."
  (declare (string str))
  (let ((properties nil))
    (dolist (term (string-tokenise '(#\,) str))
      (cond
        ((and (position #\: term)
              (> (position #\: term) 0))
         (setf (getf properties
                     (make-keyword (subseq term 0 (position #\: term))))
               (subseq term (1+ (position #\: term)))))
        (t                              ; default - no label given
         (setf (getf properties default-label) term))))
    properties))



(defun string->colournum (str)
  "Given a string STR, return the colournum that is associated with the
corresponding keyword."
  (or (colour (make-keyword str))
      0))


(defun coloured-string-length (str)
  "Return the number of printable characters in the string STR. In other words,
return the length of STR when formatting directives are excluded."
  (iterate
    (with cnt = 0)
    (with counting = t)
    (for c :in-string str)
    (cond
      (counting
       (if (eql c *text-format-start-char*)
           (setf counting nil)
           ;; else
           (incf cnt)))
      ((eql c *text-format-end-char*)
       (setf counting t))
      (t nil))
    (finally (return cnt))))


(defun right-trim-coloured-string (str n)
  "Return the N rightmost characters of string STR, ignoring fields
surrounded by { and }."
  (let ((len (coloured-string-length str)))
    (cond
      ((<= len n)
       str)
      (t
       (iterate
         (with cnt = 0)
         (with c = nil)
         (with counting = t)
         (for actual :from (1- (length str)) :downto 0)
         (setf c (char str actual))
         (cond
           (counting
            (cond
              ((eql c *text-format-end-char*)
               (setf counting nil))
              ;; else
              (t
               (incf cnt))))
           ((eql c *text-format-start-char*)
            (setf counting t))
           (t nil))
         (when (and counting (>= cnt (- len n)))
           (return (subseq str actual)))
         (finally (return str)))))))


(defun left-trim-coloured-string (str n)
  "Return the N leftmost characters of string STR, ignoring fields
surrounded by { and }."
  (let ((len (coloured-string-length str)))
    (cond
      ((<= len n)
       str)
      (t
       (iterate
         (with cnt = 0)
         (with counting = t)
         (for c :in-string str)
         (for actual :from 0)
         (cond
           (counting
            (cond
              ((eql c *text-format-start-char*)
               (setf counting nil))
              ;; else
              (t
               (incf cnt))))
           ((eql c *text-format-end-char*)
            (setf counting t))
           (t nil))
         (when (and counting (>= cnt n))
           (return (subseq str 0 (1+ actual))))
         (finally (return str)))))))



(defun colourise (val fg &optional bg)
  "Given a value, return it as a string wrapped in directives for
  {defgeneric dormouse:write-to-window-at} which will make the value appear in
  colours FG[,BG] when written to the screen."
  (cond
    (bg
     (format nil "{fg:~A,bg:~A}~A{/}"
             (keyword->string fg)
             (keyword->string bg)
             val))
    (t
     (format nil "{fg:~A}~A{/}"
             (keyword->string fg)
             val))))



(defun bar-chart (width num denom
                  &key (text nil)
                  (bar-colour :red) (empty-bar-colour :black)
                  (text-colour :white))
  "Returns a colourised string which, when printed using
  draw-string-at, will produce a string of solid blocks
  WIDTH characters long, coloured BAR-COLOUR for NUM/DENOM * the string's
  length, and EMPTY-BAR-COLOUR for the rest of the string.

If TEXT is supplied, then some text will appear in the centre of the bar chart,
with a foreground colour of TEXT-COLOUR. Possible values for TEXT are:

- A string
- :FRACTION - ``NUM/DENOM''
- :PERCENT - a percentage calculated from NUM/DENOM * 100
- nil (default) - no text.

* Example:
;;; (bar-chart 20 (hit-points *player*) (max-hit-points *player*)
;;;    :text :fraction :text-colour :cornsilk) "
  (declare (type (integer 1) width) (real num denom))
  (when (zerop denom)
    (setf denom 1))
  (let ((bar
         (cond
           ((eql text :fraction)
            (centre-string (format nil "~D/~D" num denom) width))
           ((eql text :percent)
            (centre-string (format nil "~D%" (floor (* num 100) denom)) width))
           ((stringp text)
            (centre-string text width))
           (t   ;; just a bar
            (spaces width))))
        (filled-spaces (round (* width (/ (constrain num 0 denom) denom)))))
    (concatenate 'string
                 "{fg:" (keyword->string text-colour)
                 ",bg:" (keyword->string bar-colour) "}"
                 (subseq bar 0 filled-spaces)
                 (colourise (subseq bar filled-spaces) text-colour
                            empty-bar-colour))))



;;; <<Window class>> ==========================================================


(defclass <Window> ()
  ((window-tlx :initform 0 :accessor window-tlx :type (or integer (member :centred))
               :initarg :tlx :documentation "X-coordinate of top left corner of
the window. If a negative number is given, then the coordinate is calculated
relative to the bottom right corner of the screen. If the value is :CENTRED,
the window will be placed so it is centred horizontally on the screen.")
   (window-tly :initform 0 :accessor window-tly :type (or integer (member :centred))
               :initarg :tly :documentation "Y-coordinate of top left corner of
the window. If a negative number is given, then the coordinate is calculated
relative to the bottom right corner of the screen. If the value is :CENTRED,
the window will be placed so it is centred vertically on the screen.")
   (window-width :initform 0 :accessor window-width :type integer
                 :initarg :width :documentation "Width of the window in
                 columns. A negative value means that many columns less than
the width of the root console.")
   (window-height :accessor window-height :initform 0 :type integer
                  :initarg :height :documentation "Height of the window in
                  rows. A negative value means that many rows less than
the height of the root console.")
   (window-console :accessor window-console :initform nil :initarg :console
                   :documentation "Contains the external C console pointer for
                   the window.")
   (window-foreground :writer (setf window-foreground)
                      :type keyword
                      :initarg :foreground
                      :documentation
                      "Default foreground colour for the window.")
   (window-background :writer (setf window-background)
                      :type keyword
                      :initarg :background
                      :documentation
                      "Default background colour for the window.")
   (window-highlight-foreground :writer (setf window-highlight-foreground)
                      :type keyword
                      :initarg :highlight-fg
                      :documentation
                      "Default foreground colour for highlighted text.")
   (window-highlight-background :writer (setf window-highlight-background)
                      :type keyword
                      :initarg :highlight-bg
                      :documentation
                      "Default background colour for highlighted text.")
   (window-children :accessor window-children :initform nil
                    :type list :initarg :children
                    :documentation "List of windows which are
'dependent' on this window. They are hidden, unhidden and
destroyed along with the window. Also see `WINDOW-RAISE-CHILDREN-WITH-PARENT?'
below.")
   (window-raise-children-with-parent?
    :accessor window-raise-children-with-parent? :initform t
    :type boolean :documentation  "Are child windows to be raised and
hidden when the same is done to the parent?")
   (window-auto-redraw? :writer (setf window-auto-redraw?)
                        :initarg :auto-redraw? :type boolean
                        :documentation "Should this window automatically redraw
itself if it finds WINDOW-CHANGED? is non-nil?")
   (window-auto-redraw-time :accessor window-auto-redraw-time
                            :initform nil :initarg :auto-redraw-time
                            :type (or null integer)
                            :documentation "If non-nil, must be a positive
integer. The window will automatically call PREPARE-WINDOW on itself every
time this many milliseconds elapse.")
   (window-framed? :writer (setf window-framed?)
                   :type boolean :initarg :framed?
                   :documentation "Should a frame be drawn in the edges of the
                   window?")
   (window-can-resize? :accessor window-can-resize? :initform t :type boolean
                       :initarg :can-resize? :documentation "Can window be
resized by dragging on the lower right corner with the mouse?")
   (window-can-drag? :accessor window-can-drag? :initform t :type boolean
                     :initarg :can-drag?
                     :documentation "Can the window be dragged around
the screen with the mouse?")
   (window-can-close? :accessor window-can-close? :initform t :type boolean
                      :initarg :can-close?
                      :documentation "Can the window be closed by clicking on
an 'X' in its top right corner?")
   (window-ephemeral? :accessor window-ephemeral? :initform nil
                      :type boolean :initarg :ephemeral?
                      :documentation "Ephemeral windows are destroyed
upon being hidden.")
   (window-draw-function :accessor window-draw-function :initform nil
                         :type (or null function) :initarg :draw
                         :documentation "Function taking one argument -- the
window -- that is called to 'fill in' the interior of the window when it is
drawn or redrawn.")
   (window-event-handler :accessor window-event-handler
                         :initform nil
                         :initarg :event-handler
                         :documentation "Must be either nil or a Function
accepting two arguments:
WIN and EVENT. Called when an input event is to be sent to the
window. WIN is the window in question, EVENT is an instance of GUI-EVENT.
The function must return non-nil if the event was 'handled', nil if it was
not handled and should be passed on to other possible handlers.")
   (window-title :accessor window-title :initform nil
                 :type (or null string) :initarg :title
                 :documentation "Title of the window.")
   (window-transparency :writer (setf window-transparency)
                        :type (integer 0 100)
                        :initarg :transparency
                        :documentation "Amount of transparency of the window,
from 0-100, where 100 = invisible.")
   (window-transparency-unfocussed
    :writer (setf window-transparency-unfocussed)
    :type (or null (integer 0 100)) :initarg :transparency-unfocussed
    :documentation "When this window does not have the focus, what does its
transparency become? (NIL = no change in transparency)")
   ;; Internal bookkeeping slots, usually not accessed by the user.
   (window-hidden? :accessor window-hidden? :initform nil :type boolean
                   :documentation "Is this window hidden?")
   (window-changed? :accessor window-changed? :initform t :type boolean
                    :documentation "Can be set to T if the window needs to be
updated, as a signal to process-window. Once the window has been processed it
will be reset to NIL.")
   (window-last-update-time :accessor window-last-update-time
                            :initform 0 :type integer
                            :documentation "System time in milliseconds
when this window was last redrawn.")
   (window-alive? :accessor window-alive? :initform t :type boolean
                  :documentation "Set to nil when a window has been destroyed.")
   (window-touching :accessor window-touching :initform (list) :type list
                    :documentation "List of windows that overlap this window."))
  (:documentation   "* Description: Class whose instances represent windows on
the screen.
* Examples: TODO
* See Also: "))


;;; <<Window Themes>> =========================================================


(defclass <Window-Theme> ()
  (;; Colours =================================================================
   (window-foreground :accessor window-foreground :initform :white
                      ;;:type keyword
                      :initarg :foreground
                      :documentation
                      "Default foreground colour for window contents.")
   (window-background :accessor window-background
                      :initform :dark-slate-gray :type keyword
                      :initarg :background
                      :documentation
                      "Default background colour for window contents.")
   (window-highlight-foreground :accessor window-highlight-foreground
                         :initform :black
                      ;;:type keyword
                      :initarg :highlight-fg
                      :documentation
                      "Foreground colour for highlighted or selected text.")
   (window-highlight-background :accessor window-highlight-background
                      :initform :white :type keyword
                      :initarg :highlight-bg
                      :documentation
                      "Background colour for highlighted or selected text.")
   (dialog-button-foreground :accessor dialog-button-foreground
                             :initform :black :type keyword
                             :initarg :dialog-button-foreground
                             :documentation "Default foreground colour for
dialog buttons created with [[button]].")
   (dialog-button-background :accessor dialog-button-background
                             :initform :light-grey :type keyword
                             :initarg :dialog-button-background
                             :documentation "Default background colour for
dialog buttons created with [[button]].")
   (hyperlink-foreground-colour
    :initform :light-blue :type keyword :initarg :hyperlink-fg
    :accessor hyperlink-foreground-colour)
   (window-prompt-foreground :initarg :prompt-fg
                             :writer (setf window-prompt-foreground)
                             :documentation "Foreground colour for prompts in
Terminal Windows. Defaults to WINDOW-FOREGROUND.")
   (window-prompt-background :initarg :prompt-bg
                             :writer (setf window-prompt-background))
   (window-input-foreground :initarg :input-fg
                            :writer (setf window-input-foreground)
                            :documentation "Foreground colour for input typed
by the user in Terminal Windows. Defaults to WINDOW-FOREGROUND.")
   (window-input-background :initarg :input-bg
                            :writer (setf window-input-background))
   ;; Other settings ==========================================================
   (window-framed? :accessor window-framed? :initform t
                   :type boolean :initarg :framed?
                   :documentation "Should a frame be drawn around the edges of
                   windows?")
   (window-transparency :accessor window-transparency :initform 25
                        :type (integer 0 100)
                        :initarg :transparency
                        :documentation "Amount of window transparency,
from 0-100, where 100 = invisible.")
   (window-transparency-unfocussed
    :accessor window-transparency-unfocussed :initform +DIMMED+
    :type (or null (integer 0 100))
    :initarg :transparency-unfocussed
    :documentation "When windows do not have the focus, what does their
transparency become? (NIL = no change in transparency)"))
  (:documentation
   "Object containing global appearance information, which all windows
will use unless overridden."))


(defvar *default-window-theme* (make-instance '<Window-Theme>))
(defvar *window-theme* *default-window-theme*)


;; Readers for Window slots that override Theme defaults.


(defmethod window-foreground ((win <Window>))
  (if (slot-boundp win 'window-foreground)
      (slot-value win 'window-foreground)
      (window-foreground *window-theme*)))

(defmethod window-background ((win <Window>))
  (if (slot-boundp win 'window-background)
      (slot-value win 'window-background)
      (window-background *window-theme*)))

(defmethod window-highlight-foreground ((win <Window>))
  (if (slot-boundp win 'window-highlight-foreground)
      (slot-value win 'window-highlight-foreground)
      (window-highlight-foreground *window-theme*)))

(defmethod window-highlight-background ((win <Window>))
  (if (slot-boundp win 'window-highlight-background)
      (slot-value win 'window-highlight-background)
      (window-highlight-background *window-theme*)))

(defmethod window-framed? ((win <Window>))
  (if (slot-boundp win 'window-framed?)
      (slot-value win 'window-framed?)
      (window-framed? *window-theme*)))

(defmethod window-transparency ((win <Window>))
  (if (slot-boundp win 'window-transparency)
      (slot-value win 'window-transparency)
      (window-transparency *window-theme*)))

(defmethod window-transparency-unfocussed ((win <Window>))
  (if (slot-boundp win 'window-transparency-unfocussed)
      (slot-value win 'window-transparency-unfocussed)
      (window-transparency-unfocussed *window-theme*)))

;;; Readers for window theme slots, allowing these slots to
;;; default to FG/BG values.

(defmethod window-prompt-foreground ((theme <Window-Theme>))
  (if (slot-boundp theme 'window-prompt-foreground)
      (slot-value theme 'window-prompt-foreground)
      (window-foreground theme)))

(defmethod window-prompt-background ((theme <Window-Theme>))
  (if (slot-boundp theme 'window-prompt-background)
      (slot-value theme 'window-prompt-background)
      (window-background theme)))

(defmethod window-input-foreground ((theme <Window-Theme>))
  (if (slot-boundp theme 'window-input-foreground)
      (slot-value theme 'window-input-foreground)
      (window-foreground theme)))

(defmethod window-input-background ((theme <Window-Theme>))
  (if (slot-boundp theme 'window-input-background)
      (slot-value theme 'window-input-background)
      (window-background theme)))

(defmethod window-auto-redraw? ((win <Window>))
  (if (slot-boundp win 'window-auto-redraw?)
      (slot-value win 'window-auto-redraw?)
      *auto-redraw*))


(defun screen-width ()
  "* Arguments: None.
* Returns: Integer.
* Description: Returns the width of the screen (root console) in columns."
  (tcod:console-get-width tcod:*root*))


(defun screen-height ()
  "* Arguments: None.
* Returns: Integer.
* Description: Returns the height of the screen (root console) in rows."
  (tcod:console-get-height tcod:*root*))



(defmethod initialize-instance :after ((win <Window>) &key (hidden? nil)
                                       &allow-other-keys)
  ;; Translate negative values for HEIGHT and WIDTH to to be relative
  ;; to the screen (root console) size. For example, width -6 means
  ;; 6 columns less than the root console width.
  (if (minusp (window-width win))
      (incf (window-width win) (screen-width)))
  (if (minusp (window-height win))
      (incf (window-height win) (screen-height)))
  (setf (window-console win)
        (console-new (window-width win) (window-height win)))
  (console-set-default-foreground (window-console win)
                                 (colour (window-foreground win)))
  (console-set-default-background (window-console win)
                                 (colour (window-background win)))
  (console-set-background-flag (window-console win) :set)
  (if (eql :centred (window-tlx win))
      (setf (window-tlx win) (- (floor (screen-width) 2)
                                (floor (window-width win) 2))))
  (if (eql :centred (window-tly win))
      (setf (window-tly win) (- (floor (screen-height) 2)
                                (floor (window-height win) 2))))
  ;; Translate negative numbers for TLX,TLY to be relative to the
  ;; bottom right corner of the screen.
  (translate-negative-coordinates (window-tlx win) (window-tly win))
  (cond
    (hidden?
     (setf (window-hidden? win) t)
     (push win *hidden-windows*))
    (t
     (touch-windows win)
     ;; put WIN onto stack
     (push win *window-stack*))))



(defmethod process-window ((win <Window>))
  (unless (window-hidden? win)
    (cond
      ((or (and (window-changed? win)
                (window-auto-redraw? win))
           (and (window-auto-redraw-time win)
                (> (tcod:sys-elapsed-milli)
                   (+ (window-auto-redraw-time win)
                      (window-last-update-time win)))))
       (with-window-unchanged win
         (prepare-window win)
         (redraw-window-area win :draw-window t)
         (dirty-window win)))
      (*focus-changed?*
       (redraw-window-area win :draw-window t)))))


(defun window-changed! (win)
  (setf (window-changed? win) t))


(defmethod send-to-window ((win <Window>) event)
  (declare (ignore event)) nil)


(defmethod send-to-window :around ((win <Window>) (event t))
  (if (or (null (window-event-handler win))
          (not (funcall (window-event-handler win) win event)))
      (call-next-method)))


(defmethod dirty-window ((win <Window>))
  (with-slots ((tlx window-tlx) (tly window-tly)
               (width window-width) (height window-height)) win
    (console-set-dirty (constrain tlx 0 (1- (screen-width)))
                       (constrain tly 0 (1- (screen-height)))
                       (constrain width 0 (- (screen-width) tlx))
                       (constrain height 0 (- (screen-height) tly)))))



(defmethod window-parent ((win <Window>))
  ;; TODO inefficient
  (find-if #'(lambda (parent) (member win (window-children parent)))
                (all-windows)))


(defmethod destroy-window ((win <Window>))
  (if (find win *window-stack*)
      (hide-window win))
  (when (and (window-console win)
             (not (equal *root* (window-console win)))))
  ;; If it has a parent, remove it from parent's list.
  (let ((parent (window-parent win)))
    (if parent
        (setf (window-children parent)
              (remove win (window-children parent)))))
  ;; If it has children, remove them
  (when (window-children win)
    (dolist (child (window-children win))
      (destroy-window child)))
  (setf *hidden-windows* (remove win *hidden-windows*))
  (setf (window-alive? win) nil))




(defun destroy-all-windows ()
  "* Arguments: None.
* Returns: None.
* Description: Destroy all existing window objects."
  (iterate
    (with wins = nil)
    (while (setf wins (all-windows)))
    (destroy-window (car wins))))


(defstruct window-configuration
  (visible-windows nil)
  (hidden-windows nil))


(defun save-interface-state ()
  "* Returns:
A WINDOWS-CONFIGURATION struct, which contains information sufficient to
restore the interface to its current state in future via a call to
`restore-interface-state'.

 Intended to be called if we want to make substantial changes to the interface
setup, but might later want to restore the current window setup."
  (make-window-configuration :visible-windows (copy-list *window-stack*)
                             :hidden-windows (copy-list *hidden-windows*)))


(defun restore-interface-state (state)
  "* Arguments:
- STATE :: A WINDOWS-CONFIGURATION struct, usually one created previously
by a call to `save-interface-state'.
* Returns:
A new WINDOWS-CONFIGURATION struct, containing information about the overwritten
interfact state."
  (let ((cfg (save-interface-state)))
    (setf *window-stack* (copy-list (window-configuration-visible-windows state)))
    (setf *hidden-windows* (copy-list (window-configuration-hidden-windows state)))
    (dolist (win (all-windows))
      (dirty-window win))
    cfg))


(defun destroy-interface-state (state)
  (dolist (win (window-configuration-visible-windows state))
    (destroy-window win))
  (dolist (win (window-configuration-hidden-windows state))
    (destroy-window win))
  (setf (window-configuration-visible-windows state) nil
        (window-configuration-hidden-windows state) nil)
  state)


(defmethod touch-windows ((win <Window>))
  (dolist (other *window-stack*)
    (when (and (not (equal other win))
             (windows-touching? win other))
        (pushnew other (window-touching win))
        (pushnew win (window-touching other)))))


(defmethod untouch-windows ((win <Window>))
        (dolist (other (window-touching win))
                (setf (window-touching other)
                        (remove win (window-touching other) :test #'equal)))
        (setf (window-touching win) (list)))


(defmethod move-window ((win <Window>) tlx tly)
  (translate-negative-coordinates tlx tly)
  (untouch-windows win)
  (setf (window-tlx win) tlx)
  (setf (window-tly win) tly)
  (touch-windows win))



(defun window-areas-overlap? (a-tlx a-tly a-brx a-bry
                       b-tlx b-tly b-brx b-bry)
  "* Arguments:
- A-TLX, A-TLY: coordinates of top left corner of the first area.
- A-BRX, A-BRY: coordinates of bottom right corner of the first area.
- B-TLX, B-TLY: coordinates of top left corner of the second area.
- B-BRX, B-BRY: coordinates of bottom right corner of the second area.
* Returns: Boolean.
* Description: Do the two rectangular areas A-TLX,A-TLY==>A-BRX,A-BRY and
B-TLX,B-TLY==>B-BRX,B-BRY overlap?"
  (translate-negative-coordinates a-tlx a-tly)
  (translate-negative-coordinates a-brx a-bry)
  (translate-negative-coordinates b-tlx b-tly)
  (translate-negative-coordinates b-brx b-bry)
  (not (or (< a-brx b-tlx)
           (< a-bry b-tly)
           (> a-tlx b-brx)
           (> a-tly b-bry))))


(defmethod window-touches-spot? ((win <Window>) x y)
  (translate-negative-coordinates x y)
  (and (<= (window-tlx win) x (window-brx win))
       (<= (window-tly win) y (window-bry win))))


(defmethod windows-touching? ((win <Window>) (other <Window>))
  (window-areas-overlap?
   (window-tlx win)  (window-tly win)
   (window-brx win) (window-bry win)
   (window-tlx other)  (window-tly other)
   (window-brx other) (window-bry other)))


(defmethod windows-below ((win <Window>))
  (rest (member win *window-stack*)))


(defmethod windows-above ((win <Window>))
  (subseq *window-stack* 0 (position win *window-stack*)))


(defmethod windows-overlying ((win <Window>))
  (remove-if-not #'(lambda (w) (member w (window-touching win)))
                 (windows-above win)))


(defmethod windows-underlying ((win <Window>))
  (remove-if-not #'(lambda (w) (member w (window-touching win)))
                 (windows-below win)))


(defmethod windows-overlapping ((win <Window>) &key (include-window? t))
  (remove-if #'(lambda (win2)
                 (or (and (not include-window?) (eql win win2))
                     (not (windows-touching? win win2))))
             *window-stack*))


(defmethod copy-window-to-console ((win <Window>) con)
      ;; (warn "xsrc: ~D ysrc: ~D wsrc: ~D hsrc: ~D xdest: ~D ydest: ~D srcw: ~D srch: ~D destw: ~D desth: ~D~%"
      ;;     0 0 (window-width win) (window-height win)
      ;;     (window-tlx win) (window-tly win)
      ;;     (console-get-width (window-console win))
      ;;     (console-get-height (window-console win))
      ;;     (console-get-width con)
      ;;     (console-get-height con)
      ;;     )
      ;; (break)
  (console-blit (window-console win) 0 0 (window-width win) (window-height win)
                con (window-tlx win) (window-tly win)
                (window-transparency->fade win) (window-transparency->fade win)))



(defmethod redraw-window ((win <Window>))
  (copy-window-to-console win *root*))


(defun redraw-all-windows (&key except)
  "* Arguments:
- EXCEPT :: list of window instances to exclude, or nil.
* Returns: None.
* Description: Copy all visible windows onto the root console."
  (let ((windows (set-difference *window-stack* except)))
    (dolist (win windows)
      (prepare-window win))
    (console-clear *root*)
    (copy-windows-to-console windows *root*)
    (console-set-dirty 0 0 (screen-width) (screen-height))))


(defun copy-windows-to-console (window-list con)
  "* Arguments:
- WINDOW-LIST: a list of instances of {defclass dormouse:<Window>}
- CON: a C console pointer.
* Returns: None.
* Description: Copy (draw) each window in WINDOW-LIST onto the console CON.
The FIRST window in the list is treated as the 'topmost' window and so
is copied LAST."
  (dolist (win (reverse window-list))
    (copy-window-to-console win con)))


(defun copy-console-to-console (src dest)
  "* Arguments:
- SRC, DEST: C console pointers.
* Returns: None.
* Description: Copy the entire contents of console SRC onto console DEST."
  (console-blit src 0 0
                (console-get-width src) (console-get-height src)
                dest 0 0 1.0 1.0))


(defun transparency->fade (tran)
  (- 1.0 (/ tran 100.0)))


(defun window-transparency->fade (win)
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
* Returns: A real number between 0 and 1, representing a TCOD 'fade' value.
* Description: Given a window WIN, convert the value of its WINDOW-TRANSPARENCY
slot (0-100) to a FADE value (0-1) accepted by the TCOD library."
  (transparency->fade (window-transparency win)))



(defmethod prepare-window ((win <Window>))
  (cond
    ((window-framed? win)
     (cond
         ((eql win (car *window-stack*))
         (console-print-double-frame
          (window-console win) 0 0
          (window-width win) (window-height win)
          t :set (or (window-title win) nil)))
         (t
         (console-print-frame
          (window-console win) 0 0
          (window-width win) (window-height win)
          t :set (or (window-title win) nil))))

     (when (window-can-close? win)
       (console-set-char (window-console win) (1- (window-width win))
                         0 (char-code #\X)))

     (when (window-can-resize? win)
         (console-set-char (window-console win) (1- (window-width win))
                           (1- (window-height win)) 29)))
    (t
     (console-rect (window-console win) 0 0
                   (window-width win) (window-height win) t :set)))
  (when (window-draw-function win)
       (funcall (window-draw-function win) win))
  (when (window-children win)
      (dolist (child (window-children win))
        (when (or (window-raise-children-with-parent? win)
                  (not (window-hidden? child)))
          (prepare-window child)))))


(defmethod prepare-window :after ((win <Window>))
  (setf (window-last-update-time win) (tcod:sys-elapsed-milli)))


(defun prepare-windows-by-type (winclass)
  "* Arguments:
- WINCLASS: A symbol naming a subclass of {defclass dormouse:<Window>}.
* Returns: None.
* Description: Calls {defgeneric dormouse:prepare-window} for each existing
window object that inherits from WINCLASS.
* Examples:
;;; (prepare-windows-by-type '<Message-Window>)"
  (dolist (win *window-stack*)
    (when (typep win winclass)
      (prepare-window win))))


(defun top-window-at (x y &key (windows *window-stack*)
                      (override-modal? nil))
  "* Arguments:
- X, Y: Coordinates of a point on the screen (root console).
- WINDOWS: List of window objects to consider (default is to consider
all non-hidden windows).
- OVERRIDE-MODAL?: Boolean.
* Returns: A window object or nil.
* Description:
Return the window nearest the top of *WINDOW-STACK* which touches X,Y.
If OVERRIDE-MODAL? is true, then disregard whether a window is modal or
not in deciding which window to return. If this parameter is nil (default)
then whenever a modal window is at the top of WINDOW-STACK we can only
return that window from this function. If that window does not touch X,Y
then NIL is returned."
  (translate-negative-coordinates x y)
  (let ((top (car windows)))
    (cond
      ((and (not override-modal?)
            (modal? top))
       (if (window-touches-spot? top x y)
           top
           ;; else
           nil))
      (t
       (find-if #'(lambda (win) (and (window-touches-spot? win x y)
                                     (not (ghost-window? win))))
                windows)))))



(defun window-with-mouse-focus ()
  "Returns the topmost window under the mouse pointer. Most input events will
be sent to this window."
  (top-window-at *mouse-x* *mouse-y*))


(defun window-with-keyboard-focus ()
  (if (modal? (first *window-stack*))
      (first *window-stack*)
      (window-with-mouse-focus)))



(defun windows-at (x y)
  "* Arguments:
- X, Y: Coordinates of a point on the screen (root console).
* Returns: A list of window objects, or nil.
* Description:
Return a list of all non-hidden windows that overlie the point at X,Y."
  (translate-negative-coordinates x y)
  (remove-if-not #'(lambda (win) (window-touches-spot? win x y))
                 *window-stack*))


(defun window-brx (win)
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
* Returns: An X-coordinate.
* Description:
Return the X-coordinate of the bottom right corner of the window.
* See Also: {defun dormouse:window-bry}"
  (+ (window-tlx win) (1- (window-width win))))


(defun window-bry (win)
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
* Returns: A Y-coordinate.
* Description:
Return the Y-coordinate of the bottom right corner of the window.
* See Also: {defun dormouse:window-brx}"
  (+ (window-tly win) (1- (window-height win))))


(defmethod resize-window ((win <Window>) width height)
  "Change the dimensions of window WIN to WIDTH x HEIGHT."
  (untouch-windows win)
  (setf (window-console win) (console-new width height))
  (console-set-default-foreground (window-console win)
                                 (colour (window-foreground win)))
  (console-set-default-background (window-console win)
                                 (colour (window-background win)))
  (setf (window-width win) width)
  (setf (window-height win) height)
  (touch-windows win))



(defun move-mouse-to-window (win winx winy)
  "Move mouse pointer to WINX, WINY within the window WIN."
  (translate-negative-coordinates winx winy win)
  (multiple-value-bind (font-width font-height) (sys-get-char-size)
    (mouse-move (+ (floor font-width 2)
                   (* font-width (winx->rootx win winx)))
                (+ (floor font-height 2)
                   (* font-height (winy->rooty win winy))))))



(defmethod mouse-drag-window ((win <Window>) (rodent mouse))
  (let ((offsetx (- (mouse-cx rodent) (window-tlx win)))
        (offsety (- (mouse-cy rodent) (window-tly win)))
        (tlx 0) (tly 0)
        (width (window-width win))
        (height (window-height win))
        (root-width (console-get-width *root*))
        (root-height (console-get-height *root*)))
    ;; draw everything but the window
    (raise-window win)
    ;; Draw all windows but this one onto SCRATCH.
    ;; SCRATCH now represents ROOT "minus" WIN.
    (copy-windows-to-console (remove win *window-stack*) *scratch*)
    (console-flush)
    ;; Save part of root console covered by WIN
    (console-blit *scratch* (window-tlx win) (window-tly win)
                  width height
                  *temp-con* 0 0 1.0 1.0)
    (copy-console-to-console *scratch* *root*)
    (copy-window-to-console win *root*)
    (console-flush)
    (iterate
      (while (mouse-lbutton (setf rodent (mouse-get-status t))))
      ;; Update position of WIN based on mouse position
      (setf tlx (constrain (- (mouse-cx rodent) offsetx)
                           0 (- root-width width 1)))
      (setf tly (constrain (- (mouse-cy rodent) offsety)
                           0 (- root-height height 1)))
      ;;(format t "~A ~A ~A ~A~%" tlx tly width height)
      (unless (and (= tlx (window-tlx win)) (= tly (window-tly win)))
        ;; copy saved win to root  at WIN's old position (erasing WIN)
        (console-blit *temp-con* 0 0
                      width height
                      *root* (window-tlx win) (window-tly win) 1.0 1.0)
        ;; "move" WIN to the new position
        (move-window win tlx tly)
        ;; save the part of the root console which WIN covers
        (console-blit *scratch* tlx tly
                      width height
                      *temp-con* 0 0 1.0 1.0)
        ;; copy WIN to root
        (copy-window-to-console win *root*))
      ;; Refresh root console
      (console-flush))))


(defmethod mouse-resize-window ((win <Window>) (rodent mouse))
  (let ((brx 0) (bry 0))
    ;; draw everything but the window
    (raise-window win)
    (copy-windows-to-console (remove win *window-stack*) *scratch*)
    ;; Save part of root console covered by WIN
    (console-blit *scratch* (window-tlx win) (window-tly win)
                  (window-width win) (window-height win)
                  *temp-con* 0 0 1.0 1.0)
    (copy-console-to-console *scratch* *root*)
    (copy-window-to-console win *root*)
    (console-flush)
    (iterate
      (while (mouse-lbutton (setf rodent (mouse-get-status t))))
      ;; Update position of WIN based on mouse position.  Don't allow the mouse
      ;; to go above or to left of the top left corner of the window.
      (setf brx (constrain (mouse-cx rodent) (window-tlx win)
                           (1- (console-get-width *root*))))
      (setf bry (constrain (mouse-cy rodent) (window-tly win)
                           (1- (console-get-height *root*))))
      (unless (and (= brx (window-brx win)) (= bry (window-bry win)))
        ;; copy saved win to root  at WIN's old position (erasing WIN)
        (console-blit *temp-con* 0 0
                      (window-width win) (window-height win)
                      *root* (window-tlx win) (window-tly win) 1.0 1.0)
        ;; Resize WIN (might be smaller)
        (resize-window win (1+ (- brx (window-tlx win)))
                       (1+ (- bry (window-tly win))))
        (prepare-window win)
        ;; save the part of the root console which WIN now covers
        (console-blit *scratch* (window-tlx win) (window-tly win)
                      (window-width win) (window-height win)
                      *temp-con* 0 0 1.0 1.0)
        ;; copy WIN to root
        (copy-window-to-console win *root*))
      ;; Refresh root console
      (console-flush))))


(defmethod raise-window ((win <Window>) &key (redraw *auto-redraw*)
                         (simple-redraw? nil) &allow-other-keys)
  (setf *window-stack* (remove win *window-stack* :test #'equal))
  (setf *hidden-windows* (remove win *hidden-windows* :test #'equal))
  (setf (window-hidden? win) nil)
  (window-changed! win)
  (push win *window-stack*)
  (dirty-window win)
  (when (window-children win)
    (dolist (child  (window-children win))
      (when (or (window-raise-children-with-parent? win)
                (not (window-hidden? child)))
      (raise-window child :redraw redraw :simple-redraw? simple-redraw?))))
  (when redraw
    (if simple-redraw?
        (copy-window-to-console win *root*)
        ;; else
        (redraw-window-area win))))


;;; XXX new
(defmethod raise-window :before ((win <Window>) &key)
  (when (window-changed? win)
    (prepare-window win)))



(defmethod hide-window ((win <Window>) &key (redraw *auto-redraw*))
  (when redraw
    (redraw-window-area win :draw-window nil))
  (untouch-windows win)
  (setf *window-stack* (remove win *window-stack* :test #'equal))
  (if (and (window-raise-children-with-parent? win)
           (window-children win))
      (dolist (child (window-children win))
        (hide-window child)))
  (cond
    ((window-ephemeral? win)
     (destroy-window win))
    (t
     (setf (window-hidden? win) t)
     (pushnew win *hidden-windows* :test #'equal))))


(defun hide-all-windows ()
  (dolist (win (copy-list *window-stack*))
    (hide-window win)))


(defmethod send-to-window :before ((win <Window>) (event <Key-Event>))
  ;; Ctrl-Esc and Ctrl-F1 are defined here as universal "shut down the
  ;; gui loop" keys.
  (let ((k (gui-event-keypress event)))
    (when (key-pressed k)
      (when (and (member (key-vk k) (list :escape :f1))
                 (or (key-lctrl k)
                     (key-rctrl k))
                 (not (key-shift k))
                 (not (key-lalt k))
                 (not (key-ralt k)))
        (setf *exit-gui?* t)))))




(defmethod on-border? ((win <Window>) winx winy)
  (or (= winx 0)
      (= winx (1- (window-width win)))
      (= winy 0)
      (= winy (1- (window-height win)))))



(defmethod on-lower-window-border? ((win <Window>) winx winy)
  (and (= winy (1- (console-get-height (window-console win))))
       (> winx 0)
       (< winx (1- (console-get-width (window-console win))))))



(defmethod on-upper-window-border? ((win <Window>) winx winy)
  (and (= winy 0)
       (> winx 0)
       (< winx (1- (console-get-width (window-console win))))))



(defmethod window-draw-char-at ((win <Window>) (ch integer) winx winy
                                &key (background-flag :set)
                                (fg nil) (bg nil) (redraw *auto-redraw*))
  (console-draw-char-at (window-console win) ch winx winy
                        :background-flag background-flag
                        :fg fg :bg bg)
  (when redraw
    (redraw-all-at (winx->rootx win winx) (winy->rooty win winy))))
;;    (window-redraw-at win (winx->rootx winx) (winy->rooty winy))))



(defmethod console-draw-char-at (con (ch integer) winx winy
                             &key (background-flag :set)
                                (fg nil) (bg nil))
  (cond
    ((and fg bg)
     ;; New in libtcod 1.4.3
     (console-put-char-ex con winx winy ch (colour fg) (colour bg)))
    ((or fg bg)
     (console-set-char con winx winy ch)
     (cond
       (fg
        (console-set-char-foreground con winx winy (colour fg)))
       (bg
        (console-set-char-background con winx winy (colour bg) background-flag))))
    (t
     (console-put-char con winx winy ch background-flag)))
  ;; todo restore old values after printing
  )


(defmethod window-draw-char-at ((win <Window>) (ch character) winx winy
                                &key (background-flag :set) (fg nil) (bg nil)
                                (redraw *auto-redraw*))
  (window-draw-char-at win (char-code ch) winx winy
                       :background-flag background-flag :fg fg :bg bg
                       :redraw redraw))



(defun draw-string-aux (win winx winy str &key (dialog? nil)
                                               (background-flag :set)
                                               (align :left))
  (let ((len (coloured-string-length str))
        (xstr (make-coloured-string str :dialog? dialog? :win win)))
    (translate-negative-coordinates winx winy win)
    (console-print-ex (if dialog?
                          (dialog-console win)
                          (window-console win))
                      (case align
                        (:right (- winx len))
                        ((:centre :center :centered :centred)
                         (- winx (floor len 2)))
                        (otherwise winx))
                      winy
                      background-flag :left xstr)))



(defmethod draw-string-at ((win <Window>) str winx winy
                           &key (fg nil) (bg nil) (background-flag :set)
                                (align :left) (redraw *auto-redraw*))
  (declare (ignorable redraw))
  (if fg
      (console-set-default-foreground (window-console win) (colour fg)))
  (if bg
      (console-set-default-background (window-console win) (colour bg)))
  (draw-string-aux win winx winy str :background-flag background-flag
                   :align align)
  (if fg
      (console-set-default-foreground (window-console win)
                                      (colour (window-foreground win))))
  (if bg
      (console-set-default-background (window-console win)
                                      (colour (window-background win)))))


(defun format-at (win winx winy fmt &rest args)
  (draw-string-at win (apply #'format nil fmt args) winx winy))


(defun rootx->winx (win rootx)
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}.
- ROOTX: An X-coordinate on the screen (root console).
* Returns: Integer.
* Description: Given the screen X-coordinate ROOTX, return the X-coordinate
of the same screen point relative to the top left corner of the window WIN.
* Examples:
;;; (rootx->winx mywin 10)  ; if top left corner of mywin is at (8,8)
;;;                         ; then this returns 2
* See Also:
- {defun dormouse:rooty->winy}"
  (- rootx (window-tlx win)))

(defun rooty->winy (win rooty)
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}.
- ROOTY: A Y-coordinate on the screen (root console).
* Returns: Integer.
* Description: Given the screen Y-coordinate ROOTY, return the Y-coordinate
of the same screen point relative to the top left corner of the window WIN.
* Examples:
;;; (rooty->winy mywin 10)  ; if top left corner of mywin is at (8,8)
;;;                         ; then this returns 2
* See Also:
- {defun dormouse:rootx->winx}"
  (- rooty (window-tly win)))`<

(defun winx->rootx (win winx)
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}.
- WINX: An X-coordinate relative to the top left corner of WIN.
* Returns: Integer.
* Description: Given the X-coordinate WINX, which is relative to the top left
corner of WIN, return the absolute X-coordinate of the same screen point, i.e.
its console X-coordinate.
* Examples:
;;; (winx->rootx mywin 5)  ; if top left corner of mywin is at (8,8)
;;;                         ; then this returns 13
* See Also:
- {defun dormouse:winy->rooty}"
  (+ winx (window-tlx win)))

(defun winy->rooty (win winy)
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}.
- WINY: A Y-coordinate relative to the top left corner of WIN.
* Returns: Integer.
* Description: Given the Y-coordinate WINY, which is relative to the top left
corner of WIN, return the absolute Y-coordinate of the same screen point, i.e.
its console Y-coordinate.
* Examples:
;;; (winy->rooty mywin 5)  ; if top left corner of mywin is at (8,8)
;;;                         ; then this returns 13
* See Also:
- {defun dormouse:winx->rootx}"
  (+ winy (window-tly win)))



(defmethod window-redraw-at ((win <Window>) rootx rooty)
  (translate-negative-coordinates rootx rooty)
  (if (window-touches-spot? win rootx rooty)
      (console-blit (window-console win)
                    (rootx->winx win rootx)
                    (rooty->winy win rooty)
                    1 1 *root* rootx rooty
                    (window-transparency->fade win)
                    (window-transparency->fade win))))



(defmethod redraw-window-in-area (win1 rootx1 rooty1 rootx2 rooty2
                                  &key fade)
  "Redraw that portion of WIN which lies within the rectangle X1,Y1 -> X2,Y2
on the root console."
  (translate-negative-coordinates rootx1 rooty1)
  (translate-negative-coordinates rootx2 rooty2)
  (let* ((tlx (max (window-tlx win1) rootx1))
         (tly (max (window-tly win1) rooty1))
         (brx (min (window-brx win1) rootx2))
         (bry (min (window-bry win1) rooty2)))
    (console-fill-char *root*
                       #\space
                       tlx tly
                       (- brx (1- tlx)) (- bry (1- tly)))
    (console-blit (window-console win1)
                  (rootx->winx win1 tlx)
                  (rooty->winy win1 tly)
                  (- brx (1- tlx)) (- bry (1- tly))
                  *root* tlx tly
                  (or fade (window-transparency->fade win1))
                  (or fade (window-transparency->fade win1))
                  )))


(defmethod redraw-window-intersection ((win1 <Window>) (win2 <Window>)
                                       &key fade)
  (redraw-window-in-area win1 (window-tlx win2) (window-tly win2)
                         (window-brx win2) (window-bry win2)
                         :fade fade))


(defmethod redraw-intersecting-windows-below ((win <Window>))
  (dolist (w (reverse (windows-underlying win)))
    (redraw-window-intersection w win)))


(defmethod redraw-intersecting-windows-above ((win <Window>))
  (dolist (w (reverse (windows-overlying win)))
    (redraw-window-intersection w win)))


(defun fade-for-window (win)
  (let ((focus (window-with-mouse-focus)))
    (cond
      ((or (null (window-transparency-unfocussed win))
           (eql win focus))
       (window-transparency->fade win))
      ((and (eq *focus-fade-mode* :together)
            (not (typep focus '<Background-Window>)))
       (window-transparency->fade win))
      ((and (typep focus '<window>)
            (window-raise-children-with-parent? win)
            (or (find win (window-children focus))
                (find focus (window-children win))))
       (window-transparency->fade win))
      (t
       (transparency->fade
        (window-transparency-unfocussed win))))))



(defun redraw-window-area (win &key (draw-window t))
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
- DRAW-WINDOW: Boolean (default: T)
* Returns: None.
* Description: Force the area of the screen covered by WIN to be redrawn.
If DRAW-WINDOW is non-nil, also redraw WIN itself; otherwise just redraw
all the other windows underlying WIN."
  (unless draw-window
    (console-set-default-background *root* (colour :true-black))  ; needed?
    (console-rect *root* (window-tlx win) (window-tly win)
                  (window-width win) (window-height win) t :set))
  (when (and draw-window (window-children win)) ;
    (dolist (child (window-children win))
      (unless (window-hidden? child)
        (redraw-window-area child)) :draw-window t))
  (dolist (w (nreverse (windows-overlapping win :include-window? draw-window)))
    (redraw-window-intersection w win
                                :fade (fade-for-window w)))
  (dirty-window win))


(defun redraw-all-at (rootx rooty)
  "* Arguments:
- ROOTX, ROOTY: Coordinates of a point on the screen (root console).
* Returns: None.
* Description: Force all windows which touch the screen at ROOTX, ROOTY
to be redrawn."
  (dolist (w (reverse *window-stack*))
    (window-redraw-at w rootx rooty)))


(defmethod send-to-window ((win <Window>) (event <GUI-Mouse-Drag-Event>))
  (let ((topwin nil)
        (rodent nil))
    ;; draw everything but the window
    (raise-window win)
    (iterate
      (while (mouse-lbutton (setf rodent (mouse-get-status t))))
      (setf topwin (top-window-at (mouse-cx rodent) (mouse-cy rodent)))
      (when topwin
        (raise-window topwin :redraw t))
      (console-flush))
    ;; Stopped dragging.
    (when topwin
      (mouse-drag win topwin
                  (gui-event-winx event)
                  (gui-event-winy event)
                  (rootx->winx topwin (mouse-cx rodent))
                  (rooty->winy topwin (mouse-cy rodent))))))



;;; <<Modal Window>> ==========================================================


(defclass <Modal-Window> (<Window>)
  ((window-summon-mouse-on-raise? :initform nil
                                  :accessor window-summon-mouse-on-raise?
                                  :initarg :summon-mouse-on-raise?
                                  :documentation
                                  "Move the mouse pointer into the window area
when this window is raised?"))
  (:documentation "These monopolise the mouse and keyboard whenever they are
the topmost window. The user must cause the modal window to close before events
can be sent to any other windows."
  ))

(defun modal? (win)
  "* Arguments:
- WIN: an instance of [[<Window>]]
* Returns: Boolean.
* Description: Returns T if WIN inherits from [[<Modal-Window>]]."
    (typep win '<Modal-Window>))


(defmethod raise-window :after ((win <Modal-Window>) &key)
  (if (and (window-summon-mouse-on-raise? win)
           (or (< *mouse-x* (window-tlx win))
               (> *mouse-x* (window-brx win))
               (< *mouse-y* (window-tly win))
               (> *mouse-y* (window-bry win))))
      (move-mouse-to-window win -1 -1)))


(defmethod send-to-window :around ((win <Modal-Window>) (event <Key-Event>))
  (let ((k (gui-event-keypress event)))
    (when (key-pressed k)
      (case (key-vk k)
        (:escape
         (hide-window win)
         k)
        (otherwise
         (call-next-method))))))



;;; <<Alert Window>> ==========================================================


(defclass <Alert-Window> (<Modal-Window> <Log-Window>)
  ((window-title :initform "ALERT")
   (window-initial-text :accessor window-initial-text :initform nil
                        :initarg :text)
   (window-auto-redraw? :initform t))
  (:documentation "TODO: document"))


(defmethod initialize-instance :after ((win <Alert-Window>) &key)
  (when (window-initial-text win)
    (add-message win (window-initial-text win))))


;;; <<Yes/No Window>> =========================================================


(defclass <Yes/No-Window> (<Modal-Window> <Dialog-Window>)
  ((window-title :initform "Yes or No")
   (window-prompt :accessor window-prompt :initform "Yes or No" :initarg :prompt)
   (window-tlx :initform 30)
   (window-tly :initform 20)
   (window-width :initform 30)
   (window-height :initform 5)
   (window-auto-redraw? :initform t)
   (window-choice-function :accessor window-choice-function
                           :initform nil :initarg :choice-function))
  (:documentation   "Modal dialog window that waits for the user to click
on (yes) or (no) or to press Y or N."))



(defmethod prepare-window :after ((win <Yes/No-Window>))
  (when (window-prompt win)
    (draw-string-at win (window-prompt win) 1 1))
  (draw-string-at win
               (concatenate 'string
                            (button "yes" "Yes")
                            "   "
                            (button "no" "No"))
               1 2))


(defmethod send-to-window :around ((win <Yes/No-Window>)
                                   (event <GUI-Dialog-Event>))
  (let ((str (gui-event-string event)))
    (cond
      ((and (string= str "yes")
            (window-choice-function win))
       (hide-window win)
       (funcall (window-choice-function win) t))
      ((and (string= str "no")
            (window-choice-function win))
       (hide-window win)
       (funcall (window-choice-function win) nil))
      (t
       (call-next-method)))))


(defmethod send-to-window :around ((win <Yes/No-Window>) (event <Key-Event>))
  (let ((k (gui-event-keypress event)))
    (when (key-pressed k)
      (cond
        ((and (eql :char (key-vk k))
              (member (key-c k) '(#\Y #\y))
              (window-choice-function win))
         (hide-window win)
         (funcall (window-choice-function win) t)
         k)
        ((and (eql :char (key-vk k))
              (member (key-c k) '(#\N #\n))
              (window-choice-function win))
         (hide-window win)
         (funcall (window-choice-function win) nil)
         k)
        (t
         (call-next-method))))))


;;;===========================================================================
;;; (@> "Ghost-Window")
;;;===========================================================================

(defclass <Ghost-Window> (<Window>)
  ()
  (:documentation "Window that cannot be interacted with. Athough it may be
raised to the top of the window stack, it cannot receive any messages from the
mouse or keyboard. All such messages pass through to the window below it."))


(defun ghost-window? (win)
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
* Returns: Boolean.
* Description: Returns T if WIN inherits from
{defclass dormouse:<Ghost-Window>}."
    (typep win '<Ghost-Window>))


;;; <<Background window>> =====================================================


(defclass <Background-Window> (<Window>)
  ((window-can-resize? :initform nil)
   (window-can-drag? :initform nil)
   (window-framed? :initform nil)
   (window-transparency :initform +OPAQUE+)
   (window-fades-when-unfocussed? :initform nil))
  (:documentation "Window that always makes itself the lowest in the stack."))


(defmethod initialize-instance :after ((win <Background-Window>) &key)
  ;; Background windows always sink to the bottom of the stack.
  (setf *window-stack* (append (remove win *window-stack*) (list win))))


(defmethod raise-window ((win <Background-Window>) &key &allow-other-keys)
  (unless (find win *window-stack* :test #'equal)
    (push-end win *window-stack*)))



;;; <<Meter Window>> ==========================================================


(defclass <Meter-Window> (<Window>)
  ((window-meters :initform nil :initarg :meters
                  :accessor window-meters
                  :documentation "Alist of (STRING METER-TYPE FN).
STRING is a piece of text or NIL.
For now, METER-TYPE must be :bar-chart.
FN must be a function that takes no arguments and returns a number.
If the number is a float <= 1.0 it is treated as a fraction of 1.0.
Otherwise it is assumed to be a percentage (0--100)."))
  (:documentation "The window will display a vertical list of bar charts.
Each chart will be labelled with STRING.
Note that by default the bar charts will only be updated if the
window is told it has changed (eg via WINDOW-CHANGED?). To make the
bar charts automatically update every few seconds, set the slot
WINDOW-AUTO-REDRAW-TIME to an appropriate value in milliseconds."))

(defmethod prepare-window :after ((win <Meter-Window>))
  (let ((text-width (apply #'max 0
                           (mapcar #'length (mapcar #'first
                                                    (window-meters win))))))
    (iterate
      (for (text meter-type meter-fn) in (window-meters win))
      (assert (eql :bar-chart meter-type))
      (for row from 1)
      (for val = (funcall meter-fn))
      (if (>= row (window-height win)) (finish))
      (if text
          (draw-string-at win text (1+ text-width) row :align :right))
      (draw-string-at win
                      (bar-chart (if text (- (window-width win) text-width 3)
                                     (+ -2 (window-width win)))
                                 val (if (and (floatp val) (<= val 1.0))
                                         1.0 100)
                                 :bar-colour
                                 (window-highlight-foreground win)
                                 :empty-bar-colour
                                 (window-highlight-background win))
                      (+ text-width 2) row))))


;;; <<List Window>> ===========================================================


(defclass <List-Window> (<Window>)
  ((window-items :accessor window-items :initform nil :type list)
   (window-offset :accessor window-offset :initform 0
                  :initarg :offset :type integer)
   (window-cursor :accessor window-cursor :initform 0 :type integer))
  (:documentation
   "Window that displays a list of strings which can be scrolled.

Up and down arrows move the cursor up and down the list.

Page-up and page-down keys move the cursor a page at a time.

Home and end keys move the cursor to the first and last item in the list.

Left clicking on an item in the list, moves the cursor to that item.

Pressing a 'hotkey' associated with an item, moves the cursor to that item.

Left and right clicks on the lower border of the window move the display down or
up a page at a time.

The enter key selects the item under the cursor."))



(defstruct list-item
  "* Description: TODO"
  (str nil)
  (item nil)
  (hotkey nil))


(defmethod window-item-lines ((win <List-Window>) (item list-item))
  1)


(defmethod window-items-lines ((win <List-Window>))
  (apply #'+
         (mapcar #'(lambda (item) (window-item-lines win item))
                 (window-items win))))



(defmethod add-item ((win <List-Window>) item str &optional hotkey)
  (push-end (make-list-item :str str :item item :hotkey hotkey)
            (window-items win)))


(defmethod clear-items ((win <List-Window>))
  (setf (window-items win) nil)
  (move-cursor-to win 0)
  (setf (window-offset win) 0))



(defmethod window-item-at ((win <List-Window>) winx winy)
  (let ((offset (+ (window-offset win) (1- winy))))
    (cond
      ((on-border? win winx winy)
       nil)
      ((minusp offset)
       nil)
      ((> offset (window-items-lines win))
       nil)
      (t
       (nth offset (window-items win))))))



(defmethod window-item-at-cursor ((win <List-Window>))
  (nth (window-cursor win) (window-items win)))


(defmethod window-page-length ((win <List-Window>))
  (- (window-height win) 2))


(defmethod prepare-window :after ((win <List-Window>))
  (let* ((pagelen (window-page-length win))
         (offset 0))
    ;; Configure window
    (if (>= pagelen (window-items-lines win))
        (setf (window-offset win) 0))
    (constrain! (window-cursor win) 0 (window-items-lines win))
    (if (< (window-cursor win) (window-offset win))
        (setf (window-offset win) (window-cursor win)))
    (if (>= (window-cursor win) (+ (window-offset win) pagelen))
        (setf (window-offset win) (- (window-cursor win) (1- pagelen))))
    (setf offset (window-offset win))
    ;; Draw window
    (loop for i from offset to (+ offset (1- pagelen))
       when (and (<= 0 i (1- (length (window-items win))))
                 (nth i (window-items win)))
       do (draw-item-at win (nth i (window-items win))
                        1 (1+ (- i offset))
                        (= i (window-cursor win))))))



(defmethod draw-item-at ((win <List-Window>) (item list-item) winx winy cursor?)
  (let ((pagewidth (- (window-width win) 2)))
    (draw-string-at win
                    (format nil "~vA"
                            pagewidth
                            (left-trim-coloured-string
                             (format nil "~A" (list-item-str item))
                             pagewidth))
                    winx winy
                    :bg (if cursor?
                            (invert-colour
                             (console-get-char-background
                              (window-console win) 0 0))
                            nil))))



(defmethod send-to-window ((win <List-Window>) (event <Mouse-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (mouse gui-event-mouse-state)) event
    (let ((left (mouse-lbutton mouse))
          (right (mouse-rbutton mouse))
          (wheel-up (mouse-wheel-up mouse))
          (wheel-down (mouse-wheel-down mouse)))
      (cond
        ((and (on-lower-window-border? win winx winy)
              (or left right))
         (send-key-to-window win (make-key :vk
                                           (cond
                                             (left :pagedown)
                                             (right :pageup)))
                             winx winy))
        ((and (not (on-border? win winx winy))
              wheel-up)
         (send-key-to-window win (make-key :vk :up) winx winy))
        ((and (not (on-border? win winx winy))
              wheel-down)
         (send-key-to-window win (make-key :vk :down) winx winy))
        ((and left
              (not (on-border? win winx winy)))
         (let ((newc (- (1- winy) (window-offset win))))
           (if (<= newc (window-items-lines win))
               (move-cursor-to win newc)))
         (prepare-window win)
         (redraw-window-area win))
        (t
         (call-next-method))))))




(defmethod move-cursor-to ((win <List-Window>) (cursor integer))
  (let ((oldcursor (window-cursor win)))
    (setf (window-cursor win)
          (constrain cursor 0 (max 0 (1- (length (window-items win))))))
    (when (and (/= oldcursor (window-cursor win))
               (window-item-at-cursor win))
      (cursor-moved-to-item win (window-item-at-cursor win)))))


(defmethod cursor-moved-to-item ((win <List-Window>) (item t))
  nil)



(defmethod move-cursor-by ((win <List-Window>) (increment integer))
  (move-cursor-to win (+ (window-cursor win) increment)))



(defmethod send-to-window :around ((win <List-Window>) (event <Mouse-Hover-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)) event
    (cond
      ((null (gui-event-focus event))
       (setf (gui-event-focus event) (window-item-at win winx winy))))
    (call-next-method win event)))


(defmethod send-to-window ((win <List-Window>) (event <Mouse-Double-Click-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)) event
    (unless (on-border? win winx winy)
      (move-cursor-to win (+ (window-offset win) (1- winy)))
      (send-to-window win (make-instance
                           '<GUI-Select-Event>
                           :focus (list-item-item (window-item-at-cursor win))
                           :winx winx :winy winy)))))


(defmethod send-to-window :around ((win <List-Window>) (event <Key-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (k gui-event-keypress)) event
    (when (key-pressed k)
      (let ((pagelen (- (window-height win) 2))
            (num-items (length (window-items win))))
        (case (key-vk k)
          (:up
           (move-cursor-by win -1) ;;(decf (window-cursor win))
           (if (< (window-cursor win) (window-offset win))
               (decf (window-offset win))))
          (:down
           (move-cursor-by win 1) ;;(incf (window-cursor win))
           (if (>= (window-cursor win) (+ (window-offset win) pagelen))
               (incf (window-offset win))))
          (:pageup
           (decf (window-offset win) pagelen)
           (move-cursor-by win (- pagelen))) ;;(decf (window-cursor win) pagelen))
          (:pagedown
           (incf (window-offset win) pagelen)
           (move-cursor-by win pagelen)) ;;(incf (window-cursor win) pagelen))
          (:home
           (setf (window-offset win) 0)
           (move-cursor-to win 0)) ;;(setf (window-cursor win) 0))
          (:end
           (setf (window-offset win) (- num-items pagelen))
           (move-cursor-to-end win)) ;; (setf (window-cursor win) (1- num-items)))
          (:enter
           (send-to-window win (make-instance
                                '<GUI-Select-Event>
                                :focus (list-item-item (window-item-at-cursor win))
                                :winx winx :winy winy)))
          (otherwise
           (let ((matching (find-if #'(lambda (item)
                                        (and (key-p (list-item-hotkey item))
                                             (same-keys? (list-item-hotkey item) k)))
                            (window-items win))))
             (cond
               (matching
                   (move-cursor-to win (position matching (window-items win))))
               (t
                (return-from send-to-window (call-next-method)))))))
        ;;(constrain! (window-cursor win) 0 (max 0 (1- num-items)))
        (constrain! (window-offset win)
                    (1+ (- (window-cursor win) pagelen))
                    (window-cursor win))
        (constrain! (window-offset win) 0 (max 0 (- num-items pagelen)))
        (prepare-window win)
        (redraw-window-area win)
        k))))


(defmethod move-cursor-to-end ((win <List-Window>))
  (let ((num-items (length (window-items win)))
        (pagelen (- (window-height win) 2)))
    (setf (window-offset win) (- num-items pagelen))
    (move-cursor-to win (1- num-items))
    ;;(constrain! (window-cursor win) 0 (max 0 (1- num-items)))
    (constrain! (window-offset win)
                (1+ (- (window-cursor win) pagelen))
                (window-cursor win))
    (constrain! (window-offset win) 0 (max 0 (- num-items pagelen)))))



;;; <<Filtered Window>> =======================================================


(defclass <Filtered-Window> (<List-Window>)
  ((filter-string :accessor filter-string :initform nil)
  (window-all-items :accessor window-all-items :initform nil)
  (window-auto-redraw? :initform t))
  (:documentation
   "List window which can selectively display only those items whose strings
contain the substring FILTER-STRING.  The active FILTER-STRING is displayed in
the lower border of the window.

Typing normal characters in the window will add those characters to the end of
FILTER-STRING.

Pressing BACKSPACE will erase a character from the end of FILTER-STRING.

Pressing DELETE will erase all characters in FILTER-STRING."))



(defmethod clear-filter ((win <Filtered-Window>))
  (setf (filter-string win) nil))


(defmethod clear-items :after ((win <Filtered-Window>))
  (setf (window-all-items win) nil))



(defmethod add-item :around ((win <Filtered-Window>) itemdata str &optional k)
  (let ((item (make-list-item :str str :item itemdata :hotkey k)))
    (push-end item (window-all-items win))
    (if (item-matches-filter-string? win item)
        (call-next-method))))



(defmethod item-matches-filter-string? ((win <Filtered-Window>) item)
  (or (null (filter-string win))
      (search (string-upcase (filter-string win))
              (string-upcase (list-item-str item)))))




(defmethod prepare-window :after ((win <Filtered-Window>))
  (draw-string-at win
                  ;; Uppercase version of filter-string, padded by *
                  (format nil "~A~:@([~V,,,'*A]~)~A"
                          (if (filter-string win)
                              (format nil "{fg:~A,bg:~A}"
                                      (window-highlight-foreground win)
                                      (window-highlight-background win))
                              "")
                          (- (window-width win) 4)
                          (or (filter-string win) "")
                          (if (filter-string win)
                              "{/} " ""))
                  1 (1- (window-height win))))




(defmethod send-to-window :after ((win <Filtered-Window>) (event <Key-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (k gui-event-keypress)) event
    (let ((added? nil))
      (when (key-pressed k)
        (cond
          ((and (eql (key-vk k) :char)
                (graphic-char-p (key-c k)))
           ;; add char to filter-string
           (setf (filter-string win)
                 (concatenate 'string (filter-string win) (list (key-c k))))
           (setf added? t))
          ((eql (key-vk k) :backspace)
           ;; remove one char from end of filter-string
           (if (> (length (filter-string win)) 0)
               (setf (filter-string win)
;; STRLEFT
                     (subseq (filter-string win) 0
                             (min (length (filter-string win))
                                  (1- (length (filter-string win))))))))
          ((eql (key-vk k) :delete)
           ;; clear filter-string
           (setf (filter-string win) nil))
          (t
           (return-from send-to-window nil)))
        ;; Still here means we changed filter-string.
        ;; Therefore need to recalculate lines.
        (cond
          ((and (filter-string win)
                (string> (filter-string win) ""))
           (setf (window-items win)
                 (iterate
                   (for item in (if added?
                                    (window-items win)
                                    (window-all-items win)))
                   (if (item-matches-filter-string? win item)
                       (collect item)
                       ;; else
                       nil))))
          (t
           (setf (window-items win) (copy-list (window-all-items win)))))
        (move-cursor-to win 0)
        (window-changed! win)))))





;;; <<Menu Window>> ===========================================================


(defclass <Menu-Window> (<List-Window>)
  ((window-framed? :initform nil)
   (window-can-resize? :initform nil)
   (window-can-drag? :initform nil)
   (window-menu-items :initform nil :accessor window-menu-items
                      :initarg :items
                      :documentation
                      "A list of forms, each of which takes the
form (VALUE :text TEXT :key KEY :handler HANDLER-FUNCTION).
VALUE is some constant value used to identify this item, such as a
keyword. TEXT is the text that will be displayed in the menu for this
item. KEY is a character, which can be pressed to quickly select this
item. HANDLER-FUNCTION is a function taking one argument -- the window --
which will be called if this item is selected."))
  (:documentation
   "List window that cannot be scrolled or resized. Clicking on an item
closes the menu window and returns the item. Hovering the mouse over an item
moves the cursor to that item."))


(defmethod initialize-instance :after ((win <Menu-Window>) &key)
  (when (window-menu-items win)
    (iterate
      (for item in (window-menu-items win))
      (destructuring-bind (value &key text key handler) item
        (print (list value text key handler))
        (add-item win value text (if (characterp key)
                                     (tcod-gui::make-simple-key key)))))))



(defmethod send-to-window :before ((win <Menu-Window>) (event <Mouse-Hover-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)) event
    (unless (on-border? win winx winy)
      (move-cursor-to win (+ (window-offset win) (1- winy)))
      (prepare-window win)
      (redraw-window-area win))))



(defmethod send-to-window ((win <Menu-Window>) (event <Mouse-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (mouse gui-event-mouse-state)) event
    (cond
      ((mouse-rbutton mouse)
       (hide-window win))
      ((and (mouse-lbutton mouse)
            (not (on-border? win winx winy)))
       (move-cursor-to win (+ (window-offset win) (1- winy)))
       (when (list-item-p (window-item-at-cursor win))
         ;; (warn "Menu - selected item ~S"
         ;;            (list-item-item
         ;;             (window-item-at-cursor win)))
         (hide-window win)
         (send-to-window win (make-instance
                              '<GUI-Select-Event>
                              :focus (list-item-item (window-item-at-cursor win))
                              :winx winx :winy winy)))))))


(defmethod send-to-window :after ((win <Menu-Window>) (event <Key-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (k gui-event-keypress)) event
    (when (and (key-pressed k)
               (window-item-at-cursor win)
               (list-item-hotkey (window-item-at-cursor win))
               (same-keys? k (list-item-hotkey (window-item-at-cursor win))))
      (hide-window win)
      (send-to-window win (make-instance
                           '<GUI-Select-Event>
                           :focus (list-item-item (window-item-at-cursor win))
                           :winx winx :winy winy)))))


(defmethod send-to-window ((win <Menu-Window>) (event <GUI-Select-Event>))
  (with-slots ((focus gui-event-focus)) event
    (let ((item (assoc focus (window-menu-items win))))
      (cond
        ((and item
              (getf (cdr item) :handler))
         (funcall (getf (cdr item) :handler) win))
        (t
         (call-next-method))))))



;;; <<Window with Context Menu>> ==============================================


(defparameter +DEFAULT-CONTEXT-MENU-INITARGS+
  '(:tlx 0 :tly 0 :width 20 :height 8
    :title "Context"
    :foreground :light-blue
    :background :dark-grey))


(defclass <Window-With-Context-Menu> (<Window>)
  ((window-raise-children-with-parent? :initform nil)
   (context-menu :accessor context-menu :initform nil
                 :documentation "Context menu window associated with this
window.")
   (context-menu-class :accessor context-menu-class :initform '<Context-Menu>)
   (context-menu-initargs :initform +DEFAULT-CONTEXT-MENU-INITARGS+
                          :accessor context-menu-initargs))
  (:documentation
   "Window where right-clicking brings up a menu of commands that the user
can choose to apply to the item that was clicked on."))


(defclass <Context-Menu> (<Menu-Window>)
  (;;(window-transparency :initform +OPAQUE+)
   (window-width :initform 15)
   (window-height :initform 8)
   (context-item :accessor context-item :initform nil
                 :documentation "Item (eg thing) which is the 'context' of the
current window activation.")))


(defmethod make-context-menu ((win <Window-With-Context-Menu>))
  (setf (context-menu win)
        (apply #'make-instance (context-menu-class win)
               :hidden? t (context-menu-initargs win)))
  (push (context-menu win) (window-children win)))


(defmethod initialize-instance :after ((win <Window-With-Context-Menu>)
                                       &key)
  (make-context-menu win))



(defmethod destroy-window :before ((win <Context-Menu>))
  (let ((parent (window-parent win)))
    (when (and parent
               (eql (context-menu parent) win))
      (setf (context-menu parent) nil)
      (setf (window-children parent)
            (remove win (window-children parent))))))



(defmethod raise-window :before ((win <Window-With-Context-Menu>)
                                 &key redraw &allow-other-keys)
  (declare (ignore redraw))
  (unless (or (null (context-menu win))
              (window-hidden? (context-menu win)))
    (hide-window (context-menu win))))


(defmethod hide-window :before ((win <Window-With-Context-Menu>)
                                 &key redraw &allow-other-keys)
  (declare (ignore redraw))
  (unless (or (null (context-menu win))
              (window-hidden? (context-menu win)))
    (hide-window (context-menu win))))



(defmethod send-to-window :before ((win <Window-With-Context-Menu>)
                                   (event <Mouse-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (mouse gui-event-mouse-state)) event
    (when (mouse-rbutton-pressed mouse)
    (setf (context-item (context-menu win))
          (get-context-at win winx winy)))))



(defmethod send-to-window :after ((win <Window-With-Context-Menu>)
                                  (event <Mouse-Event>))
  (with-slots ((mouse gui-event-mouse-state)) event
    (when (mouse-rbutton-pressed mouse)
      (cond
        ((window-hidden? (context-menu win))
         (move-window-beside-mouse (context-menu win))
         (prepare-window (context-menu win))
         (raise-window (context-menu win) :redraw t))
        (t
         (hide-window (context-menu win) :redraw t))))))




(defmethod get-context-at ((win <List-Window>) winx winy)
  (let ((item (window-item-at win winx winy)))
    (cond
      (item
       (list-item-item item))
      (t
       nil))))



(defmethod prepare-window :around ((win <Context-Menu>))
  (let ((cursor (window-cursor win))
        (items (get-menu-items-for-context (window-parent win)
                                           (context-item win))))
    (clear-items win)
    (cond
      ((null items)
       (resize-window win (window-width win) 3)
       (add-item win nil "(nothing)"))
      (t
       (resize-window win (window-width win) (min (- (screen-height) 2)
                                                  (+ (length items) 2)))
       (loop for item-desc-binding in items do
            (destructuring-bind (item desc &optional binding) item-desc-binding
              (add-item win item
                        (format nil "~20A{yellow}~A{/}"
                                desc
                                (if binding
                                    (key->string (binding->key binding))
                                    ""))
                        (if binding (binding->key binding)))))))
    (move-cursor-to win (min (length items) cursor))
    (call-next-method)))



(defmethod send-to-window :after ((win <Context-Menu>) (event <GUI-Select-Event>))
  (command-from-context-menu (window-parent win) (gui-event-focus event)
                             (context-item win)))


(defmethod get-menu-items-for-context ((win <Window-With-Context-Menu>)
                                       context-item)
  (declare (ignore context-item))
  nil)

(defmethod command-from-context-menu ((win <Window-With-Context-Menu>)
                                      command context-item)
  (declare (ignore command context-item))
  nil)


;;; <<Log Window>> ============================================================


(defclass <Log-Window> (<List-Window>)
  ((window-can-resize? :initform t)
   (window-can-drag? :initform t)
   (window-show-tail-by-default? :accessor window-show-tail-by-default?
                                 :initform nil
                                 :documentation "If true, show the BOTTOM of
the list of messages rather than returning to the top, when the window is
refreshed.")
   (window-max-messages :accessor window-max-messages :initform 100)
   (window-raw-messages :accessor window-raw-messages :initform (list)))
  (:documentation
     "A kind of list-window where messages are appended to the end of the list."))


(defun wrap-coloured-text (text &key width)
  "TODO document"
  (word-wrap text :width width :respect-newlines t
             :respect-hyphens t
             :exclude-start-char #\{
             :exclude-end-char #\}))


(defmethod wrap-items ((win <Log-Window>))
  (let* ((pagewidth (- (window-width win) 2))
         (wrapped (apply #'append
                         (mapcar #'(lambda (msg)
                                     (wrap-coloured-text msg :width pagewidth))
                                 (window-raw-messages win)))))
    (setf (window-items win)
          (mapcar #'(lambda (str) (make-list-item :str str :item nil :hotkey nil))
                  wrapped))))


(defmethod prepare-window :before ((win <Log-Window>))
  (wrap-items win)
  (if (window-show-tail-by-default? win)
      (move-cursor-to-end win)))



(defmethod draw-item-at ((win <Log-Window>) (item list-item)
                         winx winy (cursor? (eql t)))
  (draw-item-at win item winx winy nil))



(defmethod send-to-window :around ((win <Log-Window>) (event <Key-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (k gui-event-keypress)) event
    (when (key-pressed k)
      (let ((pagelen (- (window-height win) 2))
            (num-items (length (window-items win))))
        (case (key-vk k)
          (:up
           (decf (window-offset win)))
          (:down
           (incf (window-offset win)))
          (otherwise
           (return-from send-to-window (call-next-method))))
        ;; (warn "offset = ~D, cursor = ~D, num-items = ~D"
        ;;            (window-offset win) (window-cursor win) num-items)
        (constrain! (window-offset win) 0 (max 0 (- num-items pagelen)))
        (move-cursor-to win (window-offset win))
        ;;(constrain! (window-cursor win) 0 (max 0 (1- num-items)))
        ;; (warn "Now offset = ~D, cursor = ~D, num-items = ~D"
        ;;            (window-offset win) (window-cursor win) num-items)
        (prepare-window win)
        (redraw-window-area win))
      k)))



(defmethod add-message ((win <Log-Window>) fmt &rest args)
  (when fmt
    (let ((msg (apply #'format nil fmt args)))
      (push-end msg (window-raw-messages win))
      (iterate
        (while (> (length (window-raw-messages win)) (window-max-messages win)))
        (pop (window-raw-messages win)))
      (if (> (length msg) (- (window-width win) 2))
          (wrap-items win)
          ;; else
          (add-item win msg msg nil))
      (move-cursor-to-end win)
      (window-changed! win))))


(defmethod add-message-and-redraw ((win <Log-Window>) fmt &rest args)
  (apply #'add-message win fmt args)
  (prepare-window win)
  (redraw-window-area win)
  (console-flush))


(defmethod fill-to-end-of-window ((win <Log-Window>))
  (let ((hgt (+ -2 (window-height win)))
        (num-items (length (window-items win))))
    (when (< num-items hgt)
      (dotimes (i (- hgt num-items))
        (add-item win "" "" nil))
      (move-cursor-to-end win))))



;;;     (setf (window-offset win) (- (length (window-items win))
;;;                              (- (window-height win) 2)))
;;;     (setf (window-cursor win) (1- (length (window-items win))))
;;;     (constrain! (window-cursor win) 0 (max 0 (1- (length (window-items win)))))
;;;     (constrain! (window-offset win) 0 (max 0 (- (length (window-items win))
;;;                                             (- (window-height win) 2))))
;;;     (prepare-window win)
;;;     (redraw-window-area win)))


(defmethod clear-messages ((win <Log-Window>))
  (setf (window-raw-messages win) nil)
  (setf (window-items win) nil)
  (move-cursor-to win 0))

(defun bottom-message (fmt &rest args)
  "* Arguments:

- FMT: String, which may contain formatting directives for the Common
Lisp function FORMAT
 (see {http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm}.)
- ARGS: Zero or more arguments matching the formatting directives
in FMT.

* Returns: None.

* Description: Prints the string returned by (APPLY #'FORMAT NIL ARGS)
onto the bottom line of the root console.

* Example:
;;; (bottom-message \"Mouse position: (~D, ~D)\" *mouse-x* *mouse-y*)"
  (declare (string fmt))
  (console-rect *root* 0 (1- (console-get-height *root*))
                (console-get-width *root*) 1 t :set)
  (console-print *root* 0 (1- (console-get-height *root*))
                 (format nil "~vA" (console-get-width *root*)
                         (apply #'format nil fmt args))))


;;; <<Pager Window>> ==========================================================


(defclass <Pager-Window> (<Log-Window>)
  ())


(defmethod add-browser-line ((win <Pager-Window>) line)
  (typecase line
    (string  (add-message win line))
    (list
     (destructuring-bind (item desc) line
       (declare (ignore item))
       (add-message win desc)))))


(defmethod clear-browser-lines ((win <Pager-Window>))
    (clear-messages win))


(defmethod send-to-window :around ((win <Pager-Window>) (event <Key-Event>))
  (with-slots ((k gui-event-keypress)) event
    (when (key-pressed k)
      (case (key-vk k)
        ((:enter :kpenter)
         nil)
        (:escape
         (hide-window win))
        (otherwise
         (call-next-method))))))


;;; <<Hypertext window>> ======================================================


(defclass <Hypertext-Window> (<Dialog-Window> <Pager-Window>)
  ((hypertext-lookup-function
    :initform nil
    :initarg :lookup-function
    :accessor hypertext-lookup-function
    :documentation "Function that takes a single string as its argument.
Returns the text of the hypertext database entry whose title is the same
as the string. Returns nil if the topic does not exist.")
   (hyperlink-foreground-colour
    :initarg :hyperlink-fg
    :writer (setf hyperlink-foreground-colour))
   (hypertext-start-topic :initform "Start" :initarg :start-topic
                          :accessor hypertext-start-topic)
   (hypertext-history :initform nil :accessor hypertext-history))
  (:documentation
   "Press BACKSPACE or LEFT arrow to go back to the last topic.
Press HOME to go back to the 'root' or 'start' topic."))


(defmethod hyperlink-foreground-colour ((win <Hypertext-Window>))
  (if (slot-boundp win 'hyperlink-foreground-colour)
      (slot-value win 'hyperlink-foreground-colour)
      (hyperlink-foreground-colour *window-theme*)))


(defmethod hypertext-current-topic ((win <Hypertext-Window>))
  (car (hypertext-history win)))


(defmethod window-title ((win <Hypertext-Window>))
  (let ((topic (car (hypertext-history win))))
    (format nil "~A: ~:(~A~)"
            (slot-value win 'window-title)
            topic)))


(defun mark-hyperlinks-in-string (str &key (fg :blue))
  (cl-ppcre:regex-replace-all "\\[(.+?)\\]" str
                              (format nil "{fg:~A,click:\\1}\\1{/}" fg)
                              :preserve-case t))


(defun word-unwrap (str &key (no-wrap-prefix "|"))
  "* Description
Given a string, gets rid of line breaks within 'paragraphs' in the string.
Paragraphs are defined as groups of lines separated by blank lines.
If a line begins with the string NO-WRAP-PREFIX, it is left as is."
  (with-input-from-string (s str)
    (let ((lines nil))
      (iterate
        (with accum = nil)
        (for line = (read-line s nil :eof))
        (while (not (eq :eof line)))
        (print line)
        (cond
          ((zerop (length line))
           (when accum
             (push accum lines)
             (setf accum nil))
           (push line lines))
          ((eq 0 (search no-wrap-prefix line))
           (when accum
             (push accum lines)
             (setf accum nil))
           (push line lines))
          (t
           (setf accum (concatenate
                        'string (or accum "") line " "))))
        (finally
         (if accum (push accum lines))))
      (apply #'concatenate 'string
             (iterate
               (for line in (reverse lines))
               (collect (format nil "~A~%" line)))))))


(defmethod open-hypertext-topic ((win <Hypertext-Window>) topic)
  "If TEXT takes the form (= NEWTOPIC), then we are redirected
to NEWTOPIC.
If TEXT is a function, it will be called with no arguments, and
should return a string which will be used as the text of the topic."
  (let ((text (funcall (hypertext-lookup-function win) topic)))
    (cond
      ((null topic)
       nil)
      ((null text)
       nil)
      ((and (listp text)
            (eql (car text) '=)
            (stringp (second text)))
       (open-hypertext-topic win (second text)))
      ((or (stringp text)
           (functionp text))
       (unless (equal topic (hypertext-current-topic win))
         (push topic (hypertext-history win)))
       (clear-messages win)
       (add-message-and-redraw
        win (mark-hyperlinks-in-string
             (word-unwrap
              (if (functionp text) (funcall text) text))))))))


(defmethod initialize-instance :after ((win <Hypertext-Window>) &key)
  (unless (hypertext-current-topic win)
    (open-hypertext-topic win (hypertext-start-topic win))))


(defun make-autolinks-in-hypertext-database
    (db &key (fg (hyperlink-foreground-colour *window-theme*)))
  "* Arguments
- DB :: A hashtable of topic titles keyed to text strings.
* Returns
Nil.
* Description
Iterates through every topic in the hashtable DB. Within the text of each
topic, 'marks up' any unmarked occurrence of the title of another topic
in the same database. Finally, converts all marked hyperlinks to
the internal format recognised by the GUI."
  (iterate
    (with topics = (sort (remove-if-not #'stringp (all-hashtable-keys db))
                         #'> :key #'length))
    (for (topic text) in-hashtable db)
    (unless (stringp text) (next-iteration))
    (iterate
      (with matches = nil)
      (for topic2 in topics)
      (if (equal topic2 topic) (next-iteration))
      (if (some (lambda (match) (search topic2 match)) matches)
          (next-iteration))
      (multiple-value-bind (newtext matched?)
          (cl-ppcre:regex-replace-all
           ;; The (?i) turns case sensitivity off
           (concatenate 'string "(?i)([^[}])(" topic2 ")([^]{])")
           text (format nil "\\1{fg:~A,click:\\2}\\2{/}\\3" fg)
           :preserve-case t)
        (setf text newtext)
        (if matched? (push topic2 matches))))
    (setf text (mark-hyperlinks-in-string text :fg fg))
    (setf (gethash topic db) text)))


(defmethod send-to-window ((win <Hypertext-Window>) (event <GUI-Dialog-Event>))
  (let ((topic (gui-event-string event)))
    (open-hypertext-topic win topic)))


(defmethod send-to-window :around ((win <Hypertext-Window>)
                                   (event <Key-Event>))
  (let ((k (gui-event-keypress event)))
    (when (key-pressed k)
      (print k)
      (cond
        ((and (hypertext-history win)
              (find (key-vk k) '(:backspace :left :kp4)))
         (pop (hypertext-history win))
         (open-hypertext-topic win (hypertext-current-topic win))
         k)
        ((eql (key-vk k) :home)
         (open-hypertext-topic win (hypertext-start-topic win))
         k)
        (t
         (call-next-method))))))



;;; <<Terminal Window>> =======================================================


(defclass <Terminal-Window> (<Log-Window>)
  ((window-show-tail-by-default? :initform t)
   (window-prompt :initform "> " :initarg :prompt :accessor window-prompt)
   ;; Colours for the prompt, and the input text
   (window-prompt-foreground :initarg :prompt-fg
                             :writer (setf window-prompt-foreground))
   (window-prompt-background :initarg :prompt-bg
                             :writer (setf window-prompt-background))
   (window-input-foreground :initarg :input-fg
                             :writer (setf window-input-foreground))
   (window-input-background :initarg :input-bg
                             :writer (setf window-input-background))
   (window-echo-input? :initform t :initarg :echo-input?
                       :accessor window-echo-input?
                       :documentation "After enter is pressed, should the
input be 'printed' in the window?")
   (window-input-active? :initform t :type (member t nil :transient)
                         :accessor window-input-active?
                         :documentation "")
   (window-input-string :initform nil :accessor window-input-string)
   (window-input-rendered :initform nil
                          :documentation "List of strings, updated whenever
the current 'input string' changes. Internal slot.")
   (window-input-history :initform (list "") :accessor window-input-history
                         :documentation "List of previous input strings.")
   (window-input-history-position :initform 0
                                  :accessor window-input-history-position)
   (window-input-cursor :initform 0 :accessor window-input-cursor)
   (window-input-function :initform (lambda (win str)
                                      (declare (ignore win str))
                                      nil)
                          :accessor window-input-function
                          :initarg :input-function
                          :documentation
                          "Function which takes two arguments, WIN and STR.
WIN is the window object, STR is the string that has been entered at the
prompt. Called when a line of input is entered in the window.")))


(defmethod window-prompt-foreground ((win <Terminal-Window>))
  (if (slot-boundp win 'window-prompt-foreground)
      (slot-value win 'window-prompt-foreground)
      (window-prompt-foreground *window-theme*)))

(defmethod window-prompt-background ((win <Terminal-Window>))
  (if (slot-boundp win 'window-prompt-background)
      (slot-value win 'window-prompt-background)
      (window-prompt-background *window-theme*)))

(defmethod window-input-foreground ((win <Terminal-Window>))
  (if (slot-boundp win 'window-input-foreground)
      (slot-value win 'window-input-foreground)
      (window-input-foreground *window-theme*)))

(defmethod window-input-background ((win <Terminal-Window>))
  (if (slot-boundp win 'window-input-background)
      (slot-value win 'window-input-background)
      (window-input-background *window-theme*)))


(defmethod initialize-instance :after ((win <Terminal-Window>) &key)
  )
  ;; (unless (window-prompt-foreground win)
  ;;   (setf (window-prompt-foreground win) (window-foreground win)))
  ;; (unless (window-prompt-background win)
  ;;   (setf (window-prompt-background win) (window-background win)))
  ;; (unless (window-input-foreground win)
  ;;   (setf (window-input-foreground win) (window-foreground win)))
  ;; (unless (window-input-background win)
  ;;   (setf (window-input-background win) (window-background win))))


(defmethod window-page-length ((win <Terminal-Window>))
  (if (window-input-active? win)
      (- (window-height win)
         (max 1 (length (slot-value win 'window-input-rendered))))
      (call-next-method)))


(defmethod prepare-window :after ((win <Terminal-Window>))
  (when (window-input-active? win)
    (render-input-string win)
    (iterate
      (with numlines = (length (slot-value win 'window-input-rendered)))
      (for i from 0 to numlines)
      (for line = (nth i (slot-value win 'window-input-rendered)))
      (when (zerop i)
        (draw-string-at win (colourise (window-prompt win)
                                       (window-prompt-foreground win)
                                       (window-prompt-background win))
                        1 -2))
      (when line
        (draw-string-at win (colourise line (window-input-foreground win)
                                       (window-input-background win))
                        (if (zerop i) (+ (length (window-prompt win)) 1) 1)
                        (- i 2))))))


(defmethod (setf window-input-string) :after (value (win <Terminal-Window>))
  (render-input-string win))


(defmethod render-input-string ((win <Terminal-Window>))
  (let ((str0 (if (window-input-string win)
                  (copy-seq (window-input-string win)))))
    (cond
      ((>= (window-input-cursor win) (length str0))
       (setf str0 (concatenate 'string str0 (string (code-char 1)))))
      ((and str0
            (plusp (length str0)))
       (setf (char str0 (window-input-cursor win))
             (code-char 1)))
      (t
       (setf str0 (string (code-char 1)))))
    ;;(break)
    (let* ((str (concatenate 'string (window-prompt win) str0))
           (width (- (window-width win) 2))
           (lines nil))
      (setf lines
            (iterate
              (while (plusp (length str)))
              (for line = (subseq str 0 (min width (length str))))
              (setf str (subseq str (min width (length str))))
              ;;(format t "~S ~S~%" line str)
              (if (find (code-char 1) line)
                  (setf line (concatenate
                              'string
                              (subseq line 0 (position (code-char 1) line))
                              (colourise
                               (cond
                                 ((and (window-input-string win)
                                       (< (window-input-cursor win)
                                          (length (window-input-string win))))
                                  (string (char (window-input-string win)
                                                (window-input-cursor win))))
                                 (t
                                  " "))
                               (window-input-background win)
                               (window-input-foreground win))
                              (subseq line (1+ (position (code-char 1) line))))))
              (collect line)))
      (setf (nth 0 lines) (subseq (nth 0 lines) (length (window-prompt win))))
      (setf (slot-value win 'window-input-rendered)
            lines)
      lines)))


(defmethod send-string-to-terminal ((win <Terminal-Window>) &optional str)
  (funcall (window-input-function win)
           win
           (or str
               (window-input-string win)
               "")))


(defmethod send-string-to-terminal :around ((win <Terminal-Window>)
                                            &optional str)
  (declare (ignore str))
  (let ((retval (call-next-method)))
    (when (window-echo-input? win)
      (typecase retval
        (null nil)
        (string (add-message win retval))
        (list (dolist (line retval)
                (add-message win line)))
        (otherwise nil)))
    retval))


(defmethod send-to-window :around ((win <Terminal-Window>) (event <Key-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (k gui-event-keypress)) event
    (cond
      ((window-input-active? win)
       (when (key-pressed k)
         (let ((pagelen (- (window-height win) 2))
               (num-items (length (window-items win))))
           (cond
             ((graphic-char-p (key-c k))
              (window-insert-character win (key-c k)))
             ((eql :backspace (key-vk k))
              (window-backspace-character win))
             ((eql :delete (key-vk k))
              (window-delete-character win))
             ((eql :enter (key-vk k))
              (send-string-to-terminal win)
              (setf (window-input-cursor win) 0)
              ;; (setf (nth (window-input-history-position win)
              ;;            (window-input-history win))
              ;;       (window-input-string win))
              (setf (window-input-history win)
                    (append
                     (remove ""
                             (append (window-input-history win)
                                     (list (window-input-string win)))
                             :test #'string=)
                     (list "")))
              (setf (window-input-history-position win)
                    (1- (length (window-input-history win))))
              (setf (window-input-string win) nil)
              (if (eql :transient (window-input-active? win))
                  (setf (window-input-active? win) nil)))
             ((eql :left (key-vk k))
              (when (plusp (window-input-cursor win))
                (decf (window-input-cursor win))
                (render-input-string win)))
             ((eql :right (key-vk k))
              (when (< (window-input-cursor win)
                       (length (window-input-string win)))
                (incf (window-input-cursor win))
                (render-input-string win)))
             ((eql :home (key-vk k))
              (setf (window-input-cursor win) 0)
              (render-input-string win))
             ((eql :end (key-vk k))
              (setf (window-input-cursor win)
                    (length (window-input-string win)))
              (render-input-string win))
             ((eql :up (key-vk k))
              (when (plusp (window-input-history-position win))
                ;; (setf (nth (window-input-history-position win)
                ;;            (window-input-history win))
                ;;       (window-input-string win))
                (decf (window-input-history-position win))
                (setf (window-input-string win)
                      (nth (window-input-history-position win)
                           (window-input-history win)))
                (setf (window-input-cursor win)
                      (length (window-input-string win)))
                (render-input-string win)))
             ((eql :down (key-vk k))
              (when (< (window-input-history-position win)
                       (1- (length (window-input-history win))))
                ;; (setf (nth (window-input-history-position win)
                ;;            (window-input-history win))
                ;;       (window-input-string win))
                (incf (window-input-history-position win))
                (setf (window-input-string win)
                      (nth (window-input-history-position win)
                           (window-input-history win)))
                (setf (window-input-cursor win)
                      (length (window-input-string win)))
                (render-input-string win)))
             (t
              (return-from send-to-window (call-next-method))))
           (constrain! (window-offset win) 0 (max 0 (- num-items pagelen)))
           (move-cursor-to win (window-offset win))
           ;;(constrain! (window-cursor win) 0 (max 0 (1- num-items)))
           ;; (warn "Now offset = ~D, cursor = ~D, num-items = ~D"
           ;;            (window-offset win) (window-cursor win) num-items)
           (prepare-window win)
           (redraw-window-area win))
         k))
      (t
       (call-next-method)))))


(defmethod window-insert-character ((win <Terminal-Window>) (ch character))
  (let ((instr (window-input-string win))
        (cur (window-input-cursor win)))
    (cond
      ((> (length instr) (* 3/4 (window-height win) (window-width win)))
       ;; input too long -- ignore request to input more characters.
       )
      ((null instr)
       (setf (window-input-string win) (string ch)))
      ((>= cur (length instr))
       (setf (window-input-string win) (concatenate 'string
                                                    instr (string ch))))
      ((zerop cur)
       (setf (window-input-string win) (concatenate 'string
                                                    (string ch) instr)))
      (t
       (setf (window-input-string win)
             (concatenate 'string (subseq instr 0 cur) (string ch)
                          (subseq instr cur)))))
    (incf (window-input-cursor win))
    (render-input-string win)))


(defmethod window-delete-character ((win <Terminal-Window>))
  (let ((instr (window-input-string win))
        (cur (window-input-cursor win)))
    (cond
      ((or (null instr)
           (zerop (length instr))
           (>= cur (length instr)))
       )
      ((zerop cur)
       (setf (window-input-string win) (subseq instr 1)))
      (t
       (setf (window-input-string win)
             (concatenate 'string (subseq instr 0 cur)
                          (subseq instr (1+ cur))))))))



(defmethod window-backspace-character ((win <Terminal-Window>))
  (let ((instr (window-input-string win))
        (cur (window-input-cursor win)))
    (cond
      ((or (null instr)
           (zerop (length instr))
           (zerop cur))
       (return-from window-backspace-character nil))
      ((>= cur (length instr))
       (setf (window-input-string win) (subseq instr 0 (1- cur))))
      (t
       (setf (window-input-string win)
             (concatenate 'string (subseq instr 0 (1- cur))
                          (subseq instr cur)))))
    (decf (window-input-cursor win))
    (render-input-string win)))



;;; <<Simple Prompt Window>> ==================================================


(defclass <Simple-Prompt-Window> (<Terminal-Window> <Modal-Window>)
  ((window-echo-input? :initform nil)))



;;; <<Dialog Window>> =========================================================


(defvar *dialog->colour-table* nil
  "Hashtable DIALOG-BUTTON-VALUE -> COLOURNUM")
(defvar *colour->dialog-table* nil
  "Hashtable COLOURNUM -> DIALOG-BUTTON-VALUE")

(defvar *next-dialog-colour* 200
  "RGB value which maps to a unique dialog button.")
(defconstant +DIALOG-CONSOLE-DEFAULT-FOREGROUND+ :true-white
  "TODO document.")
(defconstant +DIALOG-CONSOLE-DEFAULT-BACKGROUND+ :true-black
  "TODO document.")

(defclass <Dialog-Window> (<Window>)
  ((dialog-console :accessor dialog-console :initform nil))
  (:documentation
     "Window where regions of text can be defined to produce particular effects
when clicked on."))


(defmethod initialize-instance :after ((win <Dialog-Window>) &key)
  (setf (dialog-console win)
        (console-new (window-width win) (window-height win)))
  (console-set-default-foreground (dialog-console win)
                                 (colour +DIALOG-CONSOLE-DEFAULT-FOREGROUND+))
  (console-set-default-background (dialog-console win)
                                 (colour +DIALOG-CONSOLE-DEFAULT-BACKGROUND+)))



(defmethod resize-window :after ((win <Dialog-Window>) width height)
  (setf (dialog-console win)
        (console-new width height))
  (console-set-default-foreground (dialog-console win)
                                 (colour (window-foreground win)))
  (console-set-default-background (dialog-console win)
                                 (colour (window-foreground win))))


(defun button (data fmt &rest args)
  (format nil "{click:~A,fg:~A,bg:~A}~A{/}"
          data (dialog-button-foreground *window-theme*)
          (dialog-button-background *window-theme*)
          (apply #'format nil "~A" fmt args)))


(defun get-next-dialog-colour ()
  "TODO document."
  (iterate
    (while t)
    (multiple-value-bind
          (r g b) (decompose-colour (incf *next-dialog-colour*))
      (when (and (> r 0) (> g 0) (> b 0))
        (return-from get-next-dialog-colour *next-dialog-colour*)))))


(defun string->dialog-colour (str)
  "TODO document."
  (let ((col (gethash str *dialog->colour-table*)))
    (or col
        (progn
          (setf col (get-next-dialog-colour))
          (setf (gethash str *dialog->colour-table*) col)
          (setf (gethash col *colour->dialog-table*)
                str)
          col))))



(defmethod draw-string-at :after ((win <Dialog-Window>) str winx winy
                                  &key (background-flag :set) (align :left)
                                  &allow-other-keys)
  (draw-string-aux win winx winy
                   str :dialog? t
                   :background-flag background-flag :align align))


(defmethod send-to-window :around ((win <Dialog-Window>) (event <Mouse-Hover-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (data gui-event-focus)) event
    (unless data
      (setf data (gethash (console-get-char-foreground
                           (dialog-console win) winx winy)
                          *colour->dialog-table*)))
    (call-next-method win event)))


    ;; (cond
    ;;   ((null data)
       ;; (call-next-method)))



(defmethod send-to-window :around ((win <Dialog-Window>) (event <Mouse-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (mouse gui-event-mouse-state)) event
    (cond
      ((mouse-lbutton mouse)
       (let ((col (console-get-char-foreground (dialog-console win) winx winy)))
         (cond
           ((/= col (colour +DIALOG-CONSOLE-DEFAULT-FOREGROUND+))
            (if (gethash col *colour->dialog-table*)
                (send-to-window win (make-instance
                                     '<GUI-Dialog-Event>
                                     :string (gethash col *colour->dialog-table*)
                                     :winx winx :winy winy))))
           (t
            ;; Still here - no button clicked.
            (call-next-method)))))
      (t
       (call-next-method)))))




;;; <<Tooltip Window>> ========================================================


(defclass <Tooltip-Window> (<Dialog-Window>)
  ((window-raise-children-with-parent? :initform nil)
   (floating-window :accessor floating-window :initform nil))
  (:documentation
   "Window which displays floating 'tooltips' next to the mouse when hovering over
certain window regions."))


;;; <<Floating Window>>
(defclass <Floating-Window> (<Log-Window> <Ghost-Window>)
  ((window-framed? :initform nil)
  (window-can-resize? :initform nil)
  (window-can-drag? :initform nil)
  (last-mousex :accessor last-mousex :initform 0)
  (last-mousey :accessor last-mousey :initform 0)
  (last-text :accessor last-text :initform nil)
  (window-owner :initform nil))
  (:documentation
     "Window used to display the tooltips for a Tooltip-Window."))


(defmethod ok-to-show-tooltip? ((win <Tooltip-Window>))
  (or (not (typep win '<Window-With-Context-Menu>))
      (null (context-menu win))
      (window-hidden? (context-menu win))))


(defmethod process-window :before ((win <Floating-Window>))
  (unless (window-hidden? win)
    (when (or (/= *mouse-x* (last-mousex win))
              (/= *mouse-y* (last-mousey win)))
      ;;    (unless (eql (top-window-at *mouse-x* *mouse-y*) (window-owner win))
      (dirty-window win)
      (hide-window win))
    (setf (last-mousex win) *mouse-x*
          (last-mousey win) *mouse-y*)))


(defmethod raise-window :before ((win <Tooltip-Window>) &key &allow-other-keys)
  (unless (window-hidden? (floating-window win))
    (hide-window (floating-window win))))


(defmethod hide-window :before ((win <Tooltip-Window>) &key &allow-other-keys)
  (unless (window-hidden? (floating-window win))
    (hide-window (floating-window win))))



(defmethod initialize-instance :after ((win <Tooltip-Window>) &key)
  (setf (floating-window win)
        (make-instance '<Floating-Window>
                       :tlx 0 :tly 0
                       :width (calculate-floating-window-width win)
                       :height 3
                       :title "Tip" :foreground :white :background :dark-grey
                       :window-owner win
                       :hidden? t))
  (push (floating-window win) (window-children win)))


(defmethod calculate-floating-window-width ((win <Tooltip-Window>))
  (max 20 (floor (* 1/2 (window-width win)))))



(defmethod send-to-window :after ((win <Tooltip-Window>) (event <Mouse-Hover-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (mouse gui-event-mouse-state)) event
    (let ((text (tooltip-text win (gui-event-focus event) winx winy)))
      (cond
        ((null text)
         ;; if focus is null or uninteresting, make sure the floating window
         ;; is NOT visible.
         )
        ((ok-to-show-tooltip? win)
         ;; Otherwise:
         ;; write the text into the floating-window
         (cond
           ((equal text (last-text (floating-window win)))
            (when (window-hidden? (floating-window win))
              (move-window-beside-mouse (floating-window win))
              (raise-window (floating-window win) :simple-redraw? nil)))
           (t
            (unless (window-hidden? (floating-window win))
              (hide-window (floating-window win)))
            (setf (last-text (floating-window win)) text)
            (clear-messages (floating-window win))
            (dolist (msg text)
              (add-message (floating-window win) msg))
            ;; resize the floating window
            (resize-window (floating-window win)
                           (calculate-floating-window-width win)
                           (min (floor (* 3/4 (screen-height)))
                                (+ 2 (length (window-items (floating-window win))))))
            (prepare-window (floating-window win))
            ;; move the floating window to an appropriate spot beside the mouse
            (move-window-beside-mouse (floating-window win))
            (raise-window (floating-window win) :simple-redraw? nil))))))))



(defun move-window-beside-mouse (win)
  "* Arguments:
- WIN: an instance of {defclass dormouse:<Window>}
* Returns: T if the new coordinates are different from the old.
* Description: Move the window WIN so that it is located next to the current
position of the mouse pointer. "
  (let ((width (window-width win))
        (height (window-height win))
        (oldx (window-tlx win))
        (oldy (window-tly win)))
    (move-window win
                 (constrain
                  (cond
                    ((> *mouse-x* (- (screen-width) width))
                     (- *mouse-x* width))
                    (t
                     (1+ *mouse-x*)))
                  0 (- (screen-width) width 1))
                 (constrain
                  (cond
                    ((> *mouse-y* (- (screen-height) height))
                     (- *mouse-y* height))
                    (t
                     (1+ *mouse-y*)))
                  0 (- (screen-height) height 1)))
    (not (and (= (window-tlx win) oldx)
              (= (window-tly win) oldy)))))



(defmethod tooltip-text ((win <Tooltip-Window>) datum winx winy)
  (declare (ignore winx winy))
  (cond
    ((null datum)
     nil)
    ((eql datum :unspecified)
     nil)
    (t
     (list "Tip is:"
           (make-coloured-string (format nil "~S" datum) :win win)))))


(defmethod tooltip-text :around ((win <Window>) datum winx winy)
  (declare (ignore datum winx winy))
  (let ((result (call-next-method)))
    (if (stringp result)
        (list result)
        ;; else
        result)))



;;; <<Viewport>> ==============================================================


(defclass <Viewport> (<Window>)
  ((window-transparency :initform +OPAQUE+)
   (map-console :accessor map-console :initform nil
                :documentation "The actual console which the viewport looks
onto.")
   (window-make-map? :accessor window-make-map? :initform t :initarg :make-map?)
   (window-map-shared :accessor window-map-shared :initform nil
                      :documentation "List of windows sharing this map")
   (map-xdim :accessor map-xdim :initarg :map-xdim :initform nil)
   (map-ydim :accessor map-ydim :initarg :map-ydim :initform nil)
   (view-tlx :accessor view-tlx :initform 0)   ; position of the viewport on
                                               ; the map
   (view-tly :accessor view-tly :initform 0))
  (:documentation
   "Window that looks onto a 'map' console, which is usually larger than the
viewport, but can be the same size or even smaller. "))



(defmethod initialize-instance :after ((win <Viewport>) &key)
  (unless (map-xdim win)
    (setf (map-xdim win) (+ 10 (window-width win))
          (map-ydim win) (+ 10 (window-height win))))
  (when (window-make-map? win)
    (setf (map-console win) (console-new (map-xdim win) (map-ydim win)))
    (console-set-default-foreground (map-console win)
                                   (colour (window-foreground win)))
    (console-set-default-background (map-console win)
                                   (colour (window-background win)))))


(defun viewport-width (win)
  "TODO document."
  (if (window-framed? win)
      (- (window-width win) 2)
      ;; else
      (window-width win)))


(defun viewport-height (win)
  "TODO document."
  (if (window-framed? win)
      (- (window-height win) 2)
      ;; else
      (window-height win)))


(defun view-brx (win)
  "TODO document."
  (+ (view-tlx win) (1- (viewport-width win))))


(defun view-bry (win)
  "TODO document."
  (+ (view-tly win) (1- (viewport-height win))))


(defun in-view? (win mapx mapy)
  "TODO document."
  (and (<= (view-tlx win) mapx (view-brx win))
       (<= (view-tly win) mapy (view-bry win))))


(defun in-viewport-map? (win mapx mapy)
  "TODO document."
  (and (< -1 mapx (map-xdim win))
       (< -1 mapy (map-ydim win))))


(defmethod prepare-window :after ((win <Viewport>))
  ;; Copy appropriate portion of map to viewport
  (when (map-console win)
    (copy-map-to-viewport win)))




(defmethod copy-map-to-viewport ((win <Viewport>))
  (let (;; Top left coordinates of MAP to copy
        (vtlx (view-tlx win))
        (vtly (view-tly win))
        ;; Top left coordinates to copy to, in WIN console
        (wintlx (+ (if (window-framed? win) 1 0)))
        (wintly (+ (if (window-framed? win) 1 0)))
        ;; Width and height of block of map to copy
        (width (- (window-width win) (if (window-framed? win) 2 0)))
        (height (- (window-height win) (if (window-framed? win) 2 0)))
        ;; Need to blank other areas of console?
        (edges-showing? nil))
    (cond
      ((< vtlx 0)
       (setf wintlx (+ wintlx (abs vtlx)))
       (setf width (+ width vtlx))
       (setf vtlx 0)
       (setf edges-showing? t))
      ((>= vtlx (- (map-xdim win) width))
       (setf width (- (map-xdim win) vtlx))
       (setf edges-showing? t)))
    (cond
      ((< vtly 0)
       (setf wintly (+ wintly (abs vtly)))
       (setf height (+ height vtly))
       (setf vtly 0)
       (setf edges-showing? t))
      ((>= vtly (- (map-ydim win) height))
       (setf height (- (map-ydim win) vtly))
       (setf edges-showing? t)))
    (when edges-showing?
      (console-rect (window-console win)
                    (if (window-framed? win) 1 0)
                    (if (window-framed? win) 1 0)
                    (- (window-width win) (if (window-framed? win) 2 0))
                    (- (window-height win) (if (window-framed? win) 2 0))
                    t :set))
    (console-blit (map-console win)
                  vtlx vtly
                  width height
                  (window-console win)
                  wintlx wintly
                  1.0 1.0)))



(defmethod clear-map ((win <Viewport>) &key (redraw *auto-redraw*))
  (console-clear (map-console win))
  (copy-map-to-viewport win)
  (when redraw
    (redraw-window-area win)))



(defmethod centre-viewport-on ((win <Viewport>) (mapx integer) (mapy integer))
  "Centre the viewport on map coordinates X, Y; does not refresh the screen"
  (setf (view-tlx win) (- mapx (floor (viewport-width win) 2)))
  (setf (view-tly win) (- mapy (floor (viewport-height win) 2))))



(defmethod share-map ((receiver <Viewport>) (giver <Viewport>) tlx tly)
  "Make RECEIVER look onto the same map console as GIVER. RECEIVER's viewport
is initially positioned with top left corner TLX,TLY on the map console."
  (when (map-console receiver)
      (dolist (w *window-stack*)
        (when (and (not (equal w receiver))
                   (typep w '<Viewport>)
                   (equal (map-console w) (map-console receiver)))
          (setf (window-map-shared w)
                (remove receiver (window-map-shared w))))))
  (setf (window-map-shared receiver) (copy-list (window-map-shared giver)))
  (dolist (w *window-stack*)
    (when (and (not (equal w receiver))
               (typep w '<Viewport>)
               (equal (map-console w) (map-console giver)))
      (pushnew receiver (window-map-shared w))))
  (setf (map-console receiver) (map-console giver))
  (setf (map-xdim receiver) (map-xdim giver))
  (setf (map-ydim receiver) (map-ydim giver))
  (setf (view-tlx receiver) tlx)
  (setf (view-tly receiver) tly)
  (prepare-window receiver))


(defmethod unshare-map ((receiver <Viewport>) (giver <Viewport>))
  (setf (window-map-shared receiver)
        (set-difference (window-map-shared receiver) (list giver receiver)))
  (setf (window-map-shared giver)
        (set-difference (window-map-shared giver) (list giver receiver))))



(defun all-windows (&key (except))
  "TODO document."
  (remove except (append *window-stack* *hidden-windows*)))



(defmethod destroy-window :before ((win <Viewport>))
  (cond
    ((and (window-map-shared win)
          (not (find win (window-map-shared win))))
     (dolist (sharer (window-map-shared win))
       (unshare-map win sharer))
     ;; do any other windows still use this console?
     (unless (find (map-console win) (all-windows :except win))
       (if (and (map-console win)
                (not (equal *root* (map-console win))))
           ;;(console-delete (map-console win))
           nil
           )))
    ;; else - only sharing with outselves
    ((if (and (map-console win)
              (not (equal *root* (map-console win))))
         nil
         ))))



(defun mapx->winx (vp x)
  "TODO document."
  (if (window-framed? vp)
      (1+ (- x (view-tlx vp)))
      ;; else
      (- x (view-tlx vp))))


(defun mapy->winy (vp y)
  "TODO document."
  (if (window-framed? vp)
      (1+ (- y (view-tly vp)))
      ;; else
      (- y (view-tly vp))))


(defun winx->mapx (vp x)
  "TODO document."
  (if (window-framed? vp)
      (1- (+ x (view-tlx vp)))
      ;; else
      (+ x (view-tlx vp))))


(defun winy->mapy (vp y)
  "TODO document."
  (if (window-framed? vp)
      (1- (+ y (view-tly vp)))
      ;; else
      (+ y (view-tly vp))))


(defmethod map-draw-char-at ((win <Viewport>) (ch integer) mapx mapy
                                &key (background-flag :set)
                                (fg nil) (bg nil) (redraw *auto-redraw*))
  (assert (map-console win))
  (console-draw-char-at (map-console win) ch mapx mapy
                        :background-flag background-flag
                        :fg fg :bg bg)
  (dolist (w (cons win (window-map-shared win)))
    (when (in-view? w mapx mapy)
      (console-blit (map-console win) mapx mapy
                    1 1
                    (window-console w)
                    (mapx->winx w mapx)
                    (mapy->winy w mapy)
                    1.0 1.0)
      (when redraw
        (redraw-all-at (winx->rootx w (mapx->winx w mapx))
                       (winy->rooty w (mapy->winy w mapy)))))))


(defmethod map-draw-char-at ((win <Viewport>) (ch character) mapx mapy
                             &key (background-flag :set)
                             (fg nil) (bg nil) (redraw *auto-redraw*))
  (map-draw-char-at win (char-code ch) mapx mapy
                        :background-flag background-flag
                        :fg fg :bg bg :redraw redraw))



(defmethod map-char-at ((win <Viewport>) mapx mapy)
  (code-char
   (console-get-char (map-console win) mapx mapy)))



(defmethod map-set-foreground-at ((win <Viewport>) colour mapx mapy
                                &key (redraw *auto-redraw*))
  (assert (map-console win))
  (console-set-char-foreground (map-console win) mapx mapy colour)
  (dolist (w (cons win (window-map-shared win)))
    (when (in-view? w mapx mapy)
      (console-blit (map-console win) mapx mapy
                    1 1
                    (window-console w)
                    (mapx->winx w mapx)
                    (mapy->winy w mapy)
                    1.0 1.0)
      (when redraw
        (redraw-all-at (winx->rootx w (mapx->winx w mapx))
                       (winy->rooty w (mapy->winy w mapy)))))))


(defmethod map-set-background-at ((win <Viewport>) colour mapx mapy
                                &key (redraw *auto-redraw*))
  (assert (map-console win))
  (console-set-char-background (map-console win) mapx mapy colour :set)
  (dolist (w (cons win (window-map-shared win)))
    (when (in-view? w mapx mapy)
      (console-blit (map-console win) mapx mapy
                    1 1
                    (window-console w)
                    (mapx->winx w mapx)
                    (mapy->winy w mapy)
                    1.0 1.0)
      (when redraw
        (redraw-all-at (winx->rootx w (mapx->winx w mapx))
                       (winy->rooty w (mapy->winy w mapy)))))))



(defmethod send-to-window ((win <Viewport>) (event <Mouse-Hover-Event>))
  nil)


(defmethod send-to-window ((win <Viewport>) (event <GUI-Mouse-Drag-Event>))
  (with-slots ((winx gui-event-winx) (winy gui-event-winy)
               (rodent gui-event-mouse-state)) event
    (let* ((start-cx (mouse-cx rodent))
           (start-cy (mouse-cy rodent))
           (started-dragging? nil)
           (prev-cx start-cx) (prev-cy start-cy)
           (deltax 0) (deltay 0))
      (iterate
        (while (mouse-lbutton (setf rodent (mouse-get-status t))))
        ;; Update position of WIN based on mouse position
        ;; offsetx = cx - view-tlx
        ;; therefore cx - offsetx = current view-tlx
        ;;
        (setf deltax (- prev-cx
                        (constrain (mouse-cx rodent)
                                   (window-tlx win)
                                   (window-brx win))))
        (setf deltay (- prev-cy
                        (constrain (mouse-cy rodent)
                                   (window-tly win)
                                   (window-bry win))))
        (unless (and (= deltax deltay 0))
          (unless started-dragging?
            (setf started-dragging? t)
            (raise-window win)
            (prepare-window win)
            (redraw-window win)
            (console-flush))
          (incf (view-tlx win) deltax)
          (incf (view-tly win) deltay)
          (setf prev-cx (mouse-cx rodent))
          (setf prev-cy (mouse-cy rodent))
          (prepare-window win)
          (redraw-window win)
          (console-flush)))
      (cond
        (started-dragging?
         (redraw-window-area win)
         (console-flush))
        (t ;; never actually dragged - interpret as left-click
         (send-to-window win (make-instance '<Mouse-Event>
                                            :mouse-state
                                            (let ((ms (mouse-get-status t)))
                                              (setf (mouse-lbutton ms) t)
                                              ms)
                                            :winx winx :winy winy)))))))





;;; <<Top-level functions>> ===================================================


(defvar *screen-resolution-x* nil)
(defvar *screen-resolution-y* nil)


(defun start-gui (&key
                  (title "The Doryen Library")
                  (width nil)
                  (height nil)
                  (font-file *default-font-file*)
                  (fps 20)
                  ;;(font-file-chars-in-columns? t)
                  )
  "* Arguments:
- TITLE: String, used as the title displayed at the top of the TCOD
window.
- WIDTH: Desired width of the TCOD root console, in characters. Default 80.
  If NIL or not given, the root console width will be auto-calculated
  based on screen resolution and font size.
- HEIGHT: Desired height of the TCOD root console, in characters. Default 25.
  If NIL or not given, the root console height will be auto-calculated
  based on screen resolution and font size.
- FONT-FILE: Path to the font file to use. The default is
[[*default-font-file*]].
* Returns: None.
* Description: Initialise the TCOD library and prepare for running
the GUI.
* See Also: [[main-gui-loop]]"
;;;                +DEFAULT-FONT-FILE-CHARS-IN-COLUMNS?+))
;;;               (font-file-columns +DEFAULT-FONT-FILE-COLUMNS+)
;;;               (font-file-rows +DEFAULT-FONT-FILE-ROWS+)
;;;               (font-file-background-colour
;;;                +DEFAULT-FONT-FILE-BACKGROUND-COLOUR+))
  ;;(declare (type (integer 1) width height))
  (if *dialog->colour-table*
      (clrhash *dialog->colour-table*)
      ;; else
      (setf *dialog->colour-table* (make-hash-table :test #'equal)))
  (if *colour->dialog-table*
      (clrhash *colour->dialog-table*)
      ;; else
      (setf *colour->dialog-table* (make-hash-table :test #'eql)))
  (when font-file
    (assert (probe-file font-file))
    (console-set-custom-font font-file
                             (if (listp *default-font-layout*)
                                 *default-font-layout*
                                 (list *default-font-layout*))
;;;                        (if font-file-chars-in-columns?
;;;                            '(:font-layout-ascii-in-col)
;;;                            '(:font-layout-ascii-in-row))
                             0 0)) ;; TCOD automatically deduces WxH
;;;                        font-file-columns font-file-rows
;;;                        font-file-chars-in-columns?
;;;                        (colour font-file-background-colour))

  ;; Store screen resolution, then auto-calculate a sensible width and
  ;; height based on screen size and character size (unless a particular
  ;; width and height have been specified)

  (unless (numberp *screen-resolution-x*)
    (multiple-value-bind (scr-xdim scr-ydim) (sys-get-current-resolution)
      (setf *screen-resolution-x* scr-xdim
            *screen-resolution-y* scr-ydim)))

  (multiple-value-bind (ch-xdim ch-ydim) (sys-get-char-size)
    (unless width
      (setf width (floor (* 0.8 (/ *screen-resolution-x* ch-xdim)))))
    (unless height
      (setf height (floor (* 0.8 (/ *screen-resolution-y* ch-ydim))))))

  (console-init-root width height title nil :RENDERER-SDL)
  (start-colours)
  (setf *window-stack* nil)
  (sys-set-fps fps)                     ; limit FPS (and CPU load)
  (setf *temp-con*
        (console-new width height))     ; must be same size as ROOT
  (setf *scratch*
        (console-new width height))     ; must be same size as ROOT
  (console-clear *root*))


(defun legal-window-coordinates? (win x y)
  (tcod:legal-console-coordinates? (window-console win) x y))


(defun process-windows ()
  "* Arguments: None.
* Returns: None.
* Description: Called once for each iteration of {defun dormouse:main-gui-loop}.
Calls process-window for each non-hidden window.
* See Also: "
  (dolist (win (all-windows))
    (process-window win))
  (console-flush))


(defvar *rodent* nil)
(defvar *last-rodent* nil)
(defvar *topwin* nil)
(defvar *last-topwin* nil)
(defvar *last-mouse-click-event* nil)
(defvar *mouse-double-click-speed* 500
  "If two clicks occur with a delay of <= this many milliseconds between them,
a double-click event is created.")


(defun send-mouse-click-event (rodent)
  (flet ((mouse-click-type (mouse)
           (cond
             ((mouse-lbutton mouse) :lclick)
             ((mouse-rbutton mouse) :rclick)
             ((mouse-mbutton mouse) :mclick)
             (t nil))))
    (let ((click-type (mouse-click-type rodent))
          (double-click? nil))
      (when *topwin*
        (cond
          ((and (eq :lclick click-type)
                (=  *mouse-y* (window-tly *topwin*))
                (=  *mouse-x* (window-brx *topwin*))
                (window-can-close? *topwin*))
           ;; Left-clicked on 'X' in top right corner
           (hide-window *topwin*))
          (t
           ;; Clicked somewhere else on the window
           (if (and *last-mouse-click-event*
                    (eq click-type (mouse-click-type
                                    (gui-event-mouse-state
                                     *last-mouse-click-event*)))
                    (<= (- (tcod:sys-elapsed-milli)
                           (gui-event-time *last-mouse-click-event*))
                        *mouse-double-click-speed*))
               (setf double-click? t))
           (raise-window *topwin*)
           (setf *last-mouse-click-event*
                 (make-instance (if double-click?
                                    '<Mouse-Double-Click-Event>
                                    '<Mouse-Event>)
                                :winx (- *mouse-x* (window-tlx *topwin*))
                                :winy (- *mouse-y* (window-tly *topwin*))
                                :mouse-state rodent))
           (send-to-window *topwin* *last-mouse-click-event*)))))))



(let ((mouse-hover-event (make-instance '<Mouse-Hover-Event>)))
  (defun main-gui-loop-aux ()
    (let ((k nil) (mouse nil))
      (process-windows)
      (when (or *exit-gui?*
                (console-is-window-closed?))
         (return-from main-gui-loop-aux nil))
      ;; Process all pending keyboard and mouse events
      (iterate
        (with events = (sys-get-events))
        (for (event-type . data) in events)
        (setf k data
              mouse data)
        (case event-type
          (:event-none nil)
          ;; === mouse movement and clicks ===
          ((:event-mouse-move :event-mouse-press :event-mouse-release)
           (setf *rodent* mouse
                 *mouse-x* (mouse-cx mouse)
                 *mouse-y* (mouse-cy mouse)
                 *topwin* (window-with-mouse-focus))
           (setf *focus-changed?* (not (eql *topwin* *last-topwin*)))
           (if (eql event-type :event-mouse-press)
               (send-mouse-click-event mouse)))
          ;; === key pressed or released ===
          ((:event-key-press :event-key-release)
           (case (key-vk k)
             (format t "key press: ~S~%" (key-c k))
             (:shift (setf *shift* (key-pressed k)))
             (:control (setf *ctrl* (key-pressed k)))
             (:alt (setf *alt* (key-pressed k)))
             (:printscreen (tcod:sys-save-screenshot))
             (otherwise
              ;; send (vk k) to window under mouse
              (when (setf *topwin* (window-with-keyboard-focus))
                (send-key-to-window *topwin* k
                                    (- *mouse-x* (window-tlx *topwin*))
                                    (- *mouse-y* (window-tly *topwin*)))))))
        (otherwise (format t "unknown event: ~S~%" event-type)))
        (finally
         (if events (console-flush))))
      ;; We have processed all events. Now look at what state the mouse is in.
      ;; Is a button being held down?
      (cond
        ((and (mouse-lbutton *rodent*)
              *topwin*)
                (raise-window *topwin*)
                (let ((start (get-internal-real-time))
                      (dragged? nil))
                  (declare (ignorable dragged?))
                  (iterate
                    (while (mouse-lbutton (setf *rodent* (mouse-get-status t))))
                    (unless (and (< (get-internal-real-time)
                                    (+ start (/ (* *drag-delay* 1000)
                                                internal-time-units-per-second)))
                                 (zerop (mouse-dx *rodent*))
                                 (zerop (mouse-dy *rodent*)))
                      (setf dragged? t)
                      (cond
                        ((and (window-can-drag? *topwin*)
                              (on-upper-window-border?
                               *topwin*
                               (- *mouse-x* (window-tlx *topwin*))
                               (- *mouse-y* (window-tly *topwin*))))
                         ;; Dragging on title bar - move the window
                         (mouse-drag-window *topwin* *rodent*))
                        ((and (window-can-resize? *topwin*)
                              (= *mouse-y* (+ (window-tly *topwin*)
                                              (1- (window-height *topwin*))))
                              (= *mouse-x* (+ (window-tlx *topwin*)
                                              (1- (window-width *topwin*)))))
                         ;; Dragging on bottom right corner
                         (mouse-resize-window *topwin* *rodent*))
                        (t
                         (send-to-window
                          *topwin*
                          (make-instance '<GUI-Mouse-Drag-Event>
                                         :winx (- *mouse-x* (window-tlx *topwin*))
                                         :winy (- *mouse-y* (window-tly *topwin*))
                                         :mouse-state *rodent*))))
                      (return)))))
             (t                         ; mouse "just hovering"
              (when *topwin*
                (setf (gui-event-winx mouse-hover-event)
                      (- *mouse-x* (window-tlx *topwin*)))
                (setf (gui-event-winy mouse-hover-event)
                      (- *mouse-y* (window-tly *topwin*)))
                (setf (gui-event-mouse-state mouse-hover-event) *rodent*)
                (setf (gui-event-focus mouse-hover-event) nil)
                ;;(format t "hover: ~S~%" mouse-hover-event)
                (send-to-window *topwin* mouse-hover-event))))
      )))


        ;; (t
        ;;  (setf *rodent* (mouse-get-status t))
        ;;  (unless (equal *rodent* *last-rodent*)
        ;;    ;; Deal with mouse events
        ;;    (setf *mouse-x* (mouse-cx *rodent*)
        ;;          *mouse-y* (mouse-cy *rodent*)
        ;;          *topwin* (window-with-mouse-focus))
        ;;    (setf *focus-changed?* (not (eql *topwin* *last-topwin*)))
        ;;    (cond
        ;;      ((or (mouse-lbutton-pressed *rodent*)
        ;;           (mouse-rbutton-pressed *rodent*)
        ;;           (mouse-mbutton-pressed *rodent*))
        ;;       ;; Mouse clicked
        ;;       (send-mouse-click-event *rodent*))
        ;;      ;; L button held down
        ;;      ((mouse-lbutton *rodent*)
        ;;       (when *topwin*
        ;;         (raise-window *topwin*)
        ;;         (let ((start (get-internal-real-time))
        ;;               (dragged? nil))
        ;;           (declare (ignorable dragged?))
        ;;           (iterate
        ;;             (while (mouse-lbutton (setf *rodent* (mouse-get-status t))))
        ;;             (unless (and (< (get-internal-real-time)
        ;;                             (+ start (/ (* *drag-delay* 1000)
        ;;                                         internal-time-units-per-second)))
        ;;                          (zerop (mouse-dx *rodent*))
        ;;                          (zerop (mouse-dy *rodent*)))
        ;;               (setf dragged? t)
        ;;               (cond
        ;;                 ((and (window-can-drag? *topwin*)
        ;;                       (on-upper-window-border?
        ;;                        *topwin*
        ;;                        (- *mouse-x* (window-tlx *topwin*))
        ;;                        (- *mouse-y* (window-tly *topwin*))))
        ;;                  ;; Dragging on title bar - move the window
        ;;                  (mouse-drag-window *topwin* *rodent*))
        ;;                 ((and (window-can-resize? *topwin*)
        ;;                       (= *mouse-y* (+ (window-tly *topwin*)
        ;;                                       (1- (window-height *topwin*))))
        ;;                       (= *mouse-x* (+ (window-tlx *topwin*)
        ;;                                       (1- (window-width *topwin*)))))
        ;;                  ;; Dragging on bottom right corner
        ;;                  (mouse-resize-window *topwin* *rodent*))
        ;;                 (t
        ;;                  (send-to-window
        ;;                   *topwin*
        ;;                   (make-instance '<GUI-Mouse-Drag-Event>
        ;;                                  :winx (- *mouse-x* (window-tlx *topwin*))
        ;;                                  :winy (- *mouse-y* (window-tly *topwin*))
        ;;                                  :mouse-state *rodent*))))
        ;;               (return))))))
        ;;
        ;;      (t                         ; mouse "just hovering"
        ;;       (when *topwin*
        ;;         (setf (gui-event-winx mouse-hover-event)
        ;;               (- *mouse-x* (window-tlx *topwin*)))
        ;;         (setf (gui-event-winy mouse-hover-event)
        ;;               (- *mouse-y* (window-tly *topwin*)))
        ;;         (setf (gui-event-mouse-state mouse-hover-event) *rodent*)
        ;;         (setf (gui-event-focus mouse-hover-event) nil)
        ;;         (send-to-window *topwin* mouse-hover-event))))
        ;;    ;; CONSOLE-FLUSH should not be done every iteration, which
        ;;    ;; is what was happening below.
        ;;    ;; This has been changed so now we only flush the console if the
        ;;    ;; mouse moves/mouse status changes, or a key is pressed.
        ;;    ;; It seems to work.
        ;;    ;;
        ;;    ;; Alternative plan could be to time since last flush, limit to
        ;;    ;; < 20 fps.
        ;;    (unless (equal *rodent* *last-rodent*)
        ;;      (setf *last-rodent* *rodent*)
        ;;      (console-flush))
        ;;    ))))))



(defun main-gui-loop (&optional tick-fn)
  "* Arguments
- TICK-FN :: if supplied, must be a function taking no arguments. This
  function will be called after every iteration through the GUI loop.
* Returns
None.
* Description

The function [[start-gui]] must be called to initialise libtcod prior to this
function being called.

When called, begins 'running' the currently defined window system. All existing
non-hidden windows are displayed, and a loop is entered where keyboard and
mouse events are intercepted and handled or sent to window objects for
handling. A special case is the PrintScreen key, which calls the TCOD library
function =sys-save-screenshot=.

The loop runs until the global variable [[*exit-gui?*]] is non-nil.
"
  (let ((*rodent* (mouse-get-status t))
        ;;(*last-rodent* (make-mouse))
        (*topwin* nil) (*last-topwin* nil))
    (redraw-all-windows)
    (setf *exit-gui?* nil)
    (console-flush)
    ;; Main loop
    (iterate
      (until (or *exit-gui?*
                 (console-is-window-closed?)))
      ;; The following snippet is taken from
      ;; http://code.google.com/p/lispbuilder/wiki/PortableInteractiveDevelopment
      ;; and allows swank to process commands from slime during the game loop.
      #+swank (let ((connection
                      (or swank::*emacs-connection* (swank::default-connection))))
                (when (and connection (not (eql swank:*communication-style* :spawn)))
                  (swank::handle-requests connection t)))
      ;; Inner part of loop moved into separate function, to allow redefinition
      ;; while within the loop.
      (main-gui-loop-aux)
      (if *focus-changed?* (setf *last-topwin* *topwin*))
      (if tick-fn (funcall tick-fn)))))



(defun resume-gui ()
  "* Arguments: None.
* Returns: None.
* Description: Resume running the currently defined window system."
  (console-flush)
  (main-gui-loop))


(defun window-to-text (win)
  "Debugging function. Prints out the contents of the window WIN as text."
  (let ((line nil))
    (dotimes (y (window-height win))
      (dotimes (x (window-width win))
        (push (code-char (console-get-char (window-console win) x y)) line))
      (format t "~3D: ~S~%" y (concatenate 'string (reverse line)))
      (setf line nil))))


(defun test-events ()
  "Debugging function, simply reports all events to the terminal."
  (iterate
    (with key = nil)
    (with mouse = nil)
    (iterate
      (for (event-type . data) in (sys-get-events))
      (setf key data
            mouse data)
      (case event-type
        (:event-none nil)
        (:event-mouse-move (format t "mouse move to ~D ~D~%"
                                   (mouse-cx mouse) (mouse-cy mouse)))
        (:event-mouse-press
         (format t "mouse press [~C~C~C] [~C~C~C] [~C~C] ~8,'0B~%"
                 (if (mouse-lbutton mouse) #\L #\space)
                 (if (mouse-mbutton mouse) #\M #\space)
                 (if (mouse-rbutton mouse) #\R #\space)
                 (if (mouse-lbutton-pressed mouse) #\L #\space)
                 (if (mouse-mbutton-pressed mouse) #\M #\space)
                 (if (mouse-rbutton-pressed mouse) #\R #\space)
                 (if (mouse-wheel-up mouse) #\U #\space)
                 (if (mouse-wheel-down mouse) #\D #\space)
                 (tcod::sdl-get-mouse-state +null+ +null+)))
        (:event-mouse-release
         (format t "mouse release [~C~C~C] [~C~C~C] [~C~C] ~8,'0B~%"
                 (if (mouse-lbutton mouse) #\L #\space)
                 (if (mouse-mbutton mouse) #\M #\space)
                 (if (mouse-rbutton mouse) #\R #\space)
                 (if (mouse-lbutton-pressed mouse) #\L #\space)
                 (if (mouse-mbutton-pressed mouse) #\M #\space)
                 (if (mouse-rbutton-pressed mouse) #\R #\space)
                 (if (mouse-wheel-up mouse) #\U #\space)
                 (if (mouse-wheel-down mouse) #\D #\space)
                 (tcod::sdl-get-mouse-state +null+ +null+)))
        (:event-key-press
         (format t "key press: ~S~%" (key-c key))
         (if (eql #\q (key-c key))
             (return-from test-events nil)))
        (:event-key-release (format t "key release~%"))
        (otherwise (format t "unknown event: ~S~%" event-type))))))


;;;; dormouse.lisp ends here =================================================
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.