summaryrefslogtreecommitdiff
path: root/src/main-gtk2.c
blob: ada45aa9b099872545723104f070cac5875e99c0 (plain)
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
/* File: main-gtk.c */

/*
 * Copyright (c) 2000-2001 Robert Ruehlmann,
 * Steven Fuerst, Uwe Siems, "pelpel", et al.
 *
 * This software may be copied and distributed for educational, research,
 * and not for profit purposes provided that this copyright and statement
 * are included in all such copies.
 */

/*
 * Robert Ruehlmann wrote the original Gtk port. Since an initial work is
 * much harder than enhancements, his effort worth more credits than
 * others.
 *
 * Steven Fuerst implemented colour-depth independent X server support,
 * graphics, resizing and big screen support for ZAngband as well as
 * fast image rescaling that is included here.
 *
 * Uwe Siems wrote smooth tiles rescaling code (on by default).
 * Try this with 8x8 tiles. They *will* look different.
 *
 * "pelpel" wrote another colour-depth independent X support
 * using GdkRGB, added several hooks and callbacks for various
 * reasons, wrote no-backing store mode (off by default),
 * added GtkItemFactory based menu system, introduced
 * USE_GRAPHICS code bloat (^ ^;), added comments (I have
 * a strange habit of writing comments while I code...)
 * and reorganised the file a bit.
 */

#include "angband.h"


/*
 * Activate variant-specific features
 *
 * Angband 2.9.3 and close variants don't require any.
 *
 * Angband 2.9.4 alpha and later removed the short-lived
 * can_save flag, so please #define can_save TRUE, or remove
 * all the references to it. They also changed long-lived
 * z-virt macro names. Find C_FREE/C_KILL and replace them
 * with FREE/KILL, which takes one pointer parameter.
 *
 * [Z]-based variants (Gum and Cth, for example) usually need
 * ANG293_COMPAT, ANG291_COMPAT and ANG281_RESET_VISUALS.
 *
 * [O] needs ANG293_COMPAT and ZANG_SAVE_GAME.
 *
 * ZAngband has its own enhanced main-gtk.c as mentioned above, and
 * you *should* use it :-)
 *
 * ANG291_COMPAT does not include Angband 2.9.x's gamma correction code.
 * If you like to use SUPPORT_GAMMA, copy the code bracketed
 * inside of #ifdef SUPPORT_GAMMA in util.c of Angband 2.9.1 or greater.
 */
#define TOME

#ifdef TOME
# define ANG293_COMPAT	/* Requires V2.9.3 compatibility code */
# define ANG291_COMPAT	/* Requires V2.9.1 compatibility code */
# define ANG281_RESET_VISUALS	/* The old style reset_visuals() */
# define INTERACTIVE_GAMMA	/* Supports interactive gamma correction */
# define SAVEFILE_SCREEN	/* New/Open integrated into the game */
# define USE_DOUBLE_TILES	/* Mogami's bigtile patch */
#endif /* TOME */

/*
 * Some examples
 */
#ifdef ANGBAND300
# define can_save TRUE	/* Mimick the short-lived flag */
# define C_FREE(P, N, T)	FREE(P)	/* Emulate the long-lived macro */
# define USE_TRANSPARENCY	/* Because it's default now */
#endif /* ANGBAND300 */

#ifdef GUMBAND
# define ANG293_COMPAT	/* Requires V2.9.3 compatibility code */
# define ANG291_COMPAT	/* Requires V2.9.1 compatibility code */
# define ANG281_RESET_VISUALS	/* The old style reset_visuals() */
# define OLD_SAVEFILE_CODE /* See also SAVEFILE_MUTABLE in files.c */
# define NO_REDRAW_SECTION	/* Doesn't have Term_redraw_section() */
#endif /* GUMBAND */

#ifdef OANGBAND
# define ANG293_COMPAT	/* Requires V2.9.3 compatibility code */
# define ZANG_SAVE_GAME	/* do_cmd_save_game with auto_save parameter */
#endif /* OANGBAND */


#ifdef USE_GTK2

/* Force ANSI standard */
/* #define __STRICT_ANSI__ */

/* No GCC-specific includes */
/* #undef __GNUC__ */

#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>

/* /me pffts Solaris */
#ifndef NAME_MAX
#define	NAME_MAX	_POSIX_NAME_MAX
#endif


/*
 * Include some helpful X11 code.
 */
#ifndef ANG293_COMPAT
# include "maid-x11.h"
#endif /* !ANG293_COMPAT */


/*
 * Number of pixels inserted between the menu bar and the main screen
 */
#define NO_PADDING 0


/*
 * Largest possible number of terminal windows supported by the game
 */
#define MAX_TERM_DATA 8


/*
 * Extra data to associate with each "window"
 *
 * Each "window" is represented by a "term_data" structure, which
 * contains a "term" structure, which contains a pointer (t->data)
 * back to the term_data structure.
 */

#ifdef USE_GRAPHICS

/*
 * Since GdkRGB doesn't provide us some useful functions...
 */
typedef struct GdkRGBImage GdkRGBImage;

struct GdkRGBImage
{
	gint width;
	gint height;
	gint ref_count;
	guchar *image;
};

#endif /* USE_GRAPHICS */


/*
 * This structure holds everything you need to manipulate terminals
 */
typedef struct term_data term_data;

struct term_data
{
	term t;

	GtkWidget *window;
	GtkWidget *drawing_area;
	GdkPixmap *backing_store;
	GdkFont *font;
	GdkGC *gc;

	bool shown;
	byte last_attr;

	int font_wid;
	int font_hgt;

	int rows;
	int cols;

#ifdef USE_GRAPHICS

	int tile_wid;
	int tile_hgt;

	GdkRGBImage *tiles;
# ifdef USE_TRANSPARENCY
	guint32 bg_pixel;
	GdkRGBImage *trans_buf;
# endif  /* USE_TRANSPARENCY */

#endif /* USE_GRAPHICS */

	cptr name;
};


/*
 * Where to draw when we call Gdk drawing primitives
 */
# define TERM_DATA_DRAWABLE(td) \
((td)->backing_store ? (td)->backing_store : (td)->drawing_area->window)

# define TERM_DATA_REFRESH(td, x, y, wid, hgt) \
if ((td)->backing_store) gdk_draw_pixmap( \
(td)->drawing_area->window, \
(td)->gc, \
(td)->backing_store, \
(x) * (td)->font_wid, \
(y) * (td)->font_hgt, \
(x) * (td)->font_wid, \
(y) * (td)->font_hgt, \
(wid) * (td)->font_wid, \
(hgt) * (td)->font_hgt)


#if 0

/* Compile time option version */

# ifdef USE_BACKING_STORE

# define TERM_DATA_DRAWABLE(td) (td)->backing_store

# define TERM_DATA_REFRESH(td, x, y, wid, hgt) \
gdk_draw_pixmap( \
(td)->drawing_area->window, \
(td)->gc, \
(td)->backing_store, \
(x) * (td)->font_wid, \
(y) * (td)->font_hgt, \
(x) * (td)->font_wid, \
(y) * (td)->font_hgt, \
(wid) * (td)->font_wid, \
(hgt) * (td)->font_hgt)

# else /* USE_BACKING_STORE */

# define TERM_DATA_DRAWABLE(td) (td)->drawing_area->window
# define TERM_DATA_REFRESH(td, x, y, wid, hgt)

# endif  /* USE_BACKING_STORE */

#endif /* 0 */


/*
 * An array of "term_data" structures, one for each "sub-window"
 */
static term_data data[MAX_TERM_DATA];

/*
 * Number of active terms
 */
static int num_term = 1;


/*
 * RGB values of the sixteen Angband colours
 */
static guint32 angband_colours[16];


/*
 * Set to TRUE when a game is in progress
 */
static bool game_in_progress = FALSE;


/*
 * This is in some cases used for double buffering as well as
 * a backing store, speeding things up under client-server
 * configurations, while turning this off *might* work better
 * with the MIT Shm extention which is usually active if you run
 * Angband locally, because it reduces amount of memory-to-memory copy.
 */
static bool use_backing_store = TRUE;




/**** Vanilla compatibility functions ****/

#ifdef ANG293_COMPAT

/*
 * Look up some environment variables to find font name for each window.
 */
static cptr get_default_font(int term)
{
	char buf[64];
	cptr font_name;

	/* Window specific font name */
	strnfmt(buf, 64, "ANGBAND_X11_FONT_%s", angband_term_name[term]);

	/* Check environment for that font */
	font_name = getenv(buf);

	/* Window specific font name */
	strnfmt(buf, 64, "ANGBAND_X11_FONT_%d", term);

	/* Check environment for that font */
	if (!font_name) font_name = getenv(buf);

	/* Check environment for "base" font */
	if (!font_name) font_name = getenv("ANGBAND_X11_FONT");

	/* No environment variables, use default font */
	if (!font_name) font_name = DEFAULT_X11_FONT_SCREEN;

	return (font_name);
}


# ifndef SAVEFILE_SCREEN

/*
 * In [V]2.9.3, this frees all dynamically allocated memory
 */
static void cleanup_angband(void)
{
	/* XXX XXX XXX */
}

# endif  /* !SAVEFILE_SCREEN */

/*
 * New global flag to indicate if it's safe to save now
 */
#define can_save TRUE

#endif /* ANG293_COMPAT */


#ifdef ANG291_COMPAT

/*
 * The standard game uses this to implement lighting effects
 * for 16x16 tiles in cave.c...
 *
 * Because of the way it is implemented in X11 ports,
 * we can set this to TRUE even if we are using the 8x8 tileset.
 */
static bool use_transparency = TRUE;

#endif /* ANG291_COMPAT */




/**** Low level routines - memory allocation ****/

/*
 * Hook to "release" memory
 */
#ifdef ANGBAND300
static vptr hook_rnfree(vptr v)
#else
static vptr hook_rnfree(vptr v, huge size)
#endif /* ANGBAND300 */
{
	/* Dispose */
	g_free(v);

	/* Success */
	return (NULL);
}


/*
 * Hook to "allocate" memory
 */
static vptr hook_ralloc(huge size)
{
	/* Make a new pointer */
	return (g_malloc(size));
}



/**** Low level routines - colours and graphics ****/

#ifdef SUPPORT_GAMMA

/*
 * When set to TRUE, indicates that we can use gamma_table
 */
static bool gamma_table_ready = FALSE;


# ifdef INTERACTIVE_GAMMA

/*
 * Initialise the gamma-correction table for current gamma_val
 * - interactive version
 */
static void setup_gamma_table(void)
{
	static u16b old_gamma_val = 0;

	/* Don't have to rebuild the table */
	if (gamma_val == old_gamma_val) return;

	/* Temporarily inactivate the table */
	gamma_table_ready = FALSE;

	/* Validate gamma_val */
	if ((gamma_val <= 0) || (gamma_val >= 256))
	{
		/* Reset */
		old_gamma_val = gamma_val = 0;

		/* Leave it inactive */
		return;
	}

	/* (Re)build the gamma table */
	build_gamma_table(gamma_val);

	/* Remember the gamma value used */
	old_gamma_val = gamma_val;

	/* Activate the table */
	gamma_table_ready = TRUE;
}

# else /* INTERACTIVE_GAMMA */

/*
 * Initialise the gamma-correction table if environment variable
 * ANGBAND_X11_GAMMA is set and contains a meaningful value
 *
 * Restored for cross-variant compatibility
 */
static void setup_gamma_table(void)
{
	cptr tmp;
	int gamma_val;


	/* The table's already set up */
	if (gamma_table_ready) return;

	/*
	 * XXX XXX It's documented nowhere, but ANGBAND_X11_GAMMA is
	 * 256 * (1 / gamma), rounded to integer. A recommended value
	 * is 183, which is an approximation of the Macintosh hardware
	 * gamma of 1.4.
	 *
	 *   gamma	ANGBAND_X11_GAMMA
	 *   -----	-----------------
	 *   1.2	213
	 *   1.25	205
	 *   1.3	197
	 *   1.35	190
	 *   1.4	183
	 *   1.45	177
	 *   1.5	171
	 *   1.6	160
	 *   1.7	151
	 *   ...
	 *
	 * XXX XXX The environment variable, or better,
	 * the interact with colours command should allow users
	 * to specify gamma values (or gamma value * 100).
	 */
	tmp = getenv("ANGBAND_X11_GAMMA");

	/* Nothing to do */
	if (tmp == NULL) return;

	/* Extract the value */
	gamma_val = atoi(tmp);

	/*
	 * Only need to build the table if gamma exists and set to
	 * a meaningful value.
	 *
	 * XXX It may be a good idea to prevent use of very high gamma values,
	 * say, greater than 2.5, which is gamma of normal CRT display IIRC.
	 */
	if ((gamma_val <= 0) || (gamma_val >= 256)) return;

	/* Build the gamma correction table */
	build_gamma_table(gamma_val);

	/* The table is properly set up */
	gamma_table_ready = TRUE;
}

# endif  /* INTERACTIVE_GAMMA */

#endif /* SUPPORT_GAMMA */


/*
 * Remeber RGB values for sixteen Angband colours, in a format
 * that is convinient for GdkRGB GC functions.
 *
 * XXX XXX Duplication of maid-x11.c is far from the Angband
 * ideal of code cleanliness, but the whole point of using GdkRGB
 * is to let it handle colour allocation which it does in a very
 * clever fashion. Ditto for the tile scaling code and the BMP loader
 * below.
 */
static void init_colours(void)
{
	int i;


#ifdef SUPPORT_GAMMA

	/* (Re)build gamma table if necessary */
	setup_gamma_table();

#endif /* SUPPORT_GAMMA */

	/* Process each colour */
	for (i = 0; i < 16; i++)
	{
		u32b red, green, blue;

		/* Retrieve RGB values from the game */
		red = angband_color_table[i][1];
		green = angband_color_table[i][2];
		blue = angband_color_table[i][3];

#ifdef SUPPORT_GAMMA

		/* Hack -- Gamma Correction */
		if (gamma_table_ready)
		{
			red = gamma_table[red];
			green = gamma_table[green];
			blue = gamma_table[blue];
		}

#endif /* SUPPORT_GAMMA */

		/* Remember a GdkRGB value, that is 0xRRGGBB */
		angband_colours[i] = (red << 16) | (green << 8) | blue;
	}
}


/*
 * Set foreground colour of window td to attr, only when it is necessary
 */
static void term_data_set_fg(term_data *td, byte attr)
{
	/* We can use the current gc */
	if (td->last_attr == attr) return;

	/* Activate the colour */
	gdk_rgb_gc_set_foreground(td->gc, angband_colours[attr]);

	/* Remember it */
	td->last_attr = attr;
}


#ifdef USE_GRAPHICS

/*
 * Graphics mode selector - current setting and requested value
 */
#define GRAF_MODE_NONE	0
#define GRAF_MODE_OLD	1
#define GRAF_MODE_NEW	2

static int graf_mode = GRAF_MODE_NONE;
static int graf_mode_request = GRAF_MODE_NONE;

/*
 * Use smooth rescaling?
 */
static bool smooth_rescaling = TRUE;
static bool smooth_rescaling_request = TRUE;

/*
 * Dithering
 */
static GdkRgbDither dith_mode = GDK_RGB_DITHER_NORMAL;

/*
 * Need to reload and resize tiles when fonts are changed.
 */
static bool resize_request = FALSE;

/*
 * Numbers of columns and rows in current tileset
 * calculated and set by the tile loading code in graf_init()
 * and used by Term_pict_gtk()
 */
static int tile_rows;
static int tile_cols;


/*
 * Directory name(s)
 */
static cptr ANGBAND_DIR_XTRA_GRAF;


/*
 * Be nice to old graphics hardwares -- using GdkRGB.
 *
 * We don't have colour allocation failure any longer this way,
 * even with 8bpp X servers. Gimp *does* work with 8bpp, why not Angband?
 *
 * Initialisation (before any widgets are created)
 *	gdk_rgb_init();
 *	gtk_widget_set_default_colormap (gdk_rgb_get_cmap());
 *	gtk_widget_set_default_visual (gdk_rgb_get_visual());
 *
 * Setting fg/bg colours
 *	void gdk_rgb_gc_set_foreground(GdkGC *gc, guint32 rgb);
 *	void gdk_rgb_gc_set_background(GdkGC *gc, guint32 rgb);
 * where rgb is 0xRRGGBB.
 *
 * Drawing rgb images
 *	void gdk_draw_rgb_image(
 *		GdkDrawable *drawable,
 *		GdkGC *gc,
 *		gint x, gint y,
 *		gint width, gint height,
 *		GdkRgbDither dith,
 *		guchar *rgb_buf,
 *		gint rowstride);
 *
 * dith:
 *	GDK_RGB_DITHER_NORMAL : dither if 8bpp or below
 *	GDK_RGB_DITHER_MAX : dither if 16bpp or below.
 *
 * for 0 <= i < width and 0 <= j < height,
 * the pixel (x + i, y + j) is colored with
 *  red value rgb_buf[j * rowstride + i * 3],
 *  green value rgb_buf[j * rowstride + i * 3 + 1], and
 *  blue value rgb_buf[j * rowstride + i * 3 + 2].
 */

