XEmacs / src / event-Xt.c

   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
/* The event_stream interface for X11 with Xt, and/or tty frames.
   Copyright (C) 1991-5, 1997 Free Software Foundation, Inc.
   Copyright (C) 1995 Sun Microsystems, Inc.
   Copyright (C) 1996 Ben Wing.

This file is part of XEmacs.

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

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

You should have received a copy of the GNU General Public License
along with XEmacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

/* Synched up with: Not in FSF. */

#include <config.h>
#include "lisp.h"

#include "console-x.h"
#include "../lwlib/lwlib.h"
#include "EmacsFrame.h"

#include "blocktype.h"
#include "buffer.h"
#include "console.h"
#include "console-tty.h"
#include "events.h"
#include "frame.h"
#include "objects-x.h"
#include "process.h"
#include "redisplay.h"
#include "elhash.h"

#include "systime.h"
#include "sysproc.h" /* for MAXDESC */

#include "xintrinsicp.h"	/* CoreP.h needs this */
#include <X11/CoreP.h>		/* Numerous places access the fields of
				   a core widget directly.  We could
				   use XtGetValues(), but ... */
#include <X11/ShellP.h>

#ifdef HAVE_XIM
#ifdef XIM_MOTIF
#include <Xm/Xm.h>
#endif
#include "lstream.h"
#include "file-coding.h"
#endif

#ifdef HAVE_DRAGNDROP
#include "dragdrop.h"
#endif

#if defined (HAVE_OFFIX_DND)
#include "offix.h"
#endif

#ifdef WINDOWSNT
/* Hmm, under unix we want X modifiers, under NT we want X modifiers if
   we are running X and Windows modifiers otherwise.
   gak. This is a kludge until we support multiple native GUIs!
*/
#undef MOD_ALT
#undef MOD_CONTROL
#undef MOD_SHIFT
#endif

#include "events-mod.h"

static void enqueue_Xt_dispatch_event (Lisp_Object event);
static void handle_focus_event_1 (struct frame *f, int in_p);

static struct event_stream *Xt_event_stream;

/* With the new event model, all events go through XtDispatchEvent()
   and are picked up by an event handler that is added to each frame
   widget. (This is how it's supposed to be.) In the old method,
   Emacs sucks out events directly from XtNextEvent() and only
   dispatches the events that it doesn't need to deal with.  This
   old way has lots of corresponding junk that is no longer
   necessary: lwlib extensions, synthetic XAnyEvents, unnecessary
   magic events, etc. */

/* The one and only one application context that Emacs uses. */
XtAppContext Xt_app_con;

/* Do we accept events sent by other clients? */
int x_allow_sendevents;

int modifier_keys_are_sticky;

#ifdef DEBUG_XEMACS
int x_debug_events;
#endif

static int process_events_occurred;
static int tty_events_occurred;

/* Mask of bits indicating the descriptors that we wait for input on */
extern SELECT_TYPE input_wait_mask, process_only_mask, tty_only_mask;

static CONST String x_fallback_resources[] =
{
  /* This file is automatically generated from the app-defaults file
     in ../etc/Emacs.ad.  These resources are consulted only if no
     app-defaults file is found at all.
   */
#include <Emacs.ad.h>
  0
};

static Lisp_Object x_keysym_to_emacs_keysym (KeySym keysym, int simple_p);
void emacs_Xt_mapping_action (Widget w, XEvent *event);
void debug_process_finalization (struct Lisp_Process *p);
void emacs_Xt_event_handler (Widget wid, XtPointer closure, XEvent *event,
			     Boolean *continue_to_dispatch);

static int last_quit_check_signal_tick_count;

Lisp_Object Qkey_mapping;
Lisp_Object Qsans_modifiers;


/************************************************************************/
/*                            keymap handling                           */
/************************************************************************/

/* X bogusly doesn't define the interpretations of any bits besides
   ModControl, ModShift, and ModLock; so the Interclient Communication
   Conventions Manual says that we have to bend over backwards to figure
   out what the other modifier bits mean.  According to ICCCM:

   - Any keycode which is assigned ModControl is a "control" key.

   - Any modifier bit which is assigned to a keycode which generates Meta_L
     or Meta_R is the modifier bit meaning "meta".  Likewise for Super, Hyper,
     etc.

   - Any keypress event which contains ModControl in its state should be
     interpreted as a "control" character.

   - Any keypress event which contains a modifier bit in its state which is
     generated by a keycode whose corresponding keysym is Meta_L or Meta_R
     should be interpreted as a "meta" character.  Likewise for Super, Hyper,
     etc.

   - It is illegal for a keysym to be associated with more than one modifier
     bit.

   This means that the only thing that emacs can reasonably interpret as a
   "meta" key is a key whose keysym is Meta_L or Meta_R, and which generates
   one of the modifier bits Mod1-Mod5.

   Unfortunately, many keyboards don't have Meta keys in their default
   configuration.  So, if there are no Meta keys, but there are "Alt" keys,
   emacs will interpret Alt as Meta.  If there are both Meta and Alt keys,
   then the Meta keys mean "Meta", and the Alt keys mean "Alt" (it used to
   mean "Symbol," but that just confused the hell out of way too many people).

   This works with the default configurations of the 19 keyboard-types I've
   checked.

   Emacs detects keyboard configurations which violate the above rules, and
   prints an error message on the standard-error-output.  (Perhaps it should
   use a pop-up-window instead.)
 */

static void
x_reset_key_mapping (struct device *d)
{
  Display *display = DEVICE_X_DISPLAY (d);
  struct x_device *xd = DEVICE_X_DATA (d);
  KeySym *keysym, *keysym_end;
  Lisp_Object hash_table;
  int key_code_count, keysyms_per_code;

  if (xd->x_keysym_map)
    XFree ((char *) xd->x_keysym_map);
  XDisplayKeycodes (display,
		    &xd->x_keysym_map_min_code,
		    &xd->x_keysym_map_max_code);
  key_code_count = xd->x_keysym_map_max_code - xd->x_keysym_map_min_code + 1;
  xd->x_keysym_map =
    XGetKeyboardMapping (display, xd->x_keysym_map_min_code, key_code_count,
			 &xd->x_keysym_map_keysyms_per_code);

  hash_table = xd->x_keysym_map_hash_table;
  if (HASH_TABLEP (hash_table))
    Fclrhash (hash_table);
  else
    xd->x_keysym_map_hash_table = hash_table =
      make_lisp_hash_table (128, HASH_TABLE_NON_WEAK, HASH_TABLE_EQUAL);

  for (keysym = xd->x_keysym_map,
	 keysyms_per_code = xd->x_keysym_map_keysyms_per_code,
	 keysym_end = keysym + (key_code_count * keysyms_per_code);
       keysym < keysym_end;
       keysym += keysyms_per_code)
    {
      int j;

      if (keysym[0] == NoSymbol)
	continue;

      {
	char *name = XKeysymToString (keysym[0]);
	Lisp_Object sym = x_keysym_to_emacs_keysym (keysym[0], 0);
	if (name)
	  {
	    Fputhash (build_string (name), Qsans_modifiers, hash_table);
	    Fputhash (sym, Qsans_modifiers, hash_table);
	  }
      }

      for (j = 1; j < keysyms_per_code; j++)
	{
	  if (keysym[j] != keysym[0] &&
	      keysym[j] != NoSymbol)
	    {
	      char *name = XKeysymToString (keysym[j]);
	      Lisp_Object sym = x_keysym_to_emacs_keysym (keysym[j], 0);
	      if (name && NILP (Fgethash (sym, hash_table, Qnil)))
		{
		  Fputhash (build_string (name), Qt, hash_table);
		  Fputhash (sym, Qt, hash_table);
		}
	    }
	}
    }
}

static CONST char *
index_to_name (int indice)
{
  switch (indice)
    {
    case ShiftMapIndex:   return "ModShift";
    case LockMapIndex:    return "ModLock";
    case ControlMapIndex: return "ModControl";
    case Mod1MapIndex:    return "Mod1";
    case Mod2MapIndex:    return "Mod2";
    case Mod3MapIndex:    return "Mod3";
    case Mod4MapIndex:    return "Mod4";
    case Mod5MapIndex:    return "Mod5";
    default:              return "???";
    }
}

/* Boy, I really wish C had local functions... */
struct c_doesnt_have_closures   /* #### not yet used */
{
  int warned_about_overlapping_modifiers;
  int warned_about_predefined_modifiers;
  int warned_about_duplicate_modifiers;
  int meta_bit;
  int hyper_bit;
  int super_bit;
  int alt_bit;
  int mode_bit;
};

static void
x_reset_modifier_mapping (struct device *d)
{
  Display *display = DEVICE_X_DISPLAY (d);
  struct x_device *xd = DEVICE_X_DATA (d);
  int modifier_index, modifier_key, column, mkpm;
  int warned_about_overlapping_modifiers = 0;
  int warned_about_predefined_modifiers  = 0;
  int warned_about_duplicate_modifiers   = 0;
  int meta_bit  = 0;
  int hyper_bit = 0;
  int super_bit = 0;
  int alt_bit   = 0;
  int mode_bit  = 0;

  xd->lock_interpretation = 0;

  if (xd->x_modifier_keymap)
    XFreeModifiermap (xd->x_modifier_keymap);

  x_reset_key_mapping (d);

  xd->x_modifier_keymap = XGetModifierMapping (display);

  /* Boy, I really wish C had local functions...
   */

  /* The call to warn_when_safe must be on the same line as the string or
     make-msgfile won't pick it up properly (the newline doesn't confuse
     it, but the backslash does). */

#define modwarn(name,old,other)						\
  warn_when_safe (Qkey_mapping, Qwarning, "XEmacs:  %s (0x%x) generates %s, which is generated by %s.",	\
		  name, code, index_to_name (old), other),		\
  warned_about_overlapping_modifiers = 1

#define modbarf(name,other)						    \
  warn_when_safe (Qkey_mapping, Qwarning, "XEmacs:  %s (0x%x) generates %s, which is nonsensical.", \
		  name, code, other),					    \
  warned_about_predefined_modifiers = 1

#define check_modifier(name,mask)					      \
  if ((1<<modifier_index) != mask)					      \
    warn_when_safe (Qkey_mapping, Qwarning, "XEmacs:  %s (0x%x) generates %s, which is nonsensical.", \
		    name, code, index_to_name (modifier_index)),	      \
    warned_about_predefined_modifiers = 1

#define store_modifier(name,old)					   \
  if (old && old != modifier_index)					   \
    warn_when_safe (Qkey_mapping, Qwarning, "XEmacs:  %s (0x%x) generates both %s and %s, which is nonsensical.",\
		    name, code, index_to_name (old),			   \
		    index_to_name (modifier_index)),			   \
    warned_about_duplicate_modifiers = 1;				   \
  if (modifier_index == ShiftMapIndex) modbarf (name,"ModShift");	   \
  else if (modifier_index == LockMapIndex) modbarf (name,"ModLock");	   \
  else if (modifier_index == ControlMapIndex) modbarf (name,"ModControl"); \
  else if (sym == XK_Mode_switch)					   \
    mode_bit = modifier_index; /* Mode_switch is special, see below... */  \
  else if (modifier_index == meta_bit && old != meta_bit)		   \
    modwarn (name, meta_bit, "Meta");					   \
  else if (modifier_index == super_bit && old != super_bit)		   \
    modwarn (name, super_bit, "Super");					   \
  else if (modifier_index == hyper_bit && old != hyper_bit)		   \
    modwarn (name, hyper_bit, "Hyper");					   \
  else if (modifier_index == alt_bit && old != alt_bit)			   \
    modwarn (name, alt_bit, "Alt");					   \
  else									   \
    old = modifier_index;

  mkpm = xd->x_modifier_keymap->max_keypermod;
  for (modifier_index = 0; modifier_index < 8; modifier_index++)
    for (modifier_key = 0; modifier_key < mkpm; modifier_key++) {
      KeySym last_sym = 0;
      for (column = 0; column < 4; column += 2) {
	KeyCode code = xd->x_modifier_keymap->modifiermap[modifier_index * mkpm
							  + modifier_key];
	KeySym sym = (code ? XKeycodeToKeysym (display, code, column) : 0);
	if (sym == last_sym) continue;
	last_sym = sym;
	switch (sym) {
	case XK_Mode_switch:store_modifier ("Mode_switch", mode_bit); break;
	case XK_Meta_L:     store_modifier ("Meta_L", meta_bit); break;
	case XK_Meta_R:     store_modifier ("Meta_R", meta_bit); break;
	case XK_Super_L:    store_modifier ("Super_L", super_bit); break;
	case XK_Super_R:    store_modifier ("Super_R", super_bit); break;
	case XK_Hyper_L:    store_modifier ("Hyper_L", hyper_bit); break;
	case XK_Hyper_R:    store_modifier ("Hyper_R", hyper_bit); break;
	case XK_Alt_L:      store_modifier ("Alt_L", alt_bit); break;
	case XK_Alt_R:      store_modifier ("Alt_R", alt_bit); break;
	case XK_Control_L:  check_modifier ("Control_L", ControlMask); break;
	case XK_Control_R:  check_modifier ("Control_R", ControlMask); break;
	case XK_Shift_L:    check_modifier ("Shift_L", ShiftMask); break;
	case XK_Shift_R:    check_modifier ("Shift_R", ShiftMask); break;
	case XK_Shift_Lock: check_modifier ("Shift_Lock", LockMask);
	  xd->lock_interpretation = XK_Shift_Lock; break;
	case XK_Caps_Lock:  check_modifier ("Caps_Lock", LockMask);
	  xd->lock_interpretation = XK_Caps_Lock; break;

	/* It probably doesn't make any sense for a modifier bit to be
	   assigned to a key that is not one of the above, but OpenWindows
	   assigns modifier bits to a couple of random function keys for
	   no reason that I can discern, so printing a warning here would
	   be annoying. */
	}
      }
    }
#undef store_modifier
#undef check_modifier
#undef modwarn
#undef modbarf

  /* If there was no Meta key, then try using the Alt key instead.
     If there is both a Meta key and an Alt key, then the Alt key
     is not disturbed and remains an Alt key. */
  if (! meta_bit && alt_bit)
    meta_bit = alt_bit, alt_bit = 0;

  /* mode_bit overrides everything, since it's processed down inside of
     XLookupString() instead of by us.  If Meta and Mode_switch both
     generate the same modifier bit (which is an error), then we don't
     interpret that bit as Meta, because we can't make XLookupString()
     not interpret it as Mode_switch; and interpreting it as both would
     be totally wrong. */
  if (mode_bit)
    {
      CONST char *warn = 0;
      if      (mode_bit == meta_bit)  warn = "Meta",  meta_bit  = 0;
      else if (mode_bit == hyper_bit) warn = "Hyper", hyper_bit = 0;
      else if (mode_bit == super_bit) warn = "Super", super_bit = 0;
      else if (mode_bit == alt_bit)   warn = "Alt",   alt_bit   = 0;
      if (warn)
	{
	  warn_when_safe
	    (Qkey_mapping, Qwarning,
	     "XEmacs:  %s is being used for both Mode_switch and %s.",
	     index_to_name (mode_bit), warn),
	    warned_about_overlapping_modifiers = 1;
	}
    }
#undef index_to_name

  xd->MetaMask   = (meta_bit   ? (1 << meta_bit)  : 0);
  xd->HyperMask  = (hyper_bit  ? (1 << hyper_bit) : 0);
  xd->SuperMask  = (super_bit  ? (1 << super_bit) : 0);
  xd->AltMask    = (alt_bit    ? (1 << alt_bit)   : 0);
  xd->ModeMask   = (mode_bit   ? (1 << mode_bit)  : 0); /* unused */


  if (warned_about_overlapping_modifiers)
    warn_when_safe (Qkey_mapping, Qwarning, "\n"
"	Two distinct modifier keys (such as Meta and Hyper) cannot generate\n"
"	the same modifier bit, because Emacs won't be able to tell which\n"
"	modifier was actually held down when some other key is pressed.  It\n"
"	won't be able to tell Meta-x and Hyper-x apart, for example.  Change\n"
"	one of these keys to use some other modifier bit.  If you intend for\n"
"	these keys to have the same behavior, then change them to have the\n"
"	same keysym as well as the same modifier bit.");

  if (warned_about_predefined_modifiers)
    warn_when_safe (Qkey_mapping, Qwarning, "\n"
"	The semantics of the modifier bits ModShift, ModLock, and ModControl\n"
"	are predefined.  It does not make sense to assign ModControl to any\n"
"	keysym other than Control_L or Control_R, or to assign any modifier\n"
"	bits to the \"control\" keysyms other than ModControl.  You can't\n"
"	turn a \"control\" key into a \"meta\" key (or vice versa) by simply\n"
"	assigning the key a different modifier bit.  You must also make that\n"
"	key generate an appropriate keysym (Control_L, Meta_L, etc).");

  /* No need to say anything more for warned_about_duplicate_modifiers. */

  if (warned_about_overlapping_modifiers || warned_about_predefined_modifiers)
    warn_when_safe (Qkey_mapping, Qwarning, "\n"
"	The meanings of the modifier bits Mod1 through Mod5 are determined\n"
"	by the keysyms used to control those bits.  Mod1 does NOT always\n"
"	mean Meta, although some non-ICCCM-compliant programs assume that.");
}

void
x_init_modifier_mapping (struct device *d)
{
  struct x_device *xd = DEVICE_X_DATA (d);
  xd->x_keysym_map_hash_table = Qnil;
  xd->x_keysym_map = NULL;
  xd->x_modifier_keymap = NULL;
  x_reset_modifier_mapping (d);
}

static int
x_key_is_modifier_p (KeyCode keycode, struct device *d)
{
  struct x_device *xd = DEVICE_X_DATA (d);
  KeySym *syms;
  int i;

  if (keycode < xd->x_keysym_map_min_code ||
      keycode > xd->x_keysym_map_max_code)
    return 0;

  syms = &xd->x_keysym_map [(keycode - xd->x_keysym_map_min_code) *
			   xd->x_keysym_map_keysyms_per_code];
  for (i = 0; i < xd->x_keysym_map_keysyms_per_code; i++)
    if (IsModifierKey (syms [i]) ||
	syms [i] == XK_Mode_switch) /* why doesn't IsModifierKey count this? */
      return 1;
  return 0;
}

/* key-handling code is always ugly.  It just ends up working out
   that way.

   Here are some pointers:

   -- DOWN_MASK indicates which modifiers should be treated as "down"
      when the corresponding upstroke happens.  It gets reset for
      a particular modifier when that modifier goes up, and reset
      for all modifiers when a non-modifier key is pressed.  Example:

      I press Control-A-Shift and then release Control-A-Shift.
      I want the Shift key to be sticky but not the Control key.

   -- LAST_DOWNKEY and RELEASE_TIME are used to keep track of
      auto-repeat -- see below.

   -- If a modifier key is sticky, I can unstick it by pressing
      the modifier key again. */

static void
x_handle_sticky_modifiers (XEvent *ev, struct device *d)
{
  struct x_device *xd;
  KeyCode keycode;
  int type;

  if (!modifier_keys_are_sticky) /* Optimize for non-sticky modifiers */
    return;

  xd = DEVICE_X_DATA (d);
  keycode = ev->xkey.keycode;
  type = ev->type;

  if (keycode < xd->x_keysym_map_min_code ||
      keycode > xd->x_keysym_map_max_code)
    return;

  if (! ((type == KeyPress || type == KeyRelease) &&
         x_key_is_modifier_p (keycode, d)))
    { /* Not a modifier key */
      Bool key_event_p = (type == KeyPress || type == KeyRelease);

      if (type == KeyPress && !xd->last_downkey)
	xd->last_downkey = keycode;
      else if (type == ButtonPress ||
	       (type == KeyPress && xd->last_downkey &&
		(keycode != xd->last_downkey ||
		 ev->xkey.time != xd->release_time)))
	{
	  xd->need_to_add_mask = 0;
	  xd->last_downkey = 0;
	}
      if (type == KeyPress)
	xd->release_time = 0;
      if (type == KeyPress || type == ButtonPress)
	xd->down_mask = 0;

      if (key_event_p)
        ev->xkey.state    |= xd->need_to_add_mask;
      else
        ev->xbutton.state |= xd->need_to_add_mask;

      if (type == KeyRelease && keycode == xd->last_downkey)
	/* If I hold press-and-release the Control key and then press
	   and hold down the right arrow, I want it to auto-repeat
	   Control-Right.  On the other hand, if I do the same but
	   manually press the Right arrow a bunch of times, I want
	   to see one Control-Right and then a bunch of Rights.
	   This means that we need to distinguish between an
	   auto-repeated key and a key pressed and released a bunch
	   of times.

	   Naturally, the designers of the X spec didn't see fit
	   to provide an obvious way to distinguish these cases.
	   So we assume that if the release and the next press
	   occur at the same time, the key was actually auto-
	   repeated.  Under Open-Windows, at least, this works. */
	xd->release_time = key_event_p ? ev->xkey.time : ev->xbutton.time;
    }
  else                          /* Modifier key pressed */
    {
      int i;
      KeySym *syms = &xd->x_keysym_map [(keycode - xd->x_keysym_map_min_code) *
					xd->x_keysym_map_keysyms_per_code];

      /* If a non-modifier key was pressed in the middle of a bunch
	 of modifiers, then it unsticks all the modifiers that were
	 previously pressed.  We cannot unstick the modifiers until
	 now because we want to check for auto-repeat of the
	 non-modifier key. */

      if (xd->last_downkey)
	{
	  xd->last_downkey = 0;
	  xd->need_to_add_mask = 0;
	}

#define FROB(mask)				\
do {						\
  if (type == KeyPress)				\
    {						\
      /* If modifier key is already sticky,	\
         then unstick it.  Note that we do	\
         not test down_mask to deal with the	\
	 unlikely but possible case that the	\
	 modifier key auto-repeats. */		\
      if (xd->need_to_add_mask & mask)		\
	{					\
	  xd->need_to_add_mask &= ~mask;	\
	  xd->down_mask &= ~mask;		\
	}					\
      else					\
	xd->down_mask |= mask;			\
    }						\
  else						\
    {						\
      if (xd->down_mask & mask)			\
	{					\
	  xd->down_mask &= ~mask;		\
	  xd->need_to_add_mask |= mask;		\
	}					\
    }						\
} while (0)

      for (i = 0; i < xd->x_keysym_map_keysyms_per_code; i++)
        switch (syms[i])
          {
          case XK_Control_L: case XK_Control_R: FROB (ControlMask);   break;
          case XK_Shift_L:   case XK_Shift_R:   FROB (ShiftMask);     break;
          case XK_Meta_L:    case XK_Meta_R:    FROB (xd->MetaMask);  break;
          case XK_Super_L:   case XK_Super_R:   FROB (xd->SuperMask); break;
          case XK_Hyper_L:   case XK_Hyper_R:   FROB (xd->HyperMask); break;
          case XK_Alt_L:     case XK_Alt_R:     FROB (xd->AltMask);   break;
          }
    }
#undef FROB
}

static void
clear_sticky_modifiers (struct device *d)
{
  struct x_device *xd = DEVICE_X_DATA (d);

  xd->need_to_add_mask = 0;
  xd->last_downkey     = 0;
  xd->release_time     = 0;
  xd->down_mask        = 0;
}

static int
keysym_obeys_caps_lock_p (KeySym sym, struct device *d)
{
  struct x_device *xd = DEVICE_X_DATA (d);
  /* Eeeeevil hack.  Don't apply Caps_Lock to things that aren't alphabetic
     characters, where "alphabetic" means something more than simply A-Z.
     That is, if Caps_Lock is down, typing ESC doesn't produce Shift-ESC.
     But if shift-lock is down, then it does. */
  if (xd->lock_interpretation == XK_Shift_Lock)
    return 1;

  return
    ((sym >= XK_A)        && (sym <= XK_Z))          ||
    ((sym >= XK_a)        && (sym <= XK_z))          ||
    ((sym >= XK_Agrave)   && (sym <= XK_Odiaeresis)) ||
    ((sym >= XK_agrave)   && (sym <= XK_odiaeresis)) ||
    ((sym >= XK_Ooblique) && (sym <= XK_Thorn))      ||
    ((sym >= XK_oslash)   && (sym <= XK_thorn));
}

/* called from EmacsFrame.c (actually from Xt itself) when a
   MappingNotify event is received.  In its infinite wisdom, Xt
   decided that Xt event handlers never get MappingNotify events.
   O'Reilly Xt Programming Manual 9.1.2 says:

   MappingNotify is automatically handled by Xt, so it isn't passed
   to event handlers and you don't need to worry about it.

   Of course, we DO worry about it, so we need a special translation. */
void
emacs_Xt_mapping_action (Widget w, XEvent* event)
{
  struct device *d = get_device_from_display (event->xany.display);

  if (DEVICE_X_BEING_DELETED (d))
    return;
#if 0
  /* nyet.  Now this is handled by Xt. */
  XRefreshKeyboardMapping (&event->xmapping);
#endif
  /* xmodmap generates about a billion MappingKeyboard events, followed
     by a single MappingModifier event, so it might be worthwhile to
     take extra MappingKeyboard events out of the queue before requesting
     the current keymap from the server. */
  switch (event->xmapping.request)
    {
    case MappingKeyboard:  x_reset_key_mapping      (d); break;
    case MappingModifier:  x_reset_modifier_mapping (d); break;
    case MappingPointer:   /* Do something here? */      break;
    default: abort();
    }
}


/************************************************************************/
/*                  X to Emacs event conversion                         */
/************************************************************************/

static Lisp_Object
x_keysym_to_emacs_keysym (KeySym keysym, int simple_p)
{
  char *name;
  if (keysym >= XK_exclam && keysym <= XK_asciitilde)
    /* We must assume that the X keysym numbers for the ASCII graphic
       characters are the same as their ASCII codes.  */
    return make_char (keysym);

  switch (keysym)
    {
      /* These would be handled correctly by the default case, but by
	 special-casing them here we don't garbage a string or call
	 intern().  */
    case XK_BackSpace:	return QKbackspace;
    case XK_Tab:	return QKtab;
    case XK_Linefeed:	return QKlinefeed;
    case XK_Return:	return QKreturn;
    case XK_Escape:	return QKescape;
    case XK_space:	return QKspace;
    case XK_Delete:	return QKdelete;
    case 0:		return Qnil;
    default:
      if (simple_p) return Qnil;
      /* !!#### not Mule-ized */
      name = XKeysymToString (keysym);
      if (!name || !name[0])
	/* This happens if there is a mismatch between the Xlib of
           XEmacs and the Xlib of the X server...

	   Let's hard-code in some knowledge of common keysyms introduced
	   in recent X11 releases.  Snarfed from X11/keysymdef.h

	   Probably we should add some stuff here for X11R6. */
	switch (keysym)
	  {
	  case 0xFF95: return KEYSYM ("kp-home");
	  case 0xFF96: return KEYSYM ("kp-left");
	  case 0xFF97: return KEYSYM ("kp-up");
	  case 0xFF98: return KEYSYM ("kp-right");
	  case 0xFF99: return KEYSYM ("kp-down");
	  case 0xFF9A: return KEYSYM ("kp-prior");
	  case 0xFF9B: return KEYSYM ("kp-next");
	  case 0xFF9C: return KEYSYM ("kp-end");
	  case 0xFF9D: return KEYSYM ("kp-begin");
	  case 0xFF9E: return KEYSYM ("kp-insert");
	  case 0xFF9F: return KEYSYM ("kp-delete");

	  case 0x1005FF10: return KEYSYM ("SunF36"); /* labeled F11 */
	  case 0x1005FF11: return KEYSYM ("SunF37"); /* labeled F12 */
	  default:
	    {
	      char buf [64];
	      sprintf (buf, "unknown-keysym-0x%X", (int) keysym);
	      return KEYSYM (buf);
	    }
	  }
      /* If it's got a one-character name, that's good enough. */
      if (!name[1])
	return make_char (name[0]);

      /* If it's in the "Keyboard" character set, downcase it.
	 The case of those keysyms is too totally random for us to
	 force anyone to remember them.
	 The case of the other character sets is significant, however.
	 */
      if ((((unsigned int) keysym) & (~0x1FF)) == ((unsigned int) 0xFE00))
	{
	  char buf [255];
	  char *s1, *s2;
	  for (s1 = name, s2 = buf; *s1; s1++, s2++) {
	    if (*s1 == '_') {
	      *s2 = '-';
	    } else {
	      *s2 = tolower (* (unsigned char *) s1);
	    }
	  }
	  *s2 = 0;
	  return KEYSYM (buf);
	}
      return KEYSYM (name);
    }
}

static Lisp_Object
x_to_emacs_keysym (XKeyPressedEvent *event, int simple_p)
     /* simple_p means don't try too hard (ASCII only) */
{
  KeySym keysym = 0;

#ifdef HAVE_XIM
  int len;
  char buffer[64];
  char *bufptr = buffer;
  int   bufsiz = sizeof (buffer);
  Status status;
#ifdef XIM_XLIB
  XIC xic = FRAME_X_XIC (x_any_window_to_frame
			 (get_device_from_display (event->display),
			  event->window));
#endif /* XIM_XLIB */
#endif /* HAVE_XIM */

  /* We use XLookupString if we're not using XIM, or are using
     XIM_XLIB but input context creation failed. */
#if ! (defined (HAVE_XIM) && defined (XIM_MOTIF))
#if defined (HAVE_XIM) && defined (XIM_XLIB)
     if (!xic)
#endif /* XIM_XLIB */
    {
      /* Apparently it's necessary to specify a dummy here (rather
         than passing in 0) to avoid crashes on German IRIX */
      char dummy[256];
      XLookupString (event, dummy, 200, &keysym, 0);
      return (IsModifierKey (keysym) || keysym == XK_Mode_switch )
	? Qnil : x_keysym_to_emacs_keysym (keysym, simple_p);
    }
#endif /* ! XIM_MOTIF */

#ifdef HAVE_XIM
 Lookup_String: /* Come-From XBufferOverflow */
#ifdef XIM_MOTIF
  len = XmImMbLookupString (XtWindowToWidget (event->display, event->window),
			    event, bufptr, bufsiz, &keysym, &status);
#else /* XIM_XLIB */
  if (xic)
    len = XmbLookupString (xic, event, bufptr, bufsiz, &keysym, &status);
#endif /* HAVE_XIM */

#ifdef DEBUG_XEMACS
  if (x_debug_events > 0)
    {
      stderr_out ("   status=");
#define print_status_when(S) if (status == S) stderr_out (#S)
      print_status_when (XLookupKeySym);
      print_status_when (XLookupBoth);
      print_status_when (XLookupChars);
      print_status_when (XLookupNone);
      print_status_when (XBufferOverflow);

      if (status == XLookupKeySym || status == XLookupBoth)
	stderr_out (" keysym=%s",  XKeysymToString (keysym));
      if (status == XLookupChars  || status == XLookupBoth)
	{
	  if (len != 1)
	    {
	      int j;
	      stderr_out (" chars=\"");
	      for (j=0; j<len; j++)
		stderr_out ("%c", bufptr[j]);
	      stderr_out ("\"");
	    }
	  else if (bufptr[0] <= 32 || bufptr[0] >= 127)
	    stderr_out (" char=0x%x", bufptr[0]);
	  else
	    stderr_out (" char=%c", bufptr[0]);
	}
      stderr_out ("\n");
    }
#endif /* DEBUG_XEMACS */

  switch (status)
    {
    case XLookupKeySym:
    case XLookupBoth:
      return (IsModifierKey (keysym) || keysym == XK_Mode_switch )
	? Qnil : x_keysym_to_emacs_keysym (keysym, simple_p);

    case XLookupChars:
      {
	/* Generate multiple emacs events */
	struct device *d = get_device_from_display (event->display);
        Emchar ch;
	Lisp_Object instream, fb_instream;
	Lstream *istr;
	struct gcpro gcpro1, gcpro2;

	fb_instream =
          make_fixed_buffer_input_stream ((unsigned char *) bufptr, len);

        /* ### Use Fget_coding_system (Vcomposed_input_coding_system) */
	instream =
	  make_decoding_input_stream (XLSTREAM (fb_instream),
				      Fget_coding_system (Qundecided));

	istr = XLSTREAM (instream);

	GCPRO2 (instream, fb_instream);
        while ((ch = Lstream_get_emchar (istr)) != EOF)
          {
            Lisp_Object emacs_event = Fmake_event (Qnil, Qnil);
	    struct Lisp_Event *ev = XEVENT (emacs_event);
            ev->channel	            = DEVICE_CONSOLE (d);
            ev->event_type	    = key_press_event;
            ev->timestamp	    = event->time;
            ev->event.key.modifiers = 0;
            ev->event.key.keysym    = make_char (ch);
            enqueue_Xt_dispatch_event (emacs_event);
          }
	Lstream_close (istr);
	UNGCPRO;
	Lstream_delete (istr);
	Lstream_delete (XLSTREAM (fb_instream));
	return Qnil;
      }
    case XLookupNone: return Qnil;
    case XBufferOverflow:
      bufptr = (char *) alloca (len+1);
      bufsiz = len+1;
      goto Lookup_String;
    }
  return Qnil; /* not reached */
#endif /* HAVE_XIM */
}

static void
set_last_server_timestamp (struct device *d, XEvent *x_event)
{
  Time t;
  switch (x_event->type)
    {
    case KeyPress:
    case KeyRelease:       t = x_event->xkey.time;              break;
    case ButtonPress:
    case ButtonRelease:    t = x_event->xbutton.time;           break;
    case EnterNotify:
    case LeaveNotify:      t = x_event->xcrossing.time;         break;
    case MotionNotify:     t = x_event->xmotion.time;           break;
    case PropertyNotify:   t = x_event->xproperty.time;         break;
    case SelectionClear:   t = x_event->xselectionclear.time;   break;
    case SelectionRequest: t = x_event->xselectionrequest.time; break;
    case SelectionNotify:  t = x_event->xselection.time;        break;
    default: return;
    }
  DEVICE_X_LAST_SERVER_TIMESTAMP (d) = t;
}

static int
x_event_to_emacs_event (XEvent *x_event, struct Lisp_Event *emacs_event)
{
  Display *display    = x_event->xany.display;
  struct device *d    = get_device_from_display (display);
  struct x_device *xd = DEVICE_X_DATA (d);

  if (DEVICE_X_BEING_DELETED (d))
     /* #### Uh, is this 0 correct? */
     return 0;

  set_last_server_timestamp (d, x_event);

  switch (x_event->type)
    {
    case KeyRelease:
      x_handle_sticky_modifiers (x_event, d);
      return 0;

    case KeyPress:
    case ButtonPress:
    case ButtonRelease:
      {
	unsigned int modifiers = 0;
	int shift_p, lock_p;
	Bool key_event_p = (x_event->type == KeyPress);
	unsigned int *state =
	  key_event_p ? &x_event->xkey.state : &x_event->xbutton.state;

	/* If this is a synthetic KeyPress or Button event, and the user
	   has expressed a disinterest in this security hole, then drop
	   it on the floor. */
	if ((key_event_p
	     ? x_event->xkey.send_event
	     : x_event->xbutton.send_event)
#ifdef EXTERNAL_WIDGET
	    /* ben: events get sent to an ExternalShell using XSendEvent.
	       This is not a perfect solution. */
	    && !FRAME_X_EXTERNAL_WINDOW_P
	    (x_any_window_to_frame (d, x_event->xany.window))
#endif
	    && !x_allow_sendevents)
	  return 0;

	DEVICE_X_MOUSE_TIMESTAMP (d) =
	  DEVICE_X_GLOBAL_MOUSE_TIMESTAMP (d) =
	  key_event_p ? x_event->xkey.time : x_event->xbutton.time;

	x_handle_sticky_modifiers (x_event, d);

	if (*state & ControlMask)    modifiers |= MOD_CONTROL;
	if (*state & xd->MetaMask)   modifiers |= MOD_META;
	if (*state & xd->SuperMask)  modifiers |= MOD_SUPER;
	if (*state & xd->HyperMask)  modifiers |= MOD_HYPER;
	if (*state & xd->AltMask)    modifiers |= MOD_ALT;

	/* Ignore the Caps_Lock key if:
	   - any other modifiers are down, so that Caps_Lock doesn't
	     turn C-x into C-X, which would suck.
	   - the event was a mouse event. */
	if (modifiers || ! key_event_p)
          *state &= (~LockMask);

	shift_p = *state & ShiftMask;
	lock_p  = *state & LockMask;

	if (shift_p || lock_p)
	  modifiers |= MOD_SHIFT;

	if (key_event_p)
	  {
	    Lisp_Object keysym;
	    XKeyEvent *ev = &x_event->xkey;
	    /* This used to compute the frame from the given X window and
	       store it here, but we really don't care about the frame. */
	    emacs_event->channel = DEVICE_CONSOLE (d);
	    keysym = x_to_emacs_keysym (&x_event->xkey, 0);

	    /* If the emacs keysym is nil, then that means that the X
	       keysym was either a Modifier or NoSymbol, which
	       probably means that we're in the midst of reading a
	       Multi_key sequence, or a "dead" key prefix, or XIM
	       input. Ignore it. */
	    if (NILP (keysym))
	      return 0;

	    /* More Caps_Lock garbage: Caps_Lock should *only* add the
	       shift modifier to two-case keys (that is, A-Z and
	       related characters). So at this point (after looking up
	       the keysym) if the keysym isn't a dual-case alphabetic,
	       and if the caps lock key was down but the shift key
	       wasn't, then turn off the shift modifier.  Gag barf */
	    /* #### type lossage: assuming equivalence of emacs and
	       X keysyms */
	    /* !!#### maybe fix for Mule */
	    if (lock_p && !shift_p &&
		! (CHAR_OR_CHAR_INTP (keysym)
		   && keysym_obeys_caps_lock_p
		   ((KeySym) XCHAR_OR_CHAR_INT (keysym), d)))
	      modifiers &= (~MOD_SHIFT);

	    /* If this key contains two distinct keysyms, that is,
	       "shift" generates a different keysym than the
	       non-shifted key, then don't apply the shift modifier
	       bit: it's implicit.  Otherwise, if there would be no
	       other way to tell the difference between the shifted
	       and unshifted version of this key, apply the shift bit.
	       Non-graphics, like Backspace and F1 get the shift bit
	       in the modifiers slot.  Neither the characters "a",
	       "A", "2", nor "@" normally have the shift bit set.
	       However, "F1" normally does. */
	    if (modifiers & MOD_SHIFT)
	      {
		int Mode_switch_p = *state & xd->ModeMask;
		KeySym bot = XLookupKeysym (ev, Mode_switch_p ? 2 : 0);
		KeySym top = XLookupKeysym (ev, Mode_switch_p ? 3 : 1);
		if (top && bot && top != bot)
		  modifiers &= ~MOD_SHIFT;
	      }
	    emacs_event->event_type	     = key_press_event;
	    emacs_event->timestamp	     = ev->time;
	    emacs_event->event.key.modifiers = modifiers;
	    emacs_event->event.key.keysym    = keysym;
	  }
	else                    /* Mouse press/release event */
	  {
	    XButtonEvent *ev = &x_event->xbutton;
	    struct frame *frame = x_window_to_frame (d, ev->window);

	    if (! frame)
	      return 0;	/* not for us */
	    XSETFRAME (emacs_event->channel, frame);

	    emacs_event->event_type = (x_event->type == ButtonPress) ?
	      button_press_event : button_release_event;

	    emacs_event->event.button.modifiers = modifiers;
	    emacs_event->timestamp		= ev->time;
	    emacs_event->event.button.button	= ev->button;
	    emacs_event->event.button.x		= ev->x;
	    emacs_event->event.button.y		= ev->y;
	    /* because we don't seem to get a FocusIn event for button clicks
	       when a widget-glyph is selected we will assume that we want the
	       focus if a button gets pressed. */
	    if (x_event->type == ButtonPress)
	      handle_focus_event_1 (frame, 1);
	  }
      }
    break;

    case MotionNotify:
      {
        XMotionEvent *ev = &x_event->xmotion;
        struct frame *frame = x_window_to_frame (d, ev->window);
        unsigned int modifiers = 0;
        XMotionEvent event2;

        if (! frame)
          return 0; /* not for us */

        /* We use MotionHintMask, so we will get only one motion event
           until the next time we call XQueryPointer or the user
           clicks the mouse.  So call XQueryPointer now (meaning that
           the event will be in sync with the server just before
           Fnext_event() returns).  If the mouse is still in motion,
           then the server will immediately generate exactly one more
           motion event, which will be on the queue waiting for us
           next time around. */
        event2 = *ev;
        if (XQueryPointer (event2.display, event2.window,
                           &event2.root,   &event2.subwindow,
                           &event2.x_root, &event2.y_root,
                           &event2.x,      &event2.y,
                           &event2.state))
          ev = &event2; /* only one structure copy */

        DEVICE_X_MOUSE_TIMESTAMP (d) = ev->time;

        XSETFRAME (emacs_event->channel, frame);
        emacs_event->event_type	    = pointer_motion_event;
        emacs_event->timestamp      = ev->time;
        emacs_event->event.motion.x = ev->x;
        emacs_event->event.motion.y = ev->y;
        if (ev->state & ShiftMask)	modifiers |= MOD_SHIFT;
        if (ev->state & ControlMask)	modifiers |= MOD_CONTROL;
        if (ev->state & xd->MetaMask)	modifiers |= MOD_META;
        if (ev->state & xd->SuperMask)	modifiers |= MOD_SUPER;
        if (ev->state & xd->HyperMask)	modifiers |= MOD_HYPER;
        if (ev->state & xd->AltMask)	modifiers |= MOD_ALT;
        /* Currently ignores Shift_Lock but probably shouldn't
           (but it definitely should ignore Caps_Lock). */
        emacs_event->event.motion.modifiers = modifiers;
      }
    break;

    case ClientMessage:
      {
        /* Patch bogus TAKE_FOCUS messages from MWM; CurrentTime is
           passed as the timestamp of the TAKE_FOCUS, which the ICCCM
           explicitly prohibits. */
        XClientMessageEvent *ev = &x_event->xclient;
#ifdef HAVE_OFFIX_DND
	if (DndIsDropMessage(x_event))
	  {
	    unsigned int state, modifiers = 0, button=0;
	    struct frame *frame = x_any_window_to_frame (d, ev->window);
	    Extbyte *data;
	    unsigned long size, dtype;
	    Lisp_Object l_type = Qnil, l_data = Qnil;
	    Lisp_Object l_dndlist = Qnil, l_item = Qnil;
	    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;

	    GCPRO4 (l_type, l_data, l_dndlist, l_item);

	    if (! frame)
	      return 0;	/* not for us */
	    XSETFRAME (emacs_event->channel, frame);

	    emacs_event->event_type = misc_user_event;
	    emacs_event->timestamp  = DEVICE_X_LAST_SERVER_TIMESTAMP (d);

	    state=DndDragButtons(x_event);

	    if (state & ShiftMask)	modifiers |= MOD_SHIFT;
	    if (state & ControlMask)	modifiers |= MOD_CONTROL;
	    if (state & xd->MetaMask)	modifiers |= MOD_META;
	    if (state & xd->SuperMask)	modifiers |= MOD_SUPER;
	    if (state & xd->HyperMask)	modifiers |= MOD_HYPER;
	    if (state & xd->AltMask)	modifiers |= MOD_ALT;

	    if (state & Button5Mask)    button = Button5;
	    if (state & Button4Mask)    button = Button4;
	    if (state & Button3Mask)    button = Button3;
	    if (state & Button2Mask)    button = Button2;
	    if (state & Button1Mask)    button = Button1;

	    emacs_event->event.misc.modifiers = modifiers;
	    emacs_event->event.misc.button    = button;

	    DndDropCoordinates(FRAME_X_TEXT_WIDGET(frame), x_event,
			       &(emacs_event->event.misc.x),
			       &(emacs_event->event.misc.y) );

	    DndGetData(x_event,&data,&size);

	    dtype=DndDataType(x_event);
	    switch (dtype)
	      {
	      case DndFiles: /* null terminated strings, end null */
		{
		  int len;
		  char *hurl = NULL;

		  while (*data)
		    {
		      len = strlen ((char*)data);
		      hurl = dnd_url_hexify_string ((char *)data, "file:");
		      l_item = make_string ((Bufbyte *)hurl, strlen (hurl));
		      l_dndlist = Fcons (l_item, l_dndlist);
		      data += len + 1;
		      xfree (hurl);
		    }
		  l_type = Qdragdrop_URL;
		}
		break;
	      case DndText:
		l_type = Qdragdrop_MIME;
		l_dndlist = list1 ( list3 ( list1 ( make_string ((Bufbyte *)"text/plain", 10) ),
					    make_string ((Bufbyte *)"8bit", 4),
					    make_ext_string ((Extbyte *)data,
							     strlen((char *)data),
							     FORMAT_CTEXT) ) );
		break;
	      case DndMIME:
		/* we have to parse this in some way to extract
		   content-type and params (in the tm way) and
		   content encoding.
		   OR: if data is string, let tm do the job
		       if data is list[2], give the first two
		       to tm...
		*/
		l_type = Qdragdrop_MIME;
		l_dndlist = list1 ( make_ext_string ((Extbyte *)data,
						     strlen((char *)data),
						     FORMAT_BINARY) );
		break;
	      case DndFile:
	      case DndDir:
	      case DndLink:
	      case DndExe:
		{
		  char *hurl = dnd_url_hexify_string ((char *) data, "file:");

		  l_dndlist = list1 ( make_string ((Bufbyte *)hurl,
						   strlen (hurl)) );
		  l_type = Qdragdrop_URL;

		  xfree (hurl);
		}
		break;
	      case DndURL:
		/* as it is a real URL it should already be escaped
		   and escaping again will break them (cause % is unsave) */
		l_dndlist = list1 ( make_ext_string ((Extbyte *)data,
						     strlen ((char *)data),
						     FORMAT_FILENAME) );
		l_type = Qdragdrop_URL;
		break;
	      default: /* Unknown, RawData and any other type */
		l_dndlist = list1 ( list3 ( list1 ( make_string ((Bufbyte *)"application/octet-stream", 24) ),
					    make_string ((Bufbyte *)"8bit", 4),
					    make_ext_string ((Extbyte *)data,
							     size,
							     FORMAT_BINARY) ) );
		l_type = Qdragdrop_MIME;
		break;
	      }

	    emacs_event->event.misc.function = Qdragdrop_drop_dispatch;
	    emacs_event->event.misc.object = Fcons (l_type, l_dndlist);

	    UNGCPRO;

	    break;
	  }
#endif /* HAVE_OFFIX_DND */
        if (ev->message_type == DEVICE_XATOM_WM_PROTOCOLS (d)
            && (Atom) (ev->data.l[0]) == DEVICE_XATOM_WM_TAKE_FOCUS (d)
            && (Atom) (ev->data.l[1]) == 0)
          {
            ev->data.l[1] = DEVICE_X_LAST_SERVER_TIMESTAMP (d);
          }
      }
    /* fall through */

    default: /* it's a magic event */
      {
        struct frame *frame;
        Window w;
	XEvent *x_event_copy = &emacs_event->event.magic.underlying_x_event;

#define FROB(event_member, window_member) \
	x_event_copy->event_member = x_event->event_member; \
	w = x_event->event_member.window_member

        switch (x_event->type)
          {
	  case SelectionRequest: FROB(xselectionrequest, owner);  break;
	  case SelectionClear:	 FROB(xselectionclear, window);	  break;
	  case SelectionNotify:	 FROB(xselection, requestor);	  break;
	  case PropertyNotify:	 FROB(xproperty, window);	  break;
	  case ClientMessage:	 FROB(xclient, window);		  break;
	  case ConfigureNotify:	 FROB(xconfigure, window);	  break;
	  case Expose:
	  case GraphicsExpose:	 FROB(xexpose, window);		  break;
	  case MapNotify:
	  case UnmapNotify:	 FROB(xmap, window);		  break;
	  case EnterNotify:
	  case LeaveNotify:	 FROB(xcrossing, window);	  break;
	  case FocusIn:
	  case FocusOut:	 FROB(xfocus, window);		  break;
	  case VisibilityNotify: FROB(xvisibility, window);	  break;
          default:
	    w = x_event->xany.window;
	    *x_event_copy = *x_event;
	    break;
          }
#undef FROB
        frame = x_any_window_to_frame (d, w);

        if (!frame)
          return 0;

        emacs_event->event_type = magic_event;
        XSETFRAME (emacs_event->channel, frame);

        break;
      }
    }
  return 1;
}



/************************************************************************/
/*                           magic-event handling                       */
/************************************************************************/

static void
handle_focus_event_1 (struct frame *f, int in_p)
{
#if XtSpecificationRelease > 5
  Widget focus_widget = XtGetKeyboardFocusWidget (FRAME_X_TEXT_WIDGET (f));
#endif
#ifdef HAVE_XIM
  XIM_focus_event (f, in_p);
#endif /* HAVE_XIM */

  /* On focus change, clear all memory of sticky modifiers
     to avoid non-intuitive behavior. */
  clear_sticky_modifiers (XDEVICE (FRAME_DEVICE (f)));

  /* We don't want to handle the focus change now, because we might
     be in an accept-process-output, sleep-for, or sit-for.  So
     we enqueue it.

     Actually, we half handle it: we handle it as far as changing the
     box cursor for redisplay, but we don't call any hooks or do any
     select-frame stuff until after the sit-for.

     Unfortunately native widgets break the model because they grab
     the keyboard focus and nothing sets it back again. I cannot find
     any reasonable way to do this elsewhere so we assert here that
     the keyboard focus is on the emacs text widget. Menus and dialogs
     do this in their selection callback, but we don't want that since
     a button having focus is legitimate. An edit field having focus
     is mandatory. Weirdly you get a FocusOut event when you click in
     a widget-glyph but you don't get a correspondng FocusIn when you
     click in the frame. Why is this?  */
  if (in_p
#if XtSpecificationRelease > 5
      && FRAME_X_TEXT_WIDGET (f) != focus_widget
#endif
      )
    {
      lw_set_keyboard_focus (FRAME_X_SHELL_WIDGET (f),
			     FRAME_X_TEXT_WIDGET (f));
    }
  /* do the generic event-stream stuff. */
  {
    Lisp_Object frm;
    Lisp_Object conser;
    struct gcpro gcpro1;

    XSETFRAME (frm, f);
    conser = Fcons (frm, Fcons (FRAME_DEVICE (f), in_p ? Qt : Qnil));
    GCPRO1 (conser);
    emacs_handle_focus_change_preliminary (conser);
    enqueue_magic_eval_event (emacs_handle_focus_change_final,
			      conser);
    UNGCPRO;
  }
}

/* This is called from the external-widget code */

void emacs_Xt_handle_focus_event (XEvent *event);
void
emacs_Xt_handle_focus_event (XEvent *event)
{
  struct device *d = get_device_from_display (event->xany.display);
  struct frame *f;

  if (DEVICE_X_BEING_DELETED (d))
    return;

  /*
   * It's curious that we're using x_any_window_to_frame() instead
   * of x_window_to_frame().  I don't know what the impact of this is.
   */
  f = x_any_window_to_frame (d, event->xfocus.window);
  if (!f)
    /* focus events are sometimes generated just before
       a frame is destroyed. */
    return;
  handle_focus_event_1 (f, event->type == FocusIn);
}

/* both MapNotify and VisibilityNotify can cause this
   JV is_visible has the same semantics as f->visible*/
static void
change_frame_visibility (struct frame *f, int is_visible)
{
  Lisp_Object frame;

  XSETFRAME (frame, f);

  if (!FRAME_VISIBLE_P (f) && is_visible)
    {
      FRAME_VISIBLE_P (f) = is_visible;
      /* This improves the double flicker when uniconifying a frame
	 some.  A lot of it is not showing a buffer which has changed
	 while the frame was iconified.  To fix it further requires
	 the good 'ol double redisplay structure. */
      MARK_FRAME_WINDOWS_STRUCTURE_CHANGED (f);
      va_run_hook_with_args (Qmap_frame_hook, 1, frame);
    }
  else if (FRAME_VISIBLE_P (f) && !is_visible)
    {
      FRAME_VISIBLE_P (f) = 0;
      va_run_hook_with_args (Qunmap_frame_hook, 1, frame);
    }
  else if (FRAME_VISIBLE_P (f) * is_visible < 0)
    {
      FRAME_VISIBLE_P(f) = - FRAME_VISIBLE_P(f);
      if (FRAME_REPAINT_P(f))
	      MARK_FRAME_WINDOWS_STRUCTURE_CHANGED (f);
      va_run_hook_with_args (Qmap_frame_hook, 1, frame);
    }
}

static void
handle_map_event (struct frame *f, XEvent *event)
{
  Lisp_Object frame;

  XSETFRAME (frame, f);
  if (event->type == MapNotify)
    {
      XWindowAttributes xwa;

      /* Bleagh!!!!!!  Apparently some window managers (e.g. MWM)
	 send synthetic MapNotify events when a window is first
	 created, EVEN IF IT'S CREATED ICONIFIED OR INVISIBLE.
	 Or something like that.  We initially tried a different
	 solution below, but that ran into a different window-
	 manager bug.

	 It seems that the only reliable way is to treat a
	 MapNotify event as a "hint" that the window might or
	 might not be visible, and check explicitly. */

      XGetWindowAttributes (event->xany.display, event->xmap.window,
			    &xwa);
      if (xwa.map_state != IsViewable)
	{
	  /* Calling Fframe_iconified_p is the only way we have to
             correctly update FRAME_ICONIFIED_P */
	  Fframe_iconified_p (frame);
	  return;
	}

      FRAME_X_TOTALLY_VISIBLE_P (f) = 1;
#if 0
      /* Bleagh again!!!!  We initially tried the following hack
	 around the MWM problem, but it turns out that TWM
	 has a race condition when you un-iconify, where it maps
	 the window and then tells the server that the window
	 is un-iconified.  Usually, XEmacs wakes up between
	 those two occurrences, and thus thinks that un-iconified
	 windows are still iconified.

	 Ah, the joys of X. */

      /* By Emacs definition, a frame that is iconified is not
	 visible.  Marking a frame as visible will automatically cause
	 frame-iconified-p to return nil, regardless of whether the
	 frame is actually iconified.  Therefore, we have to ignore
	 MapNotify events on iconified frames. (It's not obvious
	 to me why these are being sent, but it happens at startup
	 with frames that are initially iconified; perhaps they are
	 synthetic MapNotify events coming from the window manager.)
	 Note that `frame-iconified-p' queries the server
	 to determine whether the frame is currently iconified,
	 rather than consulting some internal (and likely
	 inaccurate) state flag.  Therefore, ignoring the MapNotify
	 is correct. */
      if (!FRAME_VISIBLE_P (f) && NILP (Fframe_iconified_p (frame)))
#endif /* 0 */
	change_frame_visibility (f, 1);
    }
  else
    {
      FRAME_X_TOTALLY_VISIBLE_P (f) = 0;
      change_frame_visibility (f, 0);
      /* Calling Fframe_iconified_p is the only way we have to
         correctly update FRAME_ICONIFIED_P */
      Fframe_iconified_p (frame);
    }
}

static void
handle_client_message (struct frame *f, XEvent *event)
{
  struct device *d = XDEVICE (FRAME_DEVICE (f));
  Lisp_Object frame;

  XSETFRAME (frame, f);

  if (event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d) &&
      (Atom) (event->xclient.data.l[0]) == DEVICE_XATOM_WM_DELETE_WINDOW (d))
    {
      /* WM_DELETE_WINDOW is a misc-user event, but other ClientMessages,
	 such as WM_TAKE_FOCUS, are eval events.  That's because delete-window
	 was probably executed with a mouse click, while the others could
	 have been sent as a result of mouse motion or some other implicit
	 action.  (Call this a "heuristic"...)  The reason for caring about
	 this is so that clicking on the close-box will make emacs prompt
	 using a dialog box instead of the minibuffer if there are unsaved
	 buffers.
	 */
      enqueue_misc_user_event (frame, Qeval,
			       list3 (Qdelete_frame, frame, Qt));
    }
  else if (event->xclient.message_type == DEVICE_XATOM_WM_PROTOCOLS (d) &&
	   (Atom) event->xclient.data.l[0] == DEVICE_XATOM_WM_TAKE_FOCUS (d))
    {
      handle_focus_event_1 (f, 1);
#if 0
      /* If there is a dialog box up, focus on it.

	 #### Actually, we're raising it too, which is wrong.  We should
	 #### just focus on it, but lwlib doesn't currently give us an
	 #### easy way to do that.  This should be fixed.
	 */
      unsigned long take_focus_timestamp = event->xclient.data.l[1];
      Widget widget = lw_raise_all_pop_up_widgets ();
      if (widget)
	{
	  /* kludge: raise_all returns bottommost widget, but we really
	     want the topmost.  So just raise it for now. */
	  XMapRaised (XtDisplay (widget), XtWindow (widget));
	  /* Grab the focus with the timestamp of the TAKE_FOCUS. */
	  XSetInputFocus (XtDisplay (widget), XtWindow (widget),
			  RevertToParent, take_focus_timestamp);
	}
#endif
    }
}

static void
emacs_Xt_handle_magic_event (struct Lisp_Event *emacs_event)
{
  /* This function can GC */
  XEvent *event = &emacs_event->event.magic.underlying_x_event;
  struct frame *f = XFRAME (EVENT_CHANNEL (emacs_event));

  if (!FRAME_LIVE_P (f) || DEVICE_X_BEING_DELETED (XDEVICE (FRAME_DEVICE (f))))
    return;

  switch (event->type)
    {
    case SelectionRequest:
      x_handle_selection_request (&event->xselectionrequest);
      break;

    case SelectionClear:
      x_handle_selection_clear (&event->xselectionclear);
      break;

    case SelectionNotify:
      x_handle_selection_notify (&event->xselection);
      break;

    case PropertyNotify:
      x_handle_property_notify (&event->xproperty);
      break;

    case Expose:
      if (!check_for_ignored_expose (f, event->xexpose.x, event->xexpose.y,
				     event->xexpose.width, event->xexpose.height)
	  &&
	  !find_matching_subwindow (f, event->xexpose.x, event->xexpose.y,
	  event->xexpose.width, event->xexpose.height))
	x_redraw_exposed_area (f, event->xexpose.x, event->xexpose.y,
			       event->xexpose.width, event->xexpose.height);
      break;

    case GraphicsExpose: /* This occurs when an XCopyArea's source area was
			    obscured or not available. */
      x_redraw_exposed_area (f, event->xexpose.x, event->xexpose.y,
			     event->xexpose.width, event->xexpose.height);
      break;

    case MapNotify:
    case UnmapNotify:
      handle_map_event (f, event);
      break;

    case EnterNotify:
      if (event->xcrossing.detail != NotifyInferior)
	{
	  Lisp_Object frame;

	  XSETFRAME (frame, f);
	  /* FRAME_X_MOUSE_P (f) = 1; */
	  va_run_hook_with_args (Qmouse_enter_frame_hook, 1, frame);
	}
      break;

    case LeaveNotify:
      if (event->xcrossing.detail != NotifyInferior)
	{
	  Lisp_Object frame;

	  XSETFRAME (frame, f);
	  /* FRAME_X_MOUSE_P (f) = 0; */
	  va_run_hook_with_args (Qmouse_leave_frame_hook, 1, frame);
	}
      break;

    case FocusIn:
    case FocusOut:

#ifdef EXTERNAL_WIDGET
      /* External widget lossage: Ben said:
	 YUCK.  The only way to make focus changes work properly is to
	 completely ignore all FocusIn/FocusOut events and depend only
	 on notifications from the ExternalClient widget. */
      if (FRAME_X_EXTERNAL_WINDOW_P (f))
	break;
#endif
      handle_focus_event_1 (f, event->type == FocusIn);
      break;

    case ClientMessage:
      handle_client_message (f, event);
      break;

    case VisibilityNotify: /* window visibility has changed */
      if (event->xvisibility.window == XtWindow (FRAME_X_SHELL_WIDGET (f)))
	{
	  FRAME_X_TOTALLY_VISIBLE_P (f) =
	    (event->xvisibility.state == VisibilityUnobscured);
	  /* Note that the fvwm pager only sends VisibilityNotify when
	     changing pages. Is this all we need to do ? JV */
	  /* Nope.  We must at least trigger a redisplay here.
	     Since this case seems similar to MapNotify, I've
	     factored out some code to change_frame_visibility().
	     This triggers the necessary redisplay and runs
	     (un)map-frame-hook.  - dkindred@cs.cmu.edu */
	  /* Changed it again to support the tristate visibility flag */
	  change_frame_visibility (f, (event->xvisibility.state
				       != VisibilityFullyObscured) ? 1 : -1);
	}
      break;

    case ConfigureNotify:
#ifdef HAVE_XIM
      XIM_SetGeometry (f);
#endif
      break;

    default:
      break;
    }
}


/************************************************************************/
/*				timeout events				*/
/************************************************************************/

static int timeout_id_tick;

/* Xt interval id's might not fit into an int (they're pointers, as it
   happens), so we need to provide a conversion list. */

static struct Xt_timeout
{
  int id;
  XtIntervalId interval_id;
  struct Xt_timeout *next;
} *pending_timeouts, *completed_timeouts;

static struct Xt_timeout_blocktype
{
  Blocktype_declare (struct Xt_timeout);
} *the_Xt_timeout_blocktype;

/* called by XtAppNextEvent() */
static void
Xt_timeout_callback (XtPointer closure, XtIntervalId *id)
{
  struct Xt_timeout *timeout = (struct Xt_timeout *) closure;
  struct Xt_timeout *t2 = pending_timeouts;
  /* Remove this one from the list of pending timeouts */
  if (t2 == timeout)
    pending_timeouts = pending_timeouts->next;
  else
    {
      while (t2->next && t2->next != timeout) t2 = t2->next;
      assert (t2->next);
      t2->next = t2->next->next;
    }
  /* Add this one to the list of completed timeouts */
  timeout->next = completed_timeouts;
  completed_timeouts = timeout;
}

static int
emacs_Xt_add_timeout (EMACS_TIME thyme)
{
  struct Xt_timeout *timeout = Blocktype_alloc (the_Xt_timeout_blocktype);
  EMACS_TIME current_time;
  int milliseconds;

  timeout->id = timeout_id_tick++;
  timeout->next = pending_timeouts;
  pending_timeouts = timeout;
  EMACS_GET_TIME (current_time);
  EMACS_SUB_TIME (thyme, thyme, current_time);
  milliseconds = EMACS_SECS (thyme) * 1000 +
    EMACS_USECS (thyme) / 1000;
  if (milliseconds < 1)
    milliseconds = 1;
  timeout->interval_id = XtAppAddTimeOut (Xt_app_con, milliseconds,
					  Xt_timeout_callback,
					  (XtPointer) timeout);
  return timeout->id;
}

static void
emacs_Xt_remove_timeout (int id)
{
  struct Xt_timeout *timeout, *t2;

  timeout = NULL;

  /* Find the timeout on the list of pending ones, if it's still there. */
  if (pending_timeouts)
    {
      if (id == pending_timeouts->id)
	{
	  timeout = pending_timeouts;
	  pending_timeouts = pending_timeouts->next;
	}
      else
	{
	  t2 = pending_timeouts;
	  while (t2->next && t2->next->id != id) t2 = t2->next;
	  if ( t2->next)   /*found it */
	    {
	      timeout = t2->next;
	      t2->next = t2->next->next;
	    }
	}
      /* if it was pending, we have removed it from the list */
      if (timeout)
	XtRemoveTimeOut (timeout->interval_id);
    }

  /* It could be that the Xt call back was already called but we didn't convert
     into an Emacs event yet */
  if (!timeout && completed_timeouts)
    {
      /* Code duplication! */
      if (id == completed_timeouts->id)
	{
	  timeout = completed_timeouts;
	  completed_timeouts = completed_timeouts->next;
	}
      else
	{
	  t2 = completed_timeouts;
	  while (t2->next && t2->next->id != id) t2 = t2->next;
	  if ( t2->next)   /*found it */
	    {
	      timeout = t2->next;
	      t2->next = t2->next->next;
	    }
	}
    }

  /* If we found the thing on the lists of timeouts,
     and removed it, deallocate
  */
  if (timeout)
    Blocktype_free (the_Xt_timeout_blocktype, timeout);
}

static void
Xt_timeout_to_emacs_event (struct Lisp_Event *emacs_event)
{
  struct Xt_timeout *timeout = completed_timeouts;
  assert (timeout);
  completed_timeouts = completed_timeouts->next;
  emacs_event->event_type = timeout_event;
  /* timeout events have nil as channel */
  emacs_event->timestamp  = 0; /* #### wrong!! */
  emacs_event->event.timeout.interval_id = timeout->id;
  emacs_event->event.timeout.function = Qnil;
  emacs_event->event.timeout.object = Qnil;
  Blocktype_free (the_Xt_timeout_blocktype, timeout);
}


/************************************************************************/
/*			process and tty events				*/
/************************************************************************/

struct what_is_ready_closure
{
  int fd;
  Lisp_Object what;
  XtInputId id;
};

static Lisp_Object *filedesc_with_input;
static struct what_is_ready_closure **filedesc_to_what_closure;

static void
init_what_input_once (void)
{
  int i;

  filedesc_with_input = xnew_array (Lisp_Object, MAXDESC);
  filedesc_to_what_closure =
    xnew_array (struct what_is_ready_closure *, MAXDESC);

  for (i = 0; i < MAXDESC; i++)
    {
      filedesc_to_what_closure[i] = 0;
      filedesc_with_input[i] = Qnil;
    }

  process_events_occurred = 0;
  tty_events_occurred = 0;
}

static void
mark_what_as_being_ready (struct what_is_ready_closure *closure)
{
  if (NILP (filedesc_with_input[closure->fd]))
    {
      SELECT_TYPE temp_mask;
      FD_ZERO (&temp_mask);
      FD_SET (closure->fd, &temp_mask);
      /* Check to make sure there's *really* input available.
	 Sometimes things seem to get confused and this gets called
	 for the tty fd when there's really only input available
	 on some process's fd.	(It will subsequently get called
	 for that process's fd, so returning without setting any
	 flags will take care of it.)  To see the problem, uncomment
	 the stderr_out below, turn NORMAL_QUIT_CHECK_TIMEOUT_MSECS
	 down to 25, do sh -c 'xemacs -nw -q -f shell 2>/tmp/log'
	 and press return repeatedly.  (Seen under AIX & Linux.)
	 -dkindred@cs.cmu.edu */
      if (!poll_fds_for_input (temp_mask))
	{
#if 0
	  stderr_out ("mark_what_as_being_ready: no input available (fd=%d)\n",
		      closure->fd);
#endif
	  return;
	}
      filedesc_with_input[closure->fd] = closure->what;
      if (PROCESSP (closure->what))
      /* Don't increment this if the current process is already marked
       *  as having input. */
	process_events_occurred++;
      else
	tty_events_occurred++;
    }
}

static void
Xt_what_callback (void *closure, int *source, XtInputId *id)
{
  /* If closure is 0, then we got a fake event from a signal handler.
     The only purpose of this is to make XtAppProcessEvent() stop
     blocking. */
  if (closure)
    mark_what_as_being_ready ((struct what_is_ready_closure *) closure);
  else
    {
      fake_event_occurred++;
      drain_signal_event_pipe ();
    }
}

static void
select_filedesc (int fd, Lisp_Object what)
{
  struct what_is_ready_closure *closure;

  /* If somebody is trying to select something that's already selected
     for, then something went wrong.  The generic routines ought to
     detect this and error before here. */
  assert (!filedesc_to_what_closure[fd]);

  closure = xnew (struct what_is_ready_closure);
  closure->fd = fd;
  closure->what = what;
  closure->id =
    XtAppAddInput (Xt_app_con, fd,
		   (XtPointer) (XtInputReadMask /* | XtInputExceptMask */),
		   Xt_what_callback, closure);
  filedesc_to_what_closure[fd] = closure;
}

static void
unselect_filedesc (int fd)
{
  struct what_is_ready_closure *closure = filedesc_to_what_closure[fd];

  assert (closure);
  if (!NILP (filedesc_with_input[fd]))
    {
      /* We are unselecting this process before we have drained the rest of
	 the input from it, probably from status_notify() in the command loop.
	 This can happen like so:

	  - We are waiting in XtAppNextEvent()
	  - Process generates output
	  - Process is marked as being ready
	  - Process dies, SIGCHLD gets generated before we return (!?)
	    It could happen I guess.
	  - sigchld_handler() marks process as dead
	  - Somehow we end up getting a new KeyPress event on the queue
	    at the same time (I'm really so sure how that happens but I'm
	    not sure it can't either so let's assume it can...).
	  - Key events have priority so we return that instead of the proc.
	  - Before dispatching the lisp key event we call status_notify()
	  - Which deselects the process that SIGCHLD marked as dead.

	 Thus we never remove it from _with_input and turn it into a lisp
	 event, so we need to do it here.  But this does not mean that we're
	 throwing away the last block of output - status_notify() has already
	 taken care of running the proc filter or whatever.
       */
      filedesc_with_input[fd] = Qnil;
      if (PROCESSP (closure->what))
	{
	  assert (process_events_occurred > 0);
	  process_events_occurred--;
	}
      else
	{
	  assert (tty_events_occurred > 0);
	  tty_events_occurred--;
	}
    }
  XtRemoveInput (closure->id);
  xfree (closure);
  filedesc_to_what_closure[fd] = 0;
}

static void
emacs_Xt_select_process (struct Lisp_Process *p)
{
  Lisp_Object process;
  int infd = event_stream_unixoid_select_process (p);

  XSETPROCESS (process, p);
  select_filedesc (infd, process);
}

static void
emacs_Xt_unselect_process (struct Lisp_Process *p)
{
  int infd = event_stream_unixoid_unselect_process (p);

  unselect_filedesc (infd);
}

static USID
emacs_Xt_create_stream_pair (void* inhandle, void* outhandle,
		Lisp_Object* instream, Lisp_Object* outstream, int flags)
{
  USID u = event_stream_unixoid_create_stream_pair
		(inhandle, outhandle, instream, outstream, flags);
  if (u != USID_ERROR)
    u = USID_DONTHASH;
  return u;
}

static USID
emacs_Xt_delete_stream_pair (Lisp_Object instream, Lisp_Object outstream)
{
  event_stream_unixoid_delete_stream_pair (instream, outstream);
  return USID_DONTHASH;
}

/* This is called from GC when a process object is about to be freed.
   If we've still got pointers to it in this file, we're gonna lose hard.
 */
void
debug_process_finalization (struct Lisp_Process *p)
{
#if 0 /* #### */
  int i;
  Lisp_Object instr, outstr;

  get_process_streams (p, &instr, &outstr);
  /* if it still has fds, then it hasn't been killed yet. */
  assert (NILP(instr));
  assert (NILP(outstr));
  /* Better not still be in the "with input" table; we know it's got no fds. */
  for (i = 0; i < MAXDESC; i++)
    {
      Lisp_Object process = filedesc_fds_with_input [i];
      assert (!PROCESSP (process) || XPROCESS (process) != p);
    }
#endif
}

static void
Xt_process_to_emacs_event (struct Lisp_Event *emacs_event)
{
  int i;

  assert (process_events_occurred > 0);

  for (i = 0; i < MAXDESC; i++)
    {
      Lisp_Object process = filedesc_with_input[i];
      if (PROCESSP (process))
	{
	  filedesc_with_input[i] = Qnil;
	  process_events_occurred--;
	  /* process events have nil as channel */
	  emacs_event->event_type = process_event;
	  emacs_event->timestamp  = 0; /* #### */
	  emacs_event->event.process.process = process;
	  return;
	}
    }
  abort ();
}

static void
emacs_Xt_select_console (struct console *con)
{
  Lisp_Object console;
  int infd;

  if (CONSOLE_X_P (con))
    return; /* X consoles are automatically selected for when we
	       initialize them in Xt */
  infd = event_stream_unixoid_select_console (con);
  XSETCONSOLE (console, con);
  select_filedesc (infd, console);
}

static void
emacs_Xt_unselect_console (struct console *con)
{
  Lisp_Object console;
  int infd;

  if (CONSOLE_X_P (con))
    return; /* X consoles are automatically selected for when we
	       initialize them in Xt */
  infd = event_stream_unixoid_unselect_console (con);
  XSETCONSOLE (console, con);
  unselect_filedesc (infd);
}

/* read an event from a tty, if one is available.  Returns non-zero
   if an event was available.  Note that when this function is
   called, there should always be a tty marked as ready for input.
   However, the input condition might actually be EOF, so there
   may not really be any input available. (In this case,
   read_event_from_tty_or_stream_desc() will arrange for the TTY device
   to be deleted.) */

static int
Xt_tty_to_emacs_event (struct Lisp_Event *emacs_event)
{
  int i;

  assert (tty_events_occurred > 0);
  for (i = 0; i < MAXDESC; i++)
    {
      Lisp_Object console = filedesc_with_input[i];
      if (CONSOLEP (console))
	{
	  assert (tty_events_occurred > 0);
	  tty_events_occurred--;
	  filedesc_with_input[i] = Qnil;
	  if (read_event_from_tty_or_stream_desc
	      (emacs_event, XCONSOLE (console), i))
	    return 1;
	}
    }

  return 0;
}


/************************************************************************/
/*		debugging functions to decipher an event		*/
/************************************************************************/

#ifdef DEBUG_XEMACS
#include "xintrinsicp.h"	/* only describe_event() needs this */
#include <X11/Xproto.h>		/* only describe_event() needs this */

static void
describe_event_window (Window window, Display *display)
{
  struct frame *f;
  Widget w;
  stderr_out ("   window: 0x%lx", (unsigned long) window);
  w = XtWindowToWidget (display, window);
  if (w)
    stderr_out (" %s", w->core.widget_class->core_class.class_name);
  f = x_any_window_to_frame (get_device_from_display (display), window);
  if (f)
    {
      char *buf = alloca_array (char, XSTRING_LENGTH (f->name) + 4);
      sprintf (buf, " \"%s\"", XSTRING_DATA (f->name));
      write_string_to_stdio_stream (stderr, 0, (Bufbyte *) buf, 0,
				    strlen (buf), FORMAT_TERMINAL);
    }
  stderr_out ("\n");
}

static CONST char *
XEvent_mode_to_string (int mode)
{
  switch (mode)
  {
  case NotifyNormal:	   return "Normal";
  case NotifyGrab:	   return "Grab";
  case NotifyUngrab:	   return "Ungrab";
  case NotifyWhileGrabbed: return "WhileGrabbed";
  default:		   return "???";
  }
}

static CONST char *
XEvent_detail_to_string (int detail)
{
  switch (detail)
  {
  case NotifyAncestor:		return "Ancestor";
  case NotifyInferior:		return "Inferior";
  case NotifyNonlinear:		return "Nonlinear";
  case NotifyNonlinearVirtual:	return "NonlinearVirtual";
  case NotifyPointer:		return "Pointer";
  case NotifyPointerRoot:	return "PointerRoot";
  case NotifyDetailNone:	return "DetailNone";
  default:			return "???";
  }
}

static CONST char *
XEvent_visibility_to_string (int state)
{
  switch (state)
  {
  case VisibilityFullyObscured:	    return "FullyObscured";
  case VisibilityPartiallyObscured: return "PartiallyObscured";
  case VisibilityUnobscured:        return "Unobscured";
  default:			    return "???";
  }
}

static void
describe_event (XEvent *event)
{
  char buf[100];
  struct device *d = get_device_from_display (event->xany.display);

  sprintf (buf, "%s%s", x_event_name (event->type),
	   event->xany.send_event ? " (send)" : "");
  stderr_out ("%-30s", buf);
  switch (event->type)
    {
    case FocusIn:
    case FocusOut:
      {
	XFocusChangeEvent *ev = &event->xfocus;
	describe_event_window (ev->window, ev->display);
	stderr_out ("     mode: %s\n",   XEvent_mode_to_string  (ev->mode));
	stderr_out ("     detail: %s\n", XEvent_detail_to_string(ev->detail));
	break;
      }

    case KeyPress:
      {
	XKeyEvent *ev = &event->xkey;
	unsigned int state = ev->state;

	describe_event_window (ev->window, ev->display);
	stderr_out ("   subwindow: %ld\n", ev->subwindow);
	stderr_out ("   state: ");
	/* Complete list of modifier key masks */
	if (state & ShiftMask)   stderr_out ("Shift ");
	if (state & LockMask)    stderr_out ("Lock ");
	if (state & ControlMask) stderr_out ("Control ");
	if (state & Mod1Mask)    stderr_out ("Mod1 ");
	if (state & Mod2Mask)    stderr_out ("Mod2 ");
	if (state & Mod3Mask)    stderr_out ("Mod3 ");
	if (state & Mod4Mask)    stderr_out ("Mod4 ");
	if (state & Mod5Mask)    stderr_out ("Mod5 ");

	if (! state)
	  stderr_out ("vanilla\n");
	else
	  stderr_out ("\n");
	if (x_key_is_modifier_p (ev->keycode, d))
	  stderr_out ("   Modifier key");
	stderr_out ("   keycode: 0x%x\n", ev->keycode);
      }
    break;

    case Expose:
      if (x_debug_events > 1)
	{
	  XExposeEvent *ev = &event->xexpose;
	  describe_event_window (ev->window, ev->display);
	  stderr_out ("   region: x=%d y=%d width=%d height=%d\n",
                      ev->x, ev->y, ev->width, ev->height);
	  stderr_out ("    count: %d\n", ev->count);
	}
      else
	stderr_out ("\n");
      break;

    case GraphicsExpose:
      if (x_debug_events > 1)
	{
	  XGraphicsExposeEvent *ev = &event->xgraphicsexpose;
	  describe_event_window (ev->drawable, ev->display);
	  stderr_out ("    major: %s\n",
		      (ev ->major_code == X_CopyArea  ? "CopyArea" :
		       (ev->major_code == X_CopyPlane ? "CopyPlane" : "?")));
	  stderr_out ("   region: x=%d y=%d width=%d height=%d\n",
                      ev->x, ev->y, ev->width, ev->height);
	  stderr_out ("    count: %d\n", ev->count);
	}
      else
	stderr_out ("\n");
      break;

    case EnterNotify:
    case LeaveNotify:
      if (x_debug_events > 1)
	{
	  XCrossingEvent *ev = &event->xcrossing;
	  describe_event_window (ev->window, ev->display);
#if 0
	  stderr_out(" subwindow: 0x%x\n", ev->subwindow);
	  stderr_out("      pos: %d %d\n", ev->x, ev->y);
	  stderr_out(" root pos: %d %d\n", ev->x_root, ev->y_root);
#endif
	  stderr_out("    mode: %s\n",   XEvent_mode_to_string(ev->mode));
	  stderr_out("    detail: %s\n", XEvent_detail_to_string(ev->detail));
	  stderr_out("    focus: %d\n", ev->focus);
#if 0
	  stderr_out("    state: 0x%x\n", ev->state);
#endif
	}
      else
	stderr_out("\n");
      break;

    case ConfigureNotify:
      if (x_debug_events > 1)
	{
	  XConfigureEvent *ev = &event->xconfigure;
	  describe_event_window (ev->window, ev->display);
	  stderr_out("    above: 0x%lx\n", ev->above);
	  stderr_out("     size: %d %d %d %d\n", ev->x, ev->y,
		     ev->width, ev->height);
	  stderr_out("  redirect: %d\n", ev->override_redirect);
	}
      else
	stderr_out("\n");
      break;

    case VisibilityNotify:
      if (x_debug_events > 1)
	{
	  XVisibilityEvent *ev = &event->xvisibility;
	  describe_event_window (ev->window, ev->display);
	  stderr_out("    state: %s\n", XEvent_visibility_to_string(ev->state));
	}
      else
	stderr_out ("\n");
      break;

    case ClientMessage:
      {
	XClientMessageEvent *ev = &event->xclient;
	char *name = XGetAtomName (ev->display, ev->message_type);
	stderr_out ("%s", name);
	if (!strcmp (name, "WM_PROTOCOLS")) {
	  char *protname = XGetAtomName (ev->display, ev->data.l[0]);
	  stderr_out ("(%s)", protname);
	  XFree (protname);
	}
	XFree (name);
	stderr_out ("\n");
	break;
      }

    default:
      stderr_out ("\n");
      break;
    }

  fflush (stdout);
}

#endif /* include describe_event definition */


/************************************************************************/
/*			get the next event from Xt			*/
/************************************************************************/

static Lisp_Object dispatch_event_queue, dispatch_event_queue_tail;

static void
enqueue_Xt_dispatch_event (Lisp_Object event)
{
  enqueue_event (event, &dispatch_event_queue, &dispatch_event_queue_tail);
}

static Lisp_Object
dequeue_Xt_dispatch_event (void)
{
  return dequeue_event (&dispatch_event_queue, &dispatch_event_queue_tail);
}

/* This business exists because menu events "happen" when
   menubar_selection_callback() is called from somewhere deep
   within XtAppProcessEvent in emacs_Xt_next_event().  The
   callback needs to terminate the modal loop in that function
   or else it will continue waiting until another event is
   received.

   Same business applies to scrollbar events. */

void
signal_special_Xt_user_event (Lisp_Object channel, Lisp_Object function,
			      Lisp_Object object)
{
  Lisp_Object event = Fmake_event (Qnil, Qnil);

  XEVENT (event)->event_type = misc_user_event;
  XEVENT (event)->channel = channel;
  XEVENT (event)->event.eval.function = function;
  XEVENT (event)->event.eval.object = object;

  enqueue_Xt_dispatch_event (event);
}

static void
emacs_Xt_next_event (struct Lisp_Event *emacs_event)
{
 we_didnt_get_an_event:

  while (NILP (dispatch_event_queue) &&
	 !completed_timeouts         &&
	 !fake_event_occurred        &&
	 !process_events_occurred    &&
	 !tty_events_occurred)
    {

      /* Stupid logic in XtAppProcessEvent() dictates that, if process
	 events and X events are both available, the process event gets
	 taken first.  This will cause an infinite loop if we're being
	 called from Fdiscard_input().
       */
      if (XtAppPending (Xt_app_con) & XtIMXEvent)
        XtAppProcessEvent (Xt_app_con, XtIMXEvent);
      else
	{
	  Lisp_Object devcons, concons;

	  /* We're about to block.  Xt has a bug in it (big surprise,
	     there) in that it blocks using select() and doesn't
	     flush the Xlib output buffers (XNextEvent() does this
	     automatically before blocking).  So it's necessary
	     for us to do this ourselves.  If we don't do it, then
	     display output may not be seen until the next time
	     an X event is received. (This happens esp. with
	     subprocess output that gets sent to a visible buffer.)

	     #### The above comment may not have any validity. */

	  DEVICE_LOOP_NO_BREAK (devcons, concons)
	    {
	      struct device *d;
	      d = XDEVICE (XCAR (devcons));

	      if (DEVICE_X_P (d) && DEVICE_X_DISPLAY (d))
		/* emacs may be exiting */
		XFlush (DEVICE_X_DISPLAY (d));
	    }
	  XtAppProcessEvent (Xt_app_con, XtIMAll);
	}
    }

  if (!NILP (dispatch_event_queue))
    {
      Lisp_Object event, event2;
      XSETEVENT (event2, emacs_event);
      event = dequeue_Xt_dispatch_event ();
      Fcopy_event (event, event2);
      Fdeallocate_event (event);
    }
  else if (tty_events_occurred)
    {
      if (!Xt_tty_to_emacs_event (emacs_event))
	goto we_didnt_get_an_event;
    }
  else if (completed_timeouts)
    Xt_timeout_to_emacs_event (emacs_event);
  else if (fake_event_occurred)
    {
      /* A dummy event, so that a cycle of the command loop will occur. */
      fake_event_occurred = 0;
      /* eval events have nil as channel */
      emacs_event->event_type = eval_event;
      emacs_event->event.eval.function = Qidentity;
      emacs_event->event.eval.object = Qnil;
    }
  else /* if (process_events_occurred) */
    Xt_process_to_emacs_event (emacs_event);

  /* No need to call XFilterEvent; Xt does it for us */
}

void
emacs_Xt_event_handler (Widget wid /* unused */,
			XtPointer closure /* unused */,
			XEvent *event,
			Boolean *continue_to_dispatch /* unused */)
{
  Lisp_Object emacs_event = Fmake_event (Qnil, Qnil);

#ifdef DEBUG_XEMACS
  if (x_debug_events > 0)
    {
      describe_event (event);
    }
#endif /* DEBUG_XEMACS */
  if (x_event_to_emacs_event (event, XEVENT (emacs_event)))
    enqueue_Xt_dispatch_event (emacs_event);
  else
    Fdeallocate_event (emacs_event);
}


/************************************************************************/
/*                      input pending / C-g checking                    */
/************************************************************************/

static Bool
quit_char_predicate (Display *display, XEvent *event, XPointer data)
{
  struct device *d = get_device_from_display (display);
  struct x_device *xd = DEVICE_X_DATA (d);
  char c, quit_char;
  Bool *critical = (Bool *) data;
  Lisp_Object keysym;

  if (critical)
    *critical = False;
  if ((event->type != KeyPress) ||
      (! x_any_window_to_frame (d, event->xany.window)) ||
      (event->xkey.state
       & (xd->MetaMask | xd->HyperMask | xd->SuperMask | xd->AltMask)))
    return 0;

  /* This duplicates some code that exists elsewhere, but it's relatively
     fast and doesn't cons. */
  keysym = x_to_emacs_keysym (&event->xkey, 1);
  if (NILP (keysym)) return 0;
  if (CHAR_OR_CHAR_INTP (keysym))
    c = XCHAR_OR_CHAR_INT (keysym);
  /* Highly doubtful that these are the quit character, but... */
  else if (EQ (keysym, QKbackspace))	c = '\b';
  else if (EQ (keysym, QKtab))		c = '\t';
  else if (EQ (keysym, QKlinefeed))	c = '\n';
  else if (EQ (keysym, QKreturn))	c = '\r';
  else if (EQ (keysym, QKescape))	c = 27;
  else if (EQ (keysym, QKspace))	c = ' ';
  else if (EQ (keysym, QKdelete))	c = 127;
  else return 0;

  if (event->xkey.state & xd->MetaMask)     c |= 0x80;
  if ((event->xkey.state & ControlMask) && !(c >= 'A' && c <= 'Z'))
    c &= 0x1F;			/* unshifted control characters */
  quit_char = CONSOLE_QUIT_CHAR (XCONSOLE (DEVICE_CONSOLE (d)));
  if (c == quit_char)
    return True;
  /* If we've got Control-Shift-G instead of Control-G, that means
     we have a critical_quit.  Caps_Lock is its own modifier, so it
     won't cause ^G to act differently than before. */
  if (event->xkey.state & ControlMask)  c &= 0x1F;
  if (c == quit_char)
    {
      if (critical) *critical = True;
      return True;
    }
  return False;
}

/* This scans the X input queue for a KeyPress event that matches the
   quit character, and sets Vquit_flag.  This is called from the
   QUIT macro to determine whether we should quit.

   In a SIGIO world, this won't be called unless a SIGIO has happened
   since the last time we checked.

   In a non-SIGIO world, this is called from emacs_Xt_event_pending_p
   (which is called from input_pending_p).
 */
static void
x_check_for_quit_char (Display *display)
{
  XEvent event;
  int queued;
  Bool critical_quit = False;
  XEventsQueued (display, QueuedAfterReading);
  queued = XCheckIfEvent (display, &event,
			  quit_char_predicate,
			  (char *) &critical_quit);
  if (queued)
    {
      Vquit_flag = (critical_quit ? Qcritical : Qt);
      /* don't put the event back onto the queue.  Those functions that
	 wanted to read a ^G directly have arranged to do this. */
    }
}

static void
check_for_tty_quit_char (struct device *d)
{
  SELECT_TYPE temp_mask;
  int infd = DEVICE_INFD (d);
  struct console *con = XCONSOLE (DEVICE_CONSOLE (d));
  Emchar quit_char = CONSOLE_QUIT_CHAR (con);

  FD_ZERO (&temp_mask);
  FD_SET (infd, &temp_mask);

  while (1)
    {
      Lisp_Object event;
      Emchar the_char;

      if (!poll_fds_for_input (temp_mask))
	return;

      event = Fmake_event (Qnil, Qnil);
      if (!read_event_from_tty_or_stream_desc (XEVENT (event), con, infd))
	/* EOF, or something ... */
	return;
      /* #### bogus.  quit-char should be allowed to be any sort
	 of event. */
      the_char = event_to_character (XEVENT (event), 1, 0, 0);
      if (the_char >= 0 && the_char == quit_char)
	{
	  Vquit_flag = Qt;
	  /* do not queue the C-g.  See above. */
	  return;
	}

      /* queue the read event to be read for real later. */
      enqueue_Xt_dispatch_event (event);
    }
}

static void
emacs_Xt_quit_p (void)
{
  Lisp_Object devcons, concons;
  CONSOLE_LOOP (concons)
    {
      struct console *con = XCONSOLE (XCAR (concons));
      if (!con->input_enabled)
	continue;

      CONSOLE_DEVICE_LOOP (devcons, con)
	{
	  struct device *d;
	  d = XDEVICE (XCAR (devcons));

	  if (DEVICE_X_P (d) && DEVICE_X_DISPLAY (d))
	    /* emacs may be exiting */
	    x_check_for_quit_char (DEVICE_X_DISPLAY (d));
	  else if (DEVICE_TTY_P (d))
	    check_for_tty_quit_char (d);
	}
    }
}

static void
drain_X_queue (void)
{
  while (XtAppPending (Xt_app_con) & XtIMXEvent)
    XtAppProcessEvent (Xt_app_con, XtIMXEvent);
}

static int
emacs_Xt_event_pending_p (int user_p)
{
  Lisp_Object event;
  int tick_count_val;

  /* If `user_p' is false, then this function returns whether there are any
     X, timeout, or fd events pending (that is, whether emacs_Xt_next_event()
     would return immediately without blocking).

     if `user_p' is true, then this function returns whether there are any
     *user generated* events available (that is, whether there are keyboard
     or mouse-click events ready to be read).  This also implies that
     emacs_Xt_next_event() would not block.

     In a non-SIGIO world, this also checks whether the user has typed ^G,
     since this is a convenient place to do so.  We don't need to do this
     in a SIGIO world, since input causes an interrupt.
   */

#if 0
  /* I don't think there's any point to this and it will nullify
     the speed gains achieved by the sigio_happened checking below.
     Its only advantage is that it may possibly make C-g response
     a bit faster.  The C-g will be noticed within 0.25 second, anyway,
     even without this. */
#ifndef SIGIO
  /* First check for C-g if necessary */
  emacs_Xt_quit_p ();
#endif
#endif

  /* This function used to simply check whether there were any X
     events (or if user_p was 1, it iterated over all the pending
     X events using XCheckIfEvent(), looking for keystrokes and
     button events).  That worked in the old cheesoid event loop,
     which didn't go through XtAppDispatchEvent(), but it doesn't
     work any more -- X events may not result in anything.  For
     example, a button press in a blank part of the menubar appears
     as an X event but will not result in any Emacs events (a
     button press that activates the menubar results in an Emacs
     event through the stop_next_event mechanism).

     The only accurate way of determining whether these X events
     translate into Emacs events is to go ahead and dispatch them
     until there's something on the dispatch queue. */

  /* See if there are any user events already on the queue. */
  EVENT_CHAIN_LOOP (event, dispatch_event_queue)
    if (!user_p || command_event_p (event))
      return 1;

  /* See if there's any TTY input available.
   */
  if (poll_fds_for_input (tty_only_mask))
    return 1;

  if (!user_p)
    {
      /* If not user_p and there are any timer or file-desc events
	 pending, we know there will be an event so we're through. */
      XtInputMask pending_value;

      /* Note that formerly we just checked the value of XtAppPending()
	 to determine if there was file-desc input.  This doesn't
	 work any more with the signal_event_pipe; XtAppPending()
	 will says "yes" in this case but there isn't really any
	 input.  Another way of fixing this problem is for the
	 signal_event_pipe to generate actual input in the form
	 of an identity eval event or something. (#### maybe this
	 actually happens?) */

      if (poll_fds_for_input (process_only_mask))
	return 1;

      pending_value = XtAppPending (Xt_app_con);

      if (pending_value & XtIMTimer)
	return 1;
    }

  /* XtAppPending() can be super-slow, esp. over a network connection.
     Quantify results have indicated that in some cases the
     call to detect_input_pending() completely dominates the
     running time of redisplay().  Fortunately, in a SIGIO world
     we can more quickly determine whether there are any X events:
     if an event has happened since the last time we checked, then
     a SIGIO will have happened.  On a machine with broken SIGIO,
     we'll still be in an OK state -- the sigio_happened flag
     will get set at least once a second, so we'll be no more than
     one second behind reality. (In general it's OK if we
     erroneously report no input pending when input is actually
     pending() -- preemption is just a bit less efficient, that's
     all.  It's bad bad bad if you err the other way -- you've
     promised that `next-event' won't block but it actually will,
     and some action might get delayed until the next time you
     hit a key.)
     */

  /* quit_check_signal_tick_count is volatile so try to avoid race conditions
     by using a temporary variable */
  tick_count_val = quit_check_signal_tick_count;
  if (last_quit_check_signal_tick_count != tick_count_val)
    {
      last_quit_check_signal_tick_count = tick_count_val;

      /* We need to drain the entire queue now -- if we only
         drain part of it, we may later on end up with events
         actually pending but detect_input_pending() returning
         false because there wasn't another SIGIO. */
      drain_X_queue ();

      EVENT_CHAIN_LOOP (event, dispatch_event_queue)
        if (!user_p || command_event_p (event))
          return 1;
    }

  return 0;
}


/************************************************************************/
/*            replacement for standard string-to-pixel converter        */
/************************************************************************/

/* This was constructed by ripping off the standard string-to-pixel
   converter from Converters.c in the Xt source code and modifying
   appropriately. */

#if 0

/* This is exported by the Xt library (at least by mine).  If this
   isn't the case somewhere, rename this appropriately and remove
   the '#if 0'.  Note, however, that I got "unknown structure"
   errors when I tried this. */
XtConvertArgRec Const colorConvertArgs[] = {
  {XtWidgetBaseOffset, (XtPointer)XtOffsetOf(WidgetRec, core.screen),
   sizeof(Screen *)},
  {XtWidgetBaseOffset, (XtPointer)XtOffsetOf(WidgetRec, core.colormap),
   sizeof(Colormap)}
};

#endif

#define done(type, value)               \
  if (toVal->addr != NULL) {             \
    if (toVal->size < sizeof(type)) {    \
      toVal->size = sizeof(type);        \
      return False;                      \
    }                                    \
    *(type*)(toVal->addr) = (value);     \
  } else {                               \
    static type static_val;              \
    static_val = (value);                \
    toVal->addr = (XPointer)&static_val; \
  }                                      \
  toVal->size = sizeof(type);            \
  return True /* Caller supplies `;' */

/* JH: We use this because I think there's a possibility this
   is called before the device is properly set up, in which case
   I don't want to abort. */
extern struct device *get_device_from_display_1 (Display *dpy);

static
Boolean EmacsXtCvtStringToPixel (
 Display     *dpy,
 XrmValuePtr  args,
 Cardinal    *num_args,
 XrmValuePtr  fromVal,
 XrmValuePtr  toVal,
 XtPointer   *closure_ret)
{
  String       str = (String)fromVal->addr;
  XColor       screenColor;
  XColor       exactColor;
  Screen       *screen;
  Colormap     colormap;
  Visual       *visual;
  struct device *d;
  Status       status;
  String       params[1];
  Cardinal     num_params  = 1;
  XtAppContext the_app_con = XtDisplayToApplicationContext (dpy);

  if (*num_args != 2) {
    XtAppWarningMsg(the_app_con, "wrongParameters", "cvtStringToPixel",
                    "XtToolkitError",
                    "String to pixel conversion needs screen and colormap arguments",
                    (String *)NULL, (Cardinal *)NULL);
    return False;
  }

  screen   = *((Screen **)  args[0].addr);
  colormap = *((Colormap *) args[1].addr);

  /* The original uses the private function CompareISOLatin1().
     Use XmuCompareISOLatin1() if you want, but I don't think it
     makes any difference here. */
  if (strcmp(str, XtDefaultBackground) == 0) {
    *closure_ret = False;
    /* This refers to the display's "*reverseVideo" resource.
       These display resources aren't documented anywhere that
       I can find, so I'm going to ignore this. */
    /* if (pd->rv) done(Pixel, BlackPixelOfScreen(screen)) else */
    done(Pixel, WhitePixelOfScreen(screen));
  }
  if (strcmp(str, XtDefaultForeground) == 0) {
    *closure_ret = False;
    /* if (pd->rv) done(Pixel, WhitePixelOfScreen(screen)) else */
    done(Pixel, BlackPixelOfScreen(screen));
  }

  /* Originally called XAllocNamedColor() here. */
  if ((d = get_device_from_display_1(dpy))) {
    visual = DEVICE_X_VISUAL(d);
    if (colormap != DEVICE_X_COLORMAP(d)) {
      XtAppWarningMsg(the_app_con, "wierdColormap", "cvtStringToPixel",
		      "XtToolkitWarning",
		      "The colormap passed to cvtStringToPixel doesn't match the one registerd to the device.\n",
		      NULL, 0);
      status = XAllocNamedColor(dpy, colormap, (char*)str, &screenColor, &exactColor);
    } else {
      status = XParseColor (dpy, colormap, (char*)str, &screenColor);
      if (status) {
	status = allocate_nearest_color (dpy, colormap, visual, &screenColor);
      }
    }
  } else {
    /* We haven't set up this device totally yet, so just punt */
    status = XAllocNamedColor(dpy, colormap, (char*)str, &screenColor, &exactColor);
  }
  if (status == 0) {
    params[0] = str;
    /* Server returns a specific error code but Xlib discards it.  Ugh */
    if (XLookupColor(DisplayOfScreen(screen), colormap, (char*) str,
                     &exactColor, &screenColor)) {
      XtAppWarningMsg(the_app_con, "noColormap", "cvtStringToPixel",
                      "XtToolkitError",
                      "Cannot allocate colormap entry for \"%s\"",
                      params, &num_params);

    } else {
      XtAppWarningMsg(the_app_con, "badValue", "cvtStringToPixel",
                      "XtToolkitError",
                      "Color name \"%s\" is not defined", params, &num_params);
    }

    *closure_ret = False;
    return False;
  } else {
    *closure_ret = (char*)True;
    done(Pixel, screenColor.pixel);
  }
}

/* ARGSUSED */
static void EmacsFreePixel (
  XtAppContext app,
  XrmValuePtr  toVal,
  XtPointer    closure,
  XrmValuePtr  args,
  Cardinal    *num_args)
{
  if (*num_args != 2) {
    XtAppWarningMsg(app, "wrongParameters","freePixel","XtToolkitError",
                    "Freeing a pixel requires screen and colormap arguments",
                    (String *)NULL, (Cardinal *)NULL);
    return;
  }

  if (closure) {
    Screen   *screen  = *((Screen **)  args[0].addr);
    Colormap colormap = *((Colormap *) args[1].addr);
    XFreeColors(DisplayOfScreen(screen), colormap,
                (unsigned long*)toVal->addr, 1, (unsigned long)0);
  }
}


/************************************************************************/
/*                            initialization                            */
/************************************************************************/

void
syms_of_event_Xt (void)
{
  defsymbol (&Qkey_mapping, "key-mapping");
  defsymbol (&Qsans_modifiers, "sans-modifiers");
}

void
reinit_vars_of_event_Xt (void)
{
  Xt_event_stream = xnew (struct event_stream);
  Xt_event_stream->event_pending_p 	 = emacs_Xt_event_pending_p;
  Xt_event_stream->next_event_cb	 = emacs_Xt_next_event;
  Xt_event_stream->handle_magic_event_cb = emacs_Xt_handle_magic_event;
  Xt_event_stream->add_timeout_cb 	 = emacs_Xt_add_timeout;
  Xt_event_stream->remove_timeout_cb 	 = emacs_Xt_remove_timeout;
  Xt_event_stream->select_console_cb 	 = emacs_Xt_select_console;
  Xt_event_stream->unselect_console_cb 	 = emacs_Xt_unselect_console;
  Xt_event_stream->select_process_cb 	 = emacs_Xt_select_process;
  Xt_event_stream->unselect_process_cb 	 = emacs_Xt_unselect_process;
  Xt_event_stream->quit_p_cb		 = emacs_Xt_quit_p;
  Xt_event_stream->create_stream_pair_cb = emacs_Xt_create_stream_pair;
  Xt_event_stream->delete_stream_pair_cb = emacs_Xt_delete_stream_pair;

  the_Xt_timeout_blocktype = Blocktype_new (struct Xt_timeout_blocktype);

  last_quit_check_signal_tick_count = 0;

  /* this function only makes safe calls */
  init_what_input_once ();
}

void
vars_of_event_Xt (void)
{
  reinit_vars_of_event_Xt ();

  dispatch_event_queue = Qnil;
  staticpro (&dispatch_event_queue);
  dispatch_event_queue_tail = Qnil;
  pdump_wire (&dispatch_event_queue_tail);

  DEFVAR_BOOL ("modifier-keys-are-sticky", &modifier_keys_are_sticky /*
*Non-nil makes modifier keys sticky.
This means that you can release the modifier key before pressing down
the key that you wish to be modified.  Although this is non-standard
behavior, it is recommended because it reduces the strain on your hand,
thus reducing the incidence of the dreaded Emacs-pinky syndrome.
*/ );
  modifier_keys_are_sticky = 0;

  DEFVAR_BOOL ("x-allow-sendevents", &x_allow_sendevents /*
*Non-nil means to allow synthetic events.  Nil means they are ignored.
Beware: allowing emacs to process SendEvents opens a big security hole.
*/ );
  x_allow_sendevents = 0;

#ifdef DEBUG_XEMACS
  DEFVAR_INT ("x-debug-events", &x_debug_events /*
If non-zero, display debug information about X events that XEmacs sees.
Information is displayed on stderr.  Currently defined values are:

1 == non-verbose output
2 == verbose output
*/ );
  x_debug_events = 0;
#endif
}

/* This mess is a hack that patches the shell widget to treat visual inheritance
   the same as colormap and depth inheritance */

static XtInitProc orig_shell_init_proc;

static void ShellVisualPatch(Widget wanted, Widget new,
			     ArgList args, Cardinal *num_args)
{
  Widget p;
  ShellWidget w = (ShellWidget) new;

  /* first, call the original setup */
  (*orig_shell_init_proc)(wanted, new, args, num_args);

  /* if the visual isn't explicitly set, grab it from the nearest shell ancestor */
  if (w->shell.visual == CopyFromParent) {
    p = XtParent(w);
    while (p && !XtIsShell(p)) p = XtParent(p);
    if (p) w->shell.visual = ((ShellWidget)p)->shell.visual;
  }
}

void
init_event_Xt_late (void) /* called when already initialized */
{
  timeout_id_tick = 1;
  pending_timeouts = 0;
  completed_timeouts = 0;

  event_stream = Xt_event_stream;

#if defined(HAVE_XIM) || defined(USE_XFONTSET)
  Initialize_Locale();
#endif /* HAVE_XIM || USE_XFONTSET */

  XtToolkitInitialize ();
  Xt_app_con = XtCreateApplicationContext ();
  XtAppSetFallbackResources (Xt_app_con, (String *) x_fallback_resources);

  /* In xselect.c */
  x_selection_timeout = (XtAppGetSelectionTimeout (Xt_app_con) / 1000);
  XSetErrorHandler (x_error_handler);
  XSetIOErrorHandler (x_IO_error_handler);

#ifndef WINDOWSNT
  XtAppAddInput (Xt_app_con, signal_event_pipe[0],
		 (XtPointer) (XtInputReadMask /* | XtInputExceptMask */),
		 Xt_what_callback, 0);
#endif

  XtAppSetTypeConverter (Xt_app_con, XtRString, XtRPixel,
		         EmacsXtCvtStringToPixel,
			 (XtConvertArgList) colorConvertArgs,
			 2, XtCacheByDisplay, EmacsFreePixel);

#ifdef XIM_XLIB
  XtAppSetTypeConverter (Xt_app_con, XtRString, XtRXimStyles,
		         EmacsXtCvtStringToXIMStyles,
			 NULL, 0,
			 XtCacheByDisplay, EmacsFreeXIMStyles);
#endif /* XIM_XLIB */

  /* insert the visual inheritance patch/hack described above */
  orig_shell_init_proc = shellClassRec.core_class.initialize;
  shellClassRec.core_class.initialize = ShellVisualPatch;

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