xemacs-beta / src / frame-x.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
/* Functions for the X window system.
   Copyright (C) 1989, 1992-5, 1997 Free Software Foundation, Inc.
   Copyright (C) 1995, 1996, 2001, 2002, 2004, 2010 Ben Wing.
   Copyright (C) 2010 Didier Verna

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 synched with FSF. */

/* This file has been Mule-ized, Ben Wing, 10-14-04. */

/* Substantially rewritten for XEmacs.  */

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

#include "buffer.h"
#include "device-impl.h"
#include "events.h"
#include "extents.h"
#include "faces.h"
#include "frame-impl.h"
#include "gutter.h"
#include "window.h"

#include "console-x-impl.h"
#include "glyphs-x.h"
#include "fontcolor-x-impl.h"
#include "scrollbar-x.h"

#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/Shell.h>
#include <X11/ShellP.h>
#include <X11/Xmu/Editres.h>
#include "EmacsManager.h"
#include "EmacsFrameP.h"
#include "EmacsShell.h"
#ifdef EXTERNAL_WIDGET
#include "ExternalShell.h"
#endif

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

/* Default properties to use when creating frames.  */
Lisp_Object Vdefault_x_frame_plist;

Lisp_Object Qoverride_redirect;
Lisp_Object Qx_resource_name;

static const struct memory_description x_frame_data_description_1 [] = {
  { XD_LISP_OBJECT, offsetof (struct x_frame, last_menubar_buffer) },
  { XD_LISP_OBJECT, offsetof (struct x_frame, icon_pixmap) },
  { XD_LISP_OBJECT, offsetof (struct x_frame, icon_pixmap_mask) },
  { XD_END }
};

#ifdef NEW_GC
DEFINE_DUMPABLE_INTERNAL_LISP_OBJECT ("x-frame", x_frame,
				      0, x_frame_data_description_1,
				      Lisp_X_Frame);
#else /* not NEW_GC */
extern const struct sized_memory_description x_frame_data_description;

const struct sized_memory_description x_frame_data_description = {
  sizeof (struct x_frame), x_frame_data_description_1
};
#endif /* not NEW_GC */

EXFUN (Fx_window_id, 1);


/************************************************************************/
/*                          helper functions                            */
/************************************************************************/

/* Return the Emacs frame-object corresponding to an X window */
struct frame *
x_window_to_frame (struct device *d, Window wdesc)
{
  Lisp_Object tail, frame;
  struct frame *f;

  /* This function was previously written to accept only a window argument
     (and to loop over all devices looking for a matching window), but
     that is incorrect because window ID's are not unique across displays. */

  for (tail = DEVICE_FRAME_LIST (d); CONSP (tail); tail = XCDR (tail))
    {
      frame = XCAR (tail);
      if (!FRAMEP (frame))
	continue;
      f = XFRAME (frame);
      if (FRAME_X_P (f) && XtWindow (FRAME_X_TEXT_WIDGET (f)) == wdesc)
	return f;
    }
  return 0;
}

/* Like x_window_to_frame but also compares the window with the widget's
   windows */
struct frame *
x_any_window_to_frame (struct device *d, Window wdesc)
{
  Widget w;
  assert (DEVICE_X_P (d));

  w = XtWindowToWidget (DEVICE_X_DISPLAY (d), wdesc);

  if (!w)
    return 0;

  /* We used to map over all frames here and then map over all widgets
     belonging to that frame. However it turns out that this was very fragile
     as it requires our display structures to be in sync _and_ that the
     loop is told about every new widget somebody adds. Therefore we
     now let Xt find it for us (which does a bottom-up search which
     could even be faster) */
  return  x_any_widget_or_parent_to_frame (d, w);
}

static struct frame *
x_find_frame_for_window (struct device *d, Window wdesc)
{
  Lisp_Object tail, frame;
  struct frame *f;
  /* This function was previously written to accept only a window argument
     (and to loop over all devices looking for a matching window), but
     that is incorrect because window ID's are not unique across displays. */

  for (tail = DEVICE_FRAME_LIST (d); CONSP (tail); tail = XCDR (tail))
    {
      frame = XCAR (tail);
      f = XFRAME (frame);
      /* This frame matches if the window is any of its widgets. */
      if (wdesc == XtWindow (FRAME_X_SHELL_WIDGET (f)) ||
	  wdesc == XtWindow (FRAME_X_CONTAINER_WIDGET (f)) ||
	  wdesc == XtWindow (FRAME_X_TEXT_WIDGET (f)))
	return f;

      /* Match if the window is one of the widgets at the top of the frame
	 (menubar, Energize psheets). */

      /* Note: Jamie once said

	 "Do *not* match if the window is this frame's psheet."

	 But this is wrong and will screw up some functions that expect
	 x_any_window_to_frame() to work as advertised.  I think the reason
	 for this statement is that, in the old (broken) event loop, where
	 not all events went through XtDispatchEvent(), psheet events
	 would incorrectly get sucked away by Emacs if this function matched
	 on psheet widgets. */

      /* Note: that this called only from
         x_any_widget_or_parent_to_frame it is unnecessary to iterate
         over the top level widgets. */

      /* Note:  we use to special case scrollbars but this turns out to be a bad idea
         because
         1. We sometimes get events for _unmapped_ scrollbars and our
         callers don't want us to fail.
         2. Starting with the 21.2 widget stuff there are now loads of
         widgets to check and it is easy to forget adding them in a loop here.
         See x_any_window_to_frame
         3. We pick up all widgets now anyway. */
    }

  return 0;
}

struct frame *
x_any_widget_or_parent_to_frame (struct device *d, Widget widget)
{
  while (widget)
    {
      struct frame *f = x_find_frame_for_window (d, XtWindow (widget));
      if (f)
	return f;
      widget = XtParent (widget);
    }

  return 0;
}

struct frame *
decode_x_frame (Lisp_Object frame)
{
  if (NILP (frame))
    frame = wrap_frame (selected_frame ());
  CHECK_LIVE_FRAME (frame);
  /* this will also catch dead frames, but putting in the above check
     results in a more useful error */
  CHECK_X_FRAME (frame);
  return XFRAME (frame);
}


/************************************************************************/
/*			window-manager interactions			*/
/************************************************************************/

#if 0
/* Not currently used. */

void
x_wm_mark_shell_size_user_specified (Widget wmshell)
{
  assert (XtIsWMShell (wmshell));
  EmacsShellSetSizeUserSpecified (wmshell);
}

void
x_wm_mark_shell_position_user_specified (Widget wmshell)
{
  assert (XtIsWMShell (wmshell));
  EmacsShellSetPositionUserSpecified (wmshell);
}

#endif

void
x_wm_set_shell_iconic_p (Widget shell, int iconic_p)
{
  assert (XtIsWMShell (shell));

  /* Because of questionable logic in Shell.c, this sequence can't work:

       w = XtCreatePopupShell (...);
       Xt_SET_VALUE (w, XtNiconic, True);
       XtRealizeWidget (w);

     The iconic resource is only consulted at initialization time (when
     XtCreatePopupShell is called) instead of at realization time (just
     before the window gets created, which would be more sensible) or
     at management-time (just before the window gets mapped, which would
     be most sensible of all).

     The bug is that Shell's SetValues method doesn't do anything to
     w->wm.wm_hints.initial_state until after the widget has been realized.
     Calls to XtSetValues are ignored in the window between creation and
     realization.  This is true of MIT X11R5 patch level 25, at least.
     (Apparently some other versions of Xt don't have this bug?)
   */
  Xt_SET_VALUE (shell, XtNiconic, iconic_p);
  EmacsShellSmashIconicHint (shell, iconic_p);
}

void
x_wm_set_cell_size (Widget wmshell, int cw, int ch)
{
  Arg al [2];

  assert (XtIsWMShell (wmshell));
  assert (cw > 0 && ch > 0);

  Xt_SET_ARG (al[0], XtNwidthInc,  cw);
  Xt_SET_ARG (al[1], XtNheightInc, ch);
  XtSetValues (wmshell, al, 2);
}

void
x_wm_set_variable_size (Widget wmshell, int width, int height)
{
  Arg al [2];

  assert (XtIsWMShell (wmshell));
#ifdef DEBUG_GEOMETRY_MANAGEMENT
  /* See comment in EmacsShell.c */
  printf ("x_wm_set_variable_size: %d %d\n", width, height);
  fflush (stdout);
#endif

  Xt_SET_ARG (al[0], XtNwidthCells,  width);
  Xt_SET_ARG (al[1], XtNheightCells, height);
  XtSetValues (wmshell, al, 2);
}

/* If the WM_PROTOCOLS property does not already contain WM_TAKE_FOCUS
   and WM_DELETE_WINDOW, then add them.  (They may already be present
   because of the toolkit (Motif adds them, for example, but Xt doesn't).
 */
static void
x_wm_hack_wm_protocols (Widget widget)
{
  Display *dpy = XtDisplay (widget);
  struct device *d = get_device_from_display (dpy);
  Window w = XtWindow (widget);
  int need_delete = 1;
  int need_focus = 1;

  assert (XtIsWMShell (widget));

  {
    Atom type;
    int format = 0;
    unsigned long nitems = 0;
    unsigned long bytes_after;
    Rawbyte *prop_return = 0; /* semantically a void* */

    if (Success == XGetWindowProperty (dpy, w, DEVICE_XATOM_WM_PROTOCOLS (d),
				       0, 100, False, XA_ATOM,
				       &type, &format, &nitems, &bytes_after,
				       &prop_return)
	&& format == 32 && type == XA_ATOM)
      while (nitems > 0)
	{
	  Atom *atoms = (Atom *) prop_return;
	  nitems--;
	  if (atoms[nitems] == DEVICE_XATOM_WM_DELETE_WINDOW (d))
	    need_delete = 0;
	  else if (atoms[nitems] == DEVICE_XATOM_WM_TAKE_FOCUS (d))
	    need_focus = 0;
	}
    if (prop_return) XFree ((CRawbyte *) prop_return);
  }
  {
    Atom props [10];
    int count = 0;
    if (need_delete) props[count++] = DEVICE_XATOM_WM_DELETE_WINDOW (d);
    if (need_focus)  props[count++] = DEVICE_XATOM_WM_TAKE_FOCUS (d);
    if (count)
      XChangeProperty (dpy, w, DEVICE_XATOM_WM_PROTOCOLS (d), XA_ATOM, 32,
		       PropModeAppend, (Rawbyte *) props, count);
  }
}

static void
x_wm_store_class_hints (Widget shell, Extbyte *frame_name)
{
  Display *dpy = XtDisplay (shell);
  Extbyte *app_name, *app_class;
  XClassHint classhint;

  assert (XtIsWMShell (shell));

  XtGetApplicationNameAndClass (dpy, &app_name, &app_class);
  classhint.res_name = frame_name;
  classhint.res_class = app_class;
  XSetClassHint (dpy, XtWindow (shell), &classhint);
}

#ifndef HAVE_WMCOMMAND

static void
x_wm_maybe_store_wm_command (struct frame *f)
{
  Widget w = FRAME_X_SHELL_WIDGET (f);
  struct device *d = XDEVICE (FRAME_DEVICE (f));

  assert (XtIsWMShell (w));

  if (NILP (DEVICE_X_WM_COMMAND_FRAME (d)))
    {
      int argc;
      Wexttext **argv;
      make_argc_argv (Vcommand_line_args, &argc, &argv);
      XSetCommand (XtDisplay (w), XtWindow (w), argv, argc);
      free_argc_argv (argv);
      DEVICE_X_WM_COMMAND_FRAME (d) = wrap_frame (f);
    }
}

/* If we're deleting the frame on which the WM_COMMAND property has been
   set, then move that property to another frame so that there is exactly
   one frame that has that property set.
 */
static void
x_wm_maybe_move_wm_command (struct frame *f)
{
  struct device *d = XDEVICE (FRAME_DEVICE (f));

  /* There may not be a frame in DEVICE_X_WM_COMMAND_FRAME()
     if we C-c'ed at startup at the right time. */
  if (FRAMEP (DEVICE_X_WM_COMMAND_FRAME (d))
      && f == XFRAME (DEVICE_X_WM_COMMAND_FRAME (d)))
    {
      Lisp_Object rest = DEVICE_FRAME_LIST (d);
      DEVICE_X_WM_COMMAND_FRAME (d) = Qnil;
      /* find some random other X frame that is not this one, or give up */
      /* skip non-top-level (ExternalClient) frames */
      while (!NILP (rest) &&
	     (f == XFRAME (XCAR (rest)) ||
	      !FRAME_X_TOP_LEVEL_FRAME_P (XFRAME (XCAR (rest)))))
	rest = XCDR (rest);
      if (NILP (rest))
	return;
      f = XFRAME (XCAR (rest));

      x_wm_maybe_store_wm_command (f);

    }
}