/*
 * gdk_image compatibility functions - should be part of gdk, IMHO.
 */

/*
 * Create GdkRGBImage of width * height and return pointer
 * to it. Returns NULL on failure
 */
static GdkRGBImage *gdk_rgb_image_new(
        gint width,
        gint height)
{
	GdkRGBImage *result;

	/* Allocate a struct */
	result = g_new(GdkRGBImage, 1);

	/* Oops */
	if (result == NULL) return (NULL);

	/* Allocate buffer */
	result->image = g_new0(guchar, width * height * 3);

	/* Oops */
	if (result->image == NULL)
	{
		g_free(result);
		return (NULL);
	}

	/* Initialise size fields */
	result->width = width;
	result->height = height;

	/* Initialise reference count */
	result->ref_count = 1;

	/* Success */
	return (result);
}

/*
 * Free a GdkRGBImage
 */
static void gdk_rgb_image_destroy(
        GdkRGBImage *im)
{
	/* Paranoia */
	if (im == NULL) return;

	/* Free the RGB buffer */
	g_free(im->image);

	/* Free the structure */
	g_free(im);
}


#if 0

/*
 * Unref a GdkRGBImage
 */
static void gdk_rgb_image_unref(
        GdkRGBImage *im)
{
	/* Paranoia */
	g_return_if_fail(im != NULL);

	/* Decrease reference count by 1 */
	im->ref_count--;

	/* Free if nobody's using it */
	if (im->ref_count <= 0) gdk_rgb_image_destroy(im);
}


/*
 * Reference a GdkRGBImage
 */
static void gdk_rgb_image_ref(
        GdkRGBImage *im)
{
	/* Paranoia */
	g_return_if_fail(im != NULL);

	/* Increase reference count by 1 */
	im->ref_count++;
}

#endif /* 0 */


/*
 * Write RGB pixel of the format 0xRRGGBB to (x, y) in GdkRGBImage
 */
static void gdk_rgb_image_put_pixel(
        GdkRGBImage *im,
        gint x,
        gint y,
        guint32 pixel)
{
	guchar *rgbp;

	/* Paranoia */
	g_return_if_fail(im != NULL);

	/* Paranoia */
	if ((x < 0) || (x >= im->width)) return;

	/* Paranoia */
	if ((y < 0) || (y >= im->height)) return;

	/* Access RGB data */
	rgbp = &im->image[(y * im->width * 3) + (x * 3)];

	/* Red */
	*rgbp++ = (pixel >> 16) & 0xFF;
	/* Green */
	*rgbp++ = (pixel >> 8) & 0xFF;
	/* Blue */
	*rgbp = pixel & 0xFF;
}


/*
 * Returns RGB pixel (0xRRGGBB) at (x, y) in GdkRGBImage
 */
static guint32 gdk_rgb_image_get_pixel(
        GdkRGBImage *im,
        gint x,
        gint y)
{
	guchar *rgbp;

	/* Paranoia */
	if (im == NULL) return (0);

	/* Paranoia - returns black */
	if ((x < 0) || (x >= im->width)) return (0);

	/* Paranoia */
	if ((y < 0) || (y >= im->height)) return (0);

	/* Access RGB data */
	rgbp = &im->image[(y * im->width * 3) + (x * 3)];

	/* Return result */
	return ((rgbp[0] << 16) | (rgbp[1] << 8) | (rgbp[2]));
}


/*
 * Since gdk_draw_rgb_image is a bit harder to use than it's
 * GdkImage counterpart, I wrote a grue function that takes
 * exactly the same parameters as gdk_draw_image, with
 * the GdkImage parameter replaced with GdkRGBImage.
 */
static void gdk_draw_rgb_image_2(
        GdkDrawable *drawable,
        GdkGC *gc,
        GdkRGBImage *image,
        gint xsrc,
        gint ysrc,
        gint xdest,
        gint ydest,
        gint width,
        gint height)
{
	/* Paranoia */
	g_return_if_fail(drawable != NULL);
	g_return_if_fail(image != NULL);

	/* Paranoia */
	if (xsrc < 0 || (xsrc + width - 1) >= image->width) return;
	if (ysrc < 0 || (ysrc + height - 1) >= image->height) return;

	/* Draw the image at (xdest, ydest), with dithering if bpp <= 8/16 */
	gdk_draw_rgb_image(
	        drawable,
	        gc,
	        xdest,
	        ydest,
	        width,
	        height,
	        dith_mode,
	        &image->image[(ysrc * image->width * 3) + (xsrc * 3)],
	        image->width * 3);
}


/*
 * Code for smooth icon rescaling from Uwe Siems, Jan 2000
 *
 * XXX XXX Duplication of maid-x11.c, again. It doesn't do any colour
 * allocation, either.
 */

/*
 * to save ourselves some labour, define a maximum expected icon width here:
 */
#define MAX_ICON_WIDTH 32


/*
 * Each pixel is kept in this structure during smooth rescaling
 * calculations, to make things a bit easier
 */
typedef struct rgb_type rgb_type;

struct rgb_type
{
	guint32 red;
	guint32 green;
	guint32 blue;
};

/*
 * Because there are many occurences of this, and because
 * it's logical to do so...
 */
#define pixel_to_rgb(pix, rgb_buf) \
(rgb_buf)->red   = ((pix) >> 16) & 0xFF; \
(rgb_buf)->green = ((pix) >> 8)  & 0xFF; \
(rgb_buf)->blue  = (pix) & 0xFF


/*
 * get_scaled_row reads a scan from the given GdkRGBImage, scales it smoothly
 * and returns the red, green and blue values in arrays.
 * The values in this arrays must be divided by a certain value that is
 * calculated in scale_icon.
 * x, y is the position, iw is the input width and ow the output width
 * scan must be sufficiently sized
 */
static void get_scaled_row(
        GdkRGBImage *im,
        int x,
        int y,
        int iw,
        int ow,
        rgb_type *scan)
{
	int xi, si, sifrac, ci, cifrac, add_whole, add_frac;
	guint32 pix;
	rgb_type prev;
	rgb_type next;
	bool get_next_pix;

	/* Unscaled */
	if (iw == ow)
	{
		for (xi = 0; xi < ow; xi++)
		{
			pix = gdk_rgb_image_get_pixel(im, x + xi, y);
			pixel_to_rgb(pix, &scan[xi]);
		}
	}

	/* Scaling by subsampling (grow) */
	else if (iw < ow)
	{
		iw--;
		ow--;

		/* read first pixel: */
		pix = gdk_rgb_image_get_pixel(im, x, y);
		pixel_to_rgb(pix, &next);
		prev = next;

		/* si and sifrac give the subsampling position: */
		si = x;
		sifrac = 0;

		/* get_next_pix tells us, that we need the next pixel */
		get_next_pix = TRUE;

		for (xi = 0; xi <= ow; xi++)
		{
			if (get_next_pix)
			{
				prev = next;
				if (xi < ow)
				{
					/* only get next pixel if in same icon */
					pix = gdk_rgb_image_get_pixel(im, si + 1, y);
					pixel_to_rgb(pix, &next);
				}
			}

			/* calculate subsampled color values: */
			/* division by ow occurs in scale_icon */
			scan[xi].red = prev.red * (ow - sifrac) + next.red * sifrac;
			scan[xi].green = prev.green * (ow - sifrac) + next.green * sifrac;
			scan[xi].blue = prev.blue * (ow - sifrac) + next.blue * sifrac;

			/* advance sampling position: */
			sifrac += iw;
			if (sifrac >= ow)
			{
				si++;
				sifrac -= ow;
				get_next_pix = TRUE;
			}
			else
			{
				get_next_pix = FALSE;
			}

		}
	}

	/* Scaling by averaging (shrink) */
	else
	{
		/* width of an output pixel in input pixels: */
		add_whole = iw / ow;
		add_frac = iw % ow;

		/* start position of the first output pixel: */
		si = x;
		sifrac = 0;

		/* get first input pixel: */
		pix = gdk_rgb_image_get_pixel(im, x, y);
		pixel_to_rgb(pix, &next);

		for (xi = 0; xi < ow; xi++)
		{
			/* find endpoint of the current output pixel: */
			ci = si + add_whole;
			cifrac = sifrac + add_frac;
			if (cifrac >= ow)
			{
				ci++;
				cifrac -= ow;
			}

			/* take fraction of current input pixel (starting segment): */
			scan[xi].red = next.red * (ow - sifrac);
			scan[xi].green = next.green * (ow - sifrac);
			scan[xi].blue = next.blue * (ow - sifrac);
			si++;

			/* add values for whole pixels: */
			while (si < ci)
			{
				rgb_type tmp_rgb;

				pix = gdk_rgb_image_get_pixel(im, si, y);
				pixel_to_rgb(pix, &tmp_rgb);
				scan[xi].red += tmp_rgb.red * ow;
				scan[xi].green += tmp_rgb.green * ow;
				scan[xi].blue += tmp_rgb.blue * ow;
				si++;
			}

			/* add fraction of current input pixel (ending segment): */
			if (xi < ow - 1)
			{
				/* only get next pixel if still in icon: */
				pix = gdk_rgb_image_get_pixel(im, si, y);
				pixel_to_rgb(pix, &next);
			}

			sifrac = cifrac;
			if (sifrac > 0)
			{
				scan[xi].red += next.red * sifrac;
				scan[xi].green += next.green * sifrac;
				scan[xi].blue += next.blue * sifrac;
			}
		}
	}
}


/*
 * put_rgb_scan takes arrays for red, green and blue and writes pixel values
 * according to this values in the GdkRGBImage-structure. w is the number of
 * pixels to write and div is the value by which all red/green/blue values
 * are divided first.
 */
static void put_rgb_scan(
        GdkRGBImage *im,
        int x,
        int y,
        int w,
        int div,
        rgb_type *scan)
{
	int xi;
	guint32 pix;
	guint32 adj = div / 2;

	for (xi = 0; xi < w; xi++)
	{
		byte r, g, b;

		/* un-factor the RGB values */
		r = (scan[xi].red + adj) / div;
		g = (scan[xi].green + adj) / div;
		b = (scan[xi].blue + adj) / div;

#ifdef SUPPORT_GAMMA

		/* Apply gamma correction if requested and available */
		if (gamma_table_ready)
		{
			r = gamma_table[r];
			g = gamma_table[g];
			b = gamma_table[b];
		}

#endif /* SUPPORT_GAMMA */

		/* Make a (virtual) 24-bit pixel */
		pix = (r << 16) | (g << 8) | (b);

		/* Draw it into image */
		gdk_rgb_image_put_pixel(im, x + xi, y, pix);
	}
}


/*
 * scale_icon transfers an area from GdkRGBImage im_in, locate (x1,y1) to
 * im_out, locate (x2, y2). Source size is (ix, iy) and destination size
 * is (ox, oy).
 *
 * It does this by getting icon scan line from get_scaled_scan and handling
 * them the same way as pixels are handled in get_scaled_scan.
 * This even allows icons to be scaled differently in horizontal and
 * vertical directions (eg. shrink horizontal, grow vertical).
 */
static void scale_icon(
        GdkRGBImage *im_in,
        GdkRGBImage *im_out,
        int x1,
        int y1,
        int x2,
        int y2,
        int ix,
        int iy,
        int ox,
        int oy)
{
	int div;
	int xi, yi, si, sifrac, ci, cifrac, add_whole, add_frac;

	/* buffers for pixel rows: */
	rgb_type prev[MAX_ICON_WIDTH];
	rgb_type next[MAX_ICON_WIDTH];
	rgb_type temp[MAX_ICON_WIDTH];

	bool get_next_row;

	/* get divider value for the horizontal scaling: */
	if (ix == ox)
		div = 1;
	else if (ix < ox)
		div = ox - 1;
	else
		div = ix;

	/* no scaling needed vertically: */
	if (iy == oy)
	{
		for (yi = 0; yi < oy; yi++)
		{
			get_scaled_row(im_in, x1, y1 + yi, ix, ox, temp);
			put_rgb_scan(im_out, x2, y2 + yi, ox, div, temp);
		}
	}

	/* scaling by subsampling (grow): */
	else if (iy < oy)
	{
		iy--;
		oy--;
		div *= oy;

		/* get first row: */
		get_scaled_row(im_in, x1, y1, ix, ox, next);

		/* si and sifrac give the subsampling position: */
		si = y1;
		sifrac = 0;

		/* get_next_row tells us, that we need the next row */
		get_next_row = TRUE;
		for (yi = 0; yi <= oy; yi++)
		{
			if (get_next_row)
			{
				for (xi = 0; xi < ox; xi++)
				{
					prev[xi] = next[xi];
				}
				if (yi < oy)
				{
					/* only get next row if in same icon */
					get_scaled_row(im_in, x1, si + 1, ix, ox, next);
				}
			}

			/* calculate subsampled color values: */
			/* division by oy occurs in put_rgb_scan */
			for (xi = 0; xi < ox; xi++)
			{
				temp[xi].red = (prev[xi].red * (oy - sifrac) +
				                next[xi].red * sifrac);
				temp[xi].green = (prev[xi].green * (oy - sifrac) +
				                  next[xi].green * sifrac);
				temp[xi].blue = (prev[xi].blue * (oy - sifrac) +
				                 next[xi].blue * sifrac);
			}

			/* write row to output image: */
			put_rgb_scan(im_out, x2, y2 + yi, ox, div, temp);

			/* advance sampling position: */
			sifrac += iy;
			if (sifrac >= oy)
			{
				si++;
				sifrac -= oy;
				get_next_row = TRUE;
			}
			else
			{
				get_next_row = FALSE;
			}

		}
	}

	/* scaling by averaging (shrink) */
	else
	{
		div *= iy;

		/* height of a output row in input rows: */
		add_whole = iy / oy;
		add_frac = iy % oy;

		/* start position of the first output row: */
		si = y1;
		sifrac = 0;

		/* get first input row: */
		get_scaled_row(im_in, x1, y1, ix, ox, next);
		for (yi = 0; yi < oy; yi++)
		{
			/* find endpoint of the current output row: */
			ci = si + add_whole;
			cifrac = sifrac + add_frac;
			if (cifrac >= oy)
			{
				ci++;
				cifrac -= oy;
			}

			/* take fraction of current input row (starting segment): */
			for (xi = 0; xi < ox; xi++)
			{
				temp[xi].red = next[xi].red * (oy - sifrac);
				temp[xi].green = next[xi].green * (oy - sifrac);
				temp[xi].blue = next[xi].blue * (oy - sifrac);
			}
			si++;

			/* add values for whole pixels: */
			while (si < ci)
			{
				get_scaled_row(im_in, x1, si, ix, ox, next);
				for (xi = 0; xi < ox; xi++)
				{
					temp[xi].red += next[xi].red * oy;
					temp[xi].green += next[xi].green * oy;
					temp[xi].blue += next[xi].blue * oy;
				}
				si++;
			}

			/* add fraction of current input row (ending segment): */
			if (yi < oy - 1)
			{
				/* only get next row if still in icon: */
				get_scaled_row(im_in, x1, si, ix, ox, next);
			}
			sifrac = cifrac;
			for (xi = 0; xi < ox; xi++)
			{
				temp[xi].red += next[xi].red * sifrac;
				temp[xi].green += next[xi].green * sifrac;
				temp[xi].blue += next[xi].blue * sifrac;
			}

			/* write row to output image: */
			put_rgb_scan(im_out, x2, y2 + yi, ox, div, temp);
		}
	}
}


/*
 * Rescale icons using sort of anti-aliasing technique.
 */
static GdkRGBImage *resize_tiles_smooth(
        GdkRGBImage *im,
        int ix,
        int iy,
        int ox,
        int oy)
{
	int width1, height1, width2, height2;
	int x1, x2, y1, y2;

	GdkRGBImage *tmp;

	/* Original size */
	width1 = im->width;
	height1 = im->height;

	/* Rescaled size */
	width2 = ox * width1 / ix;
	height2 = oy * height1 / iy;

	/* Allocate GdkRGBImage for resized tiles */
	tmp = gdk_rgb_image_new(width2, height2);

	/* Oops */
	if (tmp == NULL) return (NULL);

	/* Scale each icon */
	for (y1 = 0, y2 = 0; (y1 < height1) && (y2 < height2); y1 += iy, y2 += oy)
	{
		for (x1 = 0, x2 = 0; (x1 < width1) && (x2 < width2); x1 += ix, x2 += ox)
		{
			scale_icon(im, tmp, x1, y1, x2, y2,
			           ix, iy, ox, oy);
		}
	}

	return tmp;
}


/*
 * Steven Fuerst's tile resizing code
 * Taken from Z because I think the algorithm is cool.
 */

