Source

xlib / lisp / xlib-xlib.el

   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
;;; xlib-xlib.el --- X library part of new xlib.

;; Copyright (C) 2003 by Free Software Foundation, Inc.

;; Author: Eric M. Ludlam <zappo@gnu.ai.mit.edu>
;;	   Zajcev Evgeny <zevlg@yandex.ru>
;; Keywords: xlib, xwem
;; X-CVS: $Id$

;; This file is part of XWEM.

;; XWEM 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.

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

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

;;; Synched up with: Not in FSF

;;; Commentary:

;; 

;;; Code:

;;;###autoload
(defun X-invalidate-cl-struct (cl-x)
  "Invalidate CL-X, after `X-invalidate-cl-struct' it won't be cl struct anymore.
NOTE: works only if CL-X is vector."
  (if (vectorp
       (let ((i (length cl-x)))
	 (while (>= (setq i (1- i)) 0)
	   (aset cl-x i nil))
	 t))
      ))

;;;###autoload
(defun XOpenDisplay (name &optional dispnum screen)
  "Open an X connection to the display named NAME such as host:0.1.
Optionally you may pass DISPNUM - display number and SCREEN - screen number."
  ;; first, open a connection to name
  (when (string-match ":\\([0-9]*\\|[0-9]*\\)\.*\\([0-9]*\\)" name)
    (setq dispnum
	  (or dispnum
	      (truncate (string-to-int (substring name (match-beginning 1) (match-end 1))))))
    (setq screen
	  (or screen
	      (truncate (string-to-int (substring name (match-beginning 2) (match-end 2))))))
    (setq name (substring name 0 (- (match-beginning 1) 1))))

  (when (= (length name) 0)
    (setq name (system-name)))

  (let ((xdpy (X-Dpy-create-connection name dispnum)))
    ;; Connection is open, and X-info contains connection informaion.
    (let ((X-info (X-Dpy-send-read xdpy (X-Create-message X-client-to-open)
				   X-connect-response)))

      (if (null (nth 0 X-info))
	  (message "X: %s" (nth X-info 3))

	(setf (X-Dpy-proto-maj xdpy) (nth 1 X-info))
	(setf (X-Dpy-proto-min xdpy) (nth 2 X-info))
	(setf (X-Dpy-resource-base xdpy) (nth 4 X-info))
	(setf (X-Dpy-resource-mask xdpy) (nth 5 X-info))
	(setf (X-Dpy-motion-bufsize xdpy) (nth 6 X-info))
	(setf (X-Dpy-max-request-size xdpy) (nth 7 X-info))
	(setf (X-Dpy-byte-order xdpy) (nth 8 X-info))
	(setf (X-Dpy-bitmap-scanline-unit xdpy) (nth 9 X-info))
	(setf (X-Dpy-bitmap-scanline-pad xdpy) (nth 10 X-info))
	(setf (X-Dpy-bitmap-bit-order xdpy) (nth 11 X-info))
	(setf (X-Dpy-min-keycode xdpy) (nth 12 X-info))
	(setf (X-Dpy-max-keycode xdpy) (nth 13 X-info))
	(setf (X-Dpy-vendor xdpy) (nth 14 X-info))

	;; Fill formats list
	(setf (X-Dpy-formats xdpy)
	      (mapcar (lambda (fmt)
			(make-X-ScreenFormat :depth (nth 0 fmt)
					     :bits-per-pixel (nth 1 fmt)
					     :scanline-pad (nth 2 fmt)))
		      (nth 15 X-info)))

	;; Fill screens list
	(setf (X-Dpy-screens xdpy)
	      (mapcar (lambda (scr)
			(let (nscreen)
			  (setq nscreen (make-X-Screen :root (X-Win-find-or-make xdpy (nth 0 scr))
						       :colormap (make-X-Colormap :dpy xdpy :id (nth 1 scr))
						       :white-pixel (make-X-Color :dpy xdpy :id (nth 2 scr))
						       :black-pixel (make-X-Color :dpy xdpy :id (nth 3 scr))
						       :root-event-mask (nth 4 scr)
						       :width (nth 5 scr)
						       :height (nth 6 scr)
						       :mwidth (nth 7 scr)
						       :mheight (nth 8 scr)
						       :min-maps (nth 9 scr)
						       :max-maps (nth 10 scr)
						       :visualid (nth 11 scr)
						       :backingstores (nth 12 scr)
						       :save-unders (nth 13 scr)
						       :root-depth (nth 14 scr)))

			  (setf (X-Screen-depths nscreen)
				(mapcar (lambda (dpth)
					  (make-X-Depth :depth (nth 0 dpth)
							:visuals (mapcar (lambda (vis)
									   (make-X-Visual :id (nth 0 vis)
											  :class (nth 1 vis)
											  :bits-per-rgb (nth 2 vis)
											  :cmap-entries (nth 3 vis)
											  :red-mask (nth 4 vis)
											  :green-mask (nth 6 vis)
											  :blue-mask (nth 5 vis)))
									 (nth 1 dpth))))
					(nth 15 scr)))

			  ;; Create default GC
			  (setf (X-Screen-default-gc nscreen)
				(XCreateGC xdpy (X-Screen-root nscreen)
					   (make-X-Gc :dpy xdpy :id (X-Dpy-get-id xdpy)
						      :foreground (X-Screen-white-pixel nscreen)
						      :background (X-Screen-black-pixel nscreen))))
			  nscreen))
		      (nth 16 X-info)))

	;; Alert user
	(message "Connection opened to %s...done" name)
	xdpy))))

;;;###autoload
(defun XCloseDisplay (xdpy)
  "Close the connection to display XDPY."
  (X-Dpy-close xdpy))

;;;###autoload
(defun XScreenCheck (xdpy scrnum)
  "Check SCRNUM screen on display XDPY."
  (unless scrnum
    (setq scrnum 0))

  (when (> scrnum (1- (length (X-Dpy-screens xdpy))))
    (error (format "screen with number %d does not exists." scrnum)))
  scrnum)
  