#endif /* !HAVE_WMCOMMAND */

int
x_frame_window_state (struct frame *f)
{
  Atom actual_type;
  int actual_format;
  unsigned long nitems, bytesafter;
  Rawbyte *datap = 0;
  Widget widget;
  int result = -1;
  struct device *d = XDEVICE (FRAME_DEVICE (f));

  widget = FRAME_X_SHELL_WIDGET (f);
  if (Success == XGetWindowProperty (XtDisplay (widget), XtWindow (widget),
				     DEVICE_XATOM_WM_STATE (d), 0, 2, False,
				     DEVICE_XATOM_WM_STATE (d), &actual_type,
				     &actual_format, &nitems, &bytesafter,
				     &datap)
      && datap)
    {
      unsigned long *ul_result_ptr = (unsigned long *) datap;
      if (nitems <= 2)	/* "suggested" by ICCCM version 1 */
	result = (int) ul_result_ptr[0];
      XFree ((CRawbyte *) datap);
    }

  return result;
}

static int
x_frame_iconified_p (struct frame *f)
{
  return x_frame_window_state (f) == IconicState;
}


/************************************************************************/
/*                          frame properties                            */
/************************************************************************/

/* Connect the frame-property names (symbols) to the corresponding
   X Resource Manager names.  The name of a property, as a Lisp symbol,
   has an `x-resource-name' property which is a Lisp string. */

static void
init_x_prop_symbols (void)
{
#define def(sym, rsrc) \
   Fput (sym, Qx_resource_name, build_ascstring (rsrc))
#define defi(sym,rsrc) \
   def (sym, rsrc); Fput (sym, Qintegerp, Qt)

#if 0 /* this interferes with things. #### fix this right */
  def (Qminibuffer, XtNminibuffer);
  def (Qunsplittable, XtNunsplittable);
#endif
  defi(Qinternal_border_width, XtNinternalBorderWidth);
  def (Qscrollbar_placement, XtNscrollBarPlacement);
  defi(Qinter_line_space, XtNinterline);
  /* font, foreground */
  def (Qiconic, XtNiconic);
  def (Qbar_cursor, XtNbarCursor);
  def (Qvisual_bell, XtNvisualBell);
  defi(Qbell_volume, XtNbellVolume);
  def (Qpointer_background, XtNpointerBackground);
  def (Qpointer_color, XtNpointerColor);
  def (Qtext_pointer, XtNtextPointer);
  def (Qspace_pointer, XtNspacePointer);
  def (Qmodeline_pointer, XtNmodeLinePointer);
  def (Qgc_pointer, XtNgcPointer);
  /* geometry, initial_geometry */
  def (Qinitially_unmapped, XtNinitiallyUnmapped);
  /* preferred_width, preferred_height */
  def (Quse_backing_store, XtNuseBackingStore);

  /* inherited: */

  def (Qborder_color, XtNborderColor);
  defi(Qborder_width, XtNborderWidth);
  defi(Qwidth, XtNwidth);
  defi(Qheight, XtNheight);
  defi(Qleft, XtNx);
  defi(Qtop, XtNy);

#undef def
#undef defi
}

static Lisp_Object
color_to_string (Widget w, unsigned long pixel)
{
  Ibyte buf[255];

  XColor color;
  color.pixel = pixel;
  XQueryColor (XtDisplay (w), w->core.colormap, &color);
  qxesprintf (buf, "#%04x%04x%04x", color.red, color.green, color.blue);
  return build_istring (buf);
}

static void
x_get_top_level_position (Display *d, Window w, Position *x, Position *y)
{
  Window root, parent = w, *children;
  unsigned int nchildren;
  XWindowAttributes xwa;

  do
    {
      w = parent;
      if (!XQueryTree (d, w, &root, &parent, &children, &nchildren))
	{
	  *x = 0;
	  *y = 0;
	  return;
	}
      XFree (children);
    }
  while (root != parent);
  XGetWindowAttributes (d, w, &xwa);
  *x = xwa.x;
  *y = xwa.y;
}

void x_get_frame_text_position (struct frame *f)
{
  Display *dpy = DEVICE_X_DISPLAY (XDEVICE (FRAME_DEVICE (f)));
  Window window = XtWindow (FRAME_X_TEXT_WIDGET (f));
  Window root, child;
  int x, y;
  unsigned int width, height, border_width;
  unsigned int depth;

  XGetGeometry (dpy, window, &root, &x, &y, &width, &height, &border_width,
		&depth);
  XTranslateCoordinates (dpy, window, root, 0, 0, &x, &y, &child);

  FRAME_X_X (f) = x;
  FRAME_X_Y (f) = y;
}

#if 0
static void
x_smash_bastardly_shell_position (Widget shell)
{
  /* Naturally those bastards who wrote Xt couldn't be bothered
     to learn about race conditions and such.  We can't trust
     the X and Y values to have any semblance of correctness,
     so we smash the right values in place. */

 /* We might be called before we've actually realized the window (if
     we're checking for the minibuffer resource).  This will bomb in
     that case so we don't bother calling it. */
  if (XtWindow (shell))
    x_get_top_level_position (XtDisplay (shell), XtWindow (shell),
			      &shell->core.x, &shell->core.y);
}
#endif /* 0 */

static Lisp_Object
x_frame_property (struct frame *f, Lisp_Object property)
{
  Widget shell = FRAME_X_SHELL_WIDGET (f);
  EmacsFrame w = (EmacsFrame) FRAME_X_TEXT_WIDGET (f);
  Widget gw = (Widget) w;

  if (EQ (Qleft, property) || EQ (Qtop, property))
    {
      Position x, y;
      if (!XtWindow(shell))
	return Qzero;
      x_get_top_level_position (XtDisplay (shell), XtWindow (shell), &x, &y);
      if (EQ (Qleft, property)) return make_int (x);
      if (EQ (Qtop,  property)) return make_int (y);
    }
  if (EQ (Qborder_width, property))
    return make_int (w->core.border_width);
  if (EQ (Qinternal_border_width, property))
    return make_int (w->emacs_frame.internal_border_width);
  if (EQ (Qborder_color, property))
    return color_to_string (gw, w->core.border_pixel);
  if (EQ (Qinter_line_space, property))
    return make_int (w->emacs_frame.interline);
  if (EQ (Qwindow_id, property))
    return Fx_window_id (wrap_frame (f));

  return Qunbound;
}

static int
x_internal_frame_property_p (struct frame *UNUSED (f), Lisp_Object property)
{
  return EQ (property, Qleft)
    || EQ (property, Qtop)
    || EQ (property, Qborder_width)
    || EQ (property, Qinternal_border_width)
    || EQ (property, Qborder_color)
    || EQ (property, Qinter_line_space)
    || EQ (property, Qwindow_id)
    || STRINGP (property);
}

static Lisp_Object
x_frame_properties (struct frame *f)
{
  Lisp_Object props = Qnil;
  Widget shell = FRAME_X_SHELL_WIDGET (f);
  EmacsFrame w = (EmacsFrame) FRAME_X_TEXT_WIDGET (f);
  Widget gw = (Widget) w;
  Position x, y;

  props = cons3 (Qwindow_id, Fx_window_id (wrap_frame (f)), props);
  props = cons3 (Qinter_line_space, make_int (w->emacs_frame.interline), props);

  props = cons3 (Qborder_color,
		 color_to_string (gw, w->core.border_pixel), props);
  props = cons3 (Qinternal_border_width,
		 make_int (w->emacs_frame.internal_border_width), props);
  props = cons3 (Qborder_width, make_int (w->core.border_width), props);

  if (!XtWindow(shell))
    x = y = 0;
  else
    x_get_top_level_position (XtDisplay (shell), XtWindow (shell), &x, &y);

  props = cons3 (Qtop,  make_int (y), props);
  props = cons3 (Qleft, make_int (x), props);

  return props;
}


/* Functions called only from `x_set_frame_properties' to set
   individual properties. */

static void
x_set_frame_text_value (struct frame *f, Ibyte *value,
			String Xt_resource_name,
			String Xt_resource_encoding_name)
{
  Atom encoding = XA_STRING;
  String new_XtValue = (String) value;
  String old_XtValue = NULL;

#ifdef MULE
  Ibyte *ptr;
  /* Optimize for common ASCII case */
  for (ptr = value; *ptr; ptr++)
    if (!byte_ascii_p (*ptr))
      {
        encoding = DEVICE_XATOM_COMPOUND_TEXT (XDEVICE (FRAME_DEVICE (f)));
        new_XtValue = (String) ITEXT_TO_EXTERNAL (value, Qctext);
        break;
      }
#endif /* MULE */

  /* #### Caching is device-independent - belongs in update_frame_title. */
  Xt_GET_VALUE (FRAME_X_SHELL_WIDGET (f), Xt_resource_name, &old_XtValue);
  if (!old_XtValue || strcmp (new_XtValue, old_XtValue))
    {
      Arg al[2];
      Xt_SET_ARG (al[0], Xt_resource_name, new_XtValue);
      Xt_SET_ARG (al[1], Xt_resource_encoding_name, encoding);
      XtSetValues (FRAME_X_SHELL_WIDGET (f), al, 2);
    }
}

static void
x_set_title_from_ibyte (struct frame *f, Ibyte *name)
{
  x_set_frame_text_value (f, name, XtNtitle, XtNtitleEncoding);
}

static void
x_set_icon_name_from_ibyte (struct frame *f, Ibyte *name)
{
  x_set_frame_text_value (f, name, XtNiconName, XtNiconNameEncoding);
}

/* Set the initial frame size as specified.  This function is used
   when the frame's widgets have not yet been realized.  In this
   case, it is not sufficient just to set the width and height of
   the EmacsFrame widget, because they will be ignored when the
   widget is realized (instead, the shell's geometry resource is
   used). */

static void
x_set_initial_frame_size (struct frame *f, int flags, int x, int y,
			  int w, int h)
{
  Ascbyte shell_geom[255];
  int xval, yval;
  Ascbyte xsign, ysign;
  Boolbyte uspos = !!(flags & (XValue | YValue));
  Boolbyte ussize = !!(flags & (WidthValue | HeightValue));
  Ascbyte *temp;

  /* assign the correct size to the EmacsFrame widget ... */
  EmacsFrameSetCharSize (FRAME_X_TEXT_WIDGET (f), w, h);

  /* and also set the WMShell's geometry */
  (flags & XNegative) ? (xval = -x, xsign = '-') : (xval = x, xsign = '+');
  (flags & YNegative) ? (yval = -y, ysign = '-') : (yval = y, ysign = '+');

  if (uspos && ussize)
    sprintf (shell_geom, "=%dx%d%c%d%c%d", w, h, xsign, xval, ysign, yval);
  else if (uspos)
    sprintf (shell_geom, "=%c%d%c%d", xsign, xval, ysign, yval);
  else if (ussize)
    sprintf (shell_geom, "=%dx%d", w, h);

  if (uspos || ussize)
    {
      temp = xnew_ascbytes (1 + strlen (shell_geom));
      strcpy (temp, shell_geom);
      FRAME_X_GEOM_FREE_ME_PLEASE (f) = temp;
    }
  else
    temp = NULL;

  Xt_SET_VALUE (FRAME_X_SHELL_WIDGET (f), XtNgeometry, temp);
}

/* Report to X that a frame property of frame S is being set or changed.
   If the property is not specially recognized, do nothing.
 */