/* 24-bit version - GdkRGB uses 24 bit RGB data internally */
static void copy_pixels(
        int wid,
        int y,
        int offset,
        int *xoffsets,
        GdkRGBImage *old_image,
        GdkRGBImage *new_image)
{
	int i;

	/* Get source and destination */
	byte *src = &old_image->image[offset * old_image->width * 3];
	byte *dst = &new_image->image[y * new_image->width * 3];

	/* Copy to the image */
	for (i = 0; i < wid; i++)
	{
#ifdef SUPPORT_GAMMA

		if (gamma_table_ready)
		{
			*dst++ = gamma_table[src[3 * xoffsets[i]]];
			*dst++ = gamma_table[src[3 * xoffsets[i] + 1]];
			*dst++ = gamma_table[src[3 * xoffsets[i] + 2]];

			continue;
		}

#endif /* SUPPORT_GAMMA */

		*dst++ = src[3 * xoffsets[i]];
		*dst++ = src[3 * xoffsets[i] + 1];
		*dst++ = src[3 * xoffsets[i] + 2];
	}
}


#if 0

/* 32-bit version: it might be useful in the future */
static void copy_pixels(
        int wid,
        int y,
        int offset,
        int *xoffsets,
        GdkRGBImage *old_image,
        GdkRGBImage *new_image)
{
	int i;

	/* Get source and destination */
	byte *src = &old_image->image[offset * old_image->width * 4];
	byte *dst = &new_image->image[y * new_image->width * 4];

	/* Copy to the image */
	for (i = 0; i < wid; i++)
	{
		*dst++ = src[4 * xoffsets[i]];
		*dst++ = src[4 * xoffsets[i] + 1];
		*dst++ = src[4 * xoffsets[i] + 2];
		*dst++ = src[4 * xoffsets[i] + 3];
	}
}

#endif


/*
 * Resize ix * iy pixel tiles in old to ox * oy pixels
 * and return a new GdkRGBImage containing the resized tiles
 */
static GdkRGBImage *resize_tiles_fast(
        GdkRGBImage *old_image,
        int ix,
        int iy,
        int ox,
        int oy)
{
	GdkRGBImage *new_image;

	int old_wid, old_hgt;

	int new_wid, new_hgt;

	int add, remainder, rem_tot, offset;

	int *xoffsets;

	int i;


	/* Get the size of the old image */
	old_wid = old_image->width;
	old_hgt = old_image->height;

	/* Calculate the size of the new image */
	new_wid = (old_wid / ix) * ox;
	new_hgt = (old_hgt / iy) * oy;

	/* Allocate a GdkRGBImage to store resized tiles */
	new_image = gdk_rgb_image_new(new_wid, new_hgt);

	/* Paranoia */
	if (new_image == NULL) return (NULL);

	/* now begins the cool part of SF's code */

	/*
	 * Calculate an offsets table, so the transformation
	 * is faster.  This is much like the Bresenham algorithm
	 */

	/* Set up x offset table */
	C_MAKE(xoffsets, new_wid, int);

	/* Initialize line parameters */
	add = old_wid / new_wid;
	remainder = old_wid % new_wid;

	/* Start at left */
	offset = 0;

	/* Half-tile offset so 'line' is centered correctly */
	rem_tot = new_wid / 2;

	for (i = 0; i < new_wid; i++)
	{
		/* Store into the table */
		xoffsets[i] = offset;

		/* Move to next entry */
		offset += add;

		/* Take care of fractional part */
		rem_tot += remainder;
		if (rem_tot >= new_wid)
		{
			rem_tot -= new_wid;
			offset++;
		}
	}

	/* Scan each row */

	/* Initialize line parameters */
	add = old_hgt / new_hgt;
	remainder = old_hgt % new_hgt;

	/* Start at left */
	offset = 0;

	/* Half-tile offset so 'line' is centered correctly */
	rem_tot = new_hgt / 2;

	for (i = 0; i < new_hgt; i++)
	{
		/* Copy pixels to new image */
		copy_pixels(new_wid, i, offset, xoffsets, old_image, new_image);

		/* Move to next entry */
		offset += add;

		/* Take care of fractional part */
		rem_tot += remainder;
		if (rem_tot >= new_hgt)
		{
			rem_tot -= new_hgt;
			offset++;
		}
	}

	/* Free offset table */
	C_FREE(xoffsets, new_wid, int);

	return (new_image);
}


/*
 * Resize an image of ix * iy pixels and return a newly allocated
 * image of ox * oy pixels.
 */
static GdkRGBImage *resize_tiles(
        GdkRGBImage *im,
        int ix,
        int iy,
        int ox,
        int oy)
{
	GdkRGBImage *result;

	/*
	 * I hope we can always use this with GdkRGB, which uses a 5x5x5
	 * colour cube (125 colours) by default, and resort to dithering
	 * when it can't find good match there or expand the cube, so it
	 * works with 8bpp X servers.
	 */
	if (smooth_rescaling_request && (ix != ox || iy != oy))
	{
		result = resize_tiles_smooth(im, ix, iy, ox, oy);
	}

	/*
	 * Unless smoothing is requested by user, we use the fast
	 * resizing code.
	 */
	else
	{
		result = resize_tiles_fast(im, ix, iy, ox, oy);
	}

	/* Return rescaled tiles, or NULL */
	return (result);
}


/*
 * Tile loaders - XPM and BMP
 */

/*
 * A helper function for the XPM loader
 *
 * Read next string delimited by double quotes from
 * the input stream. Return TRUE on success, FALSE
 * if it finds EOF or buffer overflow.
 *
 * I never mean this to be generic, so its EOF and buffer
 * overflow behaviour is terribly stupid -- there are no
 * provisions for recovery.
 *
 * CAVEAT: treatment of backslash is not compatible with the standard
 * C usage XXX XXX XXX XXX
 */
static bool read_str(char *buf, u32b len, FILE *f)
{
	int c;

	/* Paranoia - Buffer too small */
	if (len <= 0) return (FALSE);

	/* Find " */
	while ((c = getc(f)) != '"')
	{
		/* Premature EOF */
		if (c == EOF) return (FALSE);
	}

	while (1)
	{
		/* Read next char */
		c = getc(f);

		/* Premature EOF */
		if (c == EOF) return (FALSE);

		/* Terminating " */
		if (c == '"') break;

		/* Escape */
		if (c == '\\')
		{
			/* Use next char */
			c = getc(f);

			/* Premature EOF */
			if (c == EOF) return (FALSE);
		}

		/* Store character in the buffer */
		*buf++ = c;

		/* Decrement count */
		len--;

		/* Buffer full - we have to place a NULL at the end */
		if (len <= 0) return (FALSE);
	}

	/* Make a C string if there's room left */
	if (len > 0) *buf = '\0';

	/* Success */
	return (TRUE);
}


/*
 * Remember pixel symbol to RGB colour mappings
 */

/*
 * I've forgot the formula, but I remember prime number yields
 * good results
 */
#define HASH_SIZE 19

typedef struct pal_type pal_type;

struct pal_type
{
	u32b str;
	u32b rgb;
	pal_type *next;
};


/*
 * A simple, slow and stupid XPM loader
 */
static GdkRGBImage *load_xpm(cptr filename)
{
	FILE *f;
	GdkRGBImage *img = NULL;
	int width, height, colours, chars;
	int i, j, k;
	bool ret;
	pal_type *pal = NULL;
	pal_type *head[HASH_SIZE];
	u32b buflen = 0;
	char *lin = NULL;
	char buf[1024];

	/* Build path to the XPM file */
	path_build(buf, 1024, ANGBAND_DIR_XTRA_GRAF, filename);

	/* Open it */
	f = my_fopen(buf, "r");

	/* Oops */
	if (f == NULL) return (NULL);

	/* Read header */
	ret = read_str(buf, 1024, f);

	/* Oops */
	if (!ret)
	{
		/* Notify error */
		plog("Cannot find XPM header");

		/* Failure */
		goto oops;
	}

	/* Parse header */
	if (4 != sscanf(buf, "%d %d %d %d", &width, &height, &colours, &chars))
	{
		/* Notify error */
		plog("Bad XPM header");

		/* Failure */
		goto oops;
	}

	/*
	 * Paranoia - the code can handle upto four letters per pixel,
	 * but such large number of colours certainly requires a smarter
	 * symbol-to-colour mapping algorithm...
	 */
	if ((width <= 0) || (height <= 0) || (colours <= 0) || (chars <= 0) ||
	                (chars > 2))
	{
		/* Notify error */
		plog("Invalid width/height/depth");

		/* Failure */
		goto oops;
	}

	/* Allocate palette */
	C_MAKE(pal, colours, pal_type);

	/* Initialise hash table */
	for (i = 0; i < HASH_SIZE; i++) head[i] = NULL;

	/* Parse palette */
	for (i = 0; i < colours; i++)
	{
		u32b tmp;
		int h_idx;

		/* Read next string */
		ret = read_str(buf, 1024, f);

		/* Check I/O result */
		if (!ret)
		{
			/* Notify error */
			plog("EOF in palette");

			/* Failure */
			goto oops;
		}

		/* Clear symbol code */
		tmp = 0;

		/* Encode pixel symbol */
		for (j = 0; j < chars; j++)
		{
			tmp = (tmp << 8) | (buf[j] & 0xFF);
		}

		/* Remember it */
		pal[i].str = tmp;

		/* Skip spaces */
		while ((buf[j] == ' ') || (buf[j] == '\t')) j++;

		/* Verify 'c' */
		if (buf[j] != 'c')
		{
			/* Notify error */
			plog("No 'c' in palette definition");

			/* Failure */
			goto oops;
		}

		/* Advance cursor */
		j++;

		/* Skip spaces */
		while ((buf[j] == ' ') || (buf[j] == '\t')) j++;

		/* Hack - Assume 'None' */
		if (buf[j] == 'N')
		{
			/* Angband always uses black background */
			pal[i].rgb = 0x000000;
		}

		/* Read colour */
		else if ((1 != sscanf(&buf[j], "#%06lX", &tmp)) &&
		                (1 != sscanf(&buf[j], "#%06lx", &tmp)))
		{
			/* Notify error */
			plog("Badly formatted colour");

			/* Failure */
			goto oops;
		}

		/* Remember it */
		pal[i].rgb = tmp;

		/* Store it in hash table as well */
		h_idx = pal[i].str % HASH_SIZE;

		/* Link the entry */
		pal[i].next = head[h_idx];
		head[h_idx] = &pal[i];
	}

	/* Allocate image */
	img = gdk_rgb_image_new(width, height);

	/* Oops */
	if (img == NULL)
	{
		/* Notify error */
		plog("Cannot allocate image");

		/* Failure */
		goto oops;
	}

	/* Calculate buffer length */
	buflen = width * chars + 1;

	/* Allocate line buffer */
	C_MAKE(lin, buflen, char);

	/* For each row */
	for (i = 0; i < height; i++)
	{
		/* Read a row of image data */
		ret = read_str(lin, buflen, f);

		/* Oops */
		if (!ret)
		{
			/* Notify error */
			plog("EOF in middle of image data");

			/* Failure */
			goto oops;
		}

		/* For each column */
		for (j = 0; j < width; j++)
		{
			u32b tmp;
			pal_type *h_ptr;

			/* Clear encoded pixel */
			tmp = 0;

			/* Encode pixel symbol */
			for (k = 0; k < chars; k++)
			{
				tmp = (tmp << 8) | (lin[j * chars + k] & 0xFF);
			}

			/* Find colour */
			for (h_ptr = head[tmp % HASH_SIZE];
			                h_ptr != NULL;
			                h_ptr = h_ptr->next)
			{
				/* Found a match */
				if (h_ptr->str == tmp) break;
			}

			/* No match found */
			if (h_ptr == NULL)
			{
				/* Notify error */
				plog("Invalid pixel symbol");

				/* Failure */
				goto oops;
			}

			/* Draw it */
			gdk_rgb_image_put_pixel(
			        img,
			        j,
			        i,
			        h_ptr->rgb);
		}
	}

	/* Close file */
	my_fclose(f);

	/* Free line buffer */
	C_FREE(lin, buflen, char);

	/* Free palette */
	C_FREE(pal, colours, pal_type);

	/* Return result */
	return (img);

oops:

	/* Close file */
	my_fclose(f);

	/* Free image */
	if (img) gdk_rgb_image_destroy(img);

	/* Free line buffer */
	if (lin) C_FREE(lin, buflen, char);

	/* Free palette */
	if (pal) C_FREE(pal, colours, pal_type);

	/* Failure */
	return (NULL);
}


/*
 * A BMP loader, yet another duplication of maid-x11.c functions.
 *
 * Another duplication, again because of different image format and
 * avoidance of colour allocation.
 *
 * XXX XXX XXX XXX Should avoid using a propriatary and closed format.
 * Since it's much bigger than gif that was used before, why don't
 * we switch to XPM?  NetHack does.  Well, NH has always been much
 * closer to the GNU/Un*x camp and it's GPL'ed quite early...
 *
 * The names and naming convention are worse than the worst I've ever
 * seen, so I deliberately changed them to fit well with the rest of
 * the code. Or are they what xx calls them? If it's the case, there's
 * no reason to follow *their* words.
 */

/*
 * BMP file header
 */
typedef struct bmp_file_type bmp_file_type;

struct bmp_file_type
{
	u16b type;
	u32b size;
	u16b reserved1;
	u16b reserved2;
	u32b offset;
};


/*
 * BMP file information fields
 */
typedef struct bmp_info_type bmp_info_type;

struct bmp_info_type
{
	u32b size;
	u32b width;
	u32b height;
	u16b planes;
	u16b bit_count;
	u32b compression;
	u32b size_image;
	u32b x_pels_per_meter;
	u32b y_pels_per_meter;
	u32b colors_used;
	u32b color_importand;
};

/*
 * "RGBQUAD" type.
 */
typedef struct rgb_quad_type rgb_quad_type;

struct rgb_quad_type
{
	unsigned char b, g, r;
	unsigned char filler;
};


/*** Helper functions for system independent file loading. ***/

static byte get_byte(FILE *fff)
{
	/* Get a character, and return it */
	return (getc(fff) & 0xFF);
}

static void rd_byte(FILE *fff, byte *ip)
{
	*ip = get_byte(fff);
}

static void rd_u16b(FILE *fff, u16b *ip)
{
	(*ip) = get_byte(fff);
	(*ip) |= ((u16b)(get_byte(fff)) << 8);
}

static void rd_u32b(FILE *fff, u32b *ip)
{
	(*ip) = get_byte(fff);
	(*ip) |= ((u32b)(get_byte(fff)) << 8);
	(*ip) |= ((u32b)(get_byte(fff)) << 16);
	(*ip) |= ((u32b)(get_byte(fff)) << 24);
}


/*
 * Read a BMP file (a certain trademark nuked)
 *
 * This function replaces the old ReadRaw and RemapColors functions.
 *
 * Assumes that the bitmap has a size such that no padding is needed in
 * various places.  Currently only handles bitmaps with 3 to 256 colors.
 */
GdkRGBImage *load_bmp(cptr filename)
{
	FILE *f;

	char path[1024];

	bmp_file_type file_hdr;
	bmp_info_type info_hdr;

	GdkRGBImage *result = NULL;

	int ncol;

	int i;

	u32b x, y;

	guint32 colour_pixels[256];


	/* Build the path to the bmp file */
	path_build(path, 1024, ANGBAND_DIR_XTRA_GRAF, filename);

	/* Open the BMP file */
	f = fopen(path, "r");

	/* No such file */
	if (f == NULL)
	{
		return (NULL);
	}

	/* Read the "bmp_file_type" */
	rd_u16b(f, &file_hdr.type);
	rd_u32b(f, &file_hdr.size);
	rd_u16b(f, &file_hdr.reserved1);
	rd_u16b(f, &file_hdr.reserved2);
	rd_u32b(f, &file_hdr.offset);

	/* Read the "bmp_info_type" */
	rd_u32b(f, &info_hdr.size);
	rd_u32b(f, &info_hdr.width);
	rd_u32b(f, &info_hdr.height);
	rd_u16b(f, &info_hdr.planes);
	rd_u16b(f, &info_hdr.bit_count);
	rd_u32b(f, &info_hdr.compression);
	rd_u32b(f, &info_hdr.size_image);
	rd_u32b(f, &info_hdr.x_pels_per_meter);
	rd_u32b(f, &info_hdr.y_pels_per_meter);
	rd_u32b(f, &info_hdr.colors_used);
	rd_u32b(f, &info_hdr.color_importand);

	/* Verify the header */
	if (feof(f) ||
	                (file_hdr.type != 19778) ||
	                (info_hdr.size != 40))
	{
		plog(format("Incorrect BMP file format %s", filename));
		fclose(f);
		return (NULL);
	}

	/*
	 * The two headers above occupy 54 bytes total
	 * The "offset" field says where the data starts
	 * The "colors_used" field does not seem to be reliable
	 */

	/* Compute number of colors recorded */
	ncol = (file_hdr.offset - 54) / 4;

	for (i = 0; i < ncol; i++)
	{
		rgb_quad_type clr;

		/* Read an "rgb_quad_type" */
		rd_byte(f, &clr.b);
		rd_byte(f, &clr.g);
		rd_byte(f, &clr.r);
		rd_byte(f, &clr.filler);

		/* Remember the pixel */
		colour_pixels[i] = (clr.r << 16) | (clr.g << 8) | (clr.b);
	}

	/* Allocate GdkRGBImage large enough to store the image */
	result = gdk_rgb_image_new(info_hdr.width, info_hdr.height);

	/* Failure */
	if (result == NULL)
	{
		fclose(f);
		return (NULL);
	}

	for (y = 0; y < info_hdr.height; y++)
	{
		u32b y2 = info_hdr.height - y - 1;

		for (x = 0; x < info_hdr.width; x++)
		{
			int ch = getc(f);

			/* Verify not at end of file XXX XXX */
			if (feof(f))
			{
				plog(format("Unexpected end of file in %s", filename));
				gdk_rgb_image_destroy(result);
				fclose(f);
				return (NULL);
			}

			if (info_hdr.bit_count == 24)
			{
				int c3, c2 = getc(f);

				/* Verify not at end of file XXX XXX */
				if (feof(f))
				{
					plog(format("Unexpected end of file in %s", filename));
					gdk_rgb_image_destroy(result);
					fclose(f);
					return (NULL);
				}

				c3 = getc(f);

				/* Verify not at end of file XXX XXX */
				if (feof(f))
				{
					plog(format("Unexpected end of file in %s", filename));
					gdk_rgb_image_destroy(result);
					fclose(f);
					return (NULL);
				}

				/* Draw the pixel */
				gdk_rgb_image_put_pixel(
				        result,
				        x,
				        y2,
				        (ch << 16) | (c2 << 8) | (c3));
			}
			else if (info_hdr.bit_count == 8)
			{
				gdk_rgb_image_put_pixel(result, x, y2, colour_pixels[ch]);
			}
			else if (info_hdr.bit_count == 4)
			{
				gdk_rgb_image_put_pixel(result, x, y2, colour_pixels[ch / 16]);
				x++;
				gdk_rgb_image_put_pixel(result, x, y2, colour_pixels[ch % 16]);
			}
			else
			{
				/* Technically 1 bit is legal too */
				plog(format("Illegal bit count %d in %s",
				            info_hdr.bit_count, filename));
				gdk_rgb_image_destroy(result);
				fclose(f);
				return (NULL);
			}
		}
	}

	fclose(f);

	return result;
}


/*
 * Try to load an XPM file, or a BMP file if it fails
 *
 * Choice of file format may better be made yet another option XXX
 */
static GdkRGBImage *load_tiles(cptr basename)
{
	char buf[32];
	GdkRGBImage *img;

	/* build xpm file name */
	strnfmt(buf, 32, "%s.xpm", basename);

	/* Try to load it */
	img = load_xpm(buf);

	/* OK */
	if (img) return (img);

	/* Try again for a bmp file */
	strnfmt(buf, 32, "%s.bmp", basename);

	/* Try loading it */
	img = load_bmp(buf);

	/* Return result, success or failure */
	return (img);
}


/*
 * Free all tiles and graphics buffers associated with windows
 *
 * This is conspirator of graf_init() below, sharing its inefficiency
 */
static void graf_nuke()
{
	int i;

	term_data *td;


	/* Nuke all terms */
	for (i = 0; i < MAX_TERM_DATA; i++)
	{
		/* Access term_data structure */
		td = &data[i];

		/* Disable graphics */
		td->t.higher_pict = FALSE;

		/* Free previously allocated tiles */
		if (td->tiles) gdk_rgb_image_destroy(td->tiles);

		/* Forget pointer */
		td->tiles = NULL;

# ifdef USE_TRANSPARENCY

		/* Free previously allocated transparency buffer */
		if (td->trans_buf) gdk_rgb_image_destroy(td->trans_buf);

		/* Forget stale pointer */
		td->trans_buf = NULL;

# endif  /* USE_TRANSPARENCY */

	}
}


/*
 * Load tiles, scale them to current font size, and store a pointer
 * to them in a term_data structure for each term.
 *
 * XXX XXX XXX This is a terribly stupid quick hack.
 *
 * XXX XXX XXX Windows using the same font should share resized tiles
 */
static bool graf_init(
        cptr filename,
        int tile_wid,
        int tile_hgt)
{
	term_data *td;

	bool result;

	GdkRGBImage *raw_tiles, *scaled_tiles;

# ifdef USE_TRANSPARENCY
	GdkRGBImage *buffer;
# endif  /* USE_TRANSPARENCY */

	int i;


	/* Paranoia */
	if (filename == NULL) return (FALSE);

	/* Load tiles */
	raw_tiles = load_tiles(filename);

	/* Oops */
	if (raw_tiles == NULL)
	{
		/* Clean up */
		graf_nuke();

		/* Failure */
		return (FALSE);
	}

	/* Calculate and remember numbers of rows and columns */
	tile_rows = raw_tiles->height / tile_hgt;
	tile_cols = raw_tiles->width / tile_wid;

	/* Be optimistic */
	result = TRUE;


	/*
	 * (Re-)init each term
	 * XXX It might help speeding this up to avoid doing so if a window
	 * doesn't need graphics (e.g. inventory/equipment and message recall).
	 */
	for (i = 0; i < MAX_TERM_DATA; i++)
	{
		/* Access term_data */
		td = &data[i];

		/* Shouldn't waste anything for unused terms */
		if (!td->shown) continue;

		/* Enable graphics */
		td->t.higher_pict = TRUE;

		/* See if we need rescaled tiles XXX */
		if ((td->tiles == NULL) ||
		                (td->tiles->width != td->tile_wid * tile_cols) ||
		                (td->tiles->height != td->tile_hgt * tile_rows))
		{
			/* Free old tiles if present */
			if (td->tiles) gdk_rgb_image_destroy(td->tiles);

			/* Forget pointer */
			td->tiles = NULL;

			/* Scale the tiles to current font bounding rect */
			scaled_tiles = resize_tiles(
			                       raw_tiles,
			                       tile_wid, tile_hgt,
			                       td->tile_wid, td->tile_hgt);

			/* Oops */
			if (scaled_tiles == NULL)
			{
				/* Failure */
				result = FALSE;

				break;
			}

			/* Store it */
			td->tiles = scaled_tiles;
		}

# ifdef USE_TRANSPARENCY

		/* See if we have to (re)allocate a new buffer XXX */
		if ((td->trans_buf == NULL) ||
		                (td->trans_buf->width != td->tile_wid) ||
		                (td->trans_buf->height != td->tile_hgt))
		{
			/* Free old buffer if present */
			if (td->trans_buf) gdk_rgb_image_destroy(td->trans_buf);

			/* Forget pointer */
			td->trans_buf = NULL;

			/* Allocate a new buffer */
			buffer = gdk_rgb_image_new(td->tile_wid, td->tile_hgt);

			/* Oops */
			if (buffer == NULL)
			{
				/* Failure */
				result = FALSE;

				break;
			}

			/* Store it */
			td->trans_buf = buffer;
		}

		/*
		 * Giga-Hack - assume top left corner of 0x86/0x80 should be
		 * in the background colour XXX XXX XXX XXX
		 */
		td->bg_pixel = gdk_rgb_image_get_pixel(
		                       raw_tiles,
		                       0,
		                       tile_hgt * 6);

# endif  /* USE_TRANSPARENCY */

	}


	/* Alas, we need to free wasted images */
	if (result == FALSE) graf_nuke();

	/* We don't need the raw image any longer */
	gdk_rgb_image_destroy(raw_tiles);

	/* Report success or failure */
	return (result);
}


/*
 * React to various changes in graphics mode settings
 *
 * It is *not* a requirement for tiles to have same pixel width and height.
 * The program can work with any conbinations of graf_wid and graf_hgt
 * (oops, they must be representable by u16b), as long as they are lesser
 * or equal to 32 if you use smooth rescaling.
 */
static void init_graphics(void)
{
	cptr tile_name;

	u16b graf_wid = 0, graf_hgt = 0;


	/* No graphics requests are made - Can't this be simpler? XXX XXX */
	if ((graf_mode_request == graf_mode) &&
	                (smooth_rescaling_request == smooth_rescaling) &&
	                !resize_request) return;

	/* Prevent further unsolicited reaction */
	resize_request = FALSE;


	/* Dispose unusable old tiles - awkward... XXX XXX */
	if ((graf_mode_request == GRAF_MODE_NONE) ||
	                (graf_mode_request != graf_mode) ||
	                (smooth_rescaling_request != smooth_rescaling)) graf_nuke();


	/* Setup parameters according to request */
	switch (graf_mode_request)
	{
		/* ASCII - no graphics whatsoever */
	default:
	case GRAF_MODE_NONE:
		{
			tile_name = NULL;
			use_graphics = arg_graphics = FALSE;

			break;
		}

		/*
		 * 8x8 tiles originally collected for the Amiga port
		 * from several contributers by Lars Haugseth, converted
		 * to 256 colours and expanded by the Z devteam
		 *
		 * Use the "old" tile assignments
		 *
		 * Dawnmist is working on it for ToME
		 */
	case GRAF_MODE_OLD:
		{
			tile_name = "8x8";
			graf_wid = graf_hgt = 8;
			ANGBAND_GRAF = "old";
			use_graphics = arg_graphics = TRUE;

			break;
		}

		/*
		 * Adam Bolt's 16x16 tiles
		 * "new" tile assignments
		 * It is updated for ToME by Andreas Koch
		 */
	case GRAF_MODE_NEW:
		{
			tile_name = "16x16";
			graf_wid = graf_hgt = 16;
			ANGBAND_GRAF = "new";
			use_graphics = arg_graphics = TRUE;

			break;
		}
	}


	/* load tiles and set them up if tiles are requested */
	if ((graf_mode_request != GRAF_MODE_NONE) &&
	                !graf_init(tile_name, graf_wid, graf_hgt))
	{
		/* Oops */
		plog("Cannot initialize graphics");

		/* reject requests */
		graf_mode_request = GRAF_MODE_NONE;
		smooth_rescaling_request = smooth_rescaling;

		/* reset graphics flags */
		use_graphics = arg_graphics = FALSE;
	}

	/* Update current graphics mode */
	graf_mode = graf_mode_request;
	smooth_rescaling = smooth_rescaling_request;

	/* Reset visuals */
#ifndef ANG281_RESET_VISUALS
	reset_visuals(TRUE);
#else
	reset_visuals();
#endif /* !ANG281_RESET_VISUALS */
}

#endif /* USE_GRAPHICS */




/**** Term package support routines ****/


/*
 * Free data used by a term
 */
static void Term_nuke_gtk(term *t)
{
	term_data *td = t->data;


	/* Free name */
	if (td->name) string_free(td->name);

	/* Forget it */
	td->name = NULL;

	/* Free font */
	if (td->font) gdk_font_unref(td->font);

	/* Forget it */
	td->font = NULL;

	/* Free backing store */
	if (td->backing_store) gdk_pixmap_unref(td->backing_store);

	/* Forget it too */
	td->backing_store = NULL;

#ifdef USE_GRAPHICS

	/* Free tiles */
	if (td->tiles) gdk_rgb_image_destroy(td->tiles);

	/* Forget pointer */
	td->tiles = NULL;

# ifdef USE_TRANSPARENCY

	/* Free transparency buffer */
	if (td->trans_buf) gdk_rgb_image_destroy(td->trans_buf);

	/* Amnesia */
	td->trans_buf = NULL;

# endif  /* USE_TRANSPARENCY */

#endif /* USE_GRAPHICS */
}


/*
 * Erase the whole term.
 */
static errr Term_clear_gtk(void)
{
	term_data *td = (term_data*)(Term->data);


	/* Don't draw to hidden windows */
	if (!td->shown) return (0);

	/* Paranoia */
	g_assert(td->drawing_area->window != 0);

	/* Clear the area */
	gdk_draw_rectangle(
	        TERM_DATA_DRAWABLE(td),
	        td->drawing_area->style->black_gc,
	        1,
	        0,
	        0,
	        td->cols * td->font_wid,
	        td->rows * td->font_hgt);

	/* Copy image from backing store if present */
	TERM_DATA_REFRESH(td, 0, 0, td->cols, td->rows);

	/* Success */
	return (0);
}


/*
 * Erase some characters.
 */
static errr Term_wipe_gtk(int x, int y, int n)
{
	term_data *td = (term_data*)(Term->data);


	/* Don't draw to hidden windows */
	if (!td->shown) return (0);

	/* Paranoia */
	g_assert(td->drawing_area->window != 0);

	/* Fill the area with the background colour */
	gdk_draw_rectangle(
	        TERM_DATA_DRAWABLE(td),
	        td->drawing_area->style->black_gc,
	        TRUE,
	        x * td->font_wid,
	        y * td->font_hgt,
	        n * td->font_wid,
	        td->font_hgt);

	/* Copy image from backing store if present */
	TERM_DATA_REFRESH(td, x, y, n, 1);

	/* Success */
	return (0);
}


/*
 * Draw some textual characters.
 */
static errr Term_text_gtk(int x, int y, int n, byte a, cptr s)
{
	term_data *td = (term_data*)(Term->data);


	/* Don't draw to hidden windows */
	if (!td->shown) return (0);

	/* Paranoia */
	g_assert(td->drawing_area->window != 0);

	/* Set foreground colour */
	term_data_set_fg(td, a);

	/* Clear the line */
	Term_wipe_gtk(x, y, n);

	/* Draw the text to the window */
	gdk_draw_text(
	        TERM_DATA_DRAWABLE(td),
	        td->font,
	        td->gc,
	        x * td->font_wid,
	        td->font->ascent + y * td->font_hgt,
	        s,
	        n);

	/* Copy image from backing store if present */
	TERM_DATA_REFRESH(td, x, y, n, 1);

	/* Success */
	return (0);
}


/*
 * Draw software cursor at (x, y)
 */
static errr Term_curs_gtk(int x, int y)
{
	term_data *td = (term_data*)(Term->data);
	int cells = 1;


	/* Don't draw to hidden windows */
	if (!td->shown) return (0);

	/* Paranoia */
	g_assert(td->drawing_area->window != 0);

	/* Set foreground colour */
	term_data_set_fg(td, TERM_YELLOW);

#ifdef USE_DOUBLE_TILES

	/* Mogami's bigtile patch */

	/* Adjust it if wide tiles are requested */
	if (use_bigtile &&
	                (x + 1 < Term->wid) &&
	                (Term->old->a[y][x + 1] == 255))
	{
		cells = 2;
	}

#endif /* USE_DOUBLE_TILES */

	/* Draw the software cursor */
	gdk_draw_rectangle(
	        TERM_DATA_DRAWABLE(td),
	        td->gc,
	        FALSE,
	        x * td->font_wid,
	        y * td->font_hgt,
	        td->font_wid * cells - 1,
	        td->font_hgt - 1);

	/* Copy image from backing store if present */
	TERM_DATA_REFRESH(td, x, y, cells, 1);

	/* Success */
	return (0);
}


#ifdef USE_GRAPHICS

# ifdef USE_TRANSPARENCY

/*
 * XXX XXX Low level graphics helper
 * Draw a tile at (s_x, s_y) over one at (t_x, t_y) and store the
 * result in td->trans_buf
 *
 * XXX XXX Even if CPU's are faster than necessary these days,
 * this should be made inline. Or better, there should be an API
 * to take advantage of graphics hardware. They almost always have
 * assortment of builtin bitblt's...
 */
static void overlay_tiles_2(
        term_data *td,
        int s_x, int s_y,
        int t_x, int t_y)
{
	guint32 pix;
	int x, y;


	/* Process each row */
	for (y = 0; y < td->tile_hgt; y++)
	{
		/* Process each column */
		for (x = 0; x < td->tile_wid; x++)
		{
			/* Get an overlay pixel */
			pix = gdk_rgb_image_get_pixel(td->tiles, s_x + x, s_y + y);

			/* If it's in background color, use terrain instead */
			if (pix == td->bg_pixel)
				pix = gdk_rgb_image_get_pixel(td->tiles, t_x + x, t_y + y);

			/* Store the result in trans_buf */
			gdk_rgb_image_put_pixel(td->trans_buf, x, y, pix);
		}
	}
}


# ifdef USE_EGO_GRAPHICS

/*
 * XXX XXX Low level graphics helper
 * Draw a tile at (e_x, e_y) over one at (s_x, s_y) over another one
 * at (t_x, t_y) and store the result in td->trans_buf
 *
 * XXX XXX The same comment applies as that for the above...
 */
static void overlay_tiles_3(
        term_data *td,
        int e_x, int e_y,
        int s_x, int s_y,
        int t_x, int t_y)
{
	guint32 pix;
	int x, y;


	/* Process each row */
	for (y = 0; y < td->tile_hgt; y++)
	{
		/* Process each column */
		for (x = 0; x < td->tile_wid; x++)
		{
			/* Get an overlay pixel */
			pix = gdk_rgb_image_get_pixel(td->tiles, e_x + x, e_y + y);

			/*
			 * If it's background colour, try to use one from
			 * the second layer
			 */
			if (pix == td->bg_pixel)
				pix = gdk_rgb_image_get_pixel(td->tiles, s_x + x, s_y + y);

			/*
			 * If it's background colour again, fall back to
			 * the terrain layer
			 */
			if (pix == td->bg_pixel)
				pix = gdk_rgb_image_get_pixel(td->tiles, t_x + x, t_y + y);

			/* Store the pixel in trans_buf */
			gdk_rgb_image_put_pixel(td->trans_buf, x, y, pix);
		}
	}
}

# endif  /* USE_EGO_GRAPHICS */

# endif  /* USE_TRANSPARENCY */


/*
 * Low level graphics (Assumes valid input)
 *
 * Draw "n" tiles/characters starting at (x,y)
 */
# ifdef USE_TRANSPARENCY
# ifdef USE_EGO_GRAPHICS
static errr Term_pict_gtk(
        int x, int y, int n,
        const byte *ap, const char *cp,
        const byte *tap, const char *tcp,
        const byte *eap, const char *ecp)
# else /* USE_EGO_GRAPHICS */
static errr Term_pict_gtk(
        int x, int y, int n,
        const byte *ap, const char *cp,
        const byte *tap, const char *tcp)
# endif  /* USE_EGO_GRAPHICS */
# else /* USE_TRANSPARENCY */
static errr Term_pict_gtk(
        int x, int y, int n,
        const byte *ap, const char *cp)
# endif  /* USE_TRANSPARENCY */
{
	term_data *td = (term_data*)(Term->data);

	int i;

	int d_x, d_y;

# ifdef USE_DOUBLE_TILES

	/* Hack - remember real number of columns affected XXX XXX XXX */
	int cols;

# endif  /* USE_DOUBLE_TILES */


	/* Don't draw to hidden windows */
	if (!td->shown) return (0);

	/* Paranoia */
	g_assert(td->drawing_area->window != 0);

	/* Top left corner of the destination rect */
	d_x = x * td->font_wid;
	d_y = y * td->font_hgt;


# ifdef USE_DOUBLE_TILES

	/* Reset column counter */
	cols = 0;

# endif  /* USE_DOUBLE_TILES */

	/* Scan the input */
	for (i = 0; i < n; i++)
	{
		byte a;
		char c;
		int s_x, s_y;

# ifdef USE_TRANSPARENCY

		byte ta;
		char tc;
		int t_x, t_y;

# ifdef USE_EGO_GRAPHICS

		byte ea;
		char ec;
		int e_x = 0, e_y = 0;
		bool has_overlay;

# endif  /* USE_EGO_GRAPHICS */

# endif  /* USE_TRANSPARENCY */


		/* Grid attr/char */
		a = *ap++;
		c = *cp++;

# ifdef USE_TRANSPARENCY

		/* Terrain attr/char */
		ta = *tap++;
		tc = *tcp++;

# ifdef USE_EGO_GRAPHICS

		/* Overlay attr/char */
		ea = *eap++;
		ec = *ecp++;
		has_overlay = (ea && ec);

# endif  /* USE_EGO_GRAPHICS */

# endif  /* USE_TRANSPARENCY */

		/* Row and Col */
		s_y = (((byte)a & 0x7F) % tile_rows) * td->tile_hgt;
		s_x = (((byte)c & 0x7F) % tile_cols) * td->tile_wid;

# ifdef USE_TRANSPARENCY

		/* Terrain Row and Col */
		t_y = (((byte)ta & 0x7F) % tile_rows) * td->tile_hgt;
		t_x = (((byte)tc & 0x7F) % tile_cols) * td->tile_wid;

# ifdef USE_EGO_GRAPHICS

		/* Overlay Row and Col */
		if (has_overlay)
		{
			e_y = (((byte)ea & 0x7F) % tile_rows) * td->tile_hgt;
			e_x = (((byte)ec & 0x7F) % tile_cols) * td->tile_wid;
		}

# endif  /* USE_EGO_GRAPHICS */


# ifdef USE_DOUBLE_TILES

		/* Mogami's bigtile patch */

		/* Hack -- a filler for wide tile */
		if (use_bigtile && (a == 255))
		{
			/* Advance */
			d_x += td->font_wid;

			/* Ignore */
			continue;
		}

# endif  /* USE_DOUBLE_TILES */

		/* Optimise the common case: terrain == obj/mons */
		if (!use_transparency ||
		                ((s_x == t_x) && (s_y == t_y)))
		{

# ifdef USE_EGO_GRAPHICS

			/* The simplest possible case - no overlay */
			if (!has_overlay)
			{
				/* Draw the tile */
				gdk_draw_rgb_image_2(
				        TERM_DATA_DRAWABLE(td), td->gc, td->tiles,
				        s_x, s_y,
				        d_x, d_y,
				        td->tile_wid, td->tile_hgt);
			}

			/* We have to draw overlay... */
			else
			{
				/* Overlay */
				overlay_tiles_2(td, e_x, e_y, s_x, s_y);

				/* And draw the result */
				gdk_draw_rgb_image_2(
				        TERM_DATA_DRAWABLE(td), td->gc, td->trans_buf,
				        0, 0,
				        d_x, d_y,
				        td->tile_wid, td->tile_hgt);

				/* Hack -- Prevent potential display problem */
				gdk_flush();
			}

# else /* USE_EGO_GRAPHICS */

			/* Draw the tile */
			gdk_draw_rgb_image_2(
			        TERM_DATA_DRAWABLE(td), td->gc, td->tiles,
			        s_x, s_y,
			        d_x, d_y,
			        td->tile_wid, td->tile_hgt);

# endif  /* USE_EGO_GRAPHICS */

		}

		/*
		 * Since there's no masking bitblt in X,
		 * we have to do that manually...
		 */
		else
		{

# ifndef USE_EGO_GRAPHICS

			/* Draw mon/PC/obj over terrain */
			overlay_tiles_2(td, s_x, s_y, t_x, t_y);

# else /* !USE_EGO_GRAPHICS */

			/* No overlay */
			if (!has_overlay)
			{
				/* Build terrain + masked overlay image */
				overlay_tiles_2(td, s_x, s_y, t_x, t_y);
			}

			/* With overlay */
			else
			{
				/* Ego over mon/PC over terrain */
				overlay_tiles_3(td, e_x, e_y, s_x, s_y,
				                t_x, t_y);
			}

# endif  /* !USE_EGO_GRAPHICS */

			/* Draw it */
			gdk_draw_rgb_image_2(
			        TERM_DATA_DRAWABLE(td), td->gc, td->trans_buf,
			        0, 0,
			        d_x, d_y,
			        td->tile_wid, td->tile_hgt);

			/* Hack -- Prevent potential display problem */
			gdk_flush();
		}

# else /* USE_TRANSPARENCY */

		/* Draw the tile */
		gdk_draw_rgb_image_2(
		        TERM_DATA_DRAWABLE(td), td->gc, td->tiles,
		        s_x, s_y,
		        d_x, d_y,
		        td->tile_wid, td->tile_hgt);

# endif  /* USE_TRANSPARENCY */

		/*
		 * Advance x-coordinate - wide font fillers are taken care of
		 * before entering the tile drawing code.
		 */
		d_x += td->font_wid;

# ifdef USE_DOUBLE_TILES

		/* Add up *real* number of columns updated XXX XXX XXX */
		cols += use_bigtile ? 2 : 1;

# endif  /* USE_DOUBLE_TILES */
	}

# ifndef USE_DOUBLE_TILES

	/* Copy image from backing store if present */
	TERM_DATA_REFRESH(td, x, y, n, 1);

# else

	/* Copy image from backing store if present */
	TERM_DATA_REFRESH(td, x, y, cols, 1);

# endif  /* USE_DOUBLE_TILES */

	/* Success */
	return (0);
}

#endif /* USE_GRAPHICS */


/*
 * Process an event, if there's none block when wait is set true,
 * return immediately otherwise.
 */
static void CheckEvent(bool wait)
{
	/* Process an event */
	(void)gtk_main_iteration_do(wait);
}


/*
 * Process all pending events (without blocking)
 */
static void DrainEvents(void)
{
	while (gtk_events_pending())
		gtk_main_iteration();
}


/*
 * Handle a "special request"
 */
static errr Term_xtra_gtk(int n, int v)
{
	/* Handle a subset of the legal requests */
	switch (n)
	{
		/* Make a noise */
	case TERM_XTRA_NOISE:
		{
			/* Beep */
			gdk_beep();

			/* Success */
			return (0);
		}

		/* Flush the output */
	case TERM_XTRA_FRESH:
		{
			/* Flush pending X requests - almost always no-op */
			gdk_flush();

			/* Success */
			return (0);
		}

		/* Process random events */
	case TERM_XTRA_BORED:
		{
			/* Process a pending event if there's one */
			CheckEvent(FALSE);

			/* Success */
			return (0);
		}

		/* Process Events */
	case TERM_XTRA_EVENT:
		{
			/* Process an event */
			CheckEvent(v);

			/* Success */
			return (0);
		}

		/* Flush the events */
	case TERM_XTRA_FLUSH:
		{
			/* Process all pending events */
			DrainEvents();

			/* Success */
			return (0);
		}

		/* Handle change in the "level" */
	case TERM_XTRA_LEVEL:
		return (0);

		/* Clear the screen */
	case TERM_XTRA_CLEAR:
		return (Term_clear_gtk());

		/* Delay for some milliseconds */
	case TERM_XTRA_DELAY:
		{
			/* sleep for v milliseconds */
			usleep(v * 1000);

			/* Done */
			return (0);
		}

		/* Get Delay of some milliseconds */
	case TERM_XTRA_GET_DELAY:
		{
			int ret;
			struct timeval tv;

			ret = gettimeofday(&tv, NULL);
			Term_xtra_long = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);

			return ret;
		}

		/* Subdirectory scan */
	case TERM_XTRA_SCANSUBDIR:
		{
			DIR *directory;
			struct dirent *entry;

			scansubdir_max = 0;

			directory = opendir(scansubdir_dir);
			if (!directory) return (1);

			while ((entry = readdir(directory)) != NULL)
			{
				char file[PATH_MAX + NAME_MAX + 2];
				struct stat filedata;

				file[PATH_MAX + NAME_MAX] = 0;
				strncpy(file, scansubdir_dir, PATH_MAX);
				strncat(file, "/", 2);
				strncat(file, entry->d_name, NAME_MAX);
				if ((stat(file, &filedata) == 0) && S_ISDIR(filedata.st_mode))
				{
					string_free(scansubdir_result[scansubdir_max]);
					scansubdir_result[scansubdir_max] =
					        string_make(entry->d_name);
					++scansubdir_max;
				}
			}
		}

		/* Rename main window */
	case TERM_XTRA_RENAME_MAIN_WIN: gtk_window_set_title(GTK_WINDOW(data[0].window), angband_term_name[0]); return (0);

		/* React to changes */
	case TERM_XTRA_REACT:
		{
			/* (re-)init colours */
			init_colours();

#ifdef USE_GRAPHICS

			/* Initialise graphics */
			init_graphics();

#endif /* USE_GRAPHICS */

			/* Success */
			return (0);
		}
	}

	/* Unknown */
	return (1);
}




/**** Event handlers ****/


/*
 * Operation overkill
 * Verify term size info - just because the other windowing ports have this
 */
static void term_data_check_size(term_data *td)
{
	/* Enforce minimum window size */
	if (td == &data[0])
	{
		if (td->cols < 80) td->cols = 80;
		if (td->rows < 24) td->rows = 24;
	}
	else
	{
		if (td->cols < 1) td->cols = 1;
		if (td->rows < 1) td->rows = 1;
	}

	/* Paranoia - Enforce maximum size allowed by the term package */
	if (td->cols > 255) td->cols = 255;
	if (td->rows > 255) td->rows = 255;
}


/*
 * Enforce these size constraints within Gtk/Gdk
 * These increments are nice, because you can see numbers of rows/cols
 * while you resize a term.
 */
static void term_data_set_geometry_hints(term_data *td)
{
	GdkGeometry geometry;

	/* Resizing is character size oriented */
	geometry.width_inc = td->font_wid;
	geometry.height_inc = td->font_hgt;

	/* Enforce minimum size - the main window */
	if (td == &data[0])
	{
		geometry.min_width = 80 * td->font_wid;
		geometry.min_height = 24 * td->font_hgt;
	}

	/* Subwindows can be much smaller */
	else
	{
		geometry.min_width = 1 * td->font_wid;
		geometry.min_height = 1 * td->font_hgt;
	}

	/* Enforce term package's hard limit */
	geometry.max_width = 255 * td->font_wid;
	geometry.max_height = 255 * td->font_hgt;

	/* This affects geometry display while we resize a term */
	geometry.base_width = 0;
	geometry.base_height = 0;

	/* Give the window a new set of resizing hints */
	gtk_window_set_geometry_hints(GTK_WINDOW(td->window),
	                              td->drawing_area, &geometry,
	                              GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE
	                              | GDK_HINT_BASE_SIZE | GDK_HINT_RESIZE_INC);
}


/*
 * (Re)allocate a backing store for the window
 */
static void term_data_set_backing_store(term_data *td)
{
	/* Paranoia */
	if (!GTK_WIDGET_REALIZED(td->drawing_area)) return;

	/* Free old one if we cannot use it any longer */
	if (td->backing_store)
	{
		int wid, hgt;

		/* Retrive the size of the old backing store */
		gdk_window_get_size(td->backing_store, &wid, &hgt);

		/* Continue using it if it's the same with desired size */
		if (use_backing_store &&
		                (td->cols * td->font_wid == wid) &&
		                (td->rows * td->font_hgt == hgt)) return;

		/* Free it */
		gdk_pixmap_unref(td->backing_store);

		/* Forget the pointer */
		td->backing_store = NULL;
	}

	/* See user preference */
	if (use_backing_store)
	{
		/* Allocate new backing store */
		td->backing_store = gdk_pixmap_new(
		                            td->drawing_area->window,
		                            td->cols * td->font_wid,
		                            td->rows * td->font_hgt,
		                            -1);

		/* Oops - but we can do without it */
		g_return_if_fail(td->backing_store != NULL);

		/* Clear the backing store */
		gdk_draw_rectangle(
		        td->backing_store,
		        td->drawing_area->style->black_gc,
		        TRUE,
		        0,
		        0,
		        td->cols * td->font_wid,
		        td->rows * td->font_hgt);
	}
}


/*
 * Save game only when it's safe to do so
 */
static void save_game_gtk(void)
{
	/* We have nothing to save, yet */
	if (!game_in_progress || !character_generated) return;

	/* It isn't safe to save game now */
	if (!inkey_flag || !can_save)
	{
		plog("You may not save right now.");
		return;
	}

	/* Hack -- Forget messages */
	msg_flag = FALSE;

	/* Save the game */
#ifdef ZANG_SAVE_GAME
	/* Also for OAngband - the parameter tells if it's autosave */
	do_cmd_save_game(FALSE);
#else
/* Everything else */
	do_cmd_save_game();
#endif /* ZANG_SAVE_GAME */
}


/*
 * Display message in a modal dialog
 */
static void gtk_message(cptr msg)
{
	GtkWidget *dialog, *label, *ok_button;

	/* Create the widgets */
	dialog = gtk_dialog_new();
	g_assert(dialog != NULL);

	label = gtk_label_new(msg);
	g_assert(label != NULL);

	ok_button = gtk_button_new_with_label("OK");
	g_assert(ok_button != NULL);

	/* Ensure that the dialogue box is destroyed when OK is clicked */
	gtk_signal_connect_object(
	        GTK_OBJECT(ok_button),
	        "clicked",
	        GTK_SIGNAL_FUNC(gtk_widget_destroy),
	        (gpointer)dialog);
	gtk_container_add(
	        GTK_CONTAINER(GTK_DIALOG(dialog)->action_area),
	        ok_button);

	/* Add the label, and show the dialog */
	gtk_container_add(
	        GTK_CONTAINER(GTK_DIALOG(dialog)->vbox),
	        label);

	/* And make it modal */
	gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);

	/* Show the dialog */
	gtk_widget_show_all(dialog);
}


/*
 * Hook to tell the user something important
 */
static void hook_plog(cptr str)
{
	/* Warning message */
	gtk_message(str);
}


/*
 * Process File-Quit menu command
 */
static void quit_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *was_clicked)
{
	/* Save current game */
	save_game_gtk();

	/* It's done */
	quit(NULL);
}


/*
 * Process File-Save menu command
 */
static void save_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *was_clicked)
{
	/* Save current game */
	save_game_gtk();
}


/*
 * Handle destruction of the Angband window
 */
static void destroy_main_event_handler(
        GtkButton *was_clicked,
        gpointer user_data)
{
	/* This allows for cheating, but... */
	quit(NULL);
}


/*
 * Handle destruction of Subwindows
 */
static void destroy_sub_event_handler(
        GtkWidget *window,
        gpointer user_data)
{
	/* Hide the window */
	gtk_widget_hide_all(window);
}


#ifndef SAVEFILE_SCREEN

/*
 * Process File-New menu command
 */
static void new_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *was_clicked)
{
	if (game_in_progress)
	{
		plog("You can't start a new game while you're still playing!");
		return;
	}

	/* The game is in progress */
	game_in_progress = TRUE;

	/* Flush input */
	Term_flush();

	/* Play game */
	play_game(TRUE);

	/* Houseclearing */
	cleanup_angband();

	/* Done */
	quit(NULL);
}

#endif /* !SAVEFILE_SCREEN */


/*
 * Load fond specified by an XLFD fontname and
 * set up related term_data members
 */
static void load_font(term_data *td, cptr fontname)
{
	GdkFont *old = td->font;

	/* Load font */
	td->font = gdk_font_load(fontname);

	if (td->font)
	{
		/* Free the old font */
		if (old) gdk_font_unref(old);
	}
	else
	{
		/* Oops, but we can still use the old one */
		td->font = old;
	}

	/* Calculate the size of the font XXX */
	td->font_wid = gdk_char_width(td->font, '@');
	td->font_hgt = td->font->ascent + td->font->descent;

#ifndef USE_DOUBLE_TILES

	/* Use the current font size for tiles as well */
	td->tile_wid = td->font_wid;
	td->tile_hgt = td->font_hgt;

#else /* !USE_DOUBLE_TILES */

	/* Calculate the size of tiles */
	if (use_bigtile && (td == &data[0])) td->tile_wid = td->font_wid * 2;
	else td->tile_wid = td->font_wid;
	td->tile_hgt = td->font_hgt;

#endif /* !USE_DOUBLE_TILES */
}


/*
 * React to OK button press in font selection dialogue
 */
static void font_ok_callback(
        GtkWidget *widget,
        GtkWidget *font_selector)
{
	gchar *fontname;
	term_data *td;

	td = gtk_object_get_data(GTK_OBJECT(font_selector), "term_data");

	g_assert(td != NULL);

	/* Retrieve font name from player's selection */
	fontname = gtk_font_selection_dialog_get_font_name(
	                   GTK_FONT_SELECTION_DIALOG(font_selector));

	/* Leave unless selection was valid */
	if (fontname == NULL) return;

	/* Load font and update font size info */
	load_font(td, fontname);

	/* Hack - Hide the window - finally found the trick... */
	gtk_widget_hide_all(td->window);

	/* Resizes the drawing area */
	gtk_drawing_area_size(
	        GTK_DRAWING_AREA(td->drawing_area),
	        td->cols * td->font_wid,
	        td->rows * td->font_hgt);

	/* Update the geometry hints for the window */
	term_data_set_geometry_hints(td);

	/* Reallocate the backing store */
	term_data_set_backing_store(td);

	/* Hack - Show the window */
	gtk_widget_show_all(td->window);

#ifdef USE_GRAPHICS

	/* We have to resize tiles when we are in graphics mode */
	resize_request = TRUE;

#endif /* USE_GRAPHICS */

	/* Hack - force redraw */
	Term_key_push(KTRL('R'));
}


/*
 * Process Options-Font-* menu command
 */
static void change_font_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *widget)
{
	GtkWidget *font_selector;

	font_selector = gtk_font_selection_dialog_new("Select font");
#if 0 // DGDGDGDG
	gtk_object_set_data(
	        GTK_OBJECT(font_selector),
	        "term_data",
	        user_data);

	/* Filter to show only fixed-width fonts */
	gtk_font_selection_dialog_set_filter(
	        GTK_FONT_SELECTION_DIALOG(font_selector),
	        GTK_FONT_FILTER_BASE,
	        GTK_FONT_ALL,
	        NULL,
	        NULL,
	        NULL,
	        NULL,
	        spacings,
	        NULL);

	gtk_signal_connect(
	        GTK_OBJECT(GTK_FONT_SELECTION_DIALOG(font_selector)->ok_button),
	        "clicked",
	        font_ok_callback,
	        (gpointer)font_selector);

	/*
	 * Ensure that the dialog box is destroyed when the user clicks
	 * a button.
	 */
	gtk_signal_connect_object(
	        GTK_OBJECT(GTK_FONT_SELECTION_DIALOG(font_selector)->ok_button),
	        "clicked",
	        GTK_SIGNAL_FUNC(gtk_widget_destroy),
	        (gpointer)font_selector);

	gtk_signal_connect_object(
	        GTK_OBJECT(GTK_FONT_SELECTION_DIALOG(font_selector)->cancel_button),
	        "clicked",
	        GTK_SIGNAL_FUNC(gtk_widget_destroy),
	        (gpointer)font_selector);

	gtk_widget_show(GTK_WIDGET(font_selector));
#endif
}


/*
 * Process Terms-* menu command - hide/show terminal window
 */
static void term_event_handler(
		gpointer user_data,
        guint user_action,
        GtkWidget *widget)
{
	term_data *td = &data[user_action];

	/* We don't mess with the Angband window */
	if (td == &data[0]) return;

	/* It's shown */
	if (td->shown)
	{
		/* Hide the window */
		gtk_widget_hide_all(td->window);
	}

	/* It's hidden */
	else
	{
		/* Show the window */
		gtk_widget_show_all(td->window);
	}
}


/*
 * Toggles the boolean value of use_backing_store and
 * setup / remove backing store for each term
 */
static void change_backing_store_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *was_clicked)
{
	int i;

	/* Toggle the backing store mode */
	use_backing_store = !use_backing_store;

	/* Reset terms */
	for (i = 0; i < MAX_TERM_DATA; i++)
	{
		term_data_set_backing_store(&data[i]);
	}
}


#ifdef USE_GRAPHICS

/*
 * Set graf_mode_request according to user selection,
 * and let Term_xtra react to the change.
 */
static void change_graf_mode_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *was_clicked)
{
	/* Set request according to user selection */
	graf_mode_request = (int)user_action;

	/*
	 * Hack - force redraw
	 * This induces a call to Term_xtra(TERM_XTRA_REACT, 0) as well
	 */
	Term_key_push(KTRL('R'));
}


/*
 * Set dither_mode according to user selection
 */
static void change_dith_mode_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *was_clicked)
{
	/* Set request according to user selection */
	dith_mode = (int)user_action;

	/*
	 * Hack - force redraw
	 */
	Term_key_push(KTRL('R'));
}


/*
 * Toggles the graphics tile scaling mode (Fast/Smooth)
 */
static void change_smooth_mode_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *was_clicked)
{
	/* (Try to) toggle the smooth rescaling mode */
	smooth_rescaling_request = !smooth_rescaling;

	/*
	 * Hack - force redraw
	 * This induces a call to Term_xtra(TERM_XTRA_REACT, 0) as well
	 */
	Term_key_push(KTRL('R'));
}


# ifdef USE_DOUBLE_TILES

static void change_wide_tile_mode_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *was_clicked)
{
	term *old = Term;
	term_data *td = &data[0];

	/* Toggle "use_bigtile" */
	use_bigtile = !use_bigtile;

#ifdef TOME
	/* T.o.M.E. requires this as well */
	arg_bigtile = use_bigtile;
#endif /* TOME */

	/* Double the width of tiles (only for the main window) */
	if (use_bigtile)
	{
		td->tile_wid = td->font_wid * 2;
	}

	/* Use the width of current font */
	else
	{
		td->tile_wid = td->font_wid;
	}

	/* Need to resize the tiles */
	resize_request = TRUE;

	/* Activate the main window */
	Term_activate(&td->t);

	/* Resize the term */
	Term_resize(td->cols, td->rows);

	/* Activate the old term */
	Term_activate(old);

	/* Hack - force redraw XXX ??? XXX */
	Term_key_push(KTRL('R'));
}

# endif  /* USE_DOUBLE_TILES */


# ifdef USE_TRANSPARENCY

/*
 * Toggles the boolean value of use_transparency
 */
static void change_trans_mode_event_handler(
        gpointer user_data,
		guint user_aciton,
        GtkWidget *was_clicked)
{
	/* Toggle the transparency mode */
	use_transparency = !use_transparency;

	/* Hack - force redraw */
	Term_key_push(KTRL('R'));
}

# endif  /* USE_TRANSPARENCY */

#endif /* USE_GRAPHICS */


#ifndef SAVEFILE_SCREEN

/*
 * Caution: Modal or not, callbacks are called by gtk_main(),
 * so this is the right place to start a game.
 */
static void file_ok_callback(
        GtkWidget *widget,
        GtkWidget *file_selector)
{
	strcpy(savefile,
	       gtk_file_selection_get_filename(GTK_FILE_SELECTION(file_selector)));

	gtk_widget_destroy(file_selector);

	/* game is in progress */
	game_in_progress = TRUE;

	/* Flush input */
	Term_flush();

	/* Play game */
	play_game(FALSE);

	/* Free memory allocated by game */
	cleanup_angband();

	/* Done */
	quit(NULL);
}


/*
 * Process File-Open menu command
 */
static void open_event_handler(
        gpointer user_data,
		guint user_action,
        GtkWidget *was_clicked)
{
	GtkWidget *file_selector;
	char buf[1024];


	if (game_in_progress)
	{
		plog("You can't open a new game while you're still playing!");
		return;
	}

	/* Prepare the savefile path */
	path_build(buf, 1024, ANGBAND_DIR_SAVE, "*");

	file_selector = gtk_file_selection_new("Select a savefile");
	gtk_file_selection_set_filename(
	        GTK_FILE_SELECTION(file_selector),
	        buf);
	gtk_signal_connect(
	        GTK_OBJECT(GTK_FILE_SELECTION(file_selector)->ok_button),
	        "clicked",
	        file_ok_callback,
	        (gpointer)file_selector);

	/*
	 * Ensure that the dialog box is destroyed when the user
	 * clicks a button.
	 */
	gtk_signal_connect_object(
	        GTK_OBJECT(GTK_FILE_SELECTION(file_selector)->ok_button),
	        "clicked",
	        GTK_SIGNAL_FUNC(gtk_widget_destroy),
	        (gpointer)file_selector);

	gtk_signal_connect_object(
	        GTK_OBJECT(GTK_FILE_SELECTION(file_selector)->cancel_button),
	        "clicked",
	        GTK_SIGNAL_FUNC(gtk_widget_destroy),
	        (gpointer)file_selector);

	gtk_window_set_modal(GTK_WINDOW(file_selector), TRUE);
	gtk_widget_show(GTK_WIDGET(file_selector));
}

#endif /* !SAVEFILE_SCREEN */


/*
 * React to "delete" signal sent to Window widgets
 */
static gboolean delete_event_handler(
        GtkWidget *widget,
        GdkEvent *event,
        gpointer user_data)
{
	/* Save game if possible */
	save_game_gtk();

	/* Don't prevent closure */
	return (FALSE);
}


/*
 * Convert keypress events to ASCII codes and enqueue them
 * for game
 */
static gboolean keypress_event_handler(
        GtkWidget *widget,
        GdkEventKey *event,
        gpointer user_data)
{
#if 1
	int i, mc, ms, mo, mx;

	char msg[128];

	/* Hack - do not do anything until the player picks from the menu */
	if (!game_in_progress) return (TRUE);

	/* Hack - Ignore parameters */
	(void) widget;
	(void) user_data;

	/* Extract four "modifier flags" */
	mc = (event->state & GDK_CONTROL_MASK) ? TRUE : FALSE;
	ms = (event->state & GDK_SHIFT_MASK) ? TRUE : FALSE;
	mo = (event->state & GDK_MOD1_MASK) ? TRUE : FALSE;
	mx = (event->state & GDK_MOD3_MASK) ? TRUE : FALSE;

	/*
	 * Hack XXX
	 * Parse shifted numeric (keypad) keys specially.
	 */
	if ((event->state == GDK_SHIFT_MASK)
	                && (event->keyval >= GDK_KP_0) && (event->keyval <= GDK_KP_9))
	{
		/* Build the macro trigger string */
		strnfmt(msg, 128, "%cS_%X%c", 31, event->keyval, 13);

		/* Enqueue the "macro trigger" string */
		for (i = 0; msg[i]; i++) Term_keypress(msg[i]);

		/* Hack -- auto-define macros as needed */
		if (event->length && (macro_find_exact(msg) < 0))
		{
			/* Create a macro */
			macro_add(msg, event->string);
		}

		return (TRUE);
	}

	/* Normal keys with no modifiers */
	if (event->length && !mo && !mx)
	{
		/* Enqueue the normal key(s) */
		for (i = 0; i < event->length; i++) Term_keypress(event->string[i]);

		/* All done */
		return (TRUE);
	}


	/* Handle a few standard keys (bypass modifiers) XXX XXX XXX */
	switch ((uint) event->keyval)
	{
	case GDK_Escape:
		{
			Term_keypress(ESCAPE);
			return (TRUE);
		}

	case GDK_Return:
		{
			Term_keypress('\r');
			return (TRUE);
		}

	case GDK_Tab:
		{
			Term_keypress('\t');
			return (TRUE);
		}

	case GDK_Delete:
	case GDK_BackSpace:
		{
			Term_keypress('\010');
			return (TRUE);
		}

		/* Hack - the cursor keys */
	case GDK_Up:
		{
			Term_keypress('8');
			return (TRUE);
		}

	case GDK_Down:
		{
			Term_keypress('2');
			return (TRUE);
		}

	case GDK_Left:
		{
			Term_keypress('4');
			return (TRUE);
		}

	case GDK_Right:
		{
			Term_keypress('6');
			return (TRUE);
		}

	case GDK_Shift_L:
	case GDK_Shift_R:
	case GDK_Control_L:
	case GDK_Control_R:
	case GDK_Caps_Lock:
	case GDK_Shift_Lock:
	case GDK_Meta_L:
	case GDK_Meta_R:
	case GDK_Alt_L:
	case GDK_Alt_R:
	case GDK_Super_L:
	case GDK_Super_R:
	case GDK_Hyper_L:
	case GDK_Hyper_R:
		{
			/* Hack - do nothing to control characters */
			return (TRUE);
		}
	}

	/* Build the macro trigger string */
	strnfmt(msg, 128, "%c%s%s%s%s_%X%c", 31,
	        mc ? "N" : "", ms ? "S" : "",
	        mo ? "O" : "", mx ? "M" : "",
	        event->keyval, 13);

	/* Enqueue the "macro trigger" string */
	for (i = 0; msg[i]; i++) Term_keypress(msg[i]);

	/* Hack -- auto-define macros as needed */
	if (event->length && (macro_find_exact(msg) < 0))
	{
		/* Create a macro */
		macro_add(msg, event->string);
	}

	return (TRUE);

#else
	int i, mc, ms, mo, mx;

	char msg[128];


	/* Extract four "modifier flags" */
	mc = (event->state & GDK_CONTROL_MASK) ? TRUE : FALSE;
	ms = (event->state & GDK_SHIFT_MASK) ? TRUE : FALSE;
	mo = (event->state & GDK_MOD1_MASK) ? TRUE : FALSE;
	mx = (event->state & GDK_MOD3_MASK) ? TRUE : FALSE;
	printf("0=%d 9=%d;; keyval=%d; mc=%d, ms=%d  ::=:: ", GDK_KP_0, GDK_KP_9, event->keyval, mc, ms);
	/* Enqueue the normal key(s) */
	for (i = 0; i < event->length; i++) printf("%d;", event->string[i]);
	printf("\n");

	/*
	* Hack XXX
	* Parse shifted numeric (keypad) keys specially.
	*/
	if ((event->state & GDK_SHIFT_MASK)
	                && (event->keyval >= GDK_KP_Left) && (event->keyval <= GDK_KP_Delete))
	{
		/* Build the macro trigger string */
		strnfmt(msg, 128, "%cS_%X%c", 31, event->keyval, 13);
		printf("%cS_%X%c", 31, event->keyval, 13);

		/* Enqueue the "macro trigger" string */
		for (i = 0; msg[i]; i++) Term_keypress(msg[i]);

		/* Hack -- auto-define macros as needed */
		if (event->length && (macro_find_exact(msg) < 0))
		{
			/* Create a macro */
			macro_add(msg, event->string);
		}

		return (TRUE);
	}

	/* Normal keys with no modifiers */
	if (event->length && !mo && !mx)
	{
		/* Enqueue the normal key(s) */
		for (i = 0; i < event->length; i++) Term_keypress(event->string[i]);

		/* All done */
		return (TRUE);
	}

	/* Handle a few standard keys (bypass modifiers) XXX XXX XXX */
	switch ((uint) event->keyval)
	{
	case GDK_Escape:
		{
			Term_keypress(ESCAPE);
			return (TRUE);
		}

	case GDK_Return:
		{
			Term_keypress('\r');
			return (TRUE);
		}

	case GDK_Tab:
		{
			Term_keypress('\t');
			return (TRUE);
		}

	case GDK_Delete:
	case GDK_BackSpace:
		{
			Term_keypress('\010');
			return (TRUE);
		}

	case GDK_Shift_L:
	case GDK_Shift_R:
	case GDK_Control_L:
	case GDK_Control_R:
	case GDK_Caps_Lock:
	case GDK_Shift_Lock:
	case GDK_Meta_L:
	case GDK_Meta_R:
	case GDK_Alt_L:
	case GDK_Alt_R:
	case GDK_Super_L:
	case GDK_Super_R:
	case GDK_Hyper_L:
	case GDK_Hyper_R:
		{
			/* Hack - do nothing to control characters */
			return (TRUE);
		}
	}

	/* Build the macro trigger string */
	strnfmt(msg, 128, "%c%s%s%s%s_%X%c", 31,
	        mc ? "N" : "", ms ? "S" : "",
	        mo ? "O" : "", mx ? "M" : "",
	        event->keyval, 13);

	/* Enqueue the "macro trigger" string */
	for (i = 0; msg[i]; i++) Term_keypress(msg[i]);

	/* Hack -- auto-define macros as needed */
	if (event->length && (macro_find_exact(msg) < 0))
	{
		/* Create a macro */
		macro_add(msg, event->string);
	}

	return (TRUE);
#endif
}


/*
 * Widget customisation (for drawing area) - "realize" signal
 *
 * In this program, called when window containing the drawing
 * area is shown first time.
 */
static void realize_event_handler(
        GtkWidget *widget,
        gpointer user_data)
{
	term_data *td = (term_data *)user_data;

	/* Create graphic context */
	td->gc = gdk_gc_new(td->drawing_area->window);

	/* Set foreground and background colours - isn't bg used at all? */
	gdk_rgb_gc_set_background(td->gc, 0x000000);
	gdk_rgb_gc_set_foreground(td->gc, angband_colours[TERM_WHITE]);

	/* No last foreground colour, yet */
	td->last_attr = -1;

	/* Allocate the backing store */
	term_data_set_backing_store(td);

	/* Clear the window */
	gdk_draw_rectangle(
	        widget->window,
	        widget->style->black_gc,
	        TRUE,
	        0,
	        0,
	        td->cols * td->font_wid,
	        td->rows * td->font_hgt);
}


/*
 * Widget customisation (for drawing area) - "show" signal
 */
static void show_event_handler(
        GtkWidget *widget,
        gpointer user_data)
{
	term_data *td = (term_data *)user_data;

	/* Set the shown flag */
	td->shown = TRUE;
}


/*
 * Widget customisation (for drawing area) - "hide" signal
 */
static void hide_event_handler(
        GtkWidget *widget,
        gpointer user_data)
{
	term_data *td = (term_data *)user_data;

	/* Set the shown flag */
	td->shown = FALSE;
}


/*
 * Widget customisation (for drawing area)- handle size allocation requests
 */
static void size_allocate_event_handler(
        GtkWidget *widget,
        GtkAllocation *allocation,
        gpointer user_data)
{
	term_data *td = user_data;
	int old_rows, old_cols;
	term *old = Term;

	/* Paranoia */
	g_return_if_fail(widget != NULL);
	g_return_if_fail(allocation != NULL);
	g_return_if_fail(td != NULL);

	/* Remember old values */
	old_cols = td->cols;
	old_rows = td->rows;

	/* Update numbers of rows and columns */
	td->cols = (allocation->width + td->font_wid - 1) / td->font_wid;
	td->rows = (allocation->height + td->font_hgt - 1) / td->font_hgt;

	/* Overkill - Validate them */
	term_data_check_size(td);

	/* Adjust size request and set it */
	allocation->width = td->cols * td->font_wid;
	allocation->height = td->rows * td->font_hgt;
	widget->allocation = *allocation;

	/* Widget is realized, so we do some drawing works */
	if (GTK_WIDGET_REALIZED(widget))
	{
		/* Reallocate the backing store */
		term_data_set_backing_store(td);

		/* Actually handles resizing in Gtk */
		gdk_window_move_resize(
		        widget->window,
		        allocation->x,
		        allocation->y,
		        allocation->width,
		        allocation->height);

		/* And in the term package */
		Term_activate(&td->t);

		/* Resize if necessary */
		if ((td->cols != old_cols) || (td->rows != old_rows))
			(void)Term_resize(td->cols, td->rows);

		/* Redraw its content */
		Term_redraw();

		/* Refresh */
		Term_fresh();

		/* Restore */
		Term_activate(old);
	}
}


/*
 * Update exposed area in a window (for drawing area)
 */
static gboolean expose_event_handler(
        GtkWidget *widget,
        GdkEventExpose *event,
        gpointer user_data)
{
	term_data *td = user_data;

	term *old = Term;

#ifndef NO_REDRAW_SECTION

	int x1, x2, y1, y2;

#endif /* !NO_REDRAW_SECTION */


	/* Paranoia */
	if (td == NULL) return (TRUE);

	/* The window has a backing store */
	if (td->backing_store)
	{
		/* Simply restore the exposed area from the backing store */
		gdk_draw_pixmap(
		        td->drawing_area->window,
		        td->gc,
		        td->backing_store,
		        event->area.x,
		        event->area.y,
		        event->area.x,
		        event->area.y,
		        event->area.width,
		        event->area.height);
	}

	/* No backing store - use the game's code to redraw the area */
	else
	{

		/* Activate the relevant term */
		Term_activate(&td->t);

# ifdef NO_REDRAW_SECTION

		/* K.I.S.S. version */

		/* Redraw */
		Term_redraw();

# else /* NO_REDRAW_SECTION */

		/*
		 * Complex version - The above is enough, but since we have
		 * Term_redraw_section... This might help if we had a graphics
		 * mode.
		 */

		/* Convert coordinate in pixels to character cells */
		x1 = event->area.x / td->font_wid;
		x2 = (event->area.x + event->area.width) / td->font_wid;
		y1 = event->area.y / td->font_hgt;
		y2 = (event->area.y + event->area.height) / td->font_hgt;

		/*
		 * No paranoia - boundary checking is done in
		 * Term_redraw_section
		 */

		/* Redraw the area */
		Term_redraw_section(x1, y1, x2, y2);

# endif  /* NO_REDRAW_SECTION */

		/* Refresh */
		Term_fresh();

		/* Restore */
		Term_activate(old);
	}

	/* We've processed the event ourselves */
	return (TRUE);
}




/**** Initialisation ****/

/*
 * Initialise a term_data struct
 */
static errr term_data_init(term_data *td, int i)
{
	term *t = &td->t;
	char *p;

	td->cols = 80;
	td->rows = 24;

	/* Initialize the term */
	term_init(t, td->cols, td->rows, 1024);

	/* Store the name of the term */
	td->name = string_make(angband_term_name[i]);

	/* Instance names should start with a lowercase letter XXX */
	for (p = (char *)td->name; *p; p++) *p = tolower(*p);

	/* Use a "soft" cursor */
	t->soft_cursor = TRUE;

	/* Erase with "white space" */
	t->attr_blank = TERM_WHITE;
	t->char_blank = ' ';

	t->xtra_hook = Term_xtra_gtk;
	t->text_hook = Term_text_gtk;
	t->wipe_hook = Term_wipe_gtk;
	t->curs_hook = Term_curs_gtk;
#ifdef USE_GRAPHICS
	t->pict_hook = Term_pict_gtk;
#endif /* USE_GRAPHICS */
	t->nuke_hook = Term_nuke_gtk;

	/* Save the data */
	t->data = td;

	/* Activate (important) */
	Term_activate(t);

	/* Success */
	return (0);
}


/*
 * Neater menu code with GtkItemFactory.
 *
 * Menu bar of the Angband window
 *
 * Entry format: Path, Accelerator, Callback, Callback arg, type
 * where type is one of:
 * <Item> - simple item, alias NULL
 * <Branch> - has submenu
 * <Separator> - as you read it
 * <CheckItem> - has a check mark
 * <ToggleItem> - is a toggle
 */
static GtkItemFactoryEntry main_menu_items[] =
{
	/* "File" menu */
	{ "/File", NULL,
	  NULL, 0, "<Branch>", NULL
	},
#ifndef SAVEFILE_SCREEN
	{ "/File/New", "<mod1>N",
	  new_event_handler, 0, NULL, NULL },
	{ "/File/Open", "<mod1>O",
	  open_event_handler, 0, NULL, NULL },
	{ "/File/sep1", NULL,
	  NULL, 0, "<Separator>", NULL },
#endif /* !SAVEFILE_SCREEN */
	{ "/File/Save", "<mod1>S",
	  save_event_handler, 0, NULL, NULL },
	{ "/File/Quit", "<mod1>Q",
	  quit_event_handler, 0, NULL, NULL },

	/* "Terms" menu */
	{ "/Terms", NULL,
	  NULL, 0, "<Branch>", NULL },
	/* XXX XXX XXX NULL's are replaced by the program */
	{ NULL, "<mod1>0",
	  term_event_handler, 0, "<CheckItem>", NULL },
	{ NULL, "<mod1>1",
	  term_event_handler, 1, "<CheckItem>", NULL },
	{ NULL, "<mod1>2",
	  term_event_handler, 2, "<CheckItem>", NULL },
	{ NULL, "<mod1>3",
	  term_event_handler, 3, "<CheckItem>", NULL },
	{ NULL, "<mod1>4",
	  term_event_handler, 4, "<CheckItem>", NULL },
	{ NULL, "<mod1>5",
	  term_event_handler, 5, "<CheckItem>", NULL },
	{ NULL, "<mod1>6",
	  term_event_handler, 6, "<CheckItem>", NULL },
	{ NULL, "<mod1>7",
	  term_event_handler, 7, "<CheckItem>", NULL },

	/* "Options" menu */
	{ "/Options", NULL,
	  NULL, 0, "<Branch>", NULL },

	/* "Font" submenu */
	{ "/Options/Font", NULL,
	  NULL, 0, "<Branch>", NULL },
	/* XXX XXX XXX Again, NULL's are filled by the program */
	{ NULL, NULL,
	  change_font_event_handler, 0, NULL, NULL },
	{ NULL, NULL,
	  change_font_event_handler, 1, NULL, NULL },
	{ NULL, NULL,
	  change_font_event_handler, 2, NULL, NULL },
	{ NULL, NULL,
	  change_font_event_handler, 3, NULL, NULL },
	{ NULL, NULL,
	  change_font_event_handler, 4, NULL, NULL },
	{ NULL, NULL,
	  change_font_event_handler, 5, NULL, NULL },
	{ NULL, NULL,
	  change_font_event_handler, 6, NULL, NULL },
	{ NULL, NULL,
	  change_font_event_handler, 7, NULL, NULL },

#ifdef USE_GRAPHICS

	/* "Graphics" submenu */
	{ "/Options/Graphics", NULL,
	  NULL, 0, "<Branch>", NULL },
	{ "/Options/Graphics/None", NULL,
	  change_graf_mode_event_handler, GRAF_MODE_NONE, "<CheckItem>", NULL },
	{ "/Options/Graphics/Old", NULL,
	  change_graf_mode_event_handler, GRAF_MODE_OLD, "<CheckItem>", NULL },
	{ "/Options/Graphics/New", NULL,
	  change_graf_mode_event_handler, GRAF_MODE_NEW, "<CheckItem>", NULL },
# ifdef USE_DOUBLE_TILES
	{ "/Options/Graphics/sep3", NULL,
	  NULL, 0, "<Separator>", NULL },
	{ "/Options/Graphics/Wide tiles", NULL,
	  change_wide_tile_mode_event_handler, 0, "<CheckItem>", NULL },
# endif  /* USE_DOUBLE_TILES */
	{ "/Options/Graphics/sep1", NULL,
	  NULL, 0, "<Separator>", NULL },
	{ "/Options/Graphics/Dither if <= 8bpp", NULL,
	  change_dith_mode_event_handler, GDK_RGB_DITHER_NORMAL, "<CheckItem>", NULL },
	{ "/Options/Graphics/Dither if <= 16bpp", NULL,
	  change_dith_mode_event_handler, GDK_RGB_DITHER_MAX, "<CheckItem>", NULL },
	{ "/Options/Graphics/sep2", NULL,
	  NULL, 0, "<Separator>", NULL },
	{ "/Options/Graphics/Smoothing", NULL,
	  change_smooth_mode_event_handler, 0, "<CheckItem>", NULL },
# ifdef USE_TRANSPARENCY
	{ "/Options/Graphics/Transparency", NULL,
	  change_trans_mode_event_handler, 0, "<CheckItem>", NULL },
# endif  /* USE_TRANSPARENCY */

#endif /* USE_GRAPHICS */

	/* "Misc" submenu */
	{ "/Options/Misc", NULL,
	  NULL, 0, "<Branch>", NULL },
	{ "/Options/Misc/Backing store", NULL,
	  change_backing_store_event_handler, 0, "<CheckItem>", NULL },
};


/*
 * XXX XXX Fill those NULL's in the menu definition with
 * angband_term_name[] strings
 */
static void setup_menu_paths(void)
{
	int i;
	int nmenu_items = sizeof(main_menu_items) / sizeof(main_menu_items[0]);
	GtkItemFactoryEntry *term_entry, *font_entry;
	char buf[64];

	/* Find the "Terms" menu */
	for (i = 0; i < nmenu_items; i++)
	{
		/* Skip NULLs */
		if (main_menu_items[i].path == NULL) continue;

		/* Find a match */
		if (streq(main_menu_items[i].path, "/Terms")) break;
	}
	g_assert(i < (nmenu_items - MAX_TERM_DATA));

	/* Remember the location */
	term_entry = &main_menu_items[i + 1];

	/* Find "Font" menu */
	for (i = 0; i < nmenu_items; i++)
	{
		/* Skip NULLs */
		if (main_menu_items[i].path == NULL) continue;

		/* Find a match */
		if (streq(main_menu_items[i].path, "/Options/Font")) break;
	}
	g_assert(i < (nmenu_items - MAX_TERM_DATA));

	/* Remember the location */
	font_entry = &main_menu_items[i + 1];

	/* For each terminal */
	for (i = 0; i < MAX_TERM_DATA; i++)
	{
		/* XXX XXX Build the real path name to the entry */
		strnfmt(buf, 64, "/Terms/%s", angband_term_name[i]);

		/* XXX XXX Store it in the menu definition */
		term_entry[i].path = (gchar*)string_make(buf);

		/* XXX XXX Build the real path name to the entry */
		strnfmt(buf, 64, "/Options/Font/%s", angband_term_name[i]);

		/* XXX XXX Store it in the menu definition */
		font_entry[i].path = (gchar*)string_make(buf);
	}
}


/*
 * XXX XXX Free strings allocated by setup_menu_paths()
 */
static void free_menu_paths(void)
{
	int i;
	int nmenu_items = sizeof(main_menu_items) / sizeof(main_menu_items[0]);
	GtkItemFactoryEntry *term_entry, *font_entry;

	/* Find the "Terms" menu */
	for (i = 0; i < nmenu_items; i++)
	{
		/* Skip NULLs */
		if (main_menu_items[i].path == NULL) continue;

		/* Find a match */
		if (streq(main_menu_items[i].path, "/Terms")) break;
	}
	g_assert(i < (nmenu_items - MAX_TERM_DATA));

	/* Remember the location */
	term_entry = &main_menu_items[i + 1];

	/* Find "Font" menu */
	for (i = 0; i < nmenu_items; i++)
	{
		/* Skip NULLs */
		if (main_menu_items[i].path == NULL) continue;

		/* Find a match */
		if (streq(main_menu_items[i].path, "/Options/Font")) break;
	}
	g_assert(i < (nmenu_items - MAX_TERM_DATA));

	/* Remember the location */
	font_entry = &main_menu_items[i + 1];

	/* For each terminal */
	for (i = 0; i < MAX_TERM_DATA; i++)
	{
		/* XXX XXX Free Term menu path */
		if (term_entry[i].path) string_free((cptr)term_entry[i].path);

		/* XXX XXX Free Font menu path */
		if (font_entry[i].path) string_free((cptr)font_entry[i].path);
	}
}


/*
 * Find widget corresponding to path name
 * return NULL on error
 */
static GtkWidget *get_widget_from_path(cptr path)
{
	GtkItemFactory *item_factory;
	GtkWidget *widget;

	/* Paranoia */
	if (path == NULL) return (NULL);

	/* Look up item factory */
	item_factory = gtk_item_factory_from_path(path);

	/* Oops */
	if (item_factory == NULL) return (NULL);

	/* Look up widget */
	widget = gtk_item_factory_get_widget(item_factory, path);

	/* Return result */
	return (widget);
}


/*
 * Enable/disable a menu item
 */
void enable_menu_item(cptr path, bool enabled)
{
	GtkWidget *widget;

	/* Access menu item widget */
	widget = get_widget_from_path(path);

	/* Paranoia */
	g_assert(widget != NULL);
	g_assert(GTK_IS_MENU_ITEM(widget));

	/*
	 * In Gtk's terminology, enabled is sensitive
	 * and disabled insensitive
	 */
	gtk_widget_set_sensitive(widget, enabled);
}


/*
 * Check/uncheck a menu item. The item should be of the GtkCheckMenuItem type
 */
void check_menu_item(cptr path, bool checked)
{
	GtkWidget *widget;

	/* Access menu item widget */
	widget = get_widget_from_path(path);

	/* Paranoia */
	g_assert(widget != NULL);
	g_assert(GTK_IS_CHECK_MENU_ITEM(widget));

	/*
	 * Put/remove check mark
	 *
	 * Mega-Hack -- The function supposed to be used here,
	 * gtk_check_menu_item_set_active(), emits an "activate" signal
	 * to the GtkMenuItem class of the widget, as if the menu item
	 * were selected by user, thereby causing bizarre behaviour.
	 * XXX XXX XXX
	 */
	GTK_CHECK_MENU_ITEM(widget)->active = checked;
}


/*
 * Update the "File" menu
 */
static void file_menu_update_handler(
        GtkWidget *widget,
        gpointer user_data)
{
#ifndef SAVEFILE_SCREEN
	bool game_start_ok;
#endif /* !SAVEFILE_SCREEN */
	bool save_ok, quit_ok;

#ifndef SAVEFILE_SCREEN

	/* Can we start a game now? */
	game_start_ok = !game_in_progress;

#endif /* !SAVEFILE_SCREEN */

	/* Cave we save/quit now? */
	if (!character_generated || !game_in_progress)
	{
		save_ok = FALSE;
		quit_ok = TRUE;
	}
	else
	{
		if (inkey_flag && can_save) save_ok = quit_ok = TRUE;
		else save_ok = quit_ok = FALSE;
	}

	/* Enable / disable menu items according to those conditions */
#ifndef SAVEFILE_SCREEN
	enable_menu_item("<Angband>/File/New", game_start_ok);
	enable_menu_item("<Angband>/File/Open", game_start_ok);
#endif /* !SAVEFILE_SCREEN */
	enable_menu_item("<Angband>/File/Save", save_ok);
	enable_menu_item("<Angband>/File/Quit", quit_ok);
}


/*
 * Update the "Terms" menu
 */
static void term_menu_update_handler(
        GtkWidget *widget,
        gpointer user_data)
{
	int i;
	char buf[64];

	/* For each term */
	for (i = 0; i < MAX_TERM_DATA; i++)
	{
		/* Build the path name */
		strnfmt(buf, 64, "<Angband>/Terms/%s", angband_term_name[i]);

		/* Update the check mark on the item */
		check_menu_item(buf, data[i].shown);
	}
}


/*
 * Update the "Font" submenu
 */
static void font_menu_update_handler(
        GtkWidget *widget,
        gpointer user_data)
{
	int i;
	char buf[64];

	/* For each term */
	for (i = 0; i < MAX_TERM_DATA; i++)
	{
		/* Build the path name */
		strnfmt(buf, 64, "<Angband>/Options/Font/%s", angband_term_name[i]);

		/* Enable selection if the term is shown */
		enable_menu_item(buf, data[i].shown);
	}
}


/*
 * Update the "Misc" submenu
 */
static void misc_menu_update_handler(
        GtkWidget *widget,
        gpointer user_data)
{
	/* Update an item */
	check_menu_item(
	        "<Angband>/Options/Misc/Backing store",
	        use_backing_store);
}


#ifdef USE_GRAPHICS

/*
 * Update the "Graphics" submenu
 */
static void graf_menu_update_handler(
        GtkWidget *widget,
        gpointer user_data)
{
	/* Update menu items */
	check_menu_item(
	        "<Angband>/Options/Graphics/None",
	        (graf_mode == GRAF_MODE_NONE));
	check_menu_item(
	        "<Angband>/Options/Graphics/Old",
	        (graf_mode == GRAF_MODE_OLD));
	check_menu_item(
	        "<Angband>/Options/Graphics/New",
	        (graf_mode == GRAF_MODE_NEW));

#ifdef USE_DOUBLE_TILES

	check_menu_item(
	        "<Angband>/Options/Graphics/Wide tiles",
	        use_bigtile);

#endif /* USE_DOUBLE_TILES */

	check_menu_item(
	        "<Angband>/Options/Graphics/Dither if <= 8bpp",
	        (dith_mode == GDK_RGB_DITHER_NORMAL));
	check_menu_item(
	        "<Angband>/Options/Graphics/Dither if <= 16bpp",
	        (dith_mode == GDK_RGB_DITHER_MAX));

	check_menu_item(
	        "<Angband>/Options/Graphics/Smoothing",
	        smooth_rescaling);

# ifdef USE_TRANSPARENCY

	check_menu_item(
	        "<Angband>/Options/Graphics/Transparency",
	        use_transparency);

# endif  /* USE_TRANSPARENCY */
}

#endif /* USE_GRAPHICS */


/*
 * Construct a menu hierarchy using GtkItemFactory, setting up
 * callbacks and accelerators along the way, and return
 * a GtkMenuBar widget.
 */
GtkWidget *get_main_menu(term_data *td)
{
	GtkItemFactory *item_factory;
	GtkAccelGroup *accel_group;
	gint nmenu_items = sizeof(main_menu_items) / sizeof(main_menu_items[0]);


	/* XXX XXX Setup path names in the "Terms" and "Font" menus */
	setup_menu_paths();

	/* Allocate an accelerator group */
	accel_group = gtk_accel_group_new();
	g_assert(accel_group != NULL);

	/* Initialise the item factory */
	item_factory = gtk_item_factory_new(
	                       GTK_TYPE_MENU_BAR,
	                       "<Angband>",
	                       accel_group);
	g_assert(item_factory != NULL);

	/* Generate the menu items */
	gtk_item_factory_create_items(
	        item_factory,
	        nmenu_items,
	        main_menu_items,
	        NULL);

	/* Attach the new accelerator group to the window */
	gtk_window_add_accel_group(
	        GTK_WINDOW(td->window),
	        accel_group);

	/* Return the actual menu bar created */
	return (gtk_item_factory_get_widget(item_factory, "<Angband>"));
}


/*
 * Install callbacks to update menus
 */
static void add_menu_update_callbacks()
{
	GtkWidget *widget;

	/* Access the "File" menu */
	widget = get_widget_from_path("<Angband>/File");

	/* Paranoia */
	g_assert(widget != NULL);
	g_assert(GTK_IS_MENU(widget));

	/* Assign callback */
	gtk_signal_connect(
	        GTK_OBJECT(widget),
	        "show",
	        GTK_SIGNAL_FUNC(file_menu_update_handler),
	        NULL);

	/* Access the "Terms" menu */
	widget = get_widget_from_path("<Angband>/Terms");

	/* Paranoia */
	g_assert(widget != NULL);
	g_assert(GTK_IS_MENU(widget));

	/* Assign callback */
	gtk_signal_connect(
	        GTK_OBJECT(widget),
	        "show",
	        GTK_SIGNAL_FUNC(term_menu_update_handler),
	        NULL);

	/* Access the "Font" menu */
	widget = get_widget_from_path("<Angband>/Options/Font");

	/* Paranoia */
	g_assert(widget != NULL);
	g_assert(GTK_IS_MENU(widget));

	/* Assign callback */
	gtk_signal_connect(
	        GTK_OBJECT(widget),
	        "show",
	        GTK_SIGNAL_FUNC(font_menu_update_handler),
	        NULL);

	/* Access the "Misc" menu */
	widget = get_widget_from_path("<Angband>/Options/Misc");

	/* Paranoia */
	g_assert(widget != NULL);
	g_assert(GTK_IS_MENU(widget));

	/* Assign callback */
	gtk_signal_connect(
	        GTK_OBJECT(widget),
	        "show",
	        GTK_SIGNAL_FUNC(misc_menu_update_handler),
	        NULL);

#ifdef USE_GRAPHICS

	/* Access Graphics menu */
	widget = get_widget_from_path("<Angband>/Options/Graphics");

	/* Paranoia */
	g_assert(widget != NULL);
	g_assert(GTK_IS_MENU(widget));

	/* Assign callback */
	gtk_signal_connect(
	        GTK_OBJECT(widget),
	        "show",
	        GTK_SIGNAL_FUNC(graf_menu_update_handler),
	        NULL);

#endif /* USE_GRAPHICS */
}


/*
 * Create Gtk widgets for a terminal window and set up callbacks
 */
static void init_gtk_window(term_data *td, int i)
{
	GtkWidget *menu_bar = NULL, *box;
	cptr font;

	bool main_window = (i == 0) ? TRUE : FALSE;


	/* Create window */
	td->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	/* Set title */
	gtk_window_set_title(GTK_WINDOW(td->window), td->name);


	/* Get default font for this term */
	font = get_default_font(i);

	/* Load font and initialise related term_data fields */
	load_font(td, font);


	/* Create drawing area */
	td->drawing_area = gtk_drawing_area_new();

	/* Set the size of the drawing area */
	gtk_drawing_area_size(
	        GTK_DRAWING_AREA(td->drawing_area),
	        td->cols * td->font_wid,
	        td->rows * td->font_hgt);

	/* Set geometry hints */
	term_data_set_geometry_hints(td);


	/* Install window event handlers */
	gtk_signal_connect(
	        GTK_OBJECT(td->window),
	        "delete_event",
	        GTK_SIGNAL_FUNC(delete_event_handler),
	        NULL);
	gtk_signal_connect(
	        GTK_OBJECT(td->window),
	        "key_press_event",
	        GTK_SIGNAL_FUNC(keypress_event_handler),
	        NULL);

	/* Destroying the Angband window terminates the game */
	if (main_window)
	{
		gtk_signal_connect(
		        GTK_OBJECT(td->window),
		        "destroy_event",
		        GTK_SIGNAL_FUNC(destroy_main_event_handler),
		        NULL);
	}

	/* The other windows are just hidden */
	else
	{
		gtk_signal_connect(
		        GTK_OBJECT(td->window),
		        "destroy_event",
		        GTK_SIGNAL_FUNC(destroy_sub_event_handler),
		        td);
	}


	/* Install drawing area event handlers */
	gtk_signal_connect(
	        GTK_OBJECT(td->drawing_area),
	        "realize",
	        GTK_SIGNAL_FUNC(realize_event_handler),
	        (gpointer)td);
	gtk_signal_connect(
	        GTK_OBJECT(td->drawing_area),
	        "show",
	        GTK_SIGNAL_FUNC(show_event_handler),
	        (gpointer)td);
	gtk_signal_connect(
	        GTK_OBJECT(td->drawing_area),
	        "hide",
	        GTK_SIGNAL_FUNC(hide_event_handler),
	        (gpointer)td);
	gtk_signal_connect(
	        GTK_OBJECT(td->drawing_area),
	        "size_allocate",
	        GTK_SIGNAL_FUNC(size_allocate_event_handler),
	        (gpointer)td);
	gtk_signal_connect(
	        GTK_OBJECT(td->drawing_area),
	        "expose_event",
	        GTK_SIGNAL_FUNC(expose_event_handler),
	        (gpointer)td);


	/* Create menu */
	if (main_window)
	{
		/* Build the main menu bar */
		menu_bar = get_main_menu(td);
		g_assert(menu_bar != NULL);

		/* Since it's tedious to scatter the menu update code around */
		add_menu_update_callbacks();
	}


	/* Pack the menu bar together with the main window */
	/* For vertical placement of the menu bar and the drawing area */
	box = gtk_vbox_new(FALSE, 0);

	/* Let the window widget own it */
	gtk_container_add(GTK_CONTAINER(td->window), box);

	/* The main window has a menu bar */
	if (main_window)
		gtk_box_pack_start(
		        GTK_BOX(box),
		        menu_bar,
		        FALSE,
		        FALSE,
		        NO_PADDING);

	/* And place the drawing area just beneath it */
	gtk_box_pack_start_defaults(GTK_BOX(box), td->drawing_area);


	/* Show the widgets - use of td->shown is a dirty hack XXX XXX */
	if (td->shown) gtk_widget_show_all(td->window);
}


/*
 * To be hooked into quit(). See z-util.c
 */
static void hook_quit(cptr str)
{
	/* Free menu paths dynamically allocated */
	free_menu_paths();

# ifdef USE_GRAPHICS

	/* Free pathname string */
	if (ANGBAND_DIR_XTRA_GRAF) string_free(ANGBAND_DIR_XTRA_GRAF);

# endif  /* USE_GRAPHICS */

	/* Terminate the program */
	gtk_exit(0);
}


#ifdef ANGBAND300

/*
 * Help message for this port
 */
const char help_gtk[] =
        "GTK for X11, subopts -n<windows>\n"
        "           -b(acking store off)\n"
#ifdef USE_GRAPHICS
        "           -g(raphics) -o(ld graphics) -s(moothscaling off) \n"
        "           -t(ransparency on)\n"
# ifdef USE_DOUBLE_TILES
        "           -w(ide tiles)\n"
# endif  /* USE_DOUBLE_TILES */
#endif /* USE_GRAPHICS */
        "           and standard GTK options";

#endif /* ANGBAND300 */


/*
 * Initialization function
 */
errr init_gtk2(int argc, char **argv)
{
	int i;


	/* Initialize the environment */
	gtk_init(&argc, &argv);

	/* Activate hooks - Use gtk/glib interface throughout */
	ralloc_aux = hook_ralloc;
	rnfree_aux = hook_rnfree;
	quit_aux = hook_quit;
	core_aux = hook_quit;

	/* Parse args */
	for (i = 1; i < argc; i++)
	{
		/* Number of terminals displayed at start up */
		if (prefix(argv[i], "-n"))
		{
			num_term = atoi(&argv[i][2]);
			if (num_term > MAX_TERM_DATA) num_term = MAX_TERM_DATA;
			else if (num_term < 1) num_term = 1;
			continue;
		}

		/* Disable use of pixmaps as backing store */
		if (streq(argv[i], "-b"))
		{
			use_backing_store = FALSE;
			continue;
		}

#ifdef USE_GRAPHICS

		/* Requests "old" graphics */
		if (streq(argv[i], "-o"))
		{
			graf_mode_request = GRAF_MODE_OLD;
			continue;
		}

		/* Requests "new" graphics */
		if (streq(argv[i], "-g"))
		{
			graf_mode_request = GRAF_MODE_NEW;
			continue;
		}

# ifdef USE_DOUBLE_TILES

		/* Requests wide tile mode */
		if (streq(argv[i], "-w"))
		{
			use_bigtile = TRUE;
# ifdef TOME
			/* T.o.M.E. uses older version of the patch */
			arg_bigtile = TRUE;
# endif  /* TOME */
			continue;
		}

# endif  /* USE_DOUBLE_TILES */


		/* Enable transparency effect */
		if (streq(argv[i], "-t"))
		{
			use_transparency = TRUE;
			continue;
		}

		/* Disable smooth rescaling of tiles */
		if (streq(argv[i], "-s"))
		{
			smooth_rescaling_request = FALSE;
			continue;
		}

#endif /* USE_GRAPHICS */

		/* None of the above */
		plog_fmt("Ignoring option: %s", argv[i]);
	}

#ifdef USE_GRAPHICS

	{
		char path[1024];

		/* Build the "graf" path */
		path_build(path, 1024, ANGBAND_DIR_XTRA, "graf");

		/* Allocate the path */
		ANGBAND_DIR_XTRA_GRAF = string_make(path);
	}

#endif /* USE_GRAPHICS */

	/* Initialise colours */
	gdk_rgb_init();
	gtk_widget_set_default_colormap(gdk_rgb_get_cmap());
	gtk_widget_set_default_visual(gdk_rgb_get_visual());
	init_colours();

	/*
	 * Initialise the windows backwards, so that
	 * the Angband window comes in front
	 */
	for (i = MAX_TERM_DATA - 1; i >= 0; i--)
	{
		term_data *td = &data[i];

		/* Initialize the term_data */
		term_data_init(td, i);

		/* Hack - Set the shown flag, meaning "to be shown" XXX XXX */
		if (i < num_term) td->shown = TRUE;
		else td->shown = FALSE;

		/* Save global entry */
		angband_term[i] = Term;

		/* Init the window */
		init_gtk_window(td, i);
	}

	/* Activate the "Angband" window screen */
	Term_activate(&data[0].t);

#ifndef SAVEFILE_SCREEN

	/* Set the system suffix */
	ANGBAND_SYS = "gtk";

	/* Catch nasty signals */
	signals_init();

	/* Initialize */
	init_angband();

#ifndef OLD_SAVEFILE_CODE

	/* Hack - because this port has New/Open menus XXX */
	savefile[0] = '\0';

#endif /* !OLD_SAVEFILE_CODE */

	/* Prompt the user */
	prt("[Choose 'New' or 'Open' from the 'File' menu]", 23, 17);
	Term_fresh();

	/* Activate more hook */
	plog_aux = hook_plog;


	/* Processing loop */
	gtk_main();


	/* Free allocated memory */
	cleanup_angband();

	/* Stop now */
	quit(NULL);

#else /* !SAVEFILE_SCREEN */

	/* Activate more hook */
	plog_aux = hook_plog;

	/* It's too early to set this, but cannot do so elsewhere XXX XXX */
	game_in_progress = TRUE;

#endif /* !SAVEFILE_SCREEN */

	/* Success */
	return (0);
}

#endif /* USE_GTK2 */