;;;###autoload
(defsubst XDefaultRootWindow (xdpy &optional scrnum)
  "Return default root window on XDPY."
  (X-Dpy-p xdpy 'XDefaultRootWindow)

  (X-Screen-root (nth (XScreenCheck xdpy scrnum) (X-Dpy-screens xdpy))))

;;;###autoload
(defsubst XWhitePixel (xdpy &optional scrnum)
  "Return white pixel for display XDPY."
  (X-Dpy-p xdpy 'XWhitePixel)
  
  (X-Screen-white-pixel (nth (XScreenCheck xdpy scrnum) (X-Dpy-screens xdpy))))

;;;###autoload
(defsubst XBlackPixel (xdpy &optional scrnum)
  "Return black pixel for display XDPY."
  (X-Dpy-p xdpy 'XBlackPixel)
  
  (X-Screen-black-pixel (nth (XScreenCheck xdpy scrnum) (X-Dpy-screens xdpy))))

;;;###autoload
(defsubst XDefaultColormap (xdpy &optional scrnum)
  "Return default colormap for XDPY on screen SCRNUM."
  (X-Dpy-p xdpy 'XDefaultColormap)

  (X-Screen-colormap (nth (XScreenCheck xdpy scrnum) (X-Dpy-screens xdpy))))

;;;###autoload
(defsubst XDefaultVisual (xdpy &optional scrnum)
  "Return visual on XDPY and SCRNUM."
  (X-Dpy-p xdpy 'XDefaultVisual)

  (X-Screen-visualid (nth (XScreenCheck xdpy scrnum) (X-Dpy-screens xdpy))))

;;;###autoload
(defsubst XDefaultGC (xdpy &optional scrnum)
  "Return default GC on XDPY and SCRNUM."
  (X-Dpy-p xdpy 'XDefaultGC)

  (X-Screen-default-gc (nth (XScreenCheck xdpy scrnum) (X-Dpy-screens xdpy))))

;;;###autoload
(defsubst XDefaultDepth (xdpy &optional scrnum)
  "Return default depth on XDPY and screen SCRNUM."
  (X-Dpy-p xdpy 'XDefaultDepth)

  (X-Depth-depth (car (X-Screen-depths (nth (XScreenCheck xdpy scrnum) (X-Dpy-screens xdpy))))))

;;; Simple Noise
;;;###autoload
(defun XBell (xdpy percent)
  "Ring the bell on XDPY at PERCENT volume."
  (X-Dpy-p xdpy 'XBell)
  (let ((ListOfFields
	 (list [1 104]			;opcode
	       [1 percent]		;percentage
	       [2 1])))			;length of request (in 4s)
    (X-Dpy-send xdpy (X-Create-message ListOfFields))))


;;;###autoload
(defun XCreateWindow (xdpy &optional parent x y width height
			    border-width depth class visual
			    attrs)
  "Create a window."
  (X-Dpy-p xdpy 'XCreateWindow)

  (let* ((wid (X-Dpy-get-id xdpy))
	 (attrmsg (X-Attr-message attrs))
	 (ListOfFields
	  (list [1 1]			;create window opcode
		[1 (if depth depth X-CopyFromParent)] ;depth
		[2 (+ 7 (/ (length attrmsg) 4))] ;8 means no attributes yet
		[4 wid]			;newly alloced wid.
		[4 (X-Win-id
		    (if (X-Win-p parent) parent	;the parent
		      (XDefaultRootWindow xdpy))) ]
		[2 (if x x 100)]	;x position
		[2 (if y y 100)]	;y position
		[2 (if width width 100)] ;width
		[2 (if height height 100)] ;height
		[2 (if border-width border-width 5)] ;border width
		[2 (if class class X-CopyFromParent)] ;class
		[4 (if visual visual X-CopyFromParent)] ;visual
		))
	 (msg (concat (X-Create-message ListOfFields)
		      attrmsg)))
    (X-Dpy-send xdpy msg)
    (X-Win-find-or-make xdpy wid)))

;;;###autoload
(defun XChangeWindowAttributes (xdpy win attrs)
  "On XDPY and window WIN, change to the ATTRIBUTES."
  (X-Dpy-p xdpy 'XChangeWindowAttributes)
  (X-Attr-p attrs 'XChangeWindowAttributes)
  (X-Win-p win 'XChangeWindowAttributes)

  (let* ((attrmsg (X-Attr-message attrs))
	 (ListOfFields
	  (list [1 2]			;opcode
		[1 nil]			;unused
		[2 (+ 2 (/ (length attrmsg) 4))] ;length
		[4 (X-Win-id win)]))	;window
	 (msg (concat (X-Create-message ListOfFields) attrmsg)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XSelectInput (xdpy win event)
  "On display XDPY for window WIN, set the EVENT mask."
  (XChangeWindowAttributes xdpy win (make-X-Attr :event-mask event)))

;;;###autoload
(defun XSetWindowBackground (xdpy win pixel)
  "On display XDPY for window WIN, set the background to PIXEL."
  (XChangeWindowAttributes xdpy win (make-X-Attr :background-pixel pixel)))

;(defun X-SetWindowForeground (xdpy win pixel)
;  "On display XDPY for window WIN, set the foreground to PIXEL."
;  (XChangeWindowAttributes xdpy win (make-X-Attr :foreground-pixel pixel)))
  
;;;###autoload
(defun XSetWindowBorder (xdpy win pixel)
  "On display XDPY for window WIN, set the border color to PIXEL."
  (XChangeWindowAttributes xdpy win (make-X-Attr :border-pixel pixel)))

;;;###autoload
(defun XSetWindowColormap (xdpy win cmap-id)
  "On display XDPY for window WIN, set the colormap to CMAP-ID."
  (XChangeWindowAttributes xdpy win (make-X-Attr :colormap cmap-id)))

;;;###autoload
(defun XGetWindowAttributes (xdpy win)
  "On display XDPY, get window's WIN attributes as an `X-Attr'."
  (X-Dpy-p xdpy 'XGetWindowAttributes)
  (X-Win-p win 'XGetWindowAttributes)

  (let ((ListOfFields
	 (list [ 1 3 ]			;opcode
	       [ 1 nil ]		;unused
	       [ 2 2 ]			;request length
	       [ 4 (X-Win-id win)]))	;the window
	(ReceiveFields
	 (list [1 success ]		;status
	       nil			;generic bad response
	       (list
;		[ 1 integerp ]		;reply
		[ 1 integerp ]		;backingstore
		[ 2 integerp ]		;sequence number
		[ 4 integerp ]		;reply length
		[ 4 integerp ]		;visual id
		[ 2 integerp ]		;class
		[ 1 integerp ]		;bit gravity
		[ 1 integerp ]		;win gravity
		[ 4 integerp ]		;backing planes
		[ 4 integerp ]		;backing pixel
		[ 1 integerp ]		;save under
		[ 1 integerp ]		;map is installed
		[ 1 integerp ]		;map state
		[ 1 integerp ]		;override-redirect
		[ 4 integerp ]		;colormap
		[ 4 integerp ]		;all event masks
		[ 4 integerp ]		;my event masks
		[ 2 integerp ]		;do not propagate mask
		[ 2 nil ] )))		;pad
	(r nil))

    (setq r (X-Dpy-send-read xdpy (X-Create-message ListOfFields) ReceiveFields))
    (if (not (car r))
	nil
      (make-X-Attr :backing-store (nth 1 r)
		   :visualid (nth 4 r)
		   :bit-gravity (nth 6 r)
		   :win-gravity (nth 7 r)
		   :backing-planes (nth 8 r)
		   :backing-pixel (nth 9 r)
		   :save-under (if (= (nth 10 r) 0) nil t)
		   :mapstate (nth 12 r)
		   :override-redirect (if (= (nth 13 r) 0) nil t)
		   :colormap (make-X-Colormap :dpy xdpy :id (nth 14 r))
		   :event-mask (nth 16 r)
		   :do-not-propagate-mask (nth 17 r)))))

;;;###autoload
(defun XConfigureWindow (xdpy win conf)
  "On display XDPY, change window WIN to have configuration CONF.
CONF is an `X-Conf' structure."
  (X-Dpy-p xdpy 'XConfigureWindow)
  (X-Conf-p conf 'XConfigureWindow)
  (X-Win-p win 'XConfigureWindow)

  (let* ((cfgmsg (X-Conf-message conf))
	 (ListOfFields
	  (list [1 12]			;opcode
		[1 nil]			;unused
		[2 (+ 2 (/ (length cfgmsg) 4))]	;length
		[4 (X-Win-id win)]))	;window
	 (msg (concat (X-Create-message ListOfFields) cfgmsg)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XLowerWindow (xdpy win)
  "On display XDPY, lower window WIN."
  (XConfigureWindow xdpy win (make-X-Conf :stackmode X-Below))) 

;;;###autoload
(defun XRaiseWindow (xdpy win)
  "On display XDPY, raise window WIN."
  (XConfigureWindow xdpy win (make-X-Conf :stackmode X-Above)))

;;;###autoload
(defun XMoveWindow (xdpy win x y)
  "On display XDPY, move window WIN to position X Y."
  (XConfigureWindow xdpy win (make-X-Conf :x x :y y)))

;;;###autoload
(defun XResizeWindow (xdpy win w h)
  "On display XDPY, resize window WIN to dimentions W H."
  (XConfigureWindow xdpy win (make-X-Conf :width w :height h))) 

;;;###autoload
(defun XMoveResizeWindow (xdpy win x y w h)
  "On display XDPY, move and resize window WIN to X, Y, W, H."
  (XConfigureWindow xdpy win (make-X-Conf :x x :y y :width w :height h)))

;;;###autoload
(defun XSetWindowBorderWidth (xdpy win width)
  "On display XDPY, set window's WIN border to be WIDTH pixels wide."
  (XConfigureWindow xdpy win (make-X-Conf :border-width width)))

;;;###autoload
(defun XMapWindow (xdpy win)
  "On display XDPY, map WIN to the screen (to make it visible.)."
  (X-Dpy-p xdpy 'XMapWindow)
  (X-Win-p win 'XMapWindow)

  (let ((ListOfFields
	 (list [1 8]			;opcode
	       [1 nil]			;unused
	       [2 2]			;length of request (in 4s)
	       [4 (X-Win-id win)])))	;window to map
    (X-Dpy-send xdpy (X-Create-message ListOfFields))))

;;;###autoload
(defun XUnmapWindow (xdpy win)
  "On display XDPY, unmap window WIN to make it hidden."
  (X-Dpy-p xdpy 'XUnmapWindow)
  (X-Win-p win 'XUnmapWindow)

  (let ((ListOfFields
	 (list [1 10]			;opcode
	       [1 nil]			;unused
	       [2 2]			;length of request (in 4s)
	       [4 (X-Win-id win)])))	;window to map
    (X-Dpy-send xdpy (X-Create-message ListOfFields))))

;;;###autoload
(defun XDestroyWindow (xdpy win)
  "On display XDPY, destroy window WIN."
  (X-Dpy-p xdpy 'XDestroyWindow)
  (X-Win-p win 'XDestroyWindow)

  (let ((ListOfFields
	 (list [1 4]			;opcode
	       [1 nil]			;unused
	       [2 2]			;length of request (in 4s)
	       [4 (X-Win-id win)])))	;window to map
    (X-Dpy-send xdpy (X-Create-message ListOfFields))
    ;; We don't invalidate windows because of DestroyNotify events.
    ))

;;;###autoload
(defun XDestroySubwindows (xdpy win)
  "On display XDPY, destroy subwindows of window WIN."
  (X-Dpy-p xdpy 'XDestroySubwindows)
  (X-Win-p win 'XDestroySubwindows)

  (let ((ListOfFields
	 (list [1 5]			;opcode
	       [1 nil]			;unused
	       [2 2]			;length of request (in 4s)
	       [4 (X-Win-id win)])))	;window to map
    (X-Dpy-send xdpy (X-Create-message ListOfFields))))

;;;###autoload
(defun XQueryTree (xdpy win)
  "Query display XDPY for all children of window WIN.
Returns a list of the form (ROOT PARENT CHILD1 CHILD2 ...)
on success, or nil on failure.  ROOT is the root window for the display that
WINDOW is on.  PARENT is the parent of WINDOW, and CHILDN are the
children of WINDOW."
  (X-Dpy-p xdpy 'XQueryTree)
  (X-Win-p win 'XQueryTree)

  (let* ((ListOfFields
	  (list [ 1 15 ]		;opcode
		[ 1 nil ]		;unused
		[ 2 2 ]			;request length
		[ 4 (X-Win-id win)]))	;window we are querying.
	 (ReceiveFields
	  (list [ 1 success]		;status
		nil			;generic bad response
		(list [ 1 nil]		;unused
		      [ 2 integerp ]	;sequence number
		      [ 4 length-1 ]	;length of the return in 4 blocks
		      [ 4 :X-Win ]	;root window
		      [ 4 :X-Win ]	;parent window
		      [ 2 length-2 ]	;number of children
		      [ 14 nil ]	;unused
		      [ (* 4 length-2) :X-Win])))) ;list of the children

    (X-Dpy-send-read xdpy (X-Create-message ListOfFields) ReceiveFields)))


;;; Time to play with properties and Atoms
;;
;;;###autoload
(defun XInternAtom (xdpy name only-if-exists)
  "On display XDPY, return the Atom with NAME.
If ONLY-IF-EXISTS is nil, then the atom is created if it does not already
exist.  The Atom object is returned."
  (X-Dpy-p xdpy 'XInternAtom)
  (if (not (stringp name))
      (signal 'wrong-type-argument (list 'signal 'stringp name)))

  (let ((a (X-Atom-find-by-name xdpy name)))
    (if (X-Atom-p a)
	a
      (let ((ListOfFields
	     (list [1 16]		;opcode
		   [1 only-if-exists]	;forcecreate flag.
		   [2 (+ 2 (X-padlen name))] ;message length
		   [2 (length name)]	;name length
		   [2 nil]		;unused
		   [(length name) name] ;name
		   ;; Auto-padded
		   ))
	    (ReceiveFields
	     (list [1 success]		;status message
		   nil			;generic bad response
		   (list [1 nil]	;unused
			 [2 integerp]   ;sequence
			 [4 nil]	;reply length
			 [4 :X-Atom]    ;atom id
			 [20 nil])))
	    r)

	(setq r (X-Dpy-send-read xdpy (X-Create-message ListOfFields) ReceiveFields))
	(if (car r)
	    (let ((rat (nth 2 r)))
	      (setf (X-Atom-name rat) name)
	      (X-Atom-insert xdpy rat)
	      rat)
	  nil)))))

;;;###autoload
(defun XGetAtomName (xdpy atom)
  "On display XDPY, get the textual name of ATOM.
*UNTESTED*"
  (X-Dpy-p xdpy 'XGetAtomName)
  (X-Atom-p atom 'XGetAtomName)

  (let ((a (X-Atom-find xdpy (X-Atom-id atom))))
    (if (X-Atom-p a)
	a
      (let ((ListOfFields
	     (list [ 1 17 ]		;opcode
		   [ 1 nil ]		;unused
		   [ 2 2 ]		;length
		   [ 4 (X-Atom-id atom) ])) ;atom id
	    (ReceiveFields
	     (list
	      [1 success ]		;status message
	      nil			;generic bad response
	      (list [ 1 nil ]		;unused
		    [ 2 integerp ]	;sequence
		    [ 4 length-1 ]	;reply length
		    [ 2 length-2 ]	;length of name
		    [ 22 nil ]		;unused
		    [ length-2 stringp ] ;the name
		    [ (X-pad length-2) nil ] ;padding
		    )))
	    r)
	(setq r (X-Dpy-send-read xdpy (X-Create-message ListOfFields) ReceiveFields))
	(if (car r)
	    (progn
	      (setf (X-Atom-name atom) (nth 2 r))
	      (X-Atom-insert xdpy atom)
	      (nth 2 r))
	  nil)))))

;;;###autoload
(defun XChangeProperty (xdpy win property type format mode data)
  "On display XDPY for window WIN, change PROPERTY.
PROPERTY is changed based on a TYPE, FORMAT, and MODE with DATA.
There are NElements."
  (X-Dpy-p xdpy 'XChangeProperty)
  (X-Win-p win 'XChangeProperty)
  (X-Atom-p property 'XChangeProperty)
  (X-Atom-p type 'XChangeProperty)

  (let* ((n (* (length data) (/ format 8)))
	 (p (X-pad n))
	 (ListOfFields
	  (list [1 18]			;opcode
		[1 mode]		;Mode: Replace Prepend, Append
		(vector 2 (+ 6 (/ (+ n p) 4)))	;length, shut up compiler
		[4 (X-Win-id win)]	;window
		[4 (X-Atom-id property)] ;property atom
		[4 (X-Atom-id type)]	;property type
		[1 format]		;property format
		[3 nil]
		[4 (/ n (/ format 8))]	;length of the list-byte thing
		)))
    (if (and (= format 8) (stringp data))
	(setq ListOfFields
	      (append ListOfFields (list (vector (length data) data))))
      (while data
	(let ((d (if (X-Generic-struct-p (car data))
		     (funcall (X-Generic-struct-p (car data)) (car data))
		   (car data))))
	  (setq ListOfFields
		(append ListOfFields (list (vector (/ format 8) d )))
		data (cdr data)))))
    (X-Dpy-send xdpy (X-Create-message ListOfFields))))

;; These are Xlib convenience routines
;;
;;;###autoload
(defun XSetWMProtocols (xdpy win protocol_atoms)
  "On display XDPY, set window's WIN protocols to PROTOCOL_ATOMS.
Convenience routine which calls `XChangeProperty'"
  (XChangeProperty xdpy win (XInternAtom xdpy "WM_PROTOCOLS" nil)
		    XA-atom X-format-32 X-PropModeReplace protocol_atoms))

;;;###autoload
(defun XSetWMClass (xdpy win wm-class)
  "On displayX DPY, set window's WIN Class to WM-CLASS.
WM-CLASS should be in form '(class-name class-intance)."
  (XChangeProperty xdpy win XA-wm-class XA-string X-format-8 X-PropModeReplace
		    (concat (car wm-class) (string 0) (cadr wm-class) (string 0))))

;;;###autoload
(defun XSetWMName (xdpy win wm-name)
  (XChangeProperty xdpy win XA-wm-name XA-string X-format-8 X-PropModeReplace
		    (concat wm-name)))

;;;###autoload
(defun XSetWMNormalHints (xdpy win wmnh)
  "On display XDPY, set window's WIN normal hints to HINTS.
HINTS is list in format (x1 x2 ... x18)."
  (X-WMSize-p wmnh 'XSetWMNormalHints)

  (let ((pplist (list (X-WMSize-flags wmnh) 0
		      (X-WMSize-x wmnh)
		      (X-WMSize-y wmnh)
		      (X-WMSize-width wmnh)
		      (X-WMSize-height wmnh)
		      (X-WMSize-min-width wmnh)
		      (X-WMSize-min-height wmnh)
		      (X-WMSize-max-width wmnh)
		      (X-WMSize-max-height wmnh)
		      (X-WMSize-width-inc wmnh)
		      (X-WMSize-height-inc wmnh)
		      (X-WMSize-min-aspect-x wmnh)
		      (X-WMSize-min-aspect-y wmnh)
		      (X-WMSize-max-aspect-x wmnh)
		      (X-WMSize-max-aspect-y wmnh)
		      (X-WMSize-base-width wmnh)
		      (X-WMSize-base-height wmnh)
		      (X-WMSize-gravity wmnh))))
		      
    (XChangeProperty xdpy win XA-wm-normal-hints XA-wm-size-hints X-format-32 X-PropModeReplace pplist)))

;;;###autoload
(defun XSetWMState (xdpy win wm-state &optional icon-id)
  "On display XDPY, set window's WIN state to WM-STATE.
WM-STATE is one of `X-WithdrawnState', `X-NormalState' or `X-IconicState'."
  (let ((wmsa (XInternAtom xdpy "WM_STATE" nil)))
    (XChangeProperty xdpy win wmsa wmsa X-format-32 X-PropModeReplace (list wm-state (or icon-id 0.0)))))

;;;###autoload
(defun XSetWMCommand (xdpy win cmd)
  "On display XDPY set window's WIN WM_COMMAND property to CMD."
  
  (XChangeProperty xdpy win (XInternAtom xdpy "WM_COMMAND" nil) XA-string
		   X-format-8 X-PropModeReplace cmd))

;;;###autoload
(defun XGetWindowProperty (xdpy win property &optional offset length delete required-type)
  "On display XDPY, get window's WIN PROPERTY atom value.
Get the data from optional OFFSET, and a maximum of LENGTH bytes.
OFFSET and LENGTH refer to 32 bit chunks, not 8 bit chunks.
Third optional argument DELETE will delete the property if Non-nil.
Fourth argument REQUIRED-TYPE filters only properties of the desired type.
If REQUIRED-TYPE is `XA-AnyPropertyType', or nil then no filtering is done.
The returned list is of the form:
  (TYPE_RETURN BYTES_AFTER PROP1 PROP2 ...)
Where TYPE_RETURN is the type (of same for as REQUIRED-TYPE) is the actual
type of the data being returned.
FORMAT_RETURN is the format of the data (such as 8, 16, or 32).
BYTES_AFTER is the number of bytes still attached to the property.
If there are extra bytes, then a second call to `XGetWindowProperty' will
be needed.  Lastly, PROP1 through PROPN is the list of properties
originally requested.
  It is common to call `XGetWindowProperty' asking for no data so that
BYTES_AFTER contains the exact amount of data we want to request."
  (X-Dpy-p xdpy 'XGetWindowProperty)
  (X-Win-p win 'XGetWindowProperty)
  (X-Atom-p property 'XGetWindowProperty)

  (unless offset (setq offset 0))
  (unless length (setq length 1024))
  (unless required-type (setq required-type XA-AnyPropertyType))

  (let ((ListOfFields
	 (list [ 1 20]			;opcode
	       [ 1 (if delete 1 0)]	;delete flag
	       [ 2 6 ]			;request length
	       [ 4 (X-Win-id win) ]	;the window whose property we want
	       [ 4 (X-Atom-id property) ] ;The property atom we want
	       [ 4 (X-Atom-id required-type) ] ;required type filter.
	       [ 4 offset ]		;offset in the property data
	       [ 4 length ]))		;length of data we want
	(ReceiveFields
	 (list [1 success]		;status message
	       nil			;generic bad response
	       (list
		[ 1 length-1 ]		;format of returned data
		[ 2 integerp ]		;sequence number
		[ 4 length-3 ]		;length of this request
		[ 4 integerp ]		;atom representing return type
		[ 4 integerp ]		;bytes left on server
		[ 4 length-2 ]		;length of value in format units
		[ 12 nil ]		;unused
		[ (if (= length-1 0)
		      0
		    (if (member required-type (list XA-atom XA-window XA-rectangle))
			;; known type
			(* length-2 (/ length-1 8))
		      length-2))

		  (cond ((or (= length-1 8) (eq required-type XA-string))
			 'stringp)

			((eq required-type XA-atom)
			 :X-Atom)
			
			((eq required-type XA-window)
			 :X-Win)

			((eq required-type XA-rectangle)
			 :X-Rect)

			(t '([(/ length-1 8) integerp])))]
		[ (X-pad (* length-2 (/ length-1 8))) nil ]
		)))
	(r nil)
	(proplist nil))

    (setq r (X-Dpy-send-read xdpy (X-Create-message ListOfFields) ReceiveFields))
    (if (null (car r))
	nil				;oops

      (setq proplist (list (nth 2 r) (nth 1 r))) ; start backwards
      (if (listp (nth 4 r))
	  (setq r (nth 4 r))
	(setq r (nthcdr 4 r)))

      (if (stringp r)
	  (setq proplist (cons r proplist))

	(while r
	  (let ((item (car r)))
	    (when (listp item)
	      (setq item (car item)))
	      
	  (setq proplist (cons item proplist)
		r (cdr r)))))
      (nreverse proplist))))

;; A few functions based on GetProperty
;;;###autoload
(defun XGetWMName (xdpy win)
  "On display XDPY, get window's WIN name."
  (let ((propdata
	 (XGetWindowProperty xdpy win XA-wm-name 0 1024 nil XA-string))
	(pd2 nil)
	(name ""))
    (if (and propdata (nth 2 propdata))
	(progn
	  (setq name (nth 2 propdata))
	  (if (< (nth 1 propdata) 0.0)
	      (setq pd2 (XGetWindowProperty xdpy win XA-wm-name 1024
					     (nth 1 propdata) nil XA-string)))
	  (if pd2 (setq name (concat name (nth 2 pd2))))))
    name))

;;;###autoload
(defun XGetWMHints (xdpy win)
  "On display XDPY, get window's WIN WM_HINTS."
  (let ((wmh (cdr (XGetWindowProperty xdpy win XA-wm-hints 0 1024 nil XA-wm-hints))))
    (when wmh
      (make-X-WMHints :flags (nth 0 wmh)
		      :input (nth 1 wmh)
		      :initial-state (nth 2 wmh)
		      :icon-pixmap (nth 3 wmh)
		      :icon-window (nth 4 wmh)
		      :icon-x (nth 5 wmh)
		      :icon-y (nth 6 wmh)
		      :icon-mask (nth 7 wmh)
		      :window-group (nth 8 wmh)))))

;;;###autoload
(defun XGetWMNormalHints (xdpy win)
  "On display XDPY, get normal hints for WIN."
  (let ((wmnh (cdr (XGetWindowProperty xdpy win XA-wm-normal-hints 0 40 nil XA-wm-size-hints))))
    (when (and wmnh (= (car wmnh) (X-Atom-id XA-wm-size-hints)))
      (make-X-WMSize :flags (Xtruncate (nth 1 wmnh))
		     :x (Xtruncate (nth 2 wmnh))
		     :y (Xtruncate (nth 3 wmnh))
		     :width (Xtruncate (nth 4 wmnh))
		     :height (Xtruncate (nth 5 wmnh))

		     :min-width (Xtruncate (nth 6 wmnh))
		     :min-height (Xtruncate (nth 7 wmnh))
		     :max-width (Xtruncate (nth 8 wmnh))
		     :max-height (Xtruncate (nth 9 wmnh))
		     :width-inc (Xtruncate (nth 10 wmnh))
		     :height-inc (Xtruncate (nth 11 wmnh))
		     :min-aspect-x (Xtruncate (nth 12 wmnh))
		     :min-aspect-y (Xtruncate (nth 13 wmnh))
		     :max-aspect-x (Xtruncate (nth 14 wmnh))
		     :max-aspect-y (Xtruncate (nth 15 wmnh))
		     :base-width (Xtruncate (nth 16 wmnh))
		     :base-height (Xtruncate (nth 17 wmnh))
		     :gravity (Xtruncate (nth 18 wmnh))))))

;;;###autoload
(defun XGetWMCommand (xdpy win)
  "On display XDPY, get window's WIN WM_COMMAND."
  ;; XXX
  (let ((data (XGetWindowProperty xdpy win XA-wm-command 0 1024 nil XA-string))
	(ret ""))
    (when (and data (nth 2 data))
      (setq ret (nth 2 data)))
    (if (> (length ret) 0)
	(replace-in-string (substring ret 0 (1- (length ret))) (string 0) " ")
      ret)))

;;;###autoload
(defun XGetWMClass (xdpy win)
  "On display XDPY, get window's WIN WM_CLASS."
  ;; XXX
  (let ((data (XGetWindowProperty xdpy win XA-wm-class 0 1024 nil XA-string))
	(class nil))
    (when (and data (nth 2 data))
      (setq class
	    (split-string (nth 2 data) (string 0))))
    class))

;;;###autoload
(defun XGetWMClientLeader (xdpy win)
  "Get window property for WM_CLIENT_LEADER atom."
  nil)

;;;###autoload
(defun XGetWMTransientFor (xdpy win)
  "Get WM_TRANSIENT_FOR property.
Returns list in form `(seq val window-for-wich-win-is-trasient)'."
  (let ((awid (cdr (XGetWindowProperty xdpy win XA-wm-transient-for 0 1 nil XA-window))))
    (when (and awid (= (car awid) (X-Atom-id XA-window)))
      (cadr awid))))

;;;###autoload
(defun XGetWMState (xdpy win)
  "On display XDPY get WM_STATE property for WIN."
  (let ((wmsa (XInternAtom xdpy "WM_STATE" t)))
    (cdr (XGetWindowProperty xdpy win wmsa 0 2 wmsa))))

;;;###autoload
(defun XGetWMProtocols (xdpy win)
  "On display XDPY get WM_PROTOCOLS property for WIN."
  (cdr (XGetWindowProperty xdpy win  (XInternAtom xdpy "WM_PROTOCOLS" nil) 0 1024 nil XA-atom)))

;;;###autoload
(defun XWMProtocol-set-p (xdpy wmprotos name)
  "Return non-nil when atom with NAME is in WM_PROTOCOLS WMPROTO."
;  (while wmprotos
    (let ((at (XInternAtom xdpy name t)))
      (member at wmprotos)))
;      (when (and (X-Atom-p at)
;		 (= (car wmprotos) (X-Atom-id at)))
;	(setq name nil)
;	(setq wmprotos nil)))
;    (setq wmprotos (cdr wmprotos)))
;  (not name))

;;; Colormaps
;;;###autoload
(defun XCreateColormap (xdpy win &optional v alloc)
  ;; checkdoc-params: (v alloc)
  "Create a colormap. Default values are:

VISUAL    - CopyFromParent
ALLOCATE  - All are writable (1) (0 -> none writable)

args (XDPY WIN &optional VISUAL ALLOCTE)"
  (X-Dpy-p xdpy 'XCreateColormap)
  (X-Win-p win 'XCreateColormap)

  (unless v
    (setq v (XDefaultVisual xdpy)))
  (unless alloc
    (setq alloc X-AllocAll))

  (let* ((ncmap (make-X-Colormap :dpy xdpy :id (X-Dpy-get-id xdpy)))
	 (ListOfFields
	  (list [1 78]			; opcode
		[1 alloc]		; alloc type
		[2 4]			; length
		[4 (X-Colormap-id ncmap)] ; id to use
		[4 (X-Win-id win)]	; window id
		[4 v]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)
    ncmap))

;;;###autoload
(defun XFreeColormap (xdpy cmap)
  "Frees a colormap CMAP.
args (XDPY CMAP)"
  (X-Dpy-p xdpy 'XFreeColormap)
  (X-Colormap-p cmap 'XFreeColormap)

  (let* ((ListOfFields
	  (list [1 79]			; opcode
		[1 nil]
		[2 2]			; length
		[4 (X-Colormap-id cmap)])) ; id to use
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)

    ;; Invalidate cmap structure so noone will longer use
    (X-invalidate-cl-struct cmap)
    ))

;;;###autoload
(defun XAllocColor (xdpy cmap color)
  "On display XDPY allocate in CMAP the color struct COLOR.
Use `X-Color' to create.
Returns non-nil if successful."
  (X-Dpy-p xdpy 'XAllocColor)
  (X-Colormap-p cmap 'XAllocColor)
  (X-Color-p color 'XAllocColor)

  (let ((col (X-Colormap-lookup-by-rgb cmap color)))
    (if (X-Color-p col)
	col

      (let* ((ListOfFields
	      (list [1 84]		; opcode
		    [1 nil]		; unused
		    [2 4]		; request length
		    [4 (X-Colormap-id cmap)] ; colormap handle
		    [2 (X-Color-red color)] ; red
		    [2 (X-Color-green color)] ; green
		    [2 (X-Color-blue color)] ; blue
		    [2 nil]))		; padding
	     (msg (X-Create-message ListOfFields))
	     (ReceiveFields
	      (list [1 success]		; status message
		    nil			; generic bad response
		    (list [1 nil]	; unused
			  [2 integerp]	; sequence
			  [4 nil]	; reply length
			  [2 integerp]	; red
			  [2 integerp]	; green
			  [2 integerp]	; blue
			  [2 nil]	; unused
			  [4 integerp]	; pixel value
			  [12 nil])))	; padding
	     r)
	(setq r (X-Dpy-send-read xdpy msg ReceiveFields))

	(if (car r)
	    (progn
	      (setf (X-Color-id color) (nth 5 r))
	      (setf (X-Color-red color) (nth 2 r))
	      (setf (X-Color-green color) (nth 3 r))
	      (setf (X-Color-blue color) (nth 4 r))
	      (setf (X-Color-cmap color) cmap)
	  
	      (pushnew color (X-Colormap-colors cmap)) ; cache color
	      color)
	  nil)))))

;;;###autoload
(defun XAllocNamedColor (xdpy cmap name &optional color-exact)
  "Allocate a color based on the color struct COLOR-VISUAL and COLOR-EXACT.
If COLOR-EXACT is nil or absent, ignore.
args (DISPLAY CMAP NAME COLOR-VISUAL &optional COLOR-EXACT)"
  ;; checkdoc-order: nil
  (X-Dpy-p xdpy 'XAllocNamedColor)
  (X-Colormap-p cmap 'XAllocNamedColor)

  (when color-exact
    (X-Color-p color-exact 'XAllocNamedColor))

  (let ((col (X-Colormap-lookup-by-name cmap name)))
    (if (X-Color-p col)
        col

      (let* ((ListOfFields
              (list [1 85]              ;opcode
                    [1 nil]
                    [2 (+ 3 (X-padlen name))] ;length
                    [4 (X-Colormap-id cmap)] ;colormap
                    [2 (length name)]	;length of name
                    [2 nil]             ;unused
                    [(length name) name] ;the name
                    ));; autopadded
             (msg (X-Create-message ListOfFields))
             (ReceiveFields
              (list [1 success]		;success field
                    nil
                    (list [1 nil]       ;unused
                          [2 integerp]	;sequence
                          [4 nil]       ;length
                          [4 integerp]	;pixel id
                          [2 integerp]	;exact red
                          [2 integerp]	;exact green
                          [2 integerp]	;exact blue
                          [2 integerp]	;visual red
                          [2 integerp]	;visual green
                          [2 integerp]	;visual blue
                          [8 nil])))	;padding
             r)
        (setq r (X-Dpy-send-read xdpy msg ReceiveFields))
    
        (if (car r)
            (progn
              (setq col (make-X-Color :dpy xdpy
                                      :id (nth 2 r)
                                      :red (nth 6 r)
                                      :green (nth 7 r)
                                      :blue (nth 8 r)
                                      :name name
                                      :cmap cmap))

              (when color-exact
                (setf (X-Color-id color-exact) (nth 2 r))
                (setf (X-Color-red color-exact) (nth 3 r))
                (setf (X-Color-green color-exact) (nth 4 r))
                (setf (X-Color-blue color-exact) (nth 5 r))
                (setf (X-Color-cmap color-exact) cmap))

              (pushnew col (X-Colormap-colors cmap))
              col)
          nil))
      )))

;;;###autoload
(defun XAllocColorCells (xdpy cmap ncolors nplanes &optional contiguous)
  "On display XDPY allocate NCOLORS in colormap CMAP."
  (X-Dpy-p xdpy 'XAllocColorCells)
  (X-Colormap-p cmap 'XAllocColorCells)
  
  (let* ((ListOfFields
	  (list [1 86]
		[1 contiguous]
		[2 3]			; length
		[4 (X-Colormap-id cmap)]
		[2 ncolors]
		[2 nplanes]))
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 nil]
		      [2 integerp]	;sequence
		      [4 integerp]	; length
		      [2 length-1]	; number of pixels
		      [2 length-2]	; number of masks
		      [20 nil]
		      [length-1 ([4 integerp])]
		      [length-2 ([4 integerp])]))))
    (X-Dpy-send-read xdpy msg ReceiveFields)))

;;;###autoload
(defun XStoreColors (xdpy cmap colors)
  "On display XDPY in CMAP, store COLORS. (A list of 'X-Color)
These colors are X-Color lists containing the PIXEL, RGB values and
FLAGs (which indicates what part of the RGB value is stored into
PIXEL's slot."
  (X-Dpy-p xdpy 'XStoreColors)
  (X-Colormap-p cmap 'XStoreColors)

  (let* ((ListOfFields
	  (list [1 89]			;opcode
		[1 nil]			;unused
		[2 (+ 2 (* 3 (length colors)))] ;request length
		[4 (X-Colormap-id cmap)] ;COLORMAP
		))
	 (msg (X-Create-message ListOfFields)))
    (while colors
      (setq msg (concat msg (X-Color-message (car colors)))
	    colors (cdr colors)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XStoreColor (xdpy cmap color &optional R G B)
  "On display XDPY in CMAP, store COLORS.
These colors are X-Color lists containing the PIXEL, RGB values and
FLAGs (which indicates what part of the RGB value is stored into
PIXEL's slot.
  Optionally, COLOR can be a float, and it's new value indicated by
the values of RGB, or X-Color and it will be stored as is."
  (XStoreColors
   xdpy cmap
   (if (X-Color-p color)
       (list color)
     (make-X-Color :id color
		   :red R
		   :green G
		   :blue B
		   :flags (Xmask-or (if R X-DoRed 0)
				    (if G X-DoGreen 0)
				    (if B X-DoBlue 0))))))

;;;###autoload
(defun XFreeColors (xdpy cmap colors planes)
  "On display XDPY in CMAP, free COLORS from the server.
The colors are deallocated on PLANES, which is a mask.  Use 0 for
PLANES if you don't know what it's for."
  (X-Dpy-p xdpy 'XFreeColors)
  (X-Colormap-p cmap 'XFreeColors)

  (when (not (listp colors))
    (signal 'wrong-type-argument (list 'signal 'listp colors)))
  (mapcar (lambda (c) (X-Color-p c 'XFreeColors)) colors)

  (let* ((ListOfFields
	  (list [1 88]			;opcode
		[1 nil]
		[2 (+ 3 (length colors))];length
		[4 (X-Colormap-id cmap)] ;Colormap
		[4 planes]))		;plane mask
	 (msg (concat (X-Create-message ListOfFields)
		      (X-Generate-message-for-list colors(lambda (col)
							   (int->string4 (X-Color-id col)))))))
    (X-Dpy-send xdpy msg)
    
    ;; Invalidate each color.
    (while colors
      (X-invalidate-cl-struct (car colors))
      (setq colors (cdr colors)))
    ))

;;;###autoload
(defun XQueryColors (xdpy cmap color-ids)
  "On display XDPY and colormap CMAP query COLOR-IDS."
  (X-Dpy-p xdpy 'XQueryColors)
  (X-Colormap-p cmap 'XQueryColors)

  (let* ((ListOfFields
	  (list [1 91]			;opcode
		[1 nil]			;unused
		[2 (+ 2 (length color-ids))] ;request length
		[4 (X-Colormap-id cmap)] ;COLORMAP
		))
	 (msg (concat (X-Create-message ListOfFields)
		      (X-Generate-message-for-list color-ids (lambda (colid) (int->string4 colid)))))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 nil]
		      [2 integerp]	;sequence
		      [4 integerp]	;reply length
		      [2 length-2]	;number of rgbs
		      [22 nil]
		      [length-2
		       ([2 integerp]	; red
			[2 integerp]	; green
			[2 integerp]	; blue
			[2 nil])]
		      ))))
    (X-Dpy-send-read xdpy msg ReceiveFields)))

;;; Graphical context operations
;;
;;;###autoload
(defun XCreateGC (xdpy d gc)
  "Allocate a graphic context display XDPY on the drawable D.
Base this new context on GC." 
  (X-Dpy-p xdpy 'XCreateGC)
  (X-Drawable-p d 'XCreateGC)
  (X-Gc-p gc 'XCreateGC)

  (let* ((attrmsg (X-Gc-message gc))
	 (ListOfFields 
	  (list [1 55]			;opcode
		[1 nil]			;unused
		;; 4 fields, but 1 is in attrmsg, making 3
		[2 (+ 3 (/ (length attrmsg) 4))] ;request length
		[4 (X-Gc-id gc)]	;GC id
		[4 (X-Drawable-id d)]	;drawable id
		))
	 (msg (concat (X-Create-message ListOfFields) attrmsg)))
    (X-Dpy-send xdpy msg)

    ;; Seems lame, but return the GC we were passed originally.
    gc))

;;;###autoload
(defun XChangeGC (xdpy gc)
  "On display XDPY change GC to have new VALUES.
I.e. update GC's info on server."
  (X-Dpy-p xdpy 'XChangeGC)
  (X-Gc-p gc 'XChangeGC)

  (let* ((attrmsg (X-Gc-message gc))
	 (ListOfFields 
	  (list [1 56]			;opcode
		[1 nil]			;unused
		[2 (+ 2 (/ (length attrmsg) 4))] ;request length
		[4 (X-Gc-id gc)]	;the GC
		))
	 (msg (concat (X-Create-message ListOfFields) attrmsg)))
    (X-Dpy-send xdpy msg)
    ))

;;;###autoload
(defun XSetDashes (xdpy gc dash-offset dashes)
  "On display XDPY for GC set DASH-OFFSET and DASHES for dashed line styles."
  (X-Dpy-p xdpy 'XSetDashes)
  (X-Gc-p gc 'XSetDashes)

  (let* ((dstr (mapconcat (lambda (d) (int->string1 d)) dashes ""))
	 (ListOfFields 
	  (list [1 58]			;opcode
		[1 nil]			;unused
		[2 (+ 3 (X-padlen dstr))] ;request length
		[4 (X-Gc-id gc)]	;the GC
		[2 dash-offset]
		[2 (length dashes)]
		))
	 (msg (concat (X-Create-message ListOfFields) dstr)))
    (X-Dpy-send xdpy msg)
    ))

;;;###autoload
(defun XSetClipRectangles (xdpy gc clip-x-origin clip-y-origin rectangles &optional order)
  "On display XDPY for GC change clip-mask according to CLIP-X-ORIGIN,
CLIP-Y-ORIGIN and RECTANGLES.

You may specify ORDER to speed up X server, ORDER is one of
`X-UnSorted', `X-YSorted', `X-YXSorted' or `X-YXBanded'."
  (X-Dpy-p xdpy 'XSetClipRectangles)
  (X-Gc-p gc 'XSetClipRectangles)

  (unless order
    (setq order X-UnSorted))

  (let* ((rstr (X-Generate-message-for-list rectangles 'X-Rect-message))
	 (ListOfFields 
	  (list [1 59]			;opcode
		(vector 1 order)	;Ordeding to speedup X server
		[2 (+ 3 (X-padlen rstr))] ;request length
		[4 (X-Gc-id gc)]	;the GC
		[2 clip-x-origin]
		[2 clip-y-origin]
		))
	 (msg (concat (X-Create-message ListOfFields) rstr)))
    (X-Dpy-send xdpy msg)
    ))

;;;###autoload
(defun XFreeGC (xdpy gc)
  "Allocate a graphic context display XDPY on the drawable D.
Base this new context on GC." 
  (X-Dpy-p xdpy 'XFreeGC)
  (X-Gc-p gc 'XFreeGC)

  (let* ((ListOfFields 
	  (list [1 60]			;opcode
		[1 nil]
		[2 2]			;length
		[4 (X-Gc-id gc)]	;GC id
		))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)

    ;; Invalidate gc structure.
    (X-invalidate-cl-struct gc)
    ))

;;;###autoload
(defun XClearArea (xdpy win x y width height exposures)
  "On display XDPY in WIN clear rectangle X Y WIDTH HEIGHT."
  (X-Dpy-p xdpy 'XClearArea)
  (X-Win-p win 'XClearArea)

  (let* ((ListOfFields
	  (list [1 61]			;opcode
		[1 exposures]		;exposures
		[2 4]			;length
		[4 (X-Win-id win)]	;window
		[2 x]
		[2 y]
		[2 width]
		[2 height]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XCopyArea (xdpy src-d dst-d gc src-x src-y width height dst-x dst-y)
  "On display XDPY combine specified rectangle of SCR-D with DST-D."
  (X-Dpy-p xdpy 'XCopyArea)
  (X-Drawable-p src-d 'XCopyArea)
  (X-Drawable-p src-d 'XCopyArea)

  (let* ((ListOfFields
	  (list [1 62]			;opcode
		[1 nil]
		[2 7]			;length
		[4 (X-Drawable-id src-d)] ; source drawable
		[4 (X-Drawable-id dst-d)] ; destination drawable
		[4 (X-Gc-id gc)]
		[2 src-x]
		[2 src-y]
		[2 dst-x]
		[2 dst-y]
		[2 width]
		[2 height]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XCopyPlane (xdpy src-d dst-d gc src-x src-y width height dst-x dst-y bit-plane)
  "On display XDPY ..."
  (X-Dpy-p xdpy 'XCopyPlane)
  (X-Drawable-p src-d 'XCopyPlane)
  (X-Drawable-p src-d 'XCopyPlane)

  (let* ((ListOfFields
	  (list [1 63]			;opcode
		[1 nil]
		[2 8]			;length
		[4 (X-Drawable-id src-d)] ; source drawable
		[4 (X-Drawable-id dst-d)] ; destination drawable
		[4 (X-Gc-id gc)]
		[2 src-x]
		[2 src-y]
		[2 dst-x]
		[2 dst-y]
		[2 width]
		[2 height]
		[4 bit-plane]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;; Drawing routines
;;
;;;###autoload
(defun XDrawPoints (xdpy d gc pts &optional mode)
  "Draw points on a drawable. (XDPY D GC PTS &optional MODE)."
  (X-Dpy-p xdpy 'XDrawPoints)
  (X-Drawable-p d 'XDrawPoints)
  (X-Gc-p gc 'XDrawPoints)

  (let* ((ListOfFields
	  (list [1 64]			; opcode
		[1 (or mode X-Origin)]	; mode of drawing, shutup compiler
		[2 (+ 3 (length pts))]	; request length
		[4 (X-Drawable-id d)]	; drawable id
		[4 (X-Gc-id gc)]))	; id of the GC
	 (msg (concat (X-Create-message ListOfFields)
		      (X-Generate-message-for-list pts 'X-Point-message))))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XDrawPoint (xdpy d gc x y)
  "Draw a point. (XDPY D GC X Y)."
  (XDrawPoints xdpy d gc (list (cons x y)) X-Origin))

;;;###autoload
(defun XDrawLines (xdpy d gc pts &optional mode)
  "Draw a multipoint line. (XDPY D GC PTS &optional MODE)."
  (X-Dpy-p xdpy 'XDrawLines)
  (X-Drawable-p d 'XDrawLines)
  (X-Gc-p gc 'XDrawLines)

  (let* ((ListOfFields
	  (list [1 65]			; opcode
		[1 (or mode X-Origin)]	; mode of drawing, shut up compiler
		[2 (+ 3 (length pts))]	; request length
		[4 (X-Drawable-id d)]
		[4 (X-Gc-id gc)]))
	 (msg (concat (X-Create-message ListOfFields)
		      (X-Generate-message-for-list pts 'X-Point-message))))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XFillPoly (xdpy d gc pts &optional shape mode)
  "Fill poly."
  (X-Dpy-p xdpy 'XFillPoly)
  (X-Drawable-p d 'XFillPoly)
  (X-Gc-p gc 'XFillPoly)

  (let* ((ListOfFields
	  (list [1 69]			; opcode
		[1 nil]                 ; unused
		[2 (+ 4 (length pts))]	; request length
		[4 (X-Drawable-id d)]
		[4 (X-Gc-id gc)]
                [1 (or shape X-Nonconvex)]
                [1 (or mode X-Origin)]
                [2 nil]))               ; pad
	 (msg (concat (X-Create-message ListOfFields)
		      (X-Generate-message-for-list pts 'X-Point-message))))
    (X-Dpy-send xdpy msg)))
  
;;;###autoload
(defun XDrawLine (xdpy d gc x y x2 y2)
  "Draw a line on display XDPY in drawable D.
args (XDPY D GC X Y X2 Y2)."
  (XDrawLines xdpy d gc (list (cons x y) (cons x2 y2))))

;;;###autoload
(defun XDrawSegments (xdpy d gc xsegments)
  "Draw Segments. (XDPY D GC PTS &optional MODE).
Drawing segments is different from lines in that segments are disconnected
every other pair of points."
  (X-Dpy-p xdpy 'XDrawSegments)
  (X-Drawable-p d 'XDrawSegments)
  (X-Gc-p gc 'XDrawSegments)

  (let* ((ListOfFields
	  (list [1 66]			;opcode
		[1 nil]
		[2 (+ 3 (* 2 (length xsegments)))]
		[4 (X-Drawable-id d)]
		[4 (X-Gc-id gc)]))
	 (msg (concat (X-Create-message ListOfFields)
		      (X-Generate-message-for-list xsegments 'X-Segment-message))))
    (X-Dpy-send xdpy msg)))
	
;;;###autoload
(defun XDrawRectangles (xdpy d gc rectangles &optional fill)
  "Draw rectangles. (XDPY D GC RECTANGLES &optional FILL)."
  (X-Dpy-p xdpy 'XDrawRectangles)
  (X-Drawable-p d 'XDrawRectangles)
  (X-Gc-p gc 'XDrawRectangles)

  (let* ((ListOfFields
	  (list [1 (if fill 70 67)]	;opcode
		[1 nil]			;mode of drawing
		[2 (+ 3 (* (length rectangles) 2))] ; number of rects *2
		[4 (X-Drawable-id d)]	;drawable id
		[4 (X-Gc-id gc)]))	;id of the GC
	 (msg (concat (X-Create-message ListOfFields)
		      (X-Generate-message-for-list rectangles 'X-Rect-message))))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XDrawRectangle (xdpy d gc x y width height)
  "Draw a rectangle. (XDPY D GC X Y WIDTH HEIGHT)."
  (XDrawRectangles xdpy d gc (list (make-X-Rect :x x :y y :width width :height height))))

;;;###autoload
(defun XFillRectangle (xdpy d gc x y width height)
  "Draw a rectangle. (XDPY D GC X Y WIDTH HEIGHT)."
  (XDrawRectangles xdpy d gc (list (make-X-Rect :x x :y y :width width :height height)) t))

;;;###autoload
(defun XFillRectangles (xdpy d gc rectangles)
  "Draw rectangles. (XDPY D GC RECTANGLES)."
  (XDrawRectangles xdpy d gc rectangles t))

;;;###autoload
(defun XDrawArcs (xdpy d gc xarcs &optional fill mode)
  "Draw arcs. (XDPY D GC ARCS &optional FILL)."
  (X-Dpy-p xdpy 'XDrawArcs)
  (X-Drawable-p d 'XDrawArcs)
  (X-Gc-p gc 'XDrawArcs)

  (let* ((ListOfFields
	  (list [1 (if fill 71 68)]	;opcode
		[1 mode]                ;mode of drawing
		[2 (+ 3 (* 3 (length xarcs)))] ; number of arcs * 3
		[4 (X-Drawable-id d)]	;drawable id
		[4 (X-Gc-id gc)]))	;id of the GC
	 (msg (concat (X-Create-message ListOfFields)
		      (X-Generate-message-for-list xarcs 'X-Arc-message))))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XDrawArc (xdpy d gc x y width height angle1 angle2 &optional fill mode)
  "Draw an arc on display XDPY in drawable D.
args (DISPLAY D GC X Y WIDTH HEIGHT ANGLE1 ANGLE2)"
  (XDrawArcs xdpy d gc (list (make-X-Arc :x x :y y :width width :height height :angle1 angle1 :angle2 angle2)) fill))

;;;###autoload
(defun XFillArc (xdpy d gc x y width height angle1 angle2 &optional mode)
  "Draw a filled arc on display XDPY in drawable D.
args (DISPLAY D GC X Y WIDTH HEIGHT ANGLE1 ANGLE2)"
  (XDrawArcs xdpy d gc (list (make-X-Arc :x x :y y :width width :height height :angle1 angle1 :angle2 angle2)) t mode))

;;;###autoload
(defun XFillArcs (xdpy d gc arcs &optional mode)
  "Draw filled arcs. (XDPY D GC ARCS)."
  (XDrawArcs xdpy d gc arcs t mode))

;;;###autoload
(defun XDrawString (xdpy d gc x y str &optional len)
  "Draw a string at specified point. (XDPY D GC X Y STR &optional LEN)."
  (X-Dpy-p xdpy 'XDrawString)
  (X-Drawable-p d 'XDrawString)
  (X-Gc-p gc 'XDrawString)

  ;; Check len, must be < 255
  (when (or (and len (>= len 255))
	    (>= (length str) 255))
    (signal 'overflow-error (list str (or len (length str)))))

  (let* ((slen (if len len (length str))) ;make len optional
	 (ListOfFields
	  (list [1 74]			;request value
		[1 nil]			;unused
		[2 (+ 4 (X-padlen (concat "12" str)))] ;length
		[4 (X-Drawable-id d)]	;drawable id
		[4 (X-Gc-id gc)]	;gc id
		[2 x]
		[2 y]
		(vector 1 slen)		;text length, shutup compiler
		[1 0]			;delta????????
		[slen str]		;the string
		))
		;; auto-padding in X-create
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XImageString (xdpy d gc x y str &optional len)
  "Draw a string using ImageText8 request.
XDPY, D, GC, X, Y, STR and LEN are the same as in `XDrawString'."
  (X-Dpy-p xdpy 'XImageString)
  (X-Drawable-p d 'XImageString)
  (X-Gc-p gc 'XImageString)

  (let* ((slen (if len len (length str))) ; make len optional
	 (ListOfFields
	  (list [1 76]			; request opcode
		(vector 1 slen)         ; string length, shutup compiler
		[2 (+ 4 (/ (+ (X-pad slen) slen) 4))] ;length
		[4 (X-Drawable-id d)]	;drawable id
		[4 (X-Gc-id gc)]	;gc id
		[2 x]
		[2 y]
                [slen str]
		))
          ;; auto-padding in X-create
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))
  
;;;###autoload
(defun XDrawText8 ()
  )

;;;###autoload
(defun XDrawText16 ()
  )

;;;###autoload
(defun XPutImage (xdpy d gc depth width height dst-x dst-y left-pad format data)
  "On display XDPY and drawable D, put an image."
  (X-Dpy-p xdpy 'XPutImage)
  (X-Drawable-p d 'XPutImage)
  (X-Gc-p gc 'XPutImage)

  (let* ((ListOfFields
	  (list [1 72]
		[1 format]
		[2 (+ 6 (X-padlen data))]
		[4 (X-Drawable-id d)]
		[4 (X-Gc-id gc)]
		[2 width]
		[2 height]
		[2 dst-x]
		[2 dst-y]
		[1 left-pad]
		[1 depth]
		[2 nil]
		[(length data) data]
		[(X-pad (length data)) nil]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XGetImage (xdpy d x y width height plane-mask format)
  "On display XDPY and drawable D, get image with geometry WIDTHxHEIGHT+X+Y in FORMAT.
PLANE-MASK is one of `X-AllPlanes' or something elese."
  (X-Dpy-p xdpy 'XGetImage)
  (X-Drawable-p d 'XGetImage)

  (let* ((ListOfFields
	  (list [1 73]			; opcode
		[1 format]		; format
		[2 5]			; len
		[4 (X-Drawable-id d)]	; drawable
		[2 x]
		[2 y]
		[2 width]
		[2 height]
		[4 plane-mask]))
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 integerp]	; depth
		      [2 integerp]	; sequence
		      [4 length-1]	; length
		      [4 integerp]	; visual id or X-None
		      [20 nil]		; not used
		      [(* length-1 4) stringp]))))	;data
    (X-Dpy-send-read xdpy msg ReceiveFields)))
;		      [(X-mod-4 length-1) nil])))) ; padding

;;; Selections operations
;;;###autoload
(defun XSetSelectionOwner (xdpy selection-atom &optional owner-win time)
  "Set SELECTION-ATOM to be owned by OWNER-WIN."
  (X-Dpy-p xdpy 'XSetSelectionOwner)

  (let* ((ListOfFields
	  (list [1 22]			;request value
		[1 nil]			;unused
		[2 4]			;length
		[4 (if owner-win (X-Win-id owner-win) X-None)] ;owner window
		[4 (X-Atom-id selection-atom)] ; selection atom
		[4 (if time time X-CurrentTime)]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XGetSelectionOwner (xdpy selection-atom)
  "Get owner of SELECTION-ATOM on display XDPY.
Returns nil or X-Win structure."
  (X-Dpy-p xdpy 'XGetSelectionOwner)

  (let* ((ListOfFields
          (list [1 23]			;request value
                [1 nil]                 ;unused
                [2 2]			;length
                [4 (X-Atom-id selection-atom)])) ;selection atom
         (msg (X-Create-message ListOfFields))
         (ReceiveFields
          (list [1 success]		;success field
                nil
                (list [1 nil]		;unused
                      [2 integerp]	;sequence
                      [4 nil]		;length
                      [4 integerp]	;owner window
                      [20 nil])))	;pad
         r win)
    (setq r (X-Dpy-send-read xdpy msg ReceiveFields))
    (when (car r)
      (setq win (X-Win-find-or-make xdpy (nth 2 r))))
    win))

;;;###autoload
(defun XConvertSelection (xdpy selection target prop requestor &optional time)
  "ConvertSelection."
  (X-Dpy-p xdpy 'XConvertSelection)

  (let* ((ListOfFields
	  (list [1 24]			;request value
		[1 nil]			;unused
		[2 6]			;length
		[4 (if requestor (X-Win-id requestor) X-None)] ;owner window
		[4 (X-Atom-id selection)] ; selection atom
		[4 (X-Atom-id target)]  ; target atom
		[4 (if prop (X-Atom-id prop) X-None)] ; property atom
		[4 (or time X-CurrentTime)]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;; Warping
;;;###autoload
(defun XWarpPointer (xdpy src-win dst-win src-x src-y src-width src-height dest-x dest-y)
  "On display XDPY warp pointer to DEST-X DEST-Y"
  (X-Dpy-p xdpy 'XWarpPointer)
;  (X-Win-p src-win 'XWarpPointer)
;  (X-Win-p dst-win 'XWarpPointer)

  (let* ((srcid (or (and (X-Win-p src-win) (X-Win-id src-win)) src-win))
	 (dstid (or (and (X-Win-p dst-win) (X-Win-id dst-win)) dst-win))
	 (ListOfFields
	  (list [1 41]			; request value
		[1 nil]			; unused
		[2 6]			; length
		(vector 4 srcid)	; source window
		(vector 4 dstid)	; dst window
		[2 src-x]		;
		[2 src-y]		;
		[2 src-width]
		[2 src-height]
		[2 dest-x]
		[2 dest-y]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;; Grabbing
;;;###autoload
(defun XGrabServer (xdpy)
  "Grabs X server on display XDPY"
  (X-Dpy-p xdpy 'XGrabServer)

  (let* ((ListOfFields
	  (list [1 36]			;opcode
		[1 nil]			;unused
		[2 1]))			;length
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XUngrabServer (xdpy)
  "Ungrab X server on display XDPY."
  (X-Dpy-p xdpy 'XUngrabServer)

  (let* ((ListOfFields
	  (list [1 37]			;opcode
		[1 nil]			;unused
		[2 1]))			;length
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XQueryPointer (xdpy xwin)
  "In display XDPY and window XWIN query pointer position."
  (X-Dpy-p xdpy 'XQueryPointer)

  (let* ((ListOfFields
          (list [1 38]                  ; opcode
                [1 nil]                 ; unused
                [2 2]                   ; length
                [4 (X-Win-id xwin)]))
         (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]		;success field
		nil
		(list [1 integerp]	; same-screen
		      [2 integerp]	; sequence
		      [4 nil]           ; length
                      [4 :X-Win]        ; root
                      [4 :X-Win]        ; child
                      [2 integerp]      ; root-x
                      [2 integerp]      ; root-y
                      [2 integerp]      ; win-x
                      [2 integerp]      ; win-y
                      [2 integerp]      ; mask
                      [6 nil]))))
    (X-Dpy-send-read xdpy msg ReceiveFields)))

;;;###autoload
(defun XGrabKeyboard (xdpy grab-win &optional owe pmode kmode time)
  "On display XDPY in window GRAB-WIN start grabbing keyboard.
OWE - owner events (default `nil')
PMODE - Pointer grabbing mode (default `X-GrabModeAsync')
KMODE - Keyboard grabbing mode (default `X-GrabModeAsync')
TIME - Time when start to grab (default `X-CurrentTime')"
  (X-Dpy-p xdpy 'XGrabKeyboard)
  (X-Win-p grab-win 'XGrabKeyboard)

  (let* ((ListOfFields
	  (list [1 31]			; request value
		[1 owe]			; owner_events
		[2 4]			; length
		[4 (X-Win-id grab-win)] ; grab window
		[4 (or time X-CurrentTime)] ; time
		[1 (or pmode X-GrabModeAsync)] ; pointer mode
		[1 (or kmode X-GrabModeAsync)] ; keyboard mode
		[2 nil]))		; pad
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]		;success field
		nil
		(list [1 integerp]	;status
		      [2 integerp]	;sequence
		      [4 integerp]	;length . Hmm length-1
		      [24 nil]))))	;pad
;		      [length-1
;		       ([4 nil]) ]))))	;pad
    (X-Dpy-send-read xdpy msg ReceiveFields)))

;;;###autoload
(defun XUngrabKeyboard (xdpy &optional time)
  "On display XDPY at TIME stop grabbing keyboard.
Default TIME is `X-CurrentTime'."
  (X-Dpy-p xdpy 'XUngrabKeyboard)

  (let* ((ListOfFields
	  (list [1 32]			; request value
		[1 nil]			; owner_events
		[2 2]			;length
		[4 (if time time X-CurrentTime)]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XGrabPointer (xdpy grab-win ev-mask &optional cursor owe pmode kmode confto-win time)
  "On display XDPY in window GRAB-WIN start grabbing pointer.
CURSOR - Cursor to use while grabbing.
EV-MASK - Mask for events to receive. Result of `Xmask-or'.
OWE - owner events (default `nil')
PMODE - Pointer grabbing mode (default `X-GrabModeAsync')
KMODE - Keyboard grabbing mode (default `X-GrabModeAsync')
CONFTO-WIN - Confine to window (default `nil'
TIME - Time when start to grab (default `X-CurrentTime')"
  (X-Dpy-p xdpy 'XGrabPointer)
  (X-Win-p grab-win 'XGrabPointer)

  (let* ((ListOfFields
	  (list [1 26]			;opcode
		[1 owe]
		[2 6]
		[4 (X-Win-id grab-win)] ;grab window
		[2 ev-mask]		;event mask
		[1 (or pmode X-GrabModeAsync)] ;pointerMode
		[1 (or kmode X-GrabModeAsync)] ;keyboardMode
		[4 (if confto-win (X-Win-id confto-win) 0.0)] ;confineTo window
		[4 (if cursor (X-Cursor-id cursor) 0.0)] ;Cursor
		[4 (or time X-CurrentTime)]))
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields 
	  (list [1 success]
		nil
		(list [1 nil]		;unsed
		      [2 integerp]	;sequence
		      [28 nil]))))	;padding
    (X-Dpy-send-read xdpy msg ReceiveFields)))

;;;###autoload
(defun XUngrabPointer (xdpy &optional time)
  "On display XDPY at TIME, stop grabbing pointer."
  (X-Dpy-p xdpy 'XUngrabPointer)

  (let* ((ListOfFields
	  (list [1 27]			;opcode
		[1 nil]
		[2 2]
		[4 (or time X-CurrentTime)]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XGrabButton (xdpy button mods grab-win ev-mask &optional cursor owe pmode kmode conf-to)
  "On display XDPY in window GRAB-WIN, start grabbing for BUTTON with MODS.
TODO: Describe optional arguments."
  (X-Dpy-p xdpy 'XGrabButton)
  (X-Win-p grab-win 'XGrabButton)

  (let* ((ListOfFields
	  (list [1 28]
		[1 (if owe owe nil)]
		[2 6]
		[4 (X-Win-id grab-win)]
		[2 ev-mask]
		[1 (or pmode X-GrabModeAsync)]
		[1 (or kmode X-GrabModeAsync)]
		[4 (if conf-to (X-Win-id conf-to) 0.0)]
		[4 (if cursor (X-Cursor-id cursor) 0.0)]
		[1 button]
		[1 nil]			; pad
		[2 mods]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XUngrabButton (xdpy button mods grab-win)
  "On display XDPY in window GRAB-WIN stop grabbing for BUTTON with MODS."
  (X-Dpy-p xdpy 'XUngrabButton)
  (X-Win-p grab-win 'XUngrabButton)

  (let* ((ListOfFields
	  (list [1 29]			; opcode
		[1 button]
		[2 3]			; length
		[4 (X-Win-id grab-win)]
		[2 mods]
		[2 nil]))		; pad
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))
		
;;;###autoload
(defun XGrabKey (xdpy keycode mods grab-win &optional owe pmode kmode)
  "On display XDPY in window GRAB-WIN start grabbing for KEYCODE with MODS.
TODO: Description for OWE, PMODE and KMODE."
  (X-Dpy-p xdpy 'XGrabKey)
  (X-Win-p grab-win 'XGrabKey)

  (let* ((ListOfFields
	  (list [1 33]			; request value
		[1 owe]			; owner_events
		[2 4]			; length
		[4 (X-Win-id grab-win)]	; grab window
		[2 mods]		; modifiers
		[1 keycode]		; key
		[1 (or pmode X-GrabModeAsync)] ; pointer mode
		[1 (or kmode X-GrabModeAsync)] ; keyboard mode
		[3 nil]))		; pad
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XUngrabKey (xdpy keycode mods grab-win)
  "On display XDPY in window GRAB-WIN stop grabbing KEYCODE with MODS."
  (X-Dpy-p xdpy 'XUngrabKey)
  (X-Win-p grab-win 'XUngrabKey)

  (let* ((ListOfFields
	  (list [1 34]			; request value
		[1 keycode]		; keycode
		[2 3]			; length
		[4 (X-Win-id grab-win)]	; grab window
		[2 mods]		; modifiers
		[2 nil]))		; pad
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XAllowEvents (xdpy mode &optional time)
  "On display XDPY allow events in MODE."
  (X-Dpy-p xdpy 'XAllowEvents)

  (let* ((ListOfFields
	  (list [1 35]
		[1 mode]
		[2 2]
		[4 (or time X-CurrentTime)]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))
  

;;; Focusing
;;;###autoload
(defun XGetInputFocus (xdpy)
  "On display XDPY get curret input focus."
  (X-Dpy-p xdpy 'XGetInputFocus)

  (let* ((ListOfFields
	  (list [1 43]			;opcode
		[1 nil]			;unused
		[2 1]))			;length
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 integerp]	;revertTo
		      [2 integerp]	;sequence
		      [4 nil]		;length
		      [4 integerp]	;focus win
		      [20 nil])))	;pad
	 r thing)
    (setq r (X-Dpy-send-read xdpy msg ReceiveFields))

    (when (car r)
      (if (member (nth 3 r) (list X-PointerRoot X-None))
	  (setq thing (nth 3 r))
	(setq thing (X-Win-find xdpy (nth 3 r)))))
    thing))

;;;###autoload
(defun XSetInputFocus (xdpy win-or-val rev-to &optional time)
  "On display XDPY set input focus to window WIN-OR-VAL.
REV-TO - Focus revert to when WIN-OR-VAL will lost input focus.
TIME - Set input focus at this time (default `X-CurrentTime')"
  (X-Dpy-p xdpy 'XSetInputFocus)

  (let* ((ListOfFields
	  (list [1 42]			; request value
		[1 rev-to]		; Revert to
		[2 3]			; length
		[4 (cond ((integerp win-or-val) win-or-val) ;X-PointerRoot, X-None, etc
			 ((X-Win-p win-or-val) (X-Win-id win-or-val)) ;window
			 (t nil))]	; X-None
		[4 time]))		; time
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;; Misc requests
;;;###autoload
(defun XReparentWindow (xdpy win parwin x y)
  "On display XDPY reparent window WIN to PARWIN at X Y."
  (X-Dpy-p xdpy 'XReparentWindow)
  (X-Win-p win 'XReparentWindow)
  (X-Win-p parwin 'XReparentWindow)

  (let* ((ListOfFields
	  (list [1 7]			;opcode
		[1 nil]			;pad
		[2 4]			;length
		[4 (X-Win-id win)]	;win
		[4 (X-Win-id parwin)]	;parent window
		[2 x]			;x
		[2 y]))			;y
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XGetGeometry (xdpy win)
  "On display XDPY get geomtry of WIN."
  (X-Dpy-p xdpy 'XGetGeometry)
  (X-Win-p win 'XGetGeometry)

  (let* ((ListOfFields
	  (list [1 14]			;opcode
		[1 nil]			;pad
		[2 2]			;length
		[4 (X-Win-id win)]))	;chars in string
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 integerp]	;depth
		      [2 integerp]	;sequence
		      [4 nil]		;length
		      [4 integerp]	;root
		      [2 integerp]	;x
		      [2 integerp]	;y
		      [2 integerp]	;width
		      [2 integerp]	;height
		      [2 integerp]	;border width
		      [10 nil])))	;pad
	 r rgeom)
    (setq r (X-Dpy-send-read xdpy msg ReceiveFields))
    (when (car r)
      (setq rgeom (make-X-Geom :x (nth 4 r)
			       :y (nth 5 r)
			       :width (nth 6 r)
			       :height (nth 7 r)
			       :border-width (nth 8 r))))
    rgeom))

;; TODO: XTranslateCoordinates
;;;###autoload
(defun XTranslateCoordinates (xdpy src-win dst-win src-x src-y)
  "On display XDPY translate SCR-X SCR-y coordinates to coordinates on DST-WIN."
  (X-Dpy-p xdpy 'XTranslateCoordinates)
  (X-Win-p src-win 'XTranslateCoordinates)
  (X-Win-p dst-win 'XTranslateCoordinates)

  (let* ((ListOfFields
	  (list [1 40]			;opcode
		[1 nil]			;pad
		[2 4]			;length
		[4 (X-Win-id src-win)]	;source win
		[4 (X-Win-id dst-win)]	;destination win
		[2 src-x]
		[2 src-y]))
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 booleanp]	;same-screen
		      [2 integerp]	;sequence
		      [4 nil]		;length
		      [4 :X-Win]	;child
		      [2 integerp]	;dst-x
		      [2 integerp]	;dst-y
		      [16 nil])))	;pad
	 r)
    (setq r (X-Dpy-send-read xdpy msg ReceiveFields))
    (if (car r)
	r
      nil)))

;;;###autoload
(defun XChangeSaveSet (xdpy win change-mode)
  "On display XDPY change SaveSet according to CHANGE-MODE."
  (X-Dpy-p xdpy 'XChangeSaveSet)
  (X-Win-p win 'XChangeSaveSet)

  (let* ((ListOfFields
	  (list [1 6]
		[1 change-mode]
		[2 2]			;length
		[4 (X-Win-id win)]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XSendEvent (xdpy win propogate ev_mask xevent)
  "WIN is X11 window or one of X-InputFocus, X-XXXxxxXXX.
Evil hack, do not use this function."
  (X-Dpy-p xdpy 'XSendEvent)

  (let* ((ListOfFields
	  (list [1 25]
		[1 propogate]
		[2 11] ;(+ 3 (X-padlen xevent))] ;length
		[4 (if (X-Win-p win) (X-Win-id win) win)]
		[4 ev_mask]))		;event mask
	 (padding (make-string (- 44 12 (length xevent)) 0))
	 (msg (concat (X-Create-message ListOfFields) xevent padding)))
    (X-Dpy-send xdpy msg)))


;;; Keyboard mapping
;;;###autoload
(defun XQueryKeymap (xdpy)
  "On display XDPY query keyboard mapping."
  (X-Dpy-p xdpy 'XQueryKeymap)

  (let* ((ListOfFields
	  (list [1 44]			;opcode
		[1 nil]			;pad
		[2 1]))			;length
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 nil]		;unused
		      [2 integerp]	;sequence
		      [4 integerp]	;length
		      [32 nil]))))	;unknown

    (X-Dpy-send-read xdpy msg ReceiveFields)))

;;;###autoload
(defun XGetKeyboardMapping (xdpy keycode count)
  "On display XDPY get keyboard mapping."
  (X-Dpy-p xdpy 'XGetKeyboardMapping)

  (let* ((ListOfFields
	  (list [1 101]			;opcode
		[1 nil]			;pad
		[2 2]			;length
		[1 keycode]		;first_keycode
		[1 count]		;count
		[2 nil]))		;pad
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 length-1]	;keySymsPerKeyCode
		      [2 integerp]	;sequence
		      [4 length-2]	;length
		      [24 nil]		;pad
		      [count		;list of the children
		       (make-list length-1 [4 integerp])]))))

    (X-Dpy-send-read xdpy msg ReceiveFields)))

;;;###autoload
(defun XGetModifierMapping (xdpy)
  "On display XDPY get modifiers mapping."
  (X-Dpy-p xdpy 'XGetModifierMapping)

  (let* ((ListOfFields
	  (list [1 119]			;opcode
		[1 nil]			;pad
		[2 1]))			;length
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 length-2]	;numKeyPerModifier
		      [2 integerp]	;sequence
		      [4 length-1]	;length
		      [4 integerp]	;pad
		      [4 integerp]	;pad
		      [4 integerp]	;pad
		      [4 integerp]	;pad
		      [4 integerp]	;pad
		      [4 integerp]	;pad
		      [(/ (* length-1 4) length-2) ;list of the children
		       (make-list length-2 [1 integerp])]))))

    (X-Dpy-send-read xdpy msg ReceiveFields)))

;;; Fonts supoprt
;;;###autoload
(defun XOpenFont (xdpy font)
  "On display XDPY open FONT, created using `X-Font'."
  (X-Dpy-p xdpy 'XOpenFont)
  (X-Font-p font 'XOpenFont)
  
  (let* ((name (X-Font-name font))
	 (ListOfFields
	  (list [1 45]			;opcode
		[1 nil]			;pad
		[2 (+ 3 (X-padlen name))] ;length
		[4 (X-Font-id font)]
		[2 (length name)]
		[2 nil]))		;pad
	 (msg (concat (X-Create-message ListOfFields) name (make-string (- (* 4 (X-padlen name)) (length name)) ?\0))))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XQueryFont (xdpy font)
  "On display XDPY query for FONT."
  (X-Dpy-p xdpy 'XQueryFont)

  (let* ((ListOfFields
	  (list [1 47]
		[1 nil]
		[2 2]			;length
		[4 (X-Font-id font)]))
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]		;success field
		nil
		(list [1 nil]		;unused
		      [2 integerp]	;sequence
		      [4 length-1]	;length

		      ;; xCharInfo minBounds and maxBounds
		      [2 ([2 integerp]	;leftSideBearing
			  [2 integerp]	;rightSideBearing
			  [2 integerp]	;characterWidth
			  [2 integerp]	;ascent
			  [2 integerp]	;descent
			  [2 integerp]	;attributes
			  [4 nil])]	;walign

		      [2 integerp]	;minCharOrByte2
		      [2 integerp]	;maxCharOrByte2
		      [2 integerp]	;defaultChar
		      [2 length-2]	;nFontProps
		      [1 integerp]	;drawDirection
		      [1 integerp]	;minByte1
		      [1 integerp]	;maxByte1
		      [1 booleanp]	;allCharsExist
		      [2 integerp]	;fontAscent
		      [2 integerp]	;fontDescent
		      [4 length-3]	;nCharInfos
		      
		      ;; FontProps
		      [length-2 ([4 integerp] ;atom name
				 [4 integerp])] ;value
		      
		      ;; Character info
		      [length-3 ([2 integerp] ; leftSideBearing
				 [2 integerp] ; rightSideBearing
				 [2 integerp] ; characterWidth
				 [2 integerp] ; ascent
				 [2 integerp] ; descent
				 [2 integerp])] ; attributes
		      )))
	 r)
    (setq r (X-Dpy-send-read xdpy msg ReceiveFields))

    (if (car r)
	(let ((bounds (nth 2 r))
	      (props (nth 12 r))
	      (chinfo (nth 13 r)))

	  (setf (X-Font-minb font) (vconcat (nth 0 bounds)))
	  (setf (X-Font-maxb font) (vconcat (nth 1 bounds)))
	  (setf (X-Font-micob font) (nth 3 r))
	  (setf (X-Font-macob font) (nth 4 r))
	  (setf (X-Font-defchar font) (nth 5 r))
	  (setf (X-Font-nprops font) (length props))
	  (setf (X-Font-dd font) (nth 6 r))
	  (setf (X-Font-minbyte font) (nth 7 r))
	  (setf (X-Font-maxbyte font) (nth 8 r))
	  (setf (X-Font-allce font) (nth 9 r))
	  (setf (X-Font-fontascent font) (nth 10 r))
	  (setf (X-Font-fontdescent font) (nth 11 r))
	  (setf (X-Font-ncinfo font) (length chinfo))
	  (setf (X-Font-props font) (vconcat (mapcar 'vconcat props)))
	  (setf (X-Font-chinfo font) (vconcat (mapcar 'vconcat chinfo)))
	  t)
      nil)))

;;;###autoload
(defun XQueryTextExtents (xdpy font string)
  "On display XDPY fetch FONT's info for STRING."
  (X-Dpy-p xdpy 'XQueryTextExtents)
  (X-Font-p font 'XQueryTextExtents)

  (let* ((ListOfFields
	  (list [1 48]
		[1 (% (length string) 2)] ;oddLength
		[2 (+ 2 (X-padlen (concat string string)))] ;length
		[4 (X-Font-id font)]))
	 (msg (concat (X-Create-message ListOfFields)
		      (mapconcat (lambda (c) (string ?\0 c)) string "")
		      (when (> (% (length string) 2) 0) (make-string 2 ?\0))
		      ))
	 (ReceiveFields
	  (list [1 success]		;success field
		nil
		(list [1 integerp]	;draw direction (> 0 - left to right, < - right to left)
		      [2 integerp]	;sequence
		      [4 nil]		;length
		      [2 integerp]	;font ascent
		      [2 integerp]	;font descent
		      [2 integerp]	;over all ascent
		      [2 integerp]	;over all descont
		      [4 numberp]	;over all width
		      [4 numberp]	;over all left
		      [4 numberp]	;over all right
		      [4 nil]))))	;pad

    (X-Dpy-send-read xdpy msg ReceiveFields)))

;; Pixmaps

;;;###autoload
(defun XCreatePixmap (xdpy pixmap d depth width height)
  "On display XDPY create PIXMAP using drawable D.
Return X-Pixmap structure."
  (X-Dpy-p xdpy 'XCreatePixmap)
  (X-Pixmap-p pixmap 'XCreatePixmap)
  (X-Drawable-p d)

  (let* ((ListOfFields
	  (list [1 53]			; opcode
		[1 depth]
		[2 4]			; length
		[4 (X-Pixmap-id pixmap)]
		[4 (X-Drawable-id d)]
		[2 width]
		[2 height]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)
    pixmap))

;;;###autoload
(defun XFreePixmap (xdpy pixmap)
  "On display XDPY free pixmap."
  (X-Dpy-p xdpy 'XFreePixmap)
  (X-Pixmap-p pixmap 'XFreePixmap)

  (let* ((ListOfFields
	  (list [1 54]
		[1 nil]
		[2 2]
		[4 (X-Pixmap-id pixmap)]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)

    ;; Invalidate pixmap
    (X-invalidate-cl-struct pixmap)
    ))

;; Cursoring
(defun XCreateCursor (xdpy type)
  "On display XDPY create cursor of TYPE."
  (X-Dpy-p xdpy 'XCreateCursor)

  (let* ((ListOfFields
	  (list [1 93]			;opcode
		[1 type]
		[2 2]			;length
		[4 nil]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XCreateGlyphCursor (xdpy cursor)
  "On display XDPY create CURSOR.
CURSOR is `X-Cursor' structure."
  (X-Dpy-p xdpy 'XCreateGlyphCursor)
  (X-Cursor-p cursor 'XCreateGlyphCursor)

  (unless (X-Cursor-id cursor)
    (setf (X-Cursor-id cursor) (X-Dpy-get-id xdpy)))

  (let* ((attrmsg (X-Cursor-message cursor))
	 (ListOfFields
	  (list [1 94]			;opcode
		[1 nil]			;pad
		[2 (+ 2 (/ (length attrmsg) 4))] ;length
		[4 (X-Cursor-id cursor)])) ;cursor id
	 (msg (concat (X-Create-message ListOfFields) attrmsg)))
    (X-Dpy-send xdpy msg)))
	
;;;###autoload
(defun XChangeActivePointerGrab (xdpy cursor ev-mask &optional time)
  "Change active pointer grabbing."
  (X-Dpy-p xdpy 'XChangeActivePointerGrab)
  (X-Cursor-p cursor 'XChangeActivePointerGrab)

  (let* ((ListOfFields
	  (list [1 30]			;opcode
		[1 nil]			;pad
		[2 4]			;length
		[4 (X-Cursor-id cursor)] ;cursor 
		[4 (or time X-CurrentTime)]
		[2 ev-mask]
		[2 nil]))		;pad
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;; Extensions support

;;;###autoload
(defun XQueryExtension (xdpy name)
  "On display XDPY query for extension with NAME."
  (X-Dpy-p xdpy 'XQueryExtension)

  (let* ((ListOfFields
	  (list [1 98]			;opcode
		[1 nil]			;pad
		[2 (+ 2 (X-padlen name))] ;length
		[2 (length name)]	;chars in string
		[2 nil]))		;pad
	 (msg (concat (X-Create-message ListOfFields)
		      name
		      (make-string (- (* 4 (X-padlen name)) (length name)) 0)))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 nil]		;unused
		      [2 integerp]	;sequence
		      [4 nil]		;length
		      [1 booleanp]	;present
		      [1 integerp]	;major_opcode
		      [1 integerp]	;first_event
		      [1 integerp]	;first_error
		      [20 nil])))	;padding
	 r)

    (setq r (X-Dpy-send-read xdpy msg ReceiveFields))
    (X-Dpy-log xdpy "Get reply for query ext: %s\n" 'r)

    (if (and (car r)
	     (nth 2 r))			; present field
	(pushnew (cons name r) (X-Dpy-extensions xdpy))
      nil)))

;;;###autoload
(defun X-Dpy-get-extension (xdpy extname &optional sig)
  "On display XDPY get extension with EXTNAME.
If SIG, then signal an error if extension is not available."
  (let ((ext (or (assoc extname (X-Dpy-extensions xdpy))
		 (car (XQueryExtension xdpy extname)))))
    (if (and (null ext) sig)
	(signal 'search-failed (list sig 'X-Dpy-get-extension extname))
      ext)))

;; Screen saver support
;;;###autoload
(defun XSetScreenSaver (xdpy timeout interval prefer-blacking allow-exposures)
  "On dispay XDPY set screen saver parameters."
  (X-Dpy-p xdpy 'XSetScreenSaver)

  (let* ((ListOfFields
	  (list [1 107]		; opcode
		[1 nil]
		[2 3]
		[2 timeout]
		[2 interval]
		[1 prefer-blacking]
		[1 allow-exposures]
		[2 nil]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;;;###autoload
(defun XGetScreenSaver (xdpy)
  "On display XDPY get info about screen saver."
  (X-Dpy-p xdpy 'XGetScreenSaver)

  (let* ((ListOfFields
	  (list [1 108]			;opcode
		[1 nil]			; unused
		[2 1]))
	 (msg (X-Create-message ListOfFields))
	 (ReceiveFields
	  (list [1 success]
		nil
		(list [1 nil]
		      [2 nil]
		      [4 nil]
		      [2 integerp]	; timeout
		      [2 integerp]	; interval
		      [1 booleanp]	; prefer-blacking
		      [1 booleanp]	; allow-exposures
		      [18 nil]))))
    (X-Dpy-send-read xdpy msg ReceiveFields)))

;;;###autoload
(defun XForceScreenSaver (xdpy &optional mode)
  "On display XDPY force screen saver in mode."
  (X-Dpy-p xdpy 'XForceScreenSaver)

  (let* ((ListOfFields
	  (list [1 115]
		[1 mode]
		[2 1]))
	 (msg (X-Create-message ListOfFields)))
    (X-Dpy-send xdpy msg)))

;; Additional events queue operations
;;;###autoload
(defun XNextEvent (xdpy &optional timeout)
  "On display XDPY get next X Event.
Optionally you can specify TIMEOUT.
IF TIMEOUT specified and no event arrived in TIMEOUT period, return nil."
  (let (xev done)
    (incf (X-Dpy-evq-protects xdpy))
    (unwind-protect
       (while (not done)
         (if (X-Dpy-evq xdpy)
               (setq xev (pop (X-Dpy-evq xdpy))
                     done t)

           (sit-for 0)
           (when (and (not (accept-process-output (X-Dpy-proc xdpy) (or timeout 1)))
                      timeout)
             (setq xev nil
                   done t))
           ))
      (decf (X-Dpy-evq-protects xdpy)))
    xev))

;;;###autoload
(defun XIfEvent (xdpy predicate &optional peek)
  "Block until predicate return non-nil.
If PEEK is non-nil then do not remove matched event from events queue.
Return XEV structure."
  (let (xevret evs)
    (X-Dpy-events-excursion xdpy
      (while (not xevret)
	;; Check current events queue
	(setq evs (X-Dpy-evq xdpy))
	(while (and evs (not (funcall predicate (car evs))))
	  (setq evs (cdr evs)))

	(when (X-Event-p (car evs))
	  ;; here is event
	  (setq xevret (car evs))
	  (unless peek
	    (setf (X-Dpy-evq xdpy) (delete xevret (X-Dpy-evq xdpy)))))

	;; No matched events in queue, wait server output a little
	(unless xevret
	  (sit-for 0)
	  (accept-process-output (X-Dpy-proc xdpy) 1)))) ; XXX

    xevret))
(put 'XIfEvent 'lisp-indent-function 1)

;;;###autoload
(defun XCheckIfEvent-in-queue (queue predic)
  "Check is there event in QUEUE for which PREDIC return non-nil.
Return event. If PEEK is non-nil - do not remove event from QUEUE."
  (while (and queue (not (funcall predic (car queue))))
    (setq queue (cdr queue)))

  (car queue))
  
;;;###autoload
(defun XCheckIfEvent (xdpy predic &optional peek)
  "Same as `XIfEvent', but do not block and return `nil' if there no match.
If PEEK is non-nil do not remove matching event from queue."
  (let ((evs (X-Dpy-evq xdpy)))
    (while (and evs (not (funcall predic (car evs))))
      (setq evs (cdr evs)))

    (when (X-Event-p (car evs))
      ;; here is event
      (unless peek
	(setf (X-Dpy-evq xdpy) (delete (car evs) (X-Dpy-evq xdpy)))))
    
    (car evs)))

;;;###autoload
(defun XPeekIfEvent (xdpy predic)
  "Block until PREDIC return t.
Event does not removed from events queue."
  (XIfEvent xdpy predic t))

;;;###autoload
(defun XSyncEvents (xdpy)
  "Syncronize events ready for XDPY."
  (funcall (X-Dpy-parse-guess-dispatcher xdpy) xdpy))
  
;;;###autoload
(defun XSync (xdpy &optional discard)
  "Sync with server.
When DISCARD is non nil, remove all events in events queue, even these
who was before entering `XSync'."

  (incf (X-Dpy-evq-protects xdpy))
  (XGetInputFocus xdpy)
  (decf (X-Dpy-evq-protects xdpy))

  (if (not discard)
      (XSyncEvents xdpy)

    (setf (X-Dpy-evq xdpy) nil)
    (setf (X-Dpy-evq-protects xdpy) 0)))

;;;###autoload
(defun XSetFont (xdpy gc font)
  "On display XDPY for GC set FONT."
  (X-Dpy-p xdpy 'XSetFont)
  (X-Gc-p gc 'XSetFont)
  (X-Font-p font 'XSetFont)

  (setf (X-Gc-font gc) font)
  (XChangeGC xdpy gc))


(provide 'xlib-xlib)

;;; xlib-xlib.el ends here