static void
x_set_frame_properties (struct frame *f, Lisp_Object plist)
{
  Position x, y;
  Dimension width = 0, height = 0;
  Bool width_specified_p = False;
  Bool height_specified_p = False;
  Bool x_position_specified_p = False;
  Bool y_position_specified_p = False;
  Bool internal_border_width_specified = False;
  Lisp_Object tail;
  Widget w;

  /* We can be called after the X IO error handler has seen a broken pipe on
     the relevant display. Don't do anything in that case.  */
  if (!FRAME_LIVE_P (f) || DEVICE_X_BEING_DELETED (XDEVICE (FRAME_DEVICE (f))))
    return;

  w = FRAME_X_TEXT_WIDGET (f);

  for (tail = plist; !NILP (tail); tail = Fcdr (Fcdr (tail)))
    {
      Lisp_Object prop = Fcar (tail);
      Lisp_Object val = Fcar (Fcdr (tail));

      if (STRINGP (prop))
	{
	  const Extbyte *extprop;

	  if (XSTRING_LENGTH (prop) == 0)
	    continue;

	  extprop = LISP_STRING_TO_EXTERNAL (prop, Qxt_widget_arg_encoding);
	  if (STRINGP (val))
	    {
	      const Extbyte *extval;
	      Bytecount extvallen;

	      /* !!#### I seriously doubt there is a single external format
		 for the value of a widget argument; it depends on the
		 semantics of the argument.  So use of
		 Qxt_widget_arg_encoding is totally bogus. --ben */
	      LISP_STRING_TO_SIZED_EXTERNAL (val, extval, extvallen,
					     Qxt_widget_arg_encoding);
	      XtVaSetValues (w, XtVaTypedArg, extprop,
			     /* !!#### Verify this + 1 and document
				as zero-termination */
			     XtRString, extval, extvallen + 1,
			     NULL);
	    }
	  else
	    XtVaSetValues (w, XtVaTypedArg, extprop, XtRInt,
			   XINT (val), sizeof (int),
			   NULL);
	}
      else if (SYMBOLP (prop))
	{
	  Lisp_Object str = Fget (prop, Qx_resource_name, Qnil);
	  int int_p = !NILP (Fget (prop, Qintegerp, Qnil));
	  Extbyte *strext;

	  if (NILP (prop) || NILP (str))
	    {
	      /* Kludge to handle the font property. */
	      if (EQ (prop, Qfont))
		{
		  /* If the value is not a string we silently ignore it. */
		  if (STRINGP (val))
		    {
		      Lisp_Object frm, font_spec;

		      frm = wrap_frame (f);
		      font_spec = Fget (Fget_face (Qdefault), Qfont, Qnil);

		      Fadd_spec_to_specifier (font_spec, val, frm, Qnil, Qnil);
		      update_frame_face_values (f);
		    }

		  continue;
		}
	      else
		continue;
	    }
	  CHECK_STRING (str);

	  /* Kludge the width/height so that we interpret them in characters
	     instead of pixels.  Yuck yuck yuck. */
	  if (!qxestrcmp_ascii (XSTRING_DATA (str), "width"))
	    {
	      CHECK_INT (val);
	      width = XINT (val);
	      width_specified_p = True;
	      continue;
	    }
	  if (!qxestrcmp_ascii (XSTRING_DATA (str), "height"))
	    {
	      CHECK_INT (val);
	      height = XINT (val);
	      height_specified_p = True;
	      continue;
	    }
	  /* Further kludge the x/y. */
	  if (!qxestrcmp_ascii (XSTRING_DATA (str), "x"))
	    {
	      CHECK_INT (val);
	      x = (Position) XINT (val);
	      x_position_specified_p = True;
	      continue;
	    }
	  if (!qxestrcmp_ascii (XSTRING_DATA (str), "y"))
	    {
	      CHECK_INT (val);
	      y = (Position) XINT (val);
	      y_position_specified_p = True;
	      continue;
	    }
	  /* Have you figured out by now that this entire function is
             one gigantic kludge? */
	  if (!qxestrcmp_ascii (XSTRING_DATA (str), "internalBorderWidth"))
	    {
	      internal_border_width_specified = True;
	    }

	  strext = LISP_STRING_TO_EXTERNAL (str, Qxt_widget_arg_encoding);
	  if (int_p)
	    {
	      CHECK_INT (val);
	      Xt_SET_VALUE (w, strext, XINT (val));
	    }
	  else if (EQ (val, Qt))
	    {
	      Xt_SET_VALUE (w, strext, True); /* XtN...*/
	    }
	  else if (EQ (val, Qnil))
	    {
	      Xt_SET_VALUE (w, strext, False); /* XtN...*/
	    }
	  else
	    {
	      const Extbyte *extval;
	      Bytecount extvallen;
	      CHECK_STRING (val);

	      LISP_STRING_TO_SIZED_EXTERNAL (val, extval, extvallen,
					     Qxt_widget_arg_encoding);
	      XtVaSetValues (w, XtVaTypedArg,
			     /* XtN... */
			     strext,
			     /* !!#### Verify this + 1 and document
				as zero-termination */
			     XtRString, extval, extvallen + 1,
			     NULL);
	    }

#ifdef HAVE_SCROLLBARS
	  if (!qxestrcmp_ascii (XSTRING_DATA (str), "scrollBarWidth")
	      || !qxestrcmp_ascii (XSTRING_DATA (str), "scrollBarHeight"))
	    {
	      x_update_frame_scrollbars (f);
	    }
#endif /* HAVE_SCROLLBARS */
	}
    }

  /* Kludge kludge kludge.   We need to deal with the size and position
   specially. */
  {
    int size_specified_p = width_specified_p || height_specified_p;
    int position_specified_p = x_position_specified_p ||
      y_position_specified_p;

    if (!width_specified_p)
      width = FRAME_WIDTH (f);
    if (!height_specified_p)
      height = FRAME_HEIGHT (f);

    /* Kludge kludge kludge kludge. */
    if (position_specified_p &&
	(!x_position_specified_p || !y_position_specified_p))
      {
	Position dummy;
	Widget shell = FRAME_X_SHELL_WIDGET (f);
	x_get_top_level_position (XtDisplay (shell), XtWindow (shell),
				  (x_position_specified_p ? &dummy : &x),
				  (y_position_specified_p ? &dummy : &y));
#if 0
	x = (int) (FRAME_X_SHELL_WIDGET (f)->core.x);
	y = (int) (FRAME_X_SHELL_WIDGET (f)->core.y);
#endif
      }

    if (!f->init_finished)
      {
	int flags = (size_specified_p ? WidthValue | HeightValue : 0) |
	  (position_specified_p ?
	   XValue | YValue | (x < 0 ? XNegative : 0) | (y < 0 ? YNegative : 0)
	   : 0);
	if (size_specified_p
	    || position_specified_p
	    || internal_border_width_specified)
	  x_set_initial_frame_size (f, flags, x, y, width, height);
      }
    else
      {
	if (size_specified_p || internal_border_width_specified)
	  {
	    Lisp_Object frame = wrap_frame (f);

	    Fset_frame_size (frame, make_int (width),
			      make_int (height), Qnil);
	  }
	if (position_specified_p)
	  {
	    Lisp_Object frame = wrap_frame (f);

	    Fset_frame_position (frame, make_int (x), make_int (y));
	  }
      }
  }
}

static int frame_title_format_already_set;

static void
maybe_set_frame_title_format (Widget shell)
{

  /* Only do this if this is the first X frame we're creating.

     If the *title resource (or -title option) was specified, then
     set frame-title-format to its value.
     */

  if (!frame_title_format_already_set)
    {
      /* No doubt there's a less stupid way to do this. */
      Extbyte *results[2];
      XtResource resources[2];
      results[0] = results[1] = 0;
      resources[0].resource_name = XtNtitle;
      resources[0].resource_class = XtCTitle;
      resources[0].resource_type = XtRString;
      resources[0].resource_size = sizeof (String);
      resources[0].resource_offset = 0;
      resources[0].default_type = XtRString;
      resources[0].default_addr = 0;
      resources[1].resource_name = XtNiconName;
      resources[1].resource_class = XtCIconName;
      resources[1].resource_type = XtRString;
      resources[1].resource_size = sizeof (String);
      resources[1].resource_offset = sizeof (Extbyte *);
      resources[1].default_type = XtRString;
      resources[1].default_addr = 0;
      XtGetSubresources (XtParent (shell), (XtPointer) results,
			 shell->core.name,
			 shell->core.widget_class->core_class.class_name,
			 resources, XtNumber (resources), 0, 0);
      if (results[0])
	Vframe_title_format = build_extstring (results[0], Qctext);
      if (results[1])
	Vframe_icon_title_format = build_extstring (results[1], Qctext);
    }

  frame_title_format_already_set = 1;
}

#if defined (HAVE_CDE)

static Extbyte *
start_drag_internal_1 (Lisp_Object event, Lisp_Object data,
		       Lisp_Object encoding, XEvent *x_event, int listp,
		       Widget *wid_out, Bytecount *len_out,
		       int *num_items_out)
{
  struct frame *f;
  Widget wid;
  struct device *d;
  struct x_device *xd;
  XWindowAttributes win_attrib;
  int modifier = 0, state = 0;
  Extbyte *dnd_data;
  Lisp_Event *lisp_event;

  CHECK_EVENT (event);
  lisp_event = XEVENT (event);
  if (EVENT_TYPE (lisp_event) != button_press_event)
    invalid_argument ("Need button-press event for drag", event);
  f = decode_x_frame (FW_FRAME (EVENT_CHANNEL (lisp_event)));
  wid = FRAME_X_TEXT_WIDGET (f);
  d = XDEVICE (FRAME_DEVICE (f));
  xd = DEVICE_X_DATA (d);
  *num_items_out = 0;

  if (listp)
    {
      DECLARE_EISTRING (ei);

      EXTERNAL_LIST_LOOP_2 (elt, data)
	{
	  CHECK_STRING (elt);
	  eicat_lstr (ei, elt);
	  eicat_ch (ei, '\0');
	  (*num_items_out)++;
	}
      eicat_ch (ei, '\0');
      TO_EXTERNAL_FORMAT (DATA, (eidata (ei), eilen (ei)),
			  MALLOC, (dnd_data, *len_out),
			  encoding);
    }
  else
    {
      CHECK_STRING (data);
      LISP_STRING_TO_SIZED_EXTERNAL_MALLOC (data, dnd_data, *len_out,
					    encoding);
      *len_out += EXTTEXT_ZTERM_SIZE;
      (*num_items_out)++;
    }

  /* not so gross hack that converts an emacs event back to a XEvent */

  x_event->xbutton.type = ButtonPress;
  x_event->xbutton.send_event = False;
  x_event->xbutton.display = XtDisplayOfObject (wid);
  x_event->xbutton.window = XtWindowOfObject (wid);
  x_event->xbutton.root = XRootWindow (x_event->xbutton.display, 0);
  x_event->xbutton.subwindow = 0;
  x_event->xbutton.time = lisp_event->timestamp;
  x_event->xbutton.x = EVENT_BUTTON_X (lisp_event);
  x_event->xbutton.y = EVENT_BUTTON_Y (lisp_event);
  if (Success == XGetWindowAttributes (x_event->xbutton.display,
				       x_event->xbutton.window,
				       &win_attrib))
    {
      x_event->xbutton.x_root = win_attrib.x + EVENT_BUTTON_X (lisp_event);
      x_event->xbutton.y_root = win_attrib.y + EVENT_BUTTON_Y (lisp_event);
    }
  else
    {
      x_event->xbutton.x_root = EVENT_BUTTON_X (lisp_event); /* this is wrong */
      x_event->xbutton.y_root = EVENT_BUTTON_Y (lisp_event);
    }

  modifier = EVENT_BUTTON_MODIFIERS (lisp_event);
  if (modifier & XEMACS_MOD_SHIFT)   state |= ShiftMask;
  if (modifier & XEMACS_MOD_CONTROL) state |= ControlMask;
  if (modifier & XEMACS_MOD_META)    state |= xd->MetaMask;
  if (modifier & XEMACS_MOD_SUPER)   state |= xd->SuperMask;
  if (modifier & XEMACS_MOD_HYPER)   state |= xd->HyperMask;
  if (modifier & XEMACS_MOD_ALT)     state |= xd->AltMask;
  state |= Button1Mask << (EVENT_BUTTON_BUTTON (lisp_event) - 1);

  x_event->xbutton.state = state;
  x_event->xbutton.button = EVENT_BUTTON_BUTTON (lisp_event);
  x_event->xbutton.same_screen = True;

  *wid_out = wid;
  return dnd_data;
}

#endif /* defined (HAVE_CDE) */

#ifdef HAVE_CDE
#include <Dt/Dt.h>
#include <Dt/Dnd.h>

static Widget CurrentDragWidget = NULL;
static XtCallbackRec dnd_convert_cb_rec[2];
static XtCallbackRec dnd_destroy_cb_rec[2];
static int drag_not_done = 0;

static void
x_cde_destroy_callback (Widget widget, XtPointer clientData,
			XtPointer callData)
{
  DtDndDragFinishCallbackStruct *dragFinishInfo =
    (DtDndDragFinishCallbackStruct *) callData;
  DtDndContext *dragData = dragFinishInfo->dragData;
  int i;

  /* free the items */
  if (callData != NULL && dragData != NULL)
    {
      if (dragData->protocol == DtDND_BUFFER_TRANSFER)
	{
	  for (i = 0; i < dragData->numItems; i++)
	    {
	      XtFree ((CRawbyte *) dragData->data.buffers[i].bp);
	      if (dragData->data.buffers[i].name)
		XtFree(dragData->data.buffers[i].name);
	    }
	}
      else
	{
	  for (i = 0; i < dragData->numItems; i++)
	    XtFree(dragData->data.files[i]);
	}
    }

  /* free the data string */
  xfree (clientData);

  CurrentDragWidget = NULL;
}

static void
x_cde_convert_callback (Widget widget, XtPointer clientData,
			XtPointer callData)
{
  DtDndConvertCallbackStruct *convertInfo =
    (DtDndConvertCallbackStruct *) callData;
  Extbyte *textdata = (Extbyte *) clientData;
  Extbyte *textptr = NULL;
  int i;

  if (convertInfo == NULL)
    {
      return;
    }

  if ((convertInfo->dragData->protocol != DtDND_BUFFER_TRANSFER
      && convertInfo->dragData->protocol != DtDND_FILENAME_TRANSFER) ||
     (convertInfo->reason != DtCR_DND_CONVERT_DATA))
    {
      return;
    }

  for (textptr = textdata, i = 0;
       i < convertInfo->dragData->numItems;
       textptr += strlen (textptr) + 1, i++)
    {
      if (convertInfo->dragData->protocol == DtDND_BUFFER_TRANSFER)
	{
	  convertInfo->dragData->data.buffers[i].bp = XtNewString (textptr);
	  convertInfo->dragData->data.buffers[i].size = strlen (textptr);
	  convertInfo->dragData->data.buffers[i].name = NULL;
	}
      else
	{
	  convertInfo->dragData->data.files[i] = XtNewString (textptr);
	}
    }

  convertInfo->status = DtDND_SUCCESS;
}

static Lisp_Object
abort_current_drag (Lisp_Object arg)
{
  if (CurrentDragWidget && drag_not_done)
    {
      XmDragCancel(CurrentDragWidget);
      CurrentDragWidget = NULL;
    }
  return arg;
}

DEFUN ("cde-start-drag-internal", Fcde_start_drag_internal, 3, 3, 0, /*
Start a CDE drag from a buffer.
First argument is the event that started the drag (must be a
button-press-event),
second arg defines if the data should be treated as a buffer or
a filename transfer (set to nil for buffer transfer),
and the third argument is a list of data strings.
WARNING: can only handle plain/text and file: transfers!
*/
       (event, dragtype, dragdata))
{
  Extbyte *dnd_data;
  XEvent x_event;
  Bytecount dnd_len;
  Widget wid;
  int num_items;

  dnd_data = start_drag_internal_1 (event, dragdata, Qdt_dnd_encoding,
				    &x_event, 1,
				    &wid, &dnd_len, &num_items);

  dnd_convert_cb_rec[0].callback = x_cde_convert_callback;
  dnd_convert_cb_rec[0].closure  = (XtPointer) dnd_data;
  dnd_convert_cb_rec[1].callback = NULL;
  dnd_convert_cb_rec[1].closure  = NULL;

  dnd_destroy_cb_rec[0].callback = x_cde_destroy_callback;
  dnd_destroy_cb_rec[0].closure  = (XtPointer) dnd_data;
  dnd_destroy_cb_rec[1].callback = NULL;
  dnd_destroy_cb_rec[1].closure  = NULL;

  CurrentDragWidget =
    DtDndDragStart (wid, &x_event,
		    (NILP (dragtype) ? DtDND_BUFFER_TRANSFER :
		     DtDND_FILENAME_TRANSFER),
		    num_items,
		    XmDROP_COPY,
		    dnd_convert_cb_rec,
		    dnd_destroy_cb_rec,
		    NULL, 0);

  xfree (dnd_data);

  return num_items ? Qt : Qnil;
}

static void
x_cde_transfer_callback (Widget widget, XtPointer clientData,
			 XtPointer callData)
{
  int ii, enqueue = 1;
  Lisp_Object frame = Qnil;
  Lisp_Object l_type = Qnil;
  Lisp_Object l_data = Qnil;
  DtDndTransferCallbackStruct *transferInfo = NULL;
  struct gcpro gcpro1, gcpro2, gcpro3;

  /*
    this needs to be changed to the new protocol:
    - we need the button, modifier and pointer states to create a
      correct misc_user_event
    - the data must be converted to the new format (URL/MIME)
  */
  /* return; */

  transferInfo = (DtDndTransferCallbackStruct *) callData;
  if (transferInfo == NULL)
    return;

  GCPRO3 (frame, l_type, l_data);

  frame = wrap_frame ((struct frame *) clientData);

  if (transferInfo->dropData->protocol == DtDND_FILENAME_TRANSFER)
    {
      l_type = Qdragdrop_URL;

      for (ii = 0; ii < transferInfo->dropData->numItems; ii++)
	{
	  Ibyte *fileint;
	  Ibyte *hurl;

	  fileint =
	    EXTERNAL_TO_ITEXT (transferInfo->dropData->data.files[ii],
				      Qfile_name);

	  hurl = dnd_url_hexify_string (fileint, "file:");
	  l_data = Fcons (build_istring (hurl), l_data);
	  xfree (hurl);
	}
    }
  else if (transferInfo->dropData->protocol == DtDND_BUFFER_TRANSFER)
    {
      int speccount = specpdl_depth ();

      /* !!#### Problem: all buffers a treated as text/plain!!!
	 Not appropriate for intl text.  Note that there is a function
	 DtDtsBufferToDataType(), but I don't know what the possible
	 return values are.
         Solution (?): Also support DtDND_TEXT_TRANSFER (compound text)
         perhaps implementation of the Motif protocol
         (which is the base of CDE) will clear this */
      l_type = Qdragdrop_MIME;
      record_unwind_protect (abort_current_drag, Qnil);
      drag_not_done = 1;
      for (ii = 0; ii < transferInfo->dropData->numItems; ii++)
 	{
	  /* let us forget this name thing for now... */
 	  /* filePath = transferInfo->dropData->data.buffers[ii].name;
	     path = (filePath == NULL) ? Qnil
	     : build_extstring (filePath, Q???); */
	  /* what, if the data is no text, and how can I tell it? */
	  l_data =
	    Fcons (list3 (list1 (build_ascstring ("text/plain")),
			  build_ascstring ("8bit"),
			  make_extstring
			  (transferInfo->dropData->data.buffers[ii].bp,
			   transferInfo->dropData->data.buffers[ii].size,
			   /* !!#### what goes here? */
			   Qdt_dnd_encoding)),
			   l_data);
 	}
      drag_not_done = 0;
      unbind_to (speccount);
    }
  else /* the other cases: NOOP_TRANSFER */
    enqueue = 0;

  /* The Problem: no button and mods from CDE... */
  if (enqueue)
    enqueue_misc_user_event_pos (frame, Qdragdrop_drop_dispatch,
				 Fcons (l_type, l_data),
				 0 /* this is the button */,
				 0 /* these are the mods */,
				 transferInfo->x,
				 transferInfo->y);

  UNGCPRO;
  return;
}
#endif /* HAVE_CDE */


/************************************************************************/
/*				widget creation				*/
/************************************************************************/

/* The widget hierarchy is

	argv[0]			shell		container	FRAME-NAME
	ApplicationShell	EmacsShell	EmacsManager	EmacsFrame

   We accept geometry specs in this order:

	*FRAME-NAME.geometry
	*EmacsFrame.geometry
	Emacs.geometry

   Other possibilities for widget hierarchies might be

	argv[0]			frame		container	FRAME-NAME
	ApplicationShell	EmacsShell	EmacsManager	EmacsFrame
   or
	argv[0]			FRAME-NAME	container	FRAME-NAME
	ApplicationShell	EmacsShell	EmacsManager	EmacsFrame
   or
	argv[0]			FRAME-NAME	container	emacsTextPane
	ApplicationShell	EmacsShell	EmacsManager	EmacsFrame

#ifdef EXTERNAL_WIDGET
   The ExternalShell widget is simply a replacement for the Shell widget
   which is able to deal with using an externally-supplied window instead
   of always creating its own.
#endif

*/

#ifdef EXTERNAL_WIDGET

static int
is_valid_window (Window w, struct device *d)
{
  XWindowAttributes xwa;
  Display *dpy = DEVICE_X_DISPLAY (d);

  expect_x_error (dpy);
  XGetWindowAttributes (dpy, w, &xwa);
  return !x_error_occurred_p (dpy);
}

#endif /* EXTERNAL_WIDGET */

/* This sends a synthetic mouse-motion event to the frame, if the mouse
   is over the frame.  This ensures that the cursor gets set properly
   before the user moves the mouse for the first time. */

static void
x_send_synthetic_mouse_event (struct frame *UNUSED (f))
{
  /* #### write this function. */
}

static int
first_x_frame_p (struct frame *f)
{
  Lisp_Object rest = DEVICE_FRAME_LIST (XDEVICE (f->device));
  while (!NILP (rest) &&
	 (f == XFRAME (XCAR (rest)) ||
	  !FRAME_X_P (XFRAME (XCAR (rest)))))
    rest = XCDR (rest);
  return NILP (rest);
}

/* Figure out what size the EmacsFrame widget should initially be,
   and set it.  Should be called after the default font has been
   determined but before the widget has been realized. */

static void
x_initialize_frame_size (struct frame *f)
{
  /* Geometry of the AppShell */
  int app_flags = 0;
  int app_x = 0;
  int app_y = 0;
  unsigned int app_w = 0;
  unsigned int app_h = 0;

  /* Geometry of the EmacsFrame */
  int frame_flags = 0;
  int frame_x = 0;
  int frame_y = 0;
  unsigned int frame_w = 0;
  unsigned int frame_h = 0;

  /* Hairily merged geometry */
  int x = 0;
  int y = 0;
  unsigned int w = 80;
  unsigned int h = 40;
  int flags = 0;

  Ascbyte *geom = 0, *ew_geom = 0;
  Boolean iconic_p = False, ew_iconic_p = False;

  Widget wmshell = FRAME_X_SHELL_WIDGET (f);
  /* #### This may not be an ApplicationShell any more, with the 'popup
     frame property. */
  Widget app_shell = XtParent (wmshell);
  Widget ew = FRAME_X_TEXT_WIDGET (f);

  /* set the position of the frame's root window now.  When the
     frame was created, the position was initialized to (0,0). */
  {
    struct window *win = XWINDOW (f->root_window);

    WINDOW_LEFT (win) = FRAME_PANED_LEFT_EDGE (f);
    WINDOW_TOP (win) = FRAME_PANED_TOP_EDGE (f);

    if (!NILP (f->minibuffer_window))
      {
	win = XWINDOW (f->minibuffer_window);
	WINDOW_LEFT (win) = FRAME_PANED_LEFT_EDGE (f);
      }
  }

#ifdef EXTERNAL_WIDGET
  /* If we're an external widget, then the size of the frame is predetermined
     (by the client) and is not our decision to make. */
  if (FRAME_X_EXTERNAL_WINDOW_P (f))
    return;
#endif

#if 0
  /* #### this junk has not been tested; therefore it's
     probably wrong.  Doesn't really matter at this point because
     currently all frames are either top-level or external widgets. */

  /* If we're not our own top-level window, then we shouldn't go messing around
     with top-level shells or "Emacs.geometry" or any such stuff.  Therefore,
     we do as follows to determine the size of the frame:

     1) If a value for the frame's "geometry" resource was specified, then
        use it.  (This specifies a size in characters.)
     2) Else, if the "width" and "height" resources were specified, then
        leave them alone.  (This is a value in pixels.  Sorry, we can't break
	Xt conventions here.)
     3) Else, assume a size of 64x12.  (This is somewhat arbitrary, but
        it's unlikely that a size of 80x40 is desirable because we're probably
	inside of a dialog box.)

     Set the widget's x, y, height, and width as determined.  Don't set the
     top-level container widget, because we don't necessarily know what it
     is. (Assume it is smart and pays attention to our values.)
  */

  if (!FRAME_X_TOP_LEVEL_FRAME_P (f))
    {
      Xt_GET_VALUE (ew, XtNgeometry, &ew_geom);
      if (ew_geom)
	frame_flags = XParseGeometry (ew_geom,
				      &frame_x, &frame_y,
				      &frame_w, &frame_h);
      if (! (frame_flags & (WidthValue | HeightValue)))
	{
          Arg al[2];
	  Xt_SET_ARG (al [0], XtNwidth,  &frame_w);
	  Xt_SET_ARG (al [1], XtNheight, &frame_h);
	  XtGetValues (ew, al, 2);
	  if (!frame_w && !frame_h)
	    {
	      frame_w = 64;
	      frame_h = 12;
	      frame_flags |= WidthValue | HeightValue;
	    }
	}
      if (frame_flags & (WidthValue | HeightValue))
	EmacsFrameSetCharSize (ew, frame_w, frame_h);
      if (frame_flags & (XValue | YValue))
	{
          Arg al[2];
	  Xt_SET_ARG (al [0], XtNwidth,  &frame_w);
	  Xt_SET_ARG (al [1], XtNheight, &frame_h);
	  XtGetValues (ew, al, 2);

	  if (frame_flags & XNegative)
	    frame_x += frame_w;
	  if (frame_flags & YNegative)
	    frame_y += frame_h;

	  Xt_SET_ARG (al [0], XtNx, frame_x);
	  Xt_SET_ARG (al [1], XtNy, frame_y);
	  XtSetValues (ew, al, 2);
	}
      return;
    }
#endif

  /* OK, we're a top-level shell. */

  assert (XtIsWMShell (wmshell));

  /* If the EmacsFrame doesn't have a geometry but the shell does,
     treat that as the geometry of the frame.
     (Is this bogus? I'm not sure.) */

  Xt_GET_VALUE (ew, XtNgeometry, &ew_geom);
  if (!ew_geom)
    {
      Xt_GET_VALUE (wmshell, XtNgeometry, &geom);
      if (geom)
	{
	  ew_geom = geom;
	  Xt_SET_VALUE (ew, XtNgeometry, ew_geom);
	}
    }

  /* If the Shell is iconic, then the EmacsFrame is iconic.
     (Is this bogus? I'm not sure.) */
  Xt_GET_VALUE (ew, XtNiconic, &ew_iconic_p);
  if (!ew_iconic_p)
    {
      Xt_GET_VALUE (wmshell, XtNiconic, &iconic_p);
      if (iconic_p)
	{
	  ew_iconic_p = iconic_p;
	  Xt_SET_VALUE (ew, XtNiconic, iconic_p);
	}
    }

  Xt_GET_VALUE (app_shell, XtNgeometry, &geom);
  if (geom)
    app_flags = XParseGeometry (geom, &app_x, &app_y, &app_w, &app_h);

  if (ew_geom)
    frame_flags = XParseGeometry (ew_geom,
				  &frame_x, &frame_y,
				  &frame_w, &frame_h);

  if (first_x_frame_p (f))
    {
      /* If this is the first frame created:
         ====================================

         - Use the ApplicationShell's size/position, if specified.
           (This is "Emacs.geometry", or the "-geometry" command line arg.)
         - Else use the EmacsFrame's size/position.
           (This is "*FRAME-NAME.geometry")

	 - If the AppShell is iconic, the frame should be iconic.

	 AppShell comes first so that -geometry always applies to the first
	 frame created, even if there is an "every frame" entry in the
	 resource database.
       */
      if (app_flags & (XValue | YValue))
	{
	  x = app_x; y = app_y;
	  flags |= (app_flags & (XValue | YValue | XNegative | YNegative));
	}
      else if (frame_flags & (XValue | YValue))
	{
	  x = frame_x; y = frame_y;
	  flags |= (frame_flags & (XValue | YValue | XNegative | YNegative));
	}

      if (app_flags & (WidthValue | HeightValue))
	{
	  w = app_w; h = app_h;
	  flags |= (app_flags & (WidthValue | HeightValue));
	}
      else if (frame_flags & (WidthValue | HeightValue))
	{
	  w = frame_w; h = frame_h;
	  flags |= (frame_flags & (WidthValue | HeightValue));
	}

      /* If the AppShell is iconic, then the EmacsFrame is iconic. */
      if (!ew_iconic_p)
	{
          Xt_GET_VALUE (app_shell, XtNiconic, &iconic_p);
	  if (iconic_p)
	    {
	      ew_iconic_p = iconic_p;
	      Xt_SET_VALUE (ew, XtNiconic, iconic_p);
	    }
	}
    }
  else
    {
      /* If this is not the first frame created:
         ========================================

         - use the EmacsFrame's size/position if specified
         - Otherwise, use the ApplicationShell's size, but not position.

         So that means that one can specify the position of the first frame
         with "Emacs.geometry" or `-geometry'; but can only specify the
	 position of subsequent frames with "*FRAME-NAME.geometry".

	 AppShell comes second so that -geometry does not apply to subsequent
	 frames when there is an "every frame" entry in the resource db,
	 but does apply to the first frame.
       */
      if (frame_flags & (XValue | YValue))
	{
	  x = frame_x; y = frame_y;
	  flags |= (frame_flags & (XValue | YValue | XNegative | YNegative));
	}

      if (frame_flags & (WidthValue | HeightValue))
	{
	  w = frame_w; h = frame_h;
	  flags |= (frame_flags & (WidthValue | HeightValue));
	}
      else if (app_flags & (WidthValue | HeightValue))
	{
	  w = app_w;
	  h = app_h;
	  flags |= (app_flags & (WidthValue | HeightValue));
	}
    }

  x_set_initial_frame_size (f, flags, x, y, w, h);
}

static void
x_get_layout_sizes (struct frame *f, Dimension *topbreadth)
{
  int i;

  /* compute height of all top-area widgets */
  for (i=0, *topbreadth = 0; i<FRAME_X_NUM_TOP_WIDGETS (f); i++)
    {
      Widget wid = FRAME_X_TOP_WIDGETS (f)[i];
      if (wid && XtIsManaged (wid))
	*topbreadth += wid->core.height + 2*wid->core.border_width;
    }
}

static void
x_layout_widgets (Widget UNUSED (w), XtPointer client_data,
		  XtPointer call_data)
{
  struct frame *f = (struct frame *) client_data;
  EmacsManagerResizeStruct *emst = (EmacsManagerResizeStruct *) call_data;
  Dimension width = emst->width;
  Dimension height = emst->height;
  Widget text = FRAME_X_TEXT_WIDGET (f);
  Dimension textbord = text->core.border_width;
  Dimension topbreadth;
  Position text_x = 0, text_y = 0;
  int i;

  x_get_layout_sizes (f, &topbreadth);

  /* first the menubar and psheets ... */
  for (i=0; i<FRAME_X_NUM_TOP_WIDGETS (f); i++)
    {
      Widget wid = FRAME_X_TOP_WIDGETS (f)[i];
      if (wid && XtIsManaged (wid))
	{
	  Dimension bord = wid->core.border_width;
	  XtConfigureWidget (wid, 0, text_y,
			     width - 2*bord, wid->core.height,
			     bord);
	  text_y += wid->core.height + 2*bord;
	}
    }

#ifdef HAVE_SCROLLBARS
  f->scrollbar_y_offset = topbreadth + textbord;
#endif

  /* finally the text area */
  XtConfigureWidget (text, text_x, text_y,
		     width - 2*textbord,
		     height - text_y - 2*textbord,
		     textbord);
}

static void
x_do_query_geometry (Widget UNUSED (w), XtPointer client_data,
		     XtPointer call_data)
{
  struct frame *f = (struct frame *) client_data;
  EmacsManagerQueryGeometryStruct *emst =
    (EmacsManagerQueryGeometryStruct *) call_data;
  Widget text = FRAME_X_TEXT_WIDGET (f);
  Dimension textbord = text->core.border_width;
  Dimension topbreadth;
  XtWidgetGeometry req, repl;
  int mask = emst->request_mode & (CWWidth | CWHeight);

  x_get_layout_sizes (f, &topbreadth);

  /* Strip away menubar from suggested size, and ask the text widget
     what size it wants to be.  */
  req.request_mode = mask;
  if (mask & CWWidth)
    req.width = emst->proposed_width - 2*textbord;
  if (mask & CWHeight)
    req.height = emst->proposed_height - topbreadth - 2*textbord;
  XtQueryGeometry (text, &req, &repl);

  /* Now add the menubar back again */
  emst->proposed_width  = repl.width  + 2*textbord;
  emst->proposed_height = repl.height + topbreadth + 2*textbord;
}

/* Creates the widgets for a frame.
   lisp_window_id is a Lisp description of an X window or Xt
   widget to parse.
   parent is a frame to use as the parent.
   overridep if non-nil says to set the override-redirect setting.

   This function does not create or map the windows.  (That is
   done by x_popup_frame().)
 */
static void
x_create_widgets (struct frame *f, Lisp_Object lisp_window_id,
		  Lisp_Object parent, Lisp_Object overridep)
{
  struct device *d = XDEVICE (f->device);
  Visual *visual = DEVICE_X_VISUAL (d);
  int depth = DEVICE_X_DEPTH (d);
  Colormap cmap = DEVICE_X_COLORMAP (d);
#ifdef EXTERNAL_WIDGET
  Window window_id = 0;
#endif
  const Extbyte *name;
  Arg al[25];
  int ac = 0;
  Widget text, container, shell;
  Widget parentwid = 0;
#ifdef HAVE_MENUBARS
  int menubar_visible;
  Widget menubar;
#endif

  if (STRINGP (f->name))
    name = LISP_STRING_TO_EXTERNAL (f->name, Qctext);
  else
    name = "emacs";

  /* The widget hierarchy is

	argv[0]			shell		pane		FRAME-NAME
	ApplicationShell	EmacsShell	EmacsManager	EmacsFrame

	(the type of the shell is ExternalShell if this frame is running
	in another client's window)

	However the EmacsShell widget has WM_CLASS of FRAME-NAME/Emacs.
	Normally such shells have name/class shellname/appclass, which in this
	case would be "shell/Emacs" instead of "frame-name/Emacs".  We could
	also get around this by naming the shell "frame-name", but that would
	be confusing because the text area (the EmacsFrame widget inferior of
	the shell) is also called that.  So we just set the WM_CLASS property.
   */

#ifndef EXTERNAL_WIDGET
  if (!NILP (lisp_window_id))
    signal_error
      (Qunimplemented,
       "support for external widgets was not enabled at compile-time",
       Qunbound);
#else
  if (!NILP (lisp_window_id))
    {
      Ibyte *string;

      CHECK_STRING (lisp_window_id);
      string = XSTRING_DATA (lisp_window_id);
      if (string[0] == '0' && (string[1] == 'x' || string[1] == 'X'))
	qxesscanf_ascii_1 (string + 2, "%lxu", &window_id);
#if 0
      else if (string[0] == 'w')
	{
	  qxesscanf_ascii (string + 1, "%x", &parent_widget);
	  if (parent_widget)
	    window_id = XtWindow (parent_widget);
	}
#endif
      else
	qxesscanf_ascii_1 (string, "%lu", &window_id);
      if (!is_valid_window (window_id, d))
	signal_ferror (Qinvalid_argument, "Invalid window %lu",
		       (unsigned long) window_id);
      FRAME_X_EXTERNAL_WINDOW_P (f) = 1;
    } else
#endif /* EXTERNAL_WIDGET */
      FRAME_X_TOP_LEVEL_FRAME_P (f) = 1;

  ac = 0;
  Xt_SET_ARG (al[ac], XtNallowShellResize, True); ac++;
#ifdef LWLIB_USES_MOTIF
  /* Motif sucks beans.  Without this in here, it will delete the window
     out from under us when it receives a WM_DESTROY_WINDOW message
     from the WM. */
  Xt_SET_ARG (al[ac], XmNdeleteResponse, XmDO_NOTHING); ac++;
#endif

#ifdef EXTERNAL_WIDGET
  if (window_id)
    {
      Xt_SET_ARG (al[ac], XtNwindow, window_id); ac++;
    }
  else
#endif /* EXTERNAL_WIDGET */
    {
      Xt_SET_ARG (al[ac], XtNinput, True);       ac++;
      Xt_SET_ARG (al[ac], XtNminWidthCells, 10); ac++;
      Xt_SET_ARG (al[ac], XtNminHeightCells, 1); ac++;
      Xt_SET_ARG (al[ac], XtNvisual, visual);    ac++;
      Xt_SET_ARG (al[ac], XtNdepth, depth);      ac++;
      Xt_SET_ARG (al[ac], XtNcolormap, cmap);    ac++;
    }

  if (!NILP (overridep))
    {
      Xt_SET_ARG (al[ac], XtNoverrideRedirect, True);    ac++;
    }

  /* #### maybe we should check for FRAMEP instead? */
  if (!NILP (parent))
    {
      parentwid = FRAME_X_SHELL_WIDGET (XFRAME (parent));
      Xt_SET_ARG (al[ac], XtNtransientFor, parentwid); ac++;
    }

  shell = XtCreatePopupShell ("shell",
			      (
#ifdef EXTERNAL_WIDGET
			       window_id ? externalShellWidgetClass :
#endif
			       parentwid ? transientEmacsShellWidgetClass :
			       topLevelEmacsShellWidgetClass
			       ),
			      parentwid ? parentwid :
			      DEVICE_XT_APP_SHELL (d),
			      al, ac);
  FRAME_X_SHELL_WIDGET (f) = shell;
  maybe_set_frame_title_format (shell);

  /* Create the manager widget */
  ac = 0;
  Xt_SET_ARG (al[ac], XtNvisual, visual); ac++;
  Xt_SET_ARG (al[ac], XtNdepth, depth); ac++;
  Xt_SET_ARG (al[ac], XtNcolormap, cmap); ac++;

  container = XtCreateWidget ("container",
			      emacsManagerWidgetClass, shell, al, ac);
  FRAME_X_CONTAINER_WIDGET (f) = container;
  XtAddCallback (container, XtNresizeCallback, x_layout_widgets,
		 (XtPointer) f);
  XtAddCallback (container, XtNqueryGeometryCallback, x_do_query_geometry,
		 (XtPointer) f);

  /* Create the text area */
  ac = 0;
  Xt_SET_ARG (al[ac], XtNvisual, visual); ac++;
  Xt_SET_ARG (al[ac], XtNdepth, depth); ac++;
  Xt_SET_ARG (al[ac], XtNcolormap, cmap); ac++;
  Xt_SET_ARG (al[ac], XtNborderWidth, 0); ac++; /* should this be settable? */
  Xt_SET_ARG (al[ac], XtNemacsFrame,  f); ac++;
  text = XtCreateWidget (name, emacsFrameClass, container, al, ac);
  FRAME_X_TEXT_WIDGET (f) = text;

#ifdef HAVE_MENUBARS
  /* Create the initial menubar widget. */
  menubar_visible = x_initialize_frame_menubar (f);
  FRAME_X_TOP_WIDGETS (f)[0] = menubar = FRAME_X_MENUBAR_WIDGET (f);
  FRAME_X_NUM_TOP_WIDGETS (f) = 1;

  if (menubar_visible)
    XtManageChild (menubar);
#endif /* HAVE_MENUBARS */
  XtManageChild (text);
  XtManageChild (container);
}

/* We used to call XtPopup() in x_popup_frame, but that doesn't give
   you control over whether the widget is initially mapped or not
   because XtPopup() makes an unconditional call to XMapRaised().
   Boy, those Xt designers were clever.

   When we first removed it we only kept the XtRealizeWidget call in
   XtPopup.  For everything except HP's that was enough.  For HP's,
   though, the failure to call the popup callbacks resulted in XEmacs
   not accepting any input.  Bizarre but true.  Stupid but true.

   So, in case there are any other gotchas floating out there along
   the same lines I've duplicated the majority of XtPopup here.  It
   assumes no grabs and that the widget is not already popped up, both
   valid assumptions for the one place this is called from. */
static void
xemacs_XtPopup (Widget widget)
{
  ShellWidget shell_widget = (ShellWidget) widget;
  XtGrabKind call_data = XtGrabNone;

  XtCallCallbacks (widget, XtNpopupCallback, (XtPointer) &call_data);

  shell_widget->shell.popped_up = TRUE;
  shell_widget->shell.grab_kind = XtGrabNone;
  shell_widget->shell.spring_loaded = False;

  if (shell_widget->shell.create_popup_child_proc != NULL)
    (*(shell_widget->shell.create_popup_child_proc)) (widget);

  /* The XtSetValues below are not in XtPopup menu.  We just want to
     make absolutely sure... */
  Xt_SET_VALUE (widget, XtNmappedWhenManaged, False);
  XtRealizeWidget (widget);
  Xt_SET_VALUE (widget, XtNmappedWhenManaged, True);
}

/* create the windows for the specified frame and display them.
   Note that the widgets have already been created, and any
   necessary geometry calculations have already been done. */
static void
x_popup_frame (struct frame *f)
{
  Widget shell_widget = FRAME_X_SHELL_WIDGET (f);
  Widget frame_widget = FRAME_X_TEXT_WIDGET (f);
  struct device *d = XDEVICE (FRAME_DEVICE (f));

  /* Before mapping the window, make sure that the WMShell's notion of
     whether it should be iconified is synchronized with the EmacsFrame's
     notion.
     */
  if (FRAME_X_TOP_LEVEL_FRAME_P (f))
    x_wm_set_shell_iconic_p (shell_widget,
			     ((EmacsFrame) frame_widget)
			     ->emacs_frame.iconic);

  xemacs_XtPopup (shell_widget);

  if (!((EmacsFrame) frame_widget)->emacs_frame.initially_unmapped)
    XtMapWidget (shell_widget);
  else
    {
      /* We may have set f->visible to 1 in x_init_frame(), so undo
	 that now. */
      FRAME_X_TOTALLY_VISIBLE_P (f) = 0;
      f->visible = 0;
    }

#ifdef EXTERNAL_WIDGET
  if (FRAME_X_EXTERNAL_WINDOW_P (f))
    ExternalShellReady (shell_widget, XtWindow (frame_widget), KeyPressMask);
  else
#endif
    if (FRAME_X_TOP_LEVEL_FRAME_P (f))
      {
	/* tell the window manager about us. */
	x_wm_store_class_hints (shell_widget, XtName (frame_widget));

#ifndef HAVE_WMCOMMAND
	x_wm_maybe_store_wm_command (f);
#endif /* HAVE_WMCOMMAND */

	x_wm_hack_wm_protocols (shell_widget);
      }

#ifdef HAVE_XIM
  XIM_init_frame (f);
#endif /* HAVE_XIM */

  /* Allow XEmacs to respond to EditRes requests.  See the O'Reilly Xt */
  /* Intrinsics Programming Manual, Motif Edition, Aug 1993, Sect 14.14, */
  /* pp. 483-493. */
  XtAddEventHandler (shell_widget,           /* the shell widget in question */
		     (EventMask) NoEventMask,/* OR with existing mask */
		     True,                   /* called on non-maskable events? */
		     (XtEventHandler) _XEditResCheckMessages, /* the handler */
		     NULL);

#ifdef HAVE_CDE
  {
    XtCallbackRec dnd_transfer_cb_rec[2];

    dnd_transfer_cb_rec[0].callback = x_cde_transfer_callback;
    dnd_transfer_cb_rec[0].closure = (XtPointer) f;
    dnd_transfer_cb_rec[1].callback = NULL;
    dnd_transfer_cb_rec[1].closure = NULL;

    DtDndVaDropRegister (FRAME_X_TEXT_WIDGET (f),
 			 DtDND_FILENAME_TRANSFER | DtDND_BUFFER_TRANSFER,
 			 XmDROP_COPY, dnd_transfer_cb_rec,
 			 DtNtextIsBuffer, True,
			 DtNregisterChildren, True,
			 DtNpreserveRegistration, False,
			 NULL);
  }
#endif /* HAVE_CDE */

  /* Do a stupid property change to force the server to generate a
     propertyNotify event so that the event_stream server timestamp will
     be initialized to something relevant to the time we created the window.
     */
  XChangeProperty (XtDisplay (frame_widget), XtWindow (frame_widget),
		   DEVICE_XATOM_WM_PROTOCOLS (d), XA_ATOM, 32, PropModeAppend,
		   (Rawbyte *) NULL, 0);

  x_send_synthetic_mouse_event (f);
}

static void
allocate_x_frame_struct (struct frame *f)
{
  /* zero out all slots. */
#ifdef NEW_GC
  f->frame_data = XX_FRAME (ALLOC_NORMAL_LISP_OBJECT (x_frame));
#else /* not NEW_GC */
  f->frame_data = xnew_and_zero (struct x_frame);
#endif /* not NEW_GC */

  /* yeah, except the lisp ones */
  FRAME_X_LAST_MENUBAR_BUFFER (f) = Qnil;
  FRAME_X_ICON_PIXMAP (f) = Qnil;
  FRAME_X_ICON_PIXMAP_MASK (f) = Qnil;
}


/************************************************************************/
/*				Lisp functions				*/
/************************************************************************/

static void
x_init_frame_1 (struct frame *f, Lisp_Object props,
		int UNUSED (frame_name_is_defaulted))
{
  /* This function can GC */
  Lisp_Object device = FRAME_DEVICE (f);
  Lisp_Object lisp_window_id = Fplist_get (props, Qwindow_id, Qnil);
  Lisp_Object popup = Fplist_get (props, Qpopup, Qnil);
  Lisp_Object overridep = Fplist_get (props, Qoverride_redirect, Qnil);

  if (!NILP (popup))
    {
      if (EQ (popup, Qt))
	popup = Fselected_frame (device);
      CHECK_LIVE_FRAME (popup);
      if (!EQ (device, FRAME_DEVICE (XFRAME (popup))))
	invalid_argument_2 ("Parent must be on same device as frame",
			    device, popup);
    }

  /*
   * Previously we set this only if NILP (DEVICE_SELECTED_FRAME (d))
   * to make sure that messages were displayed as soon as possible
   * if we're creating the first frame on a device.  But it is
   * better to just set this all the time, so that when a new frame
   * is created that covers the selected frame, echo area status
   * messages can still be seen.  f->visible is reset later if the
   * initially-unmapped property is found to be non-nil in the
   * frame properties.
   */
  f->visible = 1;

  allocate_x_frame_struct (f);
  x_create_widgets (f, lisp_window_id, popup, overridep);
}

static void
x_init_frame_2 (struct frame *f, Lisp_Object UNUSED (props))
{
  /* Set up the values of the widget/frame.  A case could be made for putting
     this inside of the widget's initialize method. */

  update_frame_face_values (f);
  x_initialize_frame_size (f);
  /* Kyle:
   *   update_frame_title() can't be done here, because some of the
   *   modeline specs depend on the frame's device having a selected
   *   frame, and that may not have been set up yet.  The redisplay
   *   will update the frame title anyway, so nothing is lost.
   * JV:
   *   It turns out it gives problems with FVWMs name based mapping.
   *   We'll just  need to be careful in the modeline specs.
   */
  update_frame_title (f);
  /* Henry S. Thompson:
   * Must set icon resource before mapping frame, or some WMs may
   * lose the icon (openbox).  See <f5bhc3efb17@hildegard.inf.ed.ac.uk>.
   * SJT:
   * This probably means that the frame-icon library won't work with
   * that WM.  Late breaking news: it *does* work, so possibly the
   * problem at initialization is due to a race condition.
   */
  update_frame_icon (f);
}

static void
x_init_frame_3 (struct frame *f)
{
  /* #### NOTE: This whole business of splitting frame initialization into
     #### different functions is somewhat messy. The latest one seems a good
     #### place to initialize the edit widget's position because we're sure
     #### that the frame is now relalized. -- dvl */
  
  x_popup_frame (f);
  x_get_frame_text_position (f);
}

static void
x_mark_frame (struct frame *f)
{
  mark_object (FRAME_X_LAST_MENUBAR_BUFFER (f));
  mark_object (FRAME_X_ICON_PIXMAP (f));
  mark_object (FRAME_X_ICON_PIXMAP_MASK (f));
}

static void
x_set_frame_icon (struct frame *f)
{
  Pixmap x_pixmap, x_mask;

  if (IMAGE_INSTANCEP (f->icon)
      && IMAGE_INSTANCE_PIXMAP_TYPE_P (XIMAGE_INSTANCE (f->icon)))
    {
      x_pixmap = XIMAGE_INSTANCE_X_PIXMAP (f->icon);
      x_mask = XIMAGE_INSTANCE_X_MASK (f->icon);
    }
  else
    {
      x_pixmap = 0;
      x_mask = 0;
    }

  /* Store the X data into the widget. */
  {
    Arg al[2];
    Xt_SET_ARG (al[0], XtNiconPixmap, x_pixmap);
    Xt_SET_ARG (al[1], XtNiconMask,   x_mask);
    XtSetValues (FRAME_X_SHELL_WIDGET (f), al, 2);
  }
}

static void
x_set_frame_pointer (struct frame *f)
{
  XDefineCursor (XtDisplay (FRAME_X_TEXT_WIDGET (f)),
		 XtWindow (FRAME_X_TEXT_WIDGET (f)),
		 XIMAGE_INSTANCE_X_CURSOR (f->pointer));
  XSync (XtDisplay (FRAME_X_TEXT_WIDGET (f)), 0);
}

static Lisp_Object
x_get_frame_parent (struct frame *f)
{
  Widget parentwid = 0;

  Xt_GET_VALUE (FRAME_X_SHELL_WIDGET (f), XtNtransientFor, &parentwid);
  /* find the frame whose wid is parentwid */
  if (parentwid)
    {
      Lisp_Object frmcons;
      DEVICE_FRAME_LOOP (frmcons, XDEVICE (FRAME_DEVICE (f)))
	{
	  Lisp_Object frame = XCAR (frmcons);
	  if (FRAME_X_SHELL_WIDGET (XFRAME (frame)) == parentwid)
	    return frame;
	}
    }
  return Qnil;
}

DEFUN ("x-window-id", Fx_window_id, 0, 1, 0, /*
Get the ID of the X11 window.
This gives us a chance to manipulate the Emacs window from within a
different program.  Since the ID is an unsigned long, we return it as
a string.
*/
       (frame))
{
  Ibyte str[255];
  struct frame *f = decode_x_frame (frame);

  qxesprintf (str, "%lu", XtWindow (FRAME_X_TEXT_WIDGET (f)));
  return build_istring (str);
}


/************************************************************************/
/*			manipulating the X window			*/
/************************************************************************/

static void
x_set_frame_position (struct frame *f, int xoff, int yoff)
{
  Widget w = FRAME_X_SHELL_WIDGET (f);
  Display *dpy = XtDisplay (w);
  Dimension frame_w = DisplayWidth  (dpy, DefaultScreen (dpy));
  Dimension frame_h = DisplayHeight (dpy, DefaultScreen (dpy));
  Dimension shell_w, shell_h, shell_bord;
  int win_gravity;
  Arg al[3];

  Xt_SET_ARG (al[0], XtNwidth,       &shell_w);
  Xt_SET_ARG (al[1], XtNheight,      &shell_h);
  Xt_SET_ARG (al[2], XtNborderWidth, &shell_bord);
  XtGetValues (w, al, 3);

  win_gravity =
    xoff >= 0 && yoff >= 0 ? NorthWestGravity :
    xoff >= 0 ? SouthWestGravity :
    yoff >= 0 ? NorthEastGravity :
    SouthEastGravity;
  if (xoff < 0)
    xoff += frame_w - shell_w - 2*shell_bord;
  if (yoff < 0)
    yoff += frame_h - shell_h - 2*shell_bord;

  /* Update the hints so that, if this window is currently iconified, it will
     come back at the right place.  We can't look at s->visible to determine
     whether it is iconified because it might not be up-to-date yet (the queue
     might not be processed). */
  Xt_SET_ARG (al[0], XtNwinGravity, win_gravity);
  Xt_SET_ARG (al[1], XtNx, xoff);
  Xt_SET_ARG (al[2], XtNy, yoff);
  XtSetValues (w, al, 3);

  /* Sometimes you will find that

     (set-frame-position (selected-frame) -50 -50)

     doesn't put the frame where you expect it to: i.e. it's closer to
     the lower-right corner than it should be, and it appears that the
     size of the WM decorations was not taken into account.  This is
     *not* a problem with this function.  Both mwm and twm have bugs
     in handling this situation. (mwm ignores the window gravity and
     always assumes NorthWest, except the first time you map the
     window; twm gets things almost right, but forgets to account for
     the border width of the top-level window.) This function does
     what it's supposed to according to the ICCCM, and I'm not about
     to hack around window-manager bugs. */

#if 0
  /* This is not necessary under either mwm or twm */
  x_wm_mark_shell_position_user_specified (w);
#endif
}

/* Call this to change the size of frame S's x-window. */

static void
x_set_frame_size (struct frame *f, int cols, int rows)
{
  EmacsFrameSetCharSize (FRAME_X_TEXT_WIDGET (f), cols, rows);

  if (!wedge_metacity)		/* cf. EmacsFrameResize */
    {
      /* Kick the manager so that it knows we've changed size. */
      XtWidgetGeometry req, repl;
      req.request_mode = 0;
      XtQueryGeometry (FRAME_X_CONTAINER_WIDGET (f), &req, &repl);
      EmacsManagerChangeSize (FRAME_X_CONTAINER_WIDGET (f),
			      repl.width, repl.height);
    }

#if 0
    /* this is not correct.  x_set_frame_size() is called from
       Fset_frame_size(), which may or may not have been called
       by the user (e.g. update_EmacsFrame() calls it when the font
       changes).  For now, don't bother with getting this right. */
  x_wm_mark_shell_size_user_specified (FRAME_X_SHELL_WIDGET (f));
#endif
}

static void
x_set_mouse_position (struct window *w, int x, int y)
{
  struct frame *f = XFRAME (w->frame);

  Display *display = DEVICE_X_DISPLAY (XDEVICE (f->device));
  XWarpPointer (display, None, XtWindow (FRAME_X_TEXT_WIDGET (f)),
                0, 0, 0, 0, w->pixel_left + x, w->pixel_top + y);
}

static int
x_get_mouse_position (struct device *d, Lisp_Object *frame, int *x, int *y)
{
  Display *display = DEVICE_X_DISPLAY (d);
  Window child_window;
  Window root_window;
  Window win;
  int root_x, root_y;
  int win_x, win_y;
  unsigned int keys_and_buttons;
  struct frame *f;

  if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
		     &root_window, &child_window, &root_x, &root_y,
		     &win_x, &win_y, &keys_and_buttons) == False)
    return 0;

  if (child_window == None)
    return 0;	/* not over any window. */

  while (1)
    {
      win = child_window;
      if (XTranslateCoordinates (display, root_window, win, root_x, root_y,
				 &win_x, &win_y, &child_window) == False)
	/* Huh? */
	return 0;

      if (child_window == None)
	break;
    }

  /* At this point, win is the innermost window containing the pointer
     and win_x and win_y are the coordinates of that window. */
  f = x_any_window_to_frame (d, win);
  if (!f)
    return 0;
  *frame = wrap_frame (f);

  if (XTranslateCoordinates (display, win,
			     XtWindow (FRAME_X_TEXT_WIDGET (f)),
			     win_x, win_y, x, y, &child_window) == False)
    /* Huh? */
    return 0;

  return 1;
}

static DECLARE_DOESNT_RETURN (x_cant_notify_wm_error (void));

static DOESNT_RETURN
x_cant_notify_wm_error ()
{
  signal_error (Qgui_error, "Can't notify window manager of iconification", Qunbound);
}

/* Raise frame F.  */
static void
x_raise_frame_1 (struct frame *f, int force)
{
  if (FRAME_VISIBLE_P (f) || force)
    {
      Widget bottom_dialog;
      XWindowChanges xwc;
      unsigned int flags;
      Display *display = DEVICE_X_DISPLAY (XDEVICE (f->device));
      Window emacs_window = XtWindow (FRAME_X_SHELL_WIDGET (f));

      /* first raises all the dialog boxes, then put emacs just below the
       * bottom most dialog box */
      bottom_dialog = lw_raise_all_pop_up_widgets ();
      if (bottom_dialog && XtWindow (bottom_dialog))
	{
	  xwc.sibling = XtWindow (bottom_dialog);
	  xwc.stack_mode = Below;
	  flags = CWSibling | CWStackMode;
	}
      else
	{
	  xwc.stack_mode = Above;
	  flags = CWStackMode;
	}

      if (!XReconfigureWMWindow (display, emacs_window,
				 DefaultScreen (display),
				 flags, &xwc))
	x_cant_notify_wm_error ();
    }
}

static void
x_raise_frame (struct frame *f)
{
  x_raise_frame_1 (f, 1);
}

/* Lower frame F.  */
static void
x_lower_frame (struct frame *f)
{
  if (FRAME_VISIBLE_P (f))
    {
      Display *display = DEVICE_X_DISPLAY (XDEVICE (f->device));
      XWindowChanges xwc;
      unsigned int flags = CWStackMode;

      xwc.stack_mode = Below;
      if (!XReconfigureWMWindow (display, XtWindow (FRAME_X_SHELL_WIDGET (f)),
				 DefaultScreen (display), flags, &xwc))
	x_cant_notify_wm_error ();
    }
}

static void
x_enable_frame (struct frame *f)
{
  XtSetSensitive (FRAME_X_SHELL_WIDGET (f), True);
}

static void
x_disable_frame (struct frame *f)
{
  XtSetSensitive (FRAME_X_SHELL_WIDGET (f), False);
}

/* Change from withdrawn state to mapped state. */
static void
x_make_frame_visible (struct frame *f)
{
  Display *display = DEVICE_X_DISPLAY (XDEVICE (f->device));

  if (!FRAME_VISIBLE_P(f))
    XMapRaised (display, XtWindow (FRAME_X_SHELL_WIDGET (f)));
  else
    x_raise_frame_1 (f, 0);
}

/* Change from mapped state to withdrawn state. */
static void
x_make_frame_invisible (struct frame *f)
{
  Display *display = DEVICE_X_DISPLAY (XDEVICE (f->device));

  if (!FRAME_VISIBLE_P(f))
    return;

  if (!XWithdrawWindow (display,
			XtWindow (FRAME_X_SHELL_WIDGET (f)),
			DefaultScreen (display)))
    x_cant_notify_wm_error ();
}

static int
x_frame_visible_p (struct frame *f)
{
#if 0

  /* #### Ben suggests using x_frame_window_state (f) == NormalState. */

  Display *display = DEVICE_X_DISPLAY (XDEVICE (f->device));
  XWindowAttributes xwa;
  int result;

  /* JV:
     This is bad, very bad :-(
     It is not compatible with our tristate visible and
     it should never ever change the visibility for us, this leads to
     the frame-freeze problem under fvwm because with the pager

     Mappedness != Viewability != Visibility != Emacs f->visible

     This first unequalness is the reason for the frame freezing problem
     under fvwm (it happens when the frame is another fvwm-page)

     The second unequalness happen when it is on the same fvwm-page
     but in an invisible part of the visible screen.

     For now we just return the XEmacs internal value --- which might not be up
     to date. Is that a problem? ---. Otherwise we should
     use async visibility like in standard Emacs.
     */

  if (!XGetWindowAttributes (display,
			     XtWindow (FRAME_X_SHELL_WIDGET (f)),
			     &xwa))
    result = 0;
  else
    result = xwa.map_state == IsViewable;
  /* In this implementation it should at least be != IsUnmapped
     JV */

  f->visible = result;
  return result;
#endif /* 0 */

  return f->visible;
}

static int
x_frame_totally_visible_p (struct frame *f)
{
  return FRAME_X_TOTALLY_VISIBLE_P (f);
}

/* Change window state from mapped to iconified. */
static void
x_iconify_frame (struct frame *f)
{
  Display *display = DEVICE_X_DISPLAY (XDEVICE (f->device));

  if (!XIconifyWindow (display,
		       XtWindow (FRAME_X_SHELL_WIDGET (f)),
		       DefaultScreen (display)))
    x_cant_notify_wm_error ();

  f->iconified = 1;
}

/* Sets the X focus to frame f. */
static void
x_focus_on_frame (struct frame *f)
{
  XWindowAttributes xwa;
  Widget shell_widget;
  int viewable = 0;

  assert (FRAME_X_P (f));

  shell_widget = FRAME_X_SHELL_WIDGET (f);
  if (!XtWindow (shell_widget))
    return;

#ifdef EXTERNAL_WIDGET
  if (FRAME_X_EXTERNAL_WINDOW_P (f))
    ExternalShellSetFocus (shell_widget);
#endif /* EXTERNAL_WIDGET */

  /* Do the ICCCM focus change if the window is still visible.
     The s->visible flag might not be up-to-date, because we might
     not have processed magic events recently.  So make a server
     round-trip to find out whether it's really mapped right now.
     We grab the server to do this, because that's the only way to
     eliminate the race condition.
   */
  XGrabServer (XtDisplay (shell_widget));
  if (XGetWindowAttributes (XtDisplay (shell_widget),
			    XtWindow (shell_widget),
			    &xwa))
    /* JV: it is bad to change the visibility like this, so we don't for the
       moment, at least change_frame_visibility should be called
       Note also that under fvwm a frame can be Viewable (and thus Mapped)
       but still X-invisible
    f->visible = xwa.map_state == IsViewable; */
    viewable = xwa.map_state == IsViewable;


  if (viewable)
    {
      Window focus;
      int revert_to;
      XGetInputFocus (XtDisplay (shell_widget), &focus, &revert_to);
      /* Don't explicitly set the focus on this window unless the focus
	 was on some other window (not PointerRoot).  Note that, even when
	 running a point-to-type window manager like *twm, there is always
	 a focus window; the window manager maintains that based on the
	 mouse position.  If you set the "NoTitleFocus" option in these
	 window managers, then the server itself maintains the focus via
	 PointerRoot, and changing that to focus on the window would make
	 the window grab the focus.  Very bad.
	 */
      if (focus != PointerRoot)
	{
	  XSetInputFocus (XtDisplay (shell_widget),
			  XtWindow (shell_widget),
			  RevertToParent,
			  CurrentTime);
	  XFlush (XtDisplay (shell_widget));
	}
    }
  XUngrabServer (XtDisplay (shell_widget));
  XFlush (XtDisplay (shell_widget)); /* hey, I'd like to DEBUG this... */
}

/* Destroy the X window of frame F.  */
static void
x_delete_frame (struct frame *f)
{
  Display *dpy;

#ifndef HAVE_WMCOMMAND
  if (FRAME_X_TOP_LEVEL_FRAME_P (f))
    x_wm_maybe_move_wm_command (f);
#endif /* HAVE_WMCOMMAND */

#ifdef HAVE_CDE
  DtDndDropUnregister (FRAME_X_TEXT_WIDGET (f));
#endif /* HAVE_CDE */

#ifdef HAVE_XFT
  /* If we have an XftDraw structure, we need to free it here.
     We can't ever have an XftDraw without a Display, so we are safe
     to free it in here, and we avoid too much playing around with the 
     malloc checking hooks this way. */
  if (FRAME_X_XFTDRAW (f)) 
    {
      XftDrawDestroy (FRAME_X_XFTDRAW (f));
      FRAME_X_XFTDRAW (f) = NULL;
    }
#endif


  assert (FRAME_X_SHELL_WIDGET (f) != 0);
  dpy = XtDisplay (FRAME_X_SHELL_WIDGET (f));

#ifdef EXTERNAL_WIDGET
  expect_x_error (dpy);
  /* for obscure reasons having (I think) to do with the internal
     window-to-widget hierarchy maintained by Xt, we have to call
     XtUnrealizeWidget() here.  Xt can really suck. */
  if (f->being_deleted)
    XtUnrealizeWidget (FRAME_X_SHELL_WIDGET (f));
  XtDestroyWidget (FRAME_X_SHELL_WIDGET (f));
  x_error_occurred_p (dpy);
#else
  XtDestroyWidget (FRAME_X_SHELL_WIDGET (f));
  /* make sure the windows are really gone! */
  /* #### Is this REALLY necessary? */
  XFlush (dpy);
#endif /* EXTERNAL_WIDGET */

  FRAME_X_SHELL_WIDGET (f) = 0;

  if (FRAME_X_GEOM_FREE_ME_PLEASE (f))
    {
      xfree (FRAME_X_GEOM_FREE_ME_PLEASE (f));
      FRAME_X_GEOM_FREE_ME_PLEASE (f) = 0;
    }

  if (f->frame_data)
    {
#ifndef NEW_GC
      xfree (f->frame_data);
#endif /* not NEW_GC */
      f->frame_data = 0;
    }
}

static void
x_update_frame_external_traits (struct frame *frm, Lisp_Object name)
{
  Arg al[10];
  int ac = 0;
  Lisp_Object frame = wrap_frame (frm);


  if (EQ (name, Qforeground))
   {
     Lisp_Object color = FACE_FOREGROUND (Vdefault_face, frame);
     XColor fgc;

     if (!EQ (color, Vthe_null_color_instance))
       {
	 fgc = COLOR_INSTANCE_X_COLOR (XCOLOR_INSTANCE (color));
	 Xt_SET_ARG (al[ac], XtNforeground, (void *) fgc.pixel); ac++;
       }
   }
  else if (EQ (name, Qbackground))
   {
     Lisp_Object color = FACE_BACKGROUND (Vdefault_face, frame);
     XColor bgc;

     if (!EQ (color, Vthe_null_color_instance))
       {
	 bgc = COLOR_INSTANCE_X_COLOR (XCOLOR_INSTANCE (color));
	 Xt_SET_ARG (al[ac], XtNbackground, (void *) bgc.pixel); ac++;
       }

     /* Really crappy way to force the modeline shadows to be
	redrawn.  But effective. */
     MARK_FRAME_WINDOWS_STRUCTURE_CHANGED (frm);
     MARK_FRAME_CHANGED (frm);
   }
  else if (EQ (name, Qfont))
   {
     Lisp_Object font = FACE_FONT (Vdefault_face, frame, Vcharset_ascii);

     /* It may be that instantiating the font has deleted the frame (will
	happen if the user has specified a charset registry for ASCII that
	isn't available on the server, and our fallback of iso8859-1 isn't
	available; something vanishingly rare.) In that case, return from
	this function without further manipulation of the dead frame. */

     if (!FRAME_LIVE_P(frm))
       {
	 return;
       }

     /* #### what to do about Xft?  I don't think the font is actually used
	to compute cell size for computing frame pixel dimensions (see call
	to EmacsFrameRecomputeCellSize() below); where is it used? -- sjt
        What does XtSetValues() do if that resource isn't present? */
     if (!EQ (font, Vthe_null_font_instance))
       {
	 if (0)
	   ;
#ifdef HAVE_XFT
	 else if (FONT_INSTANCE_X_XFTFONT (XFONT_INSTANCE (font)))
	   {
	     Xt_SET_ARG (al[ac], XtNxftFont,
		       (void *) FONT_INSTANCE_X_XFTFONT (XFONT_INSTANCE (font)));
	     ac++;
	   }
#endif
	 else if (FONT_INSTANCE_X_FONT (XFONT_INSTANCE (font)))
	   {
	     Xt_SET_ARG (al[ac], XtNfont,
			 (void *) FONT_INSTANCE_X_FONT (XFONT_INSTANCE (font)));
	     ac++;
	   }
       }
   }
  else
   ABORT ();

  XtSetValues (FRAME_X_TEXT_WIDGET (frm), al, ac);

#ifdef HAVE_TOOLBARS
  /* Setting the background clears the entire frame area
    including the toolbar so we force an immediate redraw of
    it. */
  if (EQ (name, Qbackground))
    MAYBE_DEVMETH (XDEVICE (frm->device), redraw_frame_toolbars, (frm));
#endif /* HAVE_TOOLBARS */

  /* Set window manager resize increment hints according to
     the new character size */
  if (EQ (name, Qfont))
    EmacsFrameRecomputeCellSize (FRAME_X_TEXT_WIDGET (frm));
}

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

void
syms_of_frame_x (void)
{
#ifdef NEW_GC
  INIT_LISP_OBJECT (x_frame);
#endif /* NEW_GC */

  DEFSYMBOL (Qoverride_redirect);
  DEFSYMBOL (Qx_resource_name);

  DEFSUBR (Fx_window_id);
#ifdef HAVE_CDE
  DEFSUBR (Fcde_start_drag_internal);
#endif
}

void
console_type_create_frame_x (void)
{
  /* frame methods */
  CONSOLE_HAS_METHOD (x, init_frame_1);
  CONSOLE_HAS_METHOD (x, init_frame_2);
  CONSOLE_HAS_METHOD (x, init_frame_3);
  CONSOLE_HAS_METHOD (x, mark_frame);
  CONSOLE_HAS_METHOD (x, focus_on_frame);
  CONSOLE_HAS_METHOD (x, delete_frame);
  CONSOLE_HAS_METHOD (x, get_mouse_position);
  CONSOLE_HAS_METHOD (x, set_mouse_position);
  CONSOLE_HAS_METHOD (x, raise_frame);
  CONSOLE_HAS_METHOD (x, lower_frame);
  CONSOLE_HAS_METHOD (x, enable_frame);
  CONSOLE_HAS_METHOD (x, disable_frame);
  CONSOLE_HAS_METHOD (x, make_frame_visible);
  CONSOLE_HAS_METHOD (x, make_frame_invisible);
  CONSOLE_HAS_METHOD (x, iconify_frame);
  CONSOLE_HAS_METHOD (x, set_frame_size);
  CONSOLE_HAS_METHOD (x, set_frame_position);
  CONSOLE_HAS_METHOD (x, frame_property);
  CONSOLE_HAS_METHOD (x, internal_frame_property_p);
  CONSOLE_HAS_METHOD (x, frame_properties);
  CONSOLE_HAS_METHOD (x, set_frame_properties);
  CONSOLE_HAS_METHOD (x, set_title_from_ibyte);
  CONSOLE_HAS_METHOD (x, set_icon_name_from_ibyte);
  CONSOLE_HAS_METHOD (x, frame_visible_p);
  CONSOLE_HAS_METHOD (x, frame_totally_visible_p);
  CONSOLE_HAS_METHOD (x, frame_iconified_p);
  CONSOLE_HAS_METHOD (x, set_frame_pointer);
  CONSOLE_HAS_METHOD (x, set_frame_icon);
  CONSOLE_HAS_METHOD (x, get_frame_parent);
  CONSOLE_HAS_METHOD (x, update_frame_external_traits);
}

void
vars_of_frame_x (void)
{
#ifdef EXTERNAL_WIDGET
  Fprovide (intern ("external-widget"));
#endif

  /* this call uses only safe functions from emacs.c */
  init_x_prop_symbols ();

  DEFVAR_LISP ("default-x-frame-plist", &Vdefault_x_frame_plist /*
Plist of default frame-creation properties for X frames.
These override what is specified in the resource database and in
`default-frame-plist', but are overridden by the arguments to the
particular call to `make-frame'.

Note: In many cases, properties of a frame are available as specifiers
instead of through the frame-properties mechanism.

Here is a list of recognized frame properties, other than those
documented in `set-frame-properties' (they can be queried and
set at any time, except as otherwise noted):

  window-id			The X window ID corresponding to the
				frame.  May be set only at startup, and
				only if external widget support was
				compiled in; doing so causes the frame
				to be created as an "external widget"
				in another program that uses an existing
				window in the program rather than creating
				a new one.
  initially-unmapped		If non-nil, the frame will not be visible
				when it is created.  In this case, you
				need to call `make-frame-visible' to make
				the frame appear.
  popup				If non-nil, it should be a frame, and this
				frame will be created as a "popup" frame
				whose parent is the given frame.  This
				will make the window manager treat the
				frame as a dialog box, which may entail
				doing different things (e.g. not asking
				for positioning, and not iconifying
				separate from its parent).
  override-redirect		If non-nil, the frame will not be subject to
				window-manager control.  In particular, it
				will lack decorations, for more attractive
				appearance of balloon help, aka tooltips.
  inter-line-space		Not currently implemented.
  toolbar-shadow-thickness	Thickness of toolbar shadows.
  background-toolbar-color	Color of toolbar background.
  bottom-toolbar-shadow-color	Color of bottom shadows on toolbars.
				(*Not* specific to the bottom-toolbar.)
  top-toolbar-shadow-color	Color of top shadows on toolbars.
				(*Not* specific to the top-toolbar.)
  internal-border-width		Width of internal border around text area.
  border-width			Width of external border around text area.
  top				Y position (in pixels) of the upper-left
				outermost corner of the frame (i.e. the
				upper-left of the window-manager
				decorations).
  left				X position (in pixels) of the upper-left
				outermost corner of the frame (i.e. the
				upper-left of the window-manager
				decorations).
  border-color			Color of external border around text area.
  cursor-color			Color of text cursor.

See also `default-frame-plist', which specifies properties which apply
to all frames, not just X frames.
*/ );
  Vdefault_x_frame_plist = Qnil;

  x_console_methods->device_specific_frame_props = &Vdefault_x_frame_plist;
}
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.