Source

xwem / lisp / xwem-clients.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
;;; xwem-clients.el --- Clients manage.

;; Copyright (C) 2003-2005 by XWEM Org.

;; Author: Zajcev Evgeny <zevlg@yandex.ru>
;;         Steve Youngs  <steve@youngs.au.com>
;;         Richard Klinda <ignotus@hixsplit.hu>
;; Created: 2 Mar 2003
;; 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:
;;
;; This file used for generic X clients management.
;;
;; Client state(`xwem-cl-state') is one of:
;; 
;;   'active    - Client managed and activated.
;;   
;;   'inactive  - CL managed, but not viewable.
;;   
;;   'iconified - CL iconified, not viewable.
;;   
;;   'destroyed - CL's x window destroyed.
;;   
;;   'unknown   - Not any of above.

;; 
;; Hooks are:
;; 
;;   `xwem-cl-create-hook' - Called when new CL just created.
;;
;;   `xwem-cl-destroy-hook' - Called when CL destroyed.
;;
;;   `xwem-cl-state-change-hook' - Called when CL changes state to one
;;                                 described above.
;; 
;;   `xwem-cl-manage-hook' - Called when CL just managed.  This hook
;;                           differs from `xwem-cl-create-hook',
;;                           `xwem-cl-create-hook' called only once
;;                           during client lifetime, but
;;                           `xwem-cl-manage-hook' calls evertime
;;                           client changes its managing model.
;; 
;;   `xwem-cl-activate-hook' - Called when CL is activated in its
;;                             context.
;;
;;   `xwem-cl-deactivate-hook' - Called when CL is deactivated in its
;;                               context.
;; 
;;   `xwem-cl-withdraw-hook' - Called when CL is about to move to
;;                             withdrawn state.
;;

;; Supported client properties:
;; 
;;   `noselect' - Non-nil to make client non-selectable.
;; 
;;   `skip-deselect' - Non-nil makes client non-deselectable.
;; 
;;   `override-skip-deselect' - Non-nil overrides `skip-deselect'
;;                              property of selected client.
;; 
;;   `skip-initial-state' - Non-nil to skip processing ICCCM initial
;;                          client state.
;; 
;;   `x-border-width' - Client's border width in pixels.
;; 
;;   `x-border-color' - Client's border color.
;; 
;;   `ignore-has-input-p' - Non-nil mean force focusing even if client
;;                          does not have ICCCM focus model.

;;; Code:

(eval-when-compile
  ;; Shutup compiler
  (defvar xwem-frame-ev-mask)
  )

(require 'xwem-load)
(require 'xwem-manage)
(require 'xwem-misc)

;;; Variables
(defgroup xwem-cl nil
  "Group to customize XWEM Clients handling."
  :prefix "xwem-cl-"
  :group 'xwem)

(defgroup xwem-modes nil
  "Group to customize XWEM managing modes."
  :prefix "xwem-"
  :group 'xwem)

(defcustom xwem-cl-use-parent-xwin t
  "*Non-nil mean that CL will use some X window, where it(CL) lowered.
This is need to fullish some X applications, which accuire clients in
such evil manner."
  :type 'boolean
  :group 'xwem-cl)

(defcustom xwem-cl-noname-name "<noname>"
  "*Name for clients which does not have name."
  :type 'string
  :group 'xwem-cl)

(defcustom xwem-cl-noicon-name "<noname>"
  "*Icon name for clients which does not have their own."
  :type 'string
  :group 'xwem-cl)

(defcustom xwem-cl-other-include-active t
  "*Non-nil mean include active clients in clients list when switching.
If `xwem-clswi-include-active' is function, it must be a function that
accepts one argument - CL and returns non-nil if CL must be included."
  :type '(choice (const :tag "No" nil)
                 (const :tag "Yes" t)
                 (function :tag "Custom function"))
  :group 'xwem-cl)

(defcustom xwem-cl-other-include-iconified nil
  "*Non-nil mean include iconified clients in clients list when switching.
If `xwem-clswi-include-iconified' is function, it must be a function that
accepts one argument - CL and returns non-nil if CL must be included."
  :type '(choice (const :tag "No" nil)
                 (const :tag "Yes" t)
                 (function :tag "Custom function"))
  :group 'xwem-cl)

(defcustom xwem-cl-switch-other-omit-mode-specific nil
  "*Non-nil mean \\<xwem-global-map>\\[xwem-switch-other-client]
wont select client that can be selected with \\<xwem-global-map>\\[xwem-cl-switch-to-other]."
  :type 'boolean
  :group 'xwem-cl)

(defcustom xwem-client-strict-activation nil
  "*Non-nil mean client is checked for aliveness before the activation.
Seting `xwem-client-strict-activation' to non-nil can decrease
activation speed a little, because it requires full interaction with X
server, however it guaranties to prevent X errors on activation."
  :type 'boolean
  :group 'xwem-cl)

(defcustom xwem-imove-visible t
  "*Non-nil mean `xwem-client-imove' will info you about new position."
  :type 'boolean
  :group 'xwem-cl)

(defcustom xwem-iresize-visible t
  "*Non-nil mean `xwem-client-iresize' will info you about new size."
  :type 'boolean
  :group 'xwem-cl)

(define-xwem-face x-border-face
  `(((selected) (:foreground "green"))
    (t (:foreground "gray80")))
  "Face for client's X border."
  :group 'xwem-cl
  :group 'xwem-faces)

;;;###xwem-autoload
(defcustom xwem-client-focusing 'advanced
  "Clients focusing type.
One of:

  'advanced -  Any client can be selected, even if it has broken focus model.
  'standard -  Strictly follow ICCCM, hoping everything will be ok.

You should change default value only in very rare circumstances.  You
should fully understand how focusing works in xwem to change default
value."
  :type '(choice (const :tag "Advanced" advanced)
                 (const :tag "Standard" standard))
  :group 'xwem-cl)

;;;###autoload
(defcustom xwem-client-default-properties
  '(x-border-width 2)
  "*Default properties for newly managed clients."
  :type 'list
  :group 'xwem-cl)

(defcustom xwem-client-selected-border-color "green"
  "*Border color when client is selected."
  :type 'color
  :group 'xwem-cl)

(defcustom xwem-client-nonselected-border-color "gray"
  "*Border color when client is not selected."
  :type 'color
  :group 'xwem-cl)

(defcustom xwem-cl-mark-ring-max 16
  "*Maximum size of `xwem-cl-mark-ring'.
Start discarding off end if gets this big."
  :type 'number
  :group 'xwem-cl)

;;;###autoload
(defcustom xwem-cl-create-hook nil
  "Hook to call when creating new client."
  :type 'hook
  :group 'xwem-cl)

;;;###autoload
(defcustom xwem-cl-destroy-hook nil
  "Hooks called with one argument - cl, when cl destroyed.
NOT USED YET."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-manage-hook nil
  "*Hooks to be called with just managed CL as argument."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-activate-hook nil
  "*Hooks to call when client activates.
Called with two arguments:
 CL   - Activated client
 TYPE - Activation type - either 'activate or 'select"
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-deactivate-hook nil
  "*Hooks to call when client deactivates.
Called with two arguments:
 CL   - Deactivated client
 TYPE - Deactivation type - either 'deactivate or 'deselect"
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-refit-hook nil
  "Hooks called when CL just refited."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-iconify-hook nil
  "Hooks called when CL just iconified."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-withdraw-hook nil
  "*Hooks to call when CL moved to withdrawn state."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-change-hook nil
  "Hooks called when something changed in CL."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-cl-state-change-hook nil
  "*Hooks to run when state of client changes.
Every hook called with three args - CL OLD-STATE NEW-STATE."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-client-select-hook nil
  "*Hooks called when new client just selected.
It is pretty guarantied that `xwem-selected-client' is valid xwem-cl
structure at time of hook execution."
  :type 'hook
  :group 'xwem-hooks)

;;;###autoload
(defcustom xwem-client-deselect-hook nil
  "Hooks called with one arg - cl, when cl deselected.
It is pretty guarantied that `xwem-selected-client' is valid xwem-cl
structure at time of hook execution."
  :type 'hook
  :group 'xwem-hooks)

;;; Internal variables


(defconst xwem-client-ev-mask
  (Xmask-or XM-ColormapChange XM-PropertyChange
            XM-FocusChange XM-EnterWindow XM-LeaveWindow
            XM-StructureNotify XM-ResizeRedirect)
  "Event mask for xwem's client.")

;;;###xwem-autoload
(defvar xwem-clients nil
  "List of all managed clients.")

;;;###xwem-autoload
(defvar xwem-current-cl nil
  "Internal variable.
Use `xwem-cl-selected' to get selected client.")

;;;###xwem-autoload
(defvar xwem-last-cl nil
  "Last selected client.
Use `(xwem-last-client)' to get last selected client.")

;;;###autoload
(defvar xwem-cl-mark-ring nil
  "The list of marked clients.")

;;;###xwem-autoload
(defmacro xwem-cl-marked-p (cl)
  "Return non-nil if client CL is marked, i.e. in `xwem-cl-mark-ring' list."
  `(memq ,cl xwem-cl-mark-ring))

;;; Client properties
;;;###xwem-autoload
(defvar xwem-supported-client-properties nil
  "List of supported client's properties definitions.
Property definition is list in form:
\(NAME . (MANAGE-TYPE (KEYWORD VAL ...) ...)).

Valid KEYWORD are:

   `:type' - Same as for `defcustom'.  eval composite type added.

   `:set' - Function to call when setting this property. Default is
            `xwem-cl-put-prop'.  Function called with three
            arguments - CL PROP VAL.

   `:get'  - Function to call in order to fetch property value. Default
             is `xwem-cl-get-prop'. Function called with two
             arguments - CL PROP.
")

;;;###xwem-autoload
(defmacro define-xwem-client-property (name manage-type doc &rest keys-vals)
  "Define new xwem client property NAME."
  `(xwem-support-cl-property (quote ,name) (quote ,manage-type)
                             (list :doc ,doc ,@keys-vals)))

;;;###xwem-autoload
(defun xwem-property-supported-p (prop)
  "Return non-nil if client property PROP is supported."
  (assq prop xwem-supported-client-properties))

;;;###xwem-autoload
(defun xwem-support-cl-property (prop-name manage-type keys-val)
  "Add supported client property."
  (let ((pdef (assq prop-name xwem-supported-client-properties)))
    (unless pdef
      (setq pdef (cons prop-name nil))
      (setq xwem-supported-client-properties
            (cons pdef xwem-supported-client-properties)))

    (setcdr pdef (plist-put (cdr pdef) manage-type keys-val))))

;;;###xwem-autoload
(defun xwem-unsupport-cl-property (prop-name manage-type)
  "Remove PROP-NAME from supported property for MANAGE-TYPE."
  (let ((pdef (assq prop-name xwem-supported-client-properties)))
    (when pdef
      (setcdr pdef (plist-remprop (cdr pdef) manage-type))
      (when (null (cdr pdef))
        (setq xwem-supported-client-properties
              (delq pdef xwem-supported-client-properties))))))

(defun xwem-clprop-get-keyword (cl prop keyword &optional default)
  "Return CL's property KEYWORD value.
If no KEYWORD for such CL, return default KEYWORD value.
Return DEFAULT if KEYWORD not found."
  (let ((prop-def (assq prop xwem-supported-client-properties)))
    (or (plist-get (plist-get (cdr prop-def) (xwem-cl-manage-type cl)) keyword)
        (plist-get (plist-get (cdr prop-def) nil) keyword default))))
  
;;;###xwem-autoload
(defun xwem-client-set-property (cl prop val)
  "Set client property."
  (funcall (xwem-clprop-get-keyword cl prop :set 'xwem-cl-put-prop)
           cl prop val)
  ;; Save new properties in CL's plist XProperty
  (xwem-cl-XProperty-plist-export cl))

;;;###xwem-autoload
(defun xwem-client-set-properties (cl props)
  "To CL's properties import PROPS."
  (while props
    (xwem-client-set-property cl (car props) (cadr props))
    (setq props (cddr props))))

;;;###xwem-autoload
(defun xwem-client-property (cl prop)
  "Return CL's property PROP."
  (funcall (xwem-clprop-get-keyword cl prop :get 'xwem-cl-get-prop)
           cl prop))

(defun xwem-client-properties (cl)
  "Return CL's properties list."
  (let ((cplist (xwem-cl-plist cl))
        (rplist nil))
    (while cplist
      (when (xwem-property-supported-p (car cplist))
        (setq rplist (plist-put rplist (car cplist) (cadr cplist))))
      (setq cplist (cddr cplist)))
    rplist))

(define-xwem-client-property x-border-width nil
  "CL's xwin border width."
  :type 'number
  :set 'xwem-client-set-x-border-width)

(define-xwem-client-property x-border-color nil
  "CL's xwin border color."
  :type 'color
  :set 'xwem-client-set-x-border-color)

(define-xwem-client-property noselect nil
  "Non-nil mean CL can't be selected."
  :type 'boolean)

(define-xwem-client-property skip-deselect nil
  "CL skips deselecting."
  :type 'boolean)

(define-xwem-client-property override-skip-deselect nil
  "CL overrides skip-deselect property of selected client."
  :type 'boolean)

(define-xwem-client-property skip-initial-state nil
  "Non-nil mean skip CL's initial state hint."
  :type 'boolean)

(define-xwem-client-property client-window nil
  "Window id where client is currently managed.
Set only if using windowing managing model."
  :type 'number)


;; X Properties stuff
(defmacro xwem-cl-XProperty-get (cl prop-atom-string)
  `(xwem-XProperty-get (xwem-cl-xwin ,cl) ,prop-atom-string))
(defmacro xwem-cl-XProperty-set (cl prop-atom-string prop-val)
  `(xwem-XProperty-set (xwem-cl-xwin ,cl) ,prop-atom-string ,prop-val))
(defmacro xwem-cl-XProperty-manage-spec (cl)
  `(xwem-cl-XProperty-get ,cl "XWEM_CLIENT_MANAGE_SPEC"))
(define-xwem-deffered xwem-cl-XProperty-manage-spec-export (cl)
  "Export CL's manage spec into XWEM_CLIENT_PLIST X property."
  (when (xwem-cl-alive-p cl)
    (xwem-cl-XProperty-set cl "XWEM_CLIENT_MANAGE_SPEC"
                           (xwem-cl-manage-spec cl))))
(defmacro xwem-cl-XProperty-plist (cl)
  `(xwem-cl-XProperty-get ,cl "XWEM_CLIENT_PLIST"))
(define-xwem-deffered xwem-cl-XProperty-plist-export (cl)
  "Export CL's plist into XWEM_CLIENT_PLIST X property."
  (when (xwem-cl-alive-p cl)
    (xwem-cl-XProperty-set cl "XWEM_CLIENT_PLIST"
                           (xwem-client-properties cl))))


;;; Functions
(defun xwem-client-set-x-border-width (cl bprop width)
  "Change CL's border with to WIDTH.
Default WIDTH is 0."
  (xwem-cl-put-prop cl bprop width)     ; save it in props

  (unless (numberp width)
    (setq width 0))                     ; XXX

  (setf (xwem-cl-new-xgeom cl) (make-X-Geom :border-width width))
  (xwem-refit cl))

(defun xwem-client-set-x-border-color (cl bprop col)
  "Change CL's border color to COL."
  (xwem-cl-put-prop cl bprop col)       ; save it in props

  (unless col
    (setq col "black"))                 ; XXX

  (XSetWindowBorder (xwem-dpy) (xwem-cl-xwin cl)
                    (XAllocColor (xwem-dpy) (XDefaultColormap (xwem-dpy))
                                 (xwem-make-color col))))

(defun xwem-cl-focus-selected ()
  "If CL is selected, set focus on it.
Used in `xwem-post-deffering-hook'."
  (xwem-focus-set (xwem-cl-selected)))

;;;###xwem-autoload
(defun xwem-cl-select (cl)
  "Set CL to be current cl."
  (xwem-client-local-variables-import (xwem-cl-selected))

  ;; Set CL to be current client
  (setf (xwem-last-client) (xwem-cl-selected))
  (setf (xwem-cl-selected) cl)

  (xwem-client-local-variables-export cl))

(define-xwem-client-property ignore-has-input-p nil
  "Ignore No Input/Globally Active input model and force focusing."
  :type 'boolean)

(defun xwem-cl-can-be-selected-p (cl)
  "Return non-nil if CL can be selected.
If `xwem-client-focusing' is not 'advanced `xwem-cl-can-be-selected-p'
can return nil in situations where you expecting t.  When changing
default value of `xwem-client-focusing' be sure your xwem configured
properly to handle applications with broken focus models."
  (and (not (xwem-client-property cl 'noselect))
       (or (xwem-client-property cl 'ignore-has-input-p)
           (eq xwem-client-focusing 'advanced)
           (X-WMHints-input-p (xwem-hints-wm-hints (xwem-cl-hints cl)))
           (XWMProtocol-set-p (xwem-dpy)
                              (xwem-hints-wm-protocols (xwem-cl-hints cl))
                              "WM_TAKE_FOCUS"))))

(define-xwem-deffered xwem-cl-apply-x-border-color (cl)
  "Apply CL's x border color to life."
  (when (xwem-cl-managed-p cl)
    (XSetWindowBorder (xwem-dpy) (xwem-cl-xwin cl)
                      (X-Gc-foreground
                       (xwem-face-get-gc 'x-border-face
                         (and (xwem-cl-selected-p cl) '(selected)) cl)))))

(defun xwem-client-default-select-hook ()
  "Default hook to be added to `xwem-client-select-hook'."
  (xwem-cl-apply-x-border-color (xwem-cl-selected)))

(defun xwem-client-default-deselect-hook ()
  "Default hook to be added to `xwem-client-deselect-hook'."
  (xwem-cl-apply-x-border-color (xwem-cl-selected)))

;;;###xwem-autoload
(defun xwem-select-client (cl)
  "Select new client CL.
CL will not be selected if currently selected client has property
`skip-deselect', unless CL has property `override-skip-deselect'.
If CL is not selected because of above condition, last client is
updated however.
If CL is non-client, dummy client will be selected."
  (unless (xwem-cl-p cl)
    (setq cl (xwem-dummy-client)))

  ;; Update CL's recency
  (setf (xwem-cl-recency cl) (current-time))

  ;; Skip clients that can't be selected
  (if (not (xwem-cl-can-be-selected-p cl))
      (xwem-activate cl)

    (cond ((and (not (xwem-cl-selected-p cl))
                (xwem-cl-active-p (xwem-cl-selected))
                (xwem-client-property (xwem-cl-selected) 'skip-deselect)
                (not (xwem-client-property cl 'override-skip-deselect)))
           ;; If client has such property it mean that no other client
           ;; can be selected untill CL will unset this property.
           ;; Good example of using it is xwem minibuffer.  When it is
           ;; active, no other clients can be selected.
           (setf (xwem-last-client) cl))

          (t
           (unless (xwem-cl-selected-p cl)
             (xwem-deactivate (xwem-cl-selected) 'deselect)
             (run-hooks 'xwem-client-deselect-hook)
             (xwem-cl-select cl)
             (run-hooks 'xwem-client-select-hook))
       
           (xwem-activate cl 'select)
           (xwem-add-hook-post-deffering 'xwem-cl-focus-selected)))
    ))

(defmacro xwem-with-current-client (cl &rest forms)
  "Make CL to be current and exectute FORMS.
After execution restore current client."
  `(let ((xwem-saved-current-client (xwem-cl-selected))
         (xwem-saved-last-client (xwem-cl-selected)))
     (xwem-cl-select ,cl)
     (prog1
         (progn ,@forms)
       (xwem-cl-select xwem-saved-current-client)
       (setf (xwem-last-client) xwem-saved-last-client))))

;;;###xwem-autoload
(defun xwem-client-name (cl &optional clist)
  "Returns unique name for CL.
If CLIST is ommited, `xwem-clients' will be used.
If CL is string, return it."
  (if (stringp cl)
      cl
    (let ((cll (or clist xwem-clients))
          (cln (xwem-hints-wm-name (xwem-cl-hints cl)))
          (cnt 0))
      (while cll
        (cond ((string= (xwem-hints-wm-name (xwem-cl-hints (car cll))) cln)
               (if (eq cl (car cll))
                   (setq cll nil)
                 (setq cnt (1+ cnt))))
              (t nil))
        (setq cll (cdr cll)))
      (if (> cnt 0)
          (format "%s<%d>" cln cnt)
        cln))))

;;;###xwem-autoload
(defun xwem-find-client (win-or-id)
  "Find WIN-OR-ID in client windows list.
WIN-OR-ID can be X-Win or id of window."
  (let ((winid (if (X-Win-p win-or-id) (X-Win-id win-or-id) win-or-id))
        (cl xwem-clients)
        (rc nil))
    (while cl
      (if (= (X-Win-id (xwem-cl-xwin (car cl))) winid)
          (progn
            (setq rc (car cl))
            (setq cl nil))
        (setq cl (cdr cl))))
    rc))

(defun xwem-remove-client (cl)
  "Delete WIN from clients list."
  (setq xwem-clients (delete cl xwem-clients)))

(defun xwem-cl-do-gravity (cl step)
  "Change CL's gravity.
NOT USED"
  )

;;;###xwem-autoload(autoload 'xwem-cl-send-config "xwem-clients")
(define-xwem-deffered xwem-cl-send-config (cl)
  "Send config info to window."
  (let ((clgeom (xwem-cl-xgeom cl))
        (win (xwem-cl-xwin cl)))
    (XSendEvent (xwem-dpy) win nil XM-StructureNotify
                (X-Create-message
                 (list [1 X-ConfigureNotify] ;type
                       [1 nil]          ;detail
                       [2 2806]         ;seq
                       [4 (X-Win-id win)] ;event
                       [4 (X-Win-id win)] ;window
                       [4 X-None]       ;above sibling
                       (vector 2 (X-Geom-x clgeom)) ; shutup compiler
                       [2 (X-Geom-y clgeom)]
                       [2 (X-Geom-width clgeom)]
                       [2 (X-Geom-height clgeom)]
                       [2 (X-Geom-border-width clgeom)] ;XXX
                       [1 nil]          ;pad override
                       [1 nil]          ;pad
                       )))
    ))


;;;###xwem-autoload
(defun xwem-clients-list (&optional predict include-dummy states)
  "Return xwem clients list.

PREDICT is function passed with one argument - CL and must return
non-nil if CL must be included in resulting list.  If PREDICT not
specified - all clients are included.

If INCLUDE-DUMMY is non-nil also include dummy clients(clients for
which `xwem-dummy-client-p' returns non-nil).

STATES is a list of valid states for client or 'any."
  (delq nil
        (mapcar #'(lambda (cl)
                    (and (or (eq states 'any)
                             (xwem-cl-managed-p cl states))
                         (or include-dummy (not (xwem-dummy-client-p cl)))
                         (or (not predict) (funcall predict cl))
                         cl))
                xwem-clients)))

;;;###xwem-autoload
(defun xwem-cl-list-sort-by-recency (cl-list)
  "Sort clients in CL-LIST by their recency."
  (sort (copy-list cl-list)
        #'(lambda (cl1 cl2)
            (let ((rc1 (xwem-cl-recency cl1))
                  (rc2 (xwem-cl-recency cl2)))

              (if (or (not rc1) (not rc2))
                  (not (null rc1))
                    
                (cond ((> (nth 0 rc1) (nth 0 rc2))
                       t)
                      ((< (nth 0 rc1) (nth 0 rc2))
                       nil)
                      (t (cond ((> (nth 1 rc1) (nth 1 rc2))
                                t)
                               ((< (nth 1 rc1) (nth 1 rc2))
                                nil)
                               (t (cond ((> (nth 2 rc1) (nth 2 rc2))
                                         t)
                                        ((< (nth 2 rc1) (nth 2 rc2))
                                         nil)
                                        (t t)))))))))))

;;;###xwem-autoload(autoload 'xwem-cl-other "xwem-clients")
(defun* xwem-cl-other (cl &key clients no-sort also-active also-iconified)
  "Return xwem client other then CL selecting from CLIENTS.
Default CLIENTS is what is returned by `xwem-clients-list'.
Deactivated clients are preferred to activated, unless ALSO-ACTIVE
is non-nil. Special clients excluded.
Unless ALSO-ICONIFIED is non-nil iconified clients will be excluded.

Use `(xwem-cl-other cl :no-sort t)' form to fetch most recent
client, other then CL.

CLIENTS is sorted by recency unless NO-SORT is non-nil."
  (unless clients
    (setq clients (xwem-clients-list)))

  (unless no-sort
    (setq clients
          (xwem-cl-list-sort-by-recency clients)))

  (let ((rcl nil)
        (notgoodcl nil))                ;not so good candidate as rcl

    (while clients
      (when (and (xwem-cl-p (car clients)) ; skip non-clients
                 (not (eq (car clients) cl)) ; skip ourself
                 ;; skip iconified
                 (or also-iconified
                     (not (eq (xwem-cl-state (car clients)) 'iconified))
                     (if (functionp xwem-cl-other-include-iconified)
                         (funcall xwem-cl-other-include-iconified
                                  (car clients))
                       xwem-cl-other-include-iconified)))
        (if (or also-active
                (not (eq (xwem-cl-state (car clients)) 'active))
                (if (functionp xwem-cl-other-include-active)
                    (funcall xwem-cl-other-include-active
                             (car clients))
                  xwem-cl-other-include-active))
            ;; Found pretty good candidate
            (setq rcl (car clients)
                  clients nil)

          (when (and also-active (null notgoodcl))
            (setq notgoodcl (car clients)))))
      (setq clients (cdr clients)))
    
    ;; Return
    (or rcl notgoodcl)))

;;;###xwem-autoload
(defun xwem-select-some-client ()
  (unless (and (xwem-cl-alive-p (xwem-cl-selected))
               (eq (xwem-cl-state (xwem-cl-selected)) 'active))
    (xwem-select-client nil)))

;;;###xwem-autoload
(defun xwem-select-last-or-other-client (cl &optional force allow-dummy)
  "Select last or other client according to CL.
New client selected only if CL is current selected or FORCE is non-nil
or dummy client currently selected.

`xwem-select-last-or-other-client' tries to avoid selecting dummy
clients, unless ALLOW-DUMMY is non-nil."
  (when (or force
            (xwem-cl-selected-p cl)
            (xwem-cl-selected-p (xwem-dummy-client)))
    (if (and (xwem-cl-alive-p (xwem-last-client))
             (not (eq (xwem-last-client) cl))
             (or allow-dummy
                 (not (xwem-dummy-client-p (xwem-last-client)))))
        (xwem-select-client (xwem-last-client))
      (xwem-select-client (xwem-cl-other cl)))))


;;;###xwem-autoload
(defun xwem-cl-correct-size-for-size (cl new-geom &optional x-type y-type)
  "Make CL's geometry as close to NEW-GEOM as possible.
X-TYPE is one of 'center 'left or 'right, default is 'center.
Y-TYPE is one of 'center 'top or 'bottom, default is 'center."
  (let* ((hthi (or (X-Geom-border-width new-geom) 0))
         (he (X-Geom-height new-geom))
         (wi (X-Geom-width new-geom))
         (clgmt (xwem-cl-xgeom cl))
         (wmnh (xwem-cl-wm-normal-hints cl))
         (wi-rmd 0) (he-rmd 0)
         bw bh wi-st he-st)

    (when wmnh
      (setq bw (X-WMSize-base-width wmnh))
      (setq bh (X-WMSize-base-height wmnh))

      (when (X-WMSize-presizeinc-p wmnh)
        (setq wi-st (X-WMSize-width-inc wmnh)) ; width step
        (setq he-st (X-WMSize-height-inc wmnh))) ; height step

      ;; - Calculate size reminders
      ;; - Adjust wi-rmd and he-rmd if needed
      (when wi-st
        (setq wi-rmd (% (abs (- wi bw (* 2 hthi))) wi-st))
        (when (> bw wi)
          (setq wi-rmd (- wi-st wi-rmd))))

      (when he-st
        (setq he-rmd (% (abs (- he bh (* 2 hthi))) he-st))
        (when (> bh he)
          (setq he-rmd (- he-st he-rmd))))

      ;; Check aspect ratio, note: major mode may have
      ;; 'omit-aspect-ratio property, in this case no aspect ratio
      ;; checking is performed.
      ;; NOTE: not full support of aspect ratios, only minimal aspect
      ;;       ratio is used in geometry calculation.
      (when (and (X-WMSize-paspect-p wmnh)
                 (not (xwem-manage-property
                       (xwem-cl-manage-type cl) 'omit-aspect-ratio)))
        (let* ((mia-x (X-WMSize-min-aspect-x wmnh))
               (mia-y (X-WMSize-min-aspect-y wmnh))
;               (maa-x (X-WMSize-max-aspect-x wmnh))
;               (maa-y (X-WMSize-max-aspect-y wmnh))
               (client-ratio (/ (float mia-x) mia-y))
               (window-ratio (/ (float wi) he))
               nw nh)
          ;;  +-------------+
          ;;  |             | <---- window aspect ratio < 
          ;;  |MMMMMMMMMMMMM|           client aspect ratio 
          ;;  |MMMMMMMMMMMMM|        (width = window width)
          ;;  |             |
          ;;  +-------------+              +-------------+
          ;;                               |   MMMMMMM   |
          ;; window aspect ratio >   ----> |   MMMMMMM   |
          ;;     client aspect ratio       |   MMMMMMM   |
          ;;  (height = window height)     |   MMMMMMM   |
          ;;                               +-------------+
 
          ;;         width        width = ratio * height
          ;; ratio = ------  =>  
          ;;         height       height = width / ratio
          ;; 
          ;; --ignotus
          (cond ((< window-ratio client-ratio)
                 (setq nw (- wi bw)
                       nh (floor (/ nw client-ratio))))
                ((> window-ratio client-ratio)
                 (setq nh (- he bh)
                       nw (floor (* client-ratio nh)))))

          ;; Set reminders according to calculated NW/NH
          (when (and nw nh)
            (setq wi-rmd (- wi nw)
                  he-rmd (- he nh))))))

    (unless (X-Geom-p clgmt)
      (setf (xwem-cl-xgeom cl) (make-X-Geom))
      (setq clgmt (xwem-cl-xgeom cl)))

    ;; Now adjust geometry according to X-TYPE and Y-TYPE layout
    (cond ((eq x-type 'left)
           (setf (X-Geom-x clgmt) (X-Geom-x new-geom)))
          ((eq x-type 'right)
           (setf (X-Geom-x clgmt) (+ (X-Geom-x new-geom) wi-rmd)))
          (t                            ; 'center or any other
           (setf (X-Geom-x clgmt) (+ (X-Geom-x new-geom) (/ wi-rmd 2)))))
    (cond ((eq y-type 'top)
           (setf (X-Geom-y clgmt) (X-Geom-y new-geom)))
          ((eq y-type 'bottom)
           (setf (X-Geom-y clgmt) (+ (X-Geom-y new-geom) he-rmd)))
          (t
           (setf (X-Geom-y clgmt) (+ (X-Geom-y new-geom) (/ he-rmd 2)))))

    (setf (X-Geom-width clgmt) (- wi (* 2 hthi) wi-rmd))
    (setf (X-Geom-height clgmt) (- he (* 2 hthi) he-rmd))))

;;;###autoload(autoload 'xwem-client-iconify "xwem-clients" "" t)
(define-xwem-command xwem-client-iconify (cl &optional arg)
  "Iconify selected client CL.
If prefix ARG is given - iconify only clients of same major mode as
selected client."
  (xwem-interactive (list (xwem-cl-selected) xwem-prefix-arg))

  (unless (xwem-cl-alive-p cl)
    (error 'xwem-error "Invalid client"))

  (if arg
      (mapc 'xwem-iconify
            (xwem-clients-list
             #'(lambda (ocl)
                 (eq (xwem-cl-manage-type ocl)
                     (xwem-cl-manage-type cl)))))
    (xwem-iconify cl)))

;;;###xwem-autoload(autoload 'xwem-client-iconify-every "xwem-clients" "" t)
(define-xwem-command xwem-client-iconify-every (arg)
  "Iconify every client.
If prefix ARG is specified - iconify also dummy clients."
  (xwem-interactive "P")

  (mapc 'xwem-client-iconify (xwem-clients-list nil arg)))

;;;###autoload(autoload 'xwem-switch-client "xwem-clients" "" t)
(define-xwem-command xwem-switch-client (arg)
  "Interactively switch to client.
When used with prefix ARG, then filter to clients of same managing
model as selected client."
  (xwem-interactive "P")

  (let* ((pred (when arg
                 (let ((mt (and (xwem-cl-p (xwem-cl-selected))
                                (xwem-cl-manage-type (xwem-cl-selected)))))
                   `(lambda (cl)
                      (eq (xwem-cl-manage-type cl) (quote ,mt))))))
         (clients (xwem-cl-list-sort-by-recency
                   (xwem-clients-list pred arg)))
         (cl (xwem-read-client
              (if arg (format "XWEM-CL (%S): "
                              (and (xwem-cl-p (xwem-cl-selected))
                                   (xwem-cl-manage-type (xwem-cl-selected))))
                "XWEM-CL: ") clients)))

    (unless (xwem-cl-alive-p cl)
      (error 'xwem-error "Invalid client"))

    (xwem-select-client cl)))

;;;###autoload(autoload 'xwem-switch-other-client "xwem-clients" "" t)
(define-xwem-command xwem-switch-other-client (arg)
  "Switch to client other then selected.
This command differs from `xwem-cl-switch-to-other' command,
'other-client' method is not examined, but most recent client is
selected, so pressing `\\<xwem-global-map>\\[xwem-switch-other-client]'
twice will select selected client, what is not guarantied by
`xwem-cl-switch-to-other'."
  (xwem-interactive "p")

  (let* ((cl (xwem-cl-selected))
         (ocl (and xwem-cl-switch-other-omit-mode-specific
                   (xwem-method-other-client cl))))
    (while (> arg 0)
      (setq cl (xwem-cl-other
                cl :clients (xwem-clients-list
                             `(lambda (cl)
                                (not (eq cl ,ocl))))))
      (decf arg))
    (unless (xwem-cl-p cl)
      (setq cl ocl))
    (unless (xwem-cl-p cl)
      (error 'xwem-error "No other client"))

    (xwem-select-client cl)))

;;;###autoload(autoload 'xwem-attach-client "xwem-clients" "" t)
(define-xwem-command xwem-attach-client (arg)
  "Attach client to current window.
When used with prefix ARG, select also clients that are already in
current window."
  (xwem-interactive "P")

  (let* ((pred #'(lambda (cl)
                   (and (xwem-manage-property
                         (xwem-cl-manage-type cl) 'win-support)
                        (or arg
                            (not (xwem-win-selected-p
                                  (xwem-cl-win cl)))))))
         (cl (xwem-read-client (if arg "XWEM-CL any: " "XWEM-CL: ")
                               (xwem-cl-list-sort-by-recency
                                (xwem-clients-list pred)))))

    (unless (xwem-cl-alive-p cl)
      (error 'xwem-error "Invalid client"))

    (xwem-win-set-cl (xwem-win-selected) cl)
    (xwem-select-client cl)))

;;;###autoload(autoload 'xwem-cl-switch-other-win "xwem-clients" "" t)
(define-xwem-command xwem-cl-switch-other-win (cl &optional arg)
  "Switch to CL in other window.
When used with prefix ARG, then focus to that other window."
  (xwem-interactive "cXWEM-CL Other: \nP")

  (let (nwin)
    (when (xwem-win-only-one-p (xwem-win-selected))
      (xwem-window-split-vertically nil)) ; XXX
    (setq nwin (xwem-win-next (xwem-win-selected)))

    (xwem-win-set-cl nwin cl)
    (when arg
      (xwem-select-window nwin))))

;;;###autoload(autoload 'xwem-cl-switch-other-frame "xwem-clients" "" t)
(define-xwem-command xwem-cl-switch-other-frame (cl &optional arg)
  "Switch to CL in other XWEM frame.
When used with prefix ARG, then create embedded frame, if creation is
needed at all."
  (xwem-interactive
   (list (xwem-read-client
          "XWEM-CL Other frame: "
          (xwem-cl-list-sort-by-recency
           (xwem-clients-list
            #'(lambda (cl)
                (xwem-manage-property (xwem-cl-manage-type cl) 'win-support)))))
         xwem-prefix-arg))

  (let ((ofr (or (xwem-frame-other (xwem-frame-selected))
                 (xwem-make-frame-1 (or (and arg 'embedded) 'desktop)
                                    :noselect t))))

    (xwem-cl-change-window cl (xwem-frame-selwin ofr))
    (xwem-select-client cl)))

;;;###autoload(autoload 'xwem-cl-switch-to-other "xwem-clients" "" t)
(define-xwem-command xwem-cl-switch-to-other (cl &optional n)
  "Switch to xwem client other then CL.
Default CL is selected client.
If prefix argument N is specified, switch to N's other client."
  (xwem-interactive (list (xwem-cl-selected)
                          (prefix-numeric-value xwem-prefix-arg)))

  (while (> n 0)
    (setq cl (xwem-method-other-client cl))
    (decf n))

  (unless (xwem-cl-alive-p cl)
    (error 'xwem-error "No other client available"))

  (xwem-select-client cl))

;;;###autoload(autoload 'xwem-cl-switch-to-other-in-other-win "xwem-clients" "" t)
(define-xwem-command xwem-cl-switch-to-other-in-other-win (n)
  "Switch to other client in other window then selected,"
  (xwem-interactive "p")

  (when (xwem-win-only-one-p)
    (error 'xwem-error "Only one window"))

  (let* ((win (xwem-window-other 1))
         (cl (xwem-win-cl win)))
    (while (> n 0)
      (setq cl (xwem-cl-other cl :clients (xwem-win-clients win)))
      (decf n))

    (unless (xwem-cl-alive-p cl)
      (error 'xwem-error "Invalid client"))

    (xwem-activate cl)))
         
;;;###autoload(autoload 'xwem-kill-cl-and-window "xwem-clients" "" t)
(define-xwem-command xwem-kill-cl-and-window (window &optional arg)
  "Kill WINDOW an client currently activated in it.
If used with prefix ARG then kill client in other window and other
window (not implemented)."
  (xwem-interactive (list (xwem-win-selected)
                          xwem-prefix-arg))

  (let* ((win (if arg (xwem-window-other 1 window) window))
         (cl (xwem-win-cl win)))

    ;; kill client
    (when (xwem-cl-p cl)
      (xwem-client-kill cl))

    ;; kill window
    (xwem-window-delete win)))

;;;###autoload(autoload 'xwem-cl-transpose "xwem-clients" "" t)
(define-xwem-command xwem-cl-transpose (cl &optional arg)
  "Transpose CL with client at right in CL's WIN.
If ARG is non-nil transpose with left client.
If CL is ommited than selected client will be used."
  (xwem-interactive (list (xwem-cl-selected)
                          xwem-prefix-arg))

  (when (xwem-cl-p cl)
    (let* ((sw (xwem-cl-win cl))
           (tai (cadr (memq cl (funcall (if arg 'reverse 'identity)
                                        (xwem-win-clients sw))))))
      (unless (xwem-cl-p tai)
        (setq tai (cadr (memq cl (funcall (if arg 'identity 'reverse)
                                          (xwem-win-clients sw))))))

      (when (xwem-cl-p tai)
        (xwem-list-exchange-els (xwem-win-clients sw) cl tai)
        (run-hook-with-args 'xwem-win-clients-change-hook sw))
      )))
(put 'xwem-cl-transpose 'xwem-frame-command t)

(defun xwem-clients-init ()
  "Clients part initializer"
  (xwem-message 'init "Initializing clients ...")

  (setq xwem-clients nil)

  ;; Add default select/deselect hooks
  (add-hook 'xwem-client-select-hook 'xwem-client-default-select-hook t)
  (add-hook 'xwem-client-deselect-hook 'xwem-client-default-deselect-hook t)

  ;; Initialise dummy client
  (xwem-dummy-client-init)

  (xwem-message 'init "Initializing clients ... done"))

;;;###xwem-autoload
(defun xwem-client-sendmsg-atom (cl atom &optional time)
  "Send Client message to client CL."
  (XSendEvent (xwem-dpy) (xwem-cl-xwin cl) nil 0
              (X-Create-message
               (list [1 X-ClientMessage] ; type
                     [1 X-format-32]    ; format
                     [2 1000]           ; XXX seq
                     [4 (X-Win-id (xwem-cl-xwin cl))] ; window
                     [4 (X-Atom-id (X-Atom-find-by-name (xwem-dpy) "WM_PROTOCOLS"))]
                     [4 (X-Atom-id atom)]
                     [4 (or time X-CurrentTime)]
                     [4 nil]))))

(defun xwem-client-delete-window (cl)
  "Close xwem client CL in safe manner.
Return non-nil, if CL supports WM_DELETE_WINDOW."
  (when (XWMProtocol-set-p (xwem-dpy)
                           (xwem-hints-wm-protocols (xwem-cl-hints cl)) "WM_DELETE_WINDOW")
    (xwem-client-sendmsg-atom cl
                              (X-Atom-find-by-name (xwem-dpy) "WM_DELETE_WINDOW"))
    t))

(define-xwem-deffered xwem-client-apply-state (cl)
  "Apply CL's state to life."
  (when (xwem-cl-alive-p cl)
    (cond ((memq (xwem-cl-state cl) '(active iconified inactive))
           (XSetWMState (xwem-dpy) (xwem-cl-xwin cl)
                        (if (eq (xwem-cl-state cl) 'active)
                            X-NormalState
                          X-IconicState)))
          ((xwem-misc-xwin-valid-p (xwem-cl-xwin cl))
           (XSetWMState (xwem-dpy) (xwem-cl-xwin cl) X-WithdrawnState)))))

;;;###xwem-autoload
(defun xwem-client-change-state (cl state)
  "Change WM_STATE for CL, to STATE.
STATE is one of 'active, 'inactive, 'iconified, 'withdrawn, etc."
  (let ((old-state (xwem-cl-state cl)))
    (setf (xwem-cl-state cl) state)
    (xwem-client-apply-state cl)
    (run-hook-with-args 'xwem-cl-state-change-hook cl old-state state)))

(defun xwem-client-withdraw (cl)
  "Put CL in withdraw state.
I.e. after `xwem-client-withdraw' CL will not have manage entry."
  (xwem-client-change-state cl 'withdrawn)
  (xwem-method-withdraw cl)

  ;; If CL was current client, uset current client
  (when (xwem-cl-selected-p cl)
    (xwem-select-client nil)))

;;; Creating new client
(defun xwem-cl-presetup (cl)
  "Reparent client CL. CL should be already setuped.
NOTE: specials clients presetuped as any other."
  (let ((xwin (xwem-cl-xwin cl)))
    ;; Select for events
    (XSelectInput (xwem-dpy) xwin (xwem-cl-ev-mask cl))
    (X-Win-EventHandler-add-new xwin 'xwem-cl-events-handler 100)

    ;; Fetch some window properties
    (setf (xwem-cl-hints cl)
          (make-xwem-hints
           :wm-normal-hints (or (XGetWMNormalHints (xwem-dpy) xwin)
                                (make-X-WMSize :flags 0))
           :wm-hints (or (XGetWMHints (xwem-dpy) xwin)
                         (make-X-WMHints :flags 0))
           :wm-class (multiple-value-bind (ci cn)
                         (values-list (XGetWMClass (xwem-dpy) xwin))
                       (cons ci cn))
           :wm-command (XGetWMCommand (xwem-dpy) xwin)
           :wm-name (XGetWMName (xwem-dpy) xwin)
           :wm-icon-name (XGetPropertyString (xwem-dpy)
                                             xwin XA-wm-icon-name)
           :wm-transient-for (XGetWMTransientFor (xwem-dpy) xwin)
           :wm-protocols (XGetWMProtocols (xwem-dpy) xwin)))

    (when (zerop (length (xwem-hints-wm-name (xwem-cl-hints cl))))
      ;; WMNAME is empty
      (setf (xwem-hints-wm-name (xwem-cl-hints cl)) xwem-cl-noname-name))

    ;; In case CL is transient for window
    (setf (xwem-cl-transient-for cl)
          (xwem-hints-wm-transient-for (xwem-cl-hints cl)))

    ;; TODO: skip clients created by xwem (for example embedded frame)
    (unless (X-Win-get-prop (xwem-cl-xwin cl) 'xwin-created-by-xwem)
      (XChangeSaveSet (xwem-dpy) (xwem-cl-xwin cl) X-SetModeInsert))

    ;; Install keyboard grabs, (ARGUSED)
    (xwem-kbd-install-grab xwem-global-map xwin)

    ;; Install keyboard grabs for global minor modes
    (mapc #'(lambda (mm-entry)
              (when (and (not (xwem-client-local-variable-p (car mm-entry)))
                         (not (xwem-client-local-variable-p (cdr mm-entry)))
                         (symbol-value (car mm-entry)))
                (xwem-kbd-install-grab (symbol-value (cdr mm-entry)) xwin)))
          xwem-minor-mode-map-alist)))

;;;###xwem-autoload
(defun xwem-make-client (xwin &optional props)
  "Make new client window.
XWIN   - X Window.
PROPS - Properties list for new client.
XWEM-WIN - xwem window where new client should be managed(if possible)."
  (let ((new-cl (make-xwem-cl
                 :xwin xwin
                 :ev-mask (Xmask-or xwem-client-ev-mask
                                    (if (xwem-frame-p (xwem-xwin-frame xwin))
                                        xwem-frame-ev-mask
                                      0)))))
    (when (xwem-misc-xwin-valid-p xwin) ; just to check that XWIN still alive
      (xwem-debug 'xwem-cl "New Client making name=%s, class=%S"
                  '(XGetWMName (xwem-dpy) xwin) '(XGetWMClass (xwem-dpy) xwin))

      (X-Win-put-prop xwin 'xwem-cl new-cl)
      (xwem-cl-presetup new-cl)

      (setf (xwem-cl-initial-xattrs new-cl)
            (XGetWindowAttributes (xwem-dpy) xwin))
      (setf (xwem-cl-initial-xgeom new-cl)
            (XGetGeometry (xwem-dpy) xwin))
      (setf (xwem-cl-xgeom new-cl)
            (copy-X-Geom (xwem-cl-initial-xgeom new-cl)))
      (setf (xwem-cl-start-time new-cl)
            (current-time))

      ;; Apply properties
      (xwem-cl-apply-plist new-cl props)

      new-cl)))

(defun xwem-unmake-client (cl)
  "Unmake client CL."
  ;; If unmaking selected client, then select dummy client
  (when (xwem-cl-selected-p cl)
    (xwem-select-client nil))

  (X-Win-rem-prop (xwem-cl-xwin cl) 'xwem-cl)
  (X-Win-EventHandler-rem (xwem-cl-xwin cl) 'xwem-cl-events-handler)

  ;; Remove from mark ring
  (setq xwem-cl-mark-ring (delq cl xwem-cl-mark-ring))

  ;; Make sure CL not in xwem-clients
  (setq xwem-clients (delq cl xwem-clients))

  (X-invalidate-cl-struct cl))

(defun xwem-client-first-manage (cl &optional props)
  "Manage client CL for the first time.
Return non-nil if CL successfully managed."
  ;; Find match spec for CL
  (let ((mspec (or (xwem-cl-XProperty-manage-spec cl)
                   (xwem-manda-find-match cl))))
    (when mspec
      ;; Add CL to clients list
      (pushnew cl xwem-clients :test 'eq)

      ;; Collaborate all the properties for client from different
      ;; sources and apply them to client.
      ;; 
      ;; Sources are:
      ;;   - Specified PROPS
      ;;   - Specified in manage specification
      ;;   - Import from X property
      (xwem-cl-apply-plist
       cl (append props (cadr mspec) (xwem-cl-XProperty-plist cl)))

      ;; Set expectance if 'client-window property is set
      (let ((ewin (xwem-client-property cl 'client-window)))
        (when ewin
          (xwem-cl-was-expected cl t)
          (xwem-client-set-property cl 'expect-win ewin)))

      ;; Setup focus mode if not already setuped
      (unless (xwem-client-property cl 'xwem-focus-mode)
        (xwem-focus-mode-set cl))
      (xwem-debug 'xwem-cl "Focus model: %S selected"
                  '(xwem-client-property cl 'xwem-focus-mode))

      ;; Apply plist before setting managing model, becase seting
      ;; properties may depend on it and will fail because client is
      ;; not yet managed by this managing model.

      ;; On the other hand not seting managing model before applying
      ;; properties may cause seting property to fail, for example
      ;; 'expect-win property, which only set for 'generic managing
      ;; model.
      (setf (xwem-cl-manage-spec cl) mspec)
      (xwem-debug 'xwem-cl "Managing model: %S selected"
                  '(xwem-cl-manage-type cl))

      ;; Run manage method
      (xwem-manage cl)

      ;; Unmark CL as it was expected in case `xwem-manda-find-match'
      ;; marked it.
      (xwem-cl-was-expected cl nil)

      ;; Honour initial client state
      (unless (xwem-client-property cl 'skip-initial-state)
        (xwem-cl-honour-init-state cl))

      ;; Honour initial client state
      (unless (xwem-client-property cl 'skip-initial-state)
        (xwem-cl-honour-init-state cl))

      ;; Run new client hook
      (when (xwem-cl-alive-p cl)
        (run-hook-with-args 'xwem-cl-create-hook cl))
      cl)))

;;;###xwem-autoload
(defun xwem-xwin-try-to-manage (xwin)
  "Try to manage X window XWIN.
Return managed client, or nil if client wasnt managed."
  (unless (xwem-xwin-cl xwin)
    (let ((cl (xwem-make-client xwin)))
      (when (xwem-cl-p cl)
        (unless (xwem-client-first-manage cl xwem-client-default-properties)
          (xwem-unmake-client cl)))
      (and (xwem-cl-p cl) cl))))

;;;###xwem-autoload
(defun xwem-cl-destroy (cl)
  "Tottally destroy CL."
  (setf (xwem-cl-state cl) 'destroyed)

  ;; If client's window was having always on top rank - unset it
  (xwem-misc-unset-always-on-top (xwem-cl-xwin cl))

  (xwem-method-on-kill cl)
  (xwem-unwind-protect
      (run-hook-with-args 'xwem-cl-destroy-hook cl)

    (xwem-select-some-client)
    (xwem-deffered-funcall 'xwem-unmake-client cl)))

;;;###xwem-autoload
(defun xwem-cl-apply-plist (cl nplist)
  "Set plist's properties in CL."
  (while nplist
    (unless (eq (cadr nplist) (xwem-client-property cl (car nplist)))
      (xwem-client-set-property cl (car nplist) (cadr nplist)))
    (setq nplist (cdr (cdr nplist)))))

;;;###xwem-autoload
(defun xwem-cl-apply-new-xgeom (cl &optional correct-including-border
                                   hold-size)
  "Apply entries in `xwem-cl-new-xgeom' to CL's x geometry.
When CORRECT-INCLUDING-BORDER is non-nil, then
`xwem-cl-correct-size-for-size' will correct size reguarding new
border width, otherwise it will correct size as if border width is 0.
If HOLD-SIZE is non-nil no size corrections are performed."
  (let ((nxgeom (xwem-cl-new-xgeom cl))
        (xgeom (xwem-cl-xgeom cl)))
    (when nxgeom
      ;; Adjust CL's border width
      (when (X-Geom-border-width nxgeom)
        (setf (X-Geom-border-width xgeom) (X-Geom-border-width nxgeom))
        (unless correct-including-border
          (setf (X-Geom-border-width nxgeom) nil)))

      ;; Fix NXGEOM before correcting size
      (unless (X-Geom-x nxgeom)
        (setf (X-Geom-x nxgeom) (X-Geom-x xgeom)))
      (unless (X-Geom-y nxgeom)
        (setf (X-Geom-y nxgeom) (X-Geom-y xgeom)))
      (unless (X-Geom-width nxgeom)
        (setf (X-Geom-width nxgeom) (X-Geom-width xgeom)))
      (unless (X-Geom-height nxgeom)
        (setf (X-Geom-height nxgeom) (X-Geom-height xgeom)))
      
      (unless hold-size
        (xwem-cl-correct-size-for-size cl nxgeom 'left 'top))

      ;; Flush new geometry
      (setf (xwem-cl-new-xgeom cl) nil))))

;;;###xwem-autoload(autoload 'xwem-cl-apply-xgeom "xwem-clients")
;;;###xwem-autoload(autoload 'xwem-cl-apply-xgeom-1 "xwem-clients")
(define-xwem-deffered xwem-cl-apply-xgeom (cl)
  "Apply CL's geometry to CL's X window."
  (let ((clxg (xwem-cl-xgeom cl)))
    (XConfigureWindow (xwem-dpy) (xwem-cl-xwin cl)
                      (make-X-Conf :x (X-Geom-x clxg)
                                   :y (X-Geom-y clxg)
                                   :width (X-Geom-width clxg)
                                   :height (X-Geom-height clxg)
                                   :border-width (X-Geom-border-width clxg)))
    (xwem-cl-send-config-1 cl)))

;;;###xwem-autoload
(defun xwem-client-move (cl new-x new-y)
  "Move client CL to NEW-X, NEW-Y."
  (setf (xwem-cl-new-xgeom cl)
        (make-X-Geom :x new-x :y new-y :border-width nil))
  (xwem-refit cl))

;;;###xwem-autoload
(defun xwem-client-resize (cl new-width new-height)
  "Resize client CL to NEW-WIDTH, NEW-HEIGHT."
  (setf (xwem-cl-new-xgeom cl)
        (make-X-Geom :width new-width :height new-height :border-width nil))
  (xwem-refit cl))

;;;###xwem-autoload
(defun xwem-client-move-resize (cl new-x new-y new-width new-height)
  "Move CL to NEW-X, NEW-Y and resize to NEW-WIDTH, NEW-HEIGHT."
  (setf (xwem-cl-new-xgeom cl)
        (make-X-Geom :x new-x :y new-y
                     :width new-width :height new-height
                     :border-width nil))
  (xwem-refit cl))


;;;###xwem-autoload
(defun xwem-cl-change-window (cl &optional new-win)
  "Change CL's window to NEW-WIN.
If NEW-WIN is nil, NEW-WIN will be other window to CL's win window."
  (unless new-win
    (setq new-win (xwem-window-other 1 (xwem-cl-win cl))))

  (unless (eq (xwem-cl-win cl) new-win)
    ;; CL's xwin should be deactivated when changing window
    (xwem-deactivate cl)
    (xwem-cl-set-win cl new-win)))


;; Commands
;;;###autoload(autoload 'xwem-client-kill "xwem-clients" "" t)
(define-xwem-command xwem-client-kill (cl &optional arg)
  "Kill xwem client CL. Also destroys CL's X window.
If used with prefix ARG is given, force CL to die, by default
WM_DELETE_WINDOW will be probed.
If CL is `nil' than client in `xwem-win-selected' assumed."
  ;; TODO: - take icccm stuff(like WM_DELETE_WINDOW) into account
  ;;       - switch to other client
  (xwem-interactive (list (xwem-cl-selected) xwem-prefix-arg))

  (if (xwem-cl-alive-p cl)
      (if arg
          ;; Force killing
          (XKillClient (xwem-dpy) (X-Win-id (xwem-cl-xwin cl)))

        ;; else try soft killing
        (or (xwem-client-delete-window cl)
            (xwem-client-kill cl t)))

    (xwem-message 'warning "Invalid client to kill.")))

;;;###autoload(autoload 'xwem-client-query-kill "xwem-clients" "" t)
(define-xwem-command xwem-client-query-kill (cl &optional arg)
  "Interactively kill client CL.
Prefix ARG directly passed to `xwem-client-kill'."
  (xwem-interactive (list
                     ;; Sort clients, so selected client will be first
                     (xwem-read-client "XWEM Kill client: "
                                       (sort xwem-clients
                                             #'(lambda (cl1 cl2)
                                                 (eq cl1 (xwem-cl-selected)))))
                     xwem-prefix-arg))

  (xwem-client-kill cl arg))

;;;###autoload(autoload 'xwem-client-demanage-others "xwem-clients" "" t)
(define-xwem-command xwem-client-iconify-others (window &optional arg)
  "Iconify others then selected client in WINDOW.
If ARG given, remain ARG most recent clients."
  (xwem-interactive (list (xwem-win-selected)
                          (prefix-numeric-value xwem-prefix-arg)))

  (let ((wclients (xwem-win-clients window)))
    (while (and wclients (> (length (xwem-win-clients window)) arg))
      (unless (eq (xwem-win-cl window) (car wclients))
        (xwem-iconify (car wclients)))
      (setq wclients (cdr wclients)))))

;;;###autoload(autoload 'xwem-client-run-copy "xwem-clients" "" t)
(define-xwem-command xwem-client-run-copy (cl &optional arg)
  "Run the same command as selected CL.
Prefix ARG specifies how many copies to run."
  (xwem-interactive (list (xwem-cl-selected)
                          (prefix-numeric-value xwem-prefix-arg)))
  (xwem-kbd-stop-grabbing)
  (unless (xwem-cl-alive-p cl)
    (error 'xwem-error "Invalid client"))

  (let ((cmd (or (xwem-client-property cl 'executed-command)
                 (xwem-hints-wm-command (xwem-cl-hints cl))))
        (mspec (xwem-cl-manage-spec cl)))

    ;; Check command for validity
    (when (or (not (stringp cmd)) (string= cmd ""))
      (error 'xwem-error "Invalid command: " cmd))

    (while (> arg 0)
      (xwem-execute-program-expecting
       cmd (car mspec) (append (cadr mspec)
                               (when (xwem-cl-win cl)
                                 `(expect-win ,(xwem-win-id (xwem-cl-win cl))))))
      (decf arg))))

;;;###autoload(autoload 'xwem-client-run-copy-other-win "xwem-clients" "" t)
(define-xwem-command xwem-client-run-copy-other-win (arg &optional cl)
  "Run copy of selected client in other window.
With prefix ARG, make horizontal split instead of vertical if split
really needed."
  (xwem-interactive "P")

  (let ((cl (or cl (xwem-cl-selected)))
        cmd own)
    (when (or (not (xwem-cl-p cl))
              (not (xwem-win-p (xwem-cl-win cl))))
      (error 'xwem-error "Can't run copy of invalid client"))

    (setq cmd (xwem-hints-wm-command (xwem-cl-hints cl)))
    (setq own (xwem-window-other 1 (xwem-cl-win cl)))

    (when cmd
      ;; Check is there split needed
      (when (eq own (xwem-win-selected))
        (if arg
            (xwem-window-split-horizontally 0)
          (xwem-window-split-vertically 0))
        (setq own (xwem-win-next (xwem-win-selected))))

      ;; Install expectance in hope it will be managed by generic
      ;; manage type, or some other type that suppors expectances.
      (xwem-manda-add-expectance `(nil (expect-win ,(xwem-win-id own)) (command ,cmd)))

      ;; Finnaly run command
      (xwem-execute-program cmd))))

;;;###autoload(autoload 'xwem-client-run-copy-other-frame "xwem-clients" "" t)
(define-xwem-command xwem-client-run-copy-other-frame (arg &optional cl)
  "Run copy of selected client in other frame.
If prefix ARG is specified, create embedded frame, if creation is
needed at all."
  (xwem-interactive "P")

  (let ((cl (or cl (xwem-cl-selected)))
        cmd ofr)

    (when (or (not (xwem-cl-p cl))
              (not (xwem-frame-p (xwem-cl-frame cl))))
      (error 'xwem-error "Can't run copy of invalid client"))

    (setq cmd (xwem-hints-wm-command (xwem-cl-hints cl)))
    (setq ofr (xwem-frame-other (xwem-cl-frame cl)))
    (when cmd
      (unless (xwem-frame-p ofr)
        (setq ofr (xwem-make-frame-1 (or (and arg 'embedded) 'desktop)
                                     :noselect t)))

      ;; Setup expectance
      (xwem-manda-add-expectance
       `(nil (expect-win ,(xwem-win-id (xwem-frame-selwin ofr))) (command ,cmd)))

      ;; Finnaly run command
      (xwem-execute-program cmd)

      ;; And select frame
      (xwem-select-frame ofr))))

(defun xwem-cl-prog-geom (cl)
  "Get program specified geometry for CL."
  (let ((wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl))))
    (when (and wmnh (X-WMSize-psize-p wmnh))
      (cons (X-WMSize-width wmnh)
            (X-WMSize-height wmnh)))))

(defun xwem-cl-base-geom (cl)
  "Return base width and height for CL."
  (let ((wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl))))
    (cond ((and wmnh (X-WMSize-pbasesize-p wmnh))
           (cons (X-WMSize-base-width wmnh) ;base width
                 (X-WMSize-base-height wmnh))) ;base height
          ((and wmnh (X-WMSize-pminsize-p wmnh))
           (cons (X-WMSize-min-width wmnh)
                 (X-WMSize-min-height wmnh))))))

;;;###xwem-autoload
(defun xwem-cl-min-geom (cl)
  "Returns minimal geometry for CL."
  (let ((wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl))))
    (when (and wmnh (X-WMSize-pminsize-p wmnh))
      (cons (X-WMSize-min-width wmnh)
            (X-WMSize-min-height wmnh)))))

;;;###xwem-autoload
(defun xwem-cl-step-geom (cl)
  "Returns vertical and horisontal step's width for CL."
  (let ((wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl))))
    (when (and wmnh (X-WMSize-presizeinc-p wmnh))
      (cons (X-WMSize-width-inc wmnh)
            (X-WMSize-height-inc wmnh)))))

;;;###xwem-autoload
(defun xwem-cl-get-init-state (cl)
  "Return CL's initial state.
Initial state is one of `X-IconicState', `X-NormalState',
or nil if initial state did not specified by client."
  (let ((wm-hints (xwem-hints-wm-hints (xwem-cl-hints cl))))
    (and (X-WMHints-state-p wm-hints) (X-WMHints-initial-state wm-hints))))

;;;###xwem-autoload
(defun xwem-cl-get-usize (cl)
  "Returns cons cell (uwi . uhe) - CL's size in steps."
  (let* ((clgmt (xwem-cl-xgeom cl))
         (wmnh (xwem-hints-wm-normal-hints (xwem-cl-hints cl)))
         (steps (xwem-cl-step-geom cl))
         (base (xwem-cl-base-geom cl))
         (minsize (xwem-cl-min-geom cl))
         (uwi (X-Geom-width clgmt))
         (uhe (X-Geom-height clgmt)))
         
    (if (and steps
             (not (= (car steps) 0))
             (not (= (cdr steps) 0)))
        (when (or base minsize)
          (progn
            (setq uwi (- uwi (if (X-WMSize-pbasesize-p wmnh)
                                 (car base)
                               (car minsize))))
            (setq uhe (- uhe (if (X-WMSize-pbasesize-p wmnh)
                                 (cdr base)
                               (cdr minsize))))))
      (setq steps '(1 . 1)))

    (cons (/ uwi (car steps))
          (/ uhe (cdr steps)))))

;;;###xwem-autoload
(defun xwem-cl-get-psize (cl)
  "Return pixel size of CL (pwi . phe)."
  (let ((gmt (xwem-cl-xgeom cl)))
    (cons (X-Geom-width gmt) (X-Geom-height gmt))))

(defun xwem-cl-get-uptime-1 (cl)
  (let ((ctime (current-time))
        (stime (xwem-cl-start-time cl)))
    (list (- (nth 0 ctime) (nth 0 stime))
          (- (nth 1 ctime) (nth 1 stime))
          (- (nth 2 ctime) (nth 2 stime)))))

;;;###xwem-autoload
(defun xwem-cl-get-uptime (cl &optional format)
  "Return CL's uptime.
FORMAT can contain %-sequences to substitute parts of the uptime.
%d is replaced by the days
%h is replaced by the hours
%m is replaced by the minutes
%s is replaced by the seconds
%A is replaced by autogenerated format."
  (let* ((upt (xwem-cl-get-uptime-1 cl))
         (upt (+ (* (nth 0 upt) 65536) (mod (nth 1 upt) 65536)))
         (days (/ upt 86400))
         (hours (/ (mod upt 86400) 3600))
         (minutes (/ (mod upt 3600) 60))
         (seconds (mod upt 60))
         (fmt (or format "%A"))
         (rup ""))
    
    (let ((flst (string-to-list fmt))
          chr)
      (while flst
        (setq chr (car flst))
        (cond ((= chr ?%)
               (setq flst (cdr flst))
               (setq chr (car flst))
               (cond ((= chr ?d)
                      (setq rup (concat rup (format "%d" days))))
                     ((= chr ?h)
                      (setq rup (concat rup (format "%d" hours))))
                     ((= chr ?m)
                      (setq rup (concat rup (format "%d" minutes))))
                     ((= chr ?s)
                      (setq rup (concat rup (format "%d" seconds))))
                     ((= chr ?A)
                      (setq rup (concat
                                 (cond ((> days 0) (format "%dd %dh %dm %ds" days hours minutes seconds))
                                       ((> hours 0) (format "%dh %dm %ds" hours minutes seconds))
                                       ((> minutes 0) (format "%dm %ds" minutes seconds))
                                       ((> seconds 0) (format "%d seconds" seconds))
                                       (t "")))))
                     (t (error "Invalid format"))))
                  
              (t (setq rup (concat rup (char-to-string chr)))))
        (setq flst (cdr flst))))
    rup))

;;;###autoload(autoload 'xwem-client-info "xwem-clients" "" t)
(define-xwem-command xwem-client-info (cl &optional arg)
  "Display info about xwem client CL.
If used with prefix ARG, insert to current client."
  (xwem-interactive (list (xwem-cl-selected)
                          xwem-prefix-arg))

  (unless (xwem-cl-alive-p cl)
    (error 'xwem-error "invalid client"))

  (let* ((usz (xwem-cl-get-usize cl))
         (psz (xwem-cl-get-psize cl))
         (msg (format "%s | 0x%d | %dx%d/%dx%d | Uptime: %s | app: %s | %s"
                      (upcase (symbol-name (xwem-cl-manage-type cl)))
                      (X-Win-id (xwem-cl-xwin cl))
                      (car usz) (cdr usz)
                      (car psz) (cdr psz)
                      (xwem-cl-get-uptime cl)
                      (or (car (xwem-client-application cl)) "UNKNOWN")
                      (xwem-client-name cl))))
    (if arg
        (progn
          (xwem-kbd-stop-grabbing)
          (xwem-kbd-force-mods-release)
          (xwem-kbd-add-pending-keys msg))

      (xwem-message 'info "%s" msg))))

;;;###autoload(autoload 'xwem-cl-pop-to-client "xwem-clients" "" t)
(define-xwem-command xwem-cl-pop-to-client (cl &optional warp)
  "Pop to client CL, i.e. switch to its frame and manage it.
If CL have no frame, popup it in current frame."
  (xwem-interactive "cXWEM-CL Pop: \nP")

  (unless (xwem-cl-alive-p cl)
    (error 'xwem-error "Invalid client"))

  (xwem-select-client cl)
  (when warp
    (XWarpPointer (xwem-dpy) X-None (xwem-cl-xwin cl) 0 0 0 0 10 10)))

;;;###autoload(autoload 'xwem-cl-set-title "xwem-clients" "" t)
(define-xwem-command xwem-client-set-title (title &optional cl)
  "Set new TITLE for client CL."
  (xwem-interactive
   (list (xwem-read-from-minibuffer
          "XWEM Set title: " (xwem-client-name (xwem-cl-selected)))
         (xwem-cl-selected)))

  (unless (xwem-cl-p cl)
    (error 'xwem-error "Invalid client" cl))

  (XSetWMName (xwem-dpy) (xwem-cl-xwin cl) title))

;;;###autoload(autoload 'xwem-client-unset-mark "xwem-clients" "" t)
(define-xwem-command xwem-client-unset-mark (cl)
  "Uset mark on CL."
  (xwem-interactive (list (xwem-cl-selected)))

  (when (xwem-cl-marked-p cl)
    (setq xwem-cl-mark-ring (delq cl xwem-cl-mark-ring))

    ;; Now run cl-change hooks
    (run-hook-with-args 'xwem-cl-change-hook cl)))
  
;;;###autoload(autoload 'xwem-client-set-mark "xwem-clients" "" t)
(define-xwem-command xwem-client-set-mark (cl &optional arg)
  "Mark selected client CL.
If CL is ommited or `xwem-client-set-mark' called interactively then
selected client assumed.
With no prefix ARG push selected client to `xwem-cl-mark-ring'.
With positive prefix ARG, jump to ARG's client in `xwem-cl-mark-ring'.
With negative prefix ARG, unset mark from CL."
  (xwem-interactive
   (list (if (and (not (null xwem-prefix-arg))
                  (> (prefix-numeric-value xwem-prefix-arg) 0))
             (nth (1- (prefix-numeric-value xwem-prefix-arg))
                  xwem-cl-mark-ring)
           (xwem-cl-selected))
         xwem-prefix-arg))

  (unless (xwem-cl-p cl)
    (error 'xwem-error "Invalid client"))

  (cond ((< (prefix-numeric-value arg) 0)
         (xwem-client-unset-mark cl))
        ((null arg)
         ;; Push cl and adjust `xwem-cl-mark-ring' according to
         ;; `xwem-cl-mark-ring-max' value if needed.
         (when (= (length xwem-cl-mark-ring) xwem-cl-mark-ring-max)
           ;; Remove last item
           (xwem-client-unset-mark (car (last xwem-cl-mark-ring))))

         (push cl xwem-cl-mark-ring)

         ;; Now run cl-change hooks
         (run-hook-with-args 'xwem-cl-change-hook cl)

         (xwem-message 'info "Marking selected client, total ring size %d"
                       (length xwem-cl-mark-ring)))
        ((> (prefix-numeric-value arg) 0)
         (xwem-cl-pop-to-client cl))))

;;;###autoload(autoload 'xwem-client-exchange-selected-and-mark "xwem-clients" "" t)
(define-xwem-command xwem-client-exchange-selected-and-mark (cl)
  "Exchange marked client with selected client CL.
I.e. marked client will be selected and unmarked, and selected client
will be deselected and marked."
  (xwem-interactive (list (xwem-cl-selected)))

  (let ((mcl (car xwem-cl-mark-ring)))
    (unless (xwem-cl-p mcl)
      (error 'xwem-error "No marked client"))
    (xwem-client-unset-mark mcl)
    (xwem-client-set-mark cl)
    (xwem-select-client mcl)))

;;;###xwem-autoload
(defun xwem-fini-clients ()
  "Fini all clients."
  (while xwem-clients
    ;; Make CL to be child of root window
    (let* ((cl (car xwem-clients))
           (geom (xwem-cl-xgeom cl)))
      (XReparentWindow (xwem-dpy) (xwem-cl-xwin cl)
                       (xwem-rootwin) (X-Geom-x geom) (X-Geom-y geom))
      (setf (xwem-cl-state cl) 'unknown))
    (setq xwem-clients (cdr xwem-clients))))


;;; Events handling for client windows
(defun xwem-cl-hproperty (cl xev)
  "PropertyNotify."
  (let ((xwin (xwem-cl-xwin cl))
        (atom-id (X-Atom-id (X-Event-xproperty-atom xev)))
        (state (X-Event-xproperty-state xev))
        rhook)

    ;; Some CL's property changed
    (xwem-debug 'xwem-cl "CLIENT .. PropertyNotify: Atom-id = %d" 'atom-id)

    (cond ((and (= atom-id (X-Atom-id XA-wm-normal-hints))
                (= state X-PropertyNewValue))
           ;; WM_NORMAL_HINTS changed
           (setf (xwem-cl-wm-normal-hints cl)
                 (XGetWMNormalHints (xwem-dpy) xwin))
           (setq rhook t))

          ((and (= atom-id (X-Atom-id XA-wm-hints))
                (= state X-PropertyNewValue))
           ;; WM_HINTS changed
           (setf (xwem-cl-wm-hints cl) (XGetWMHints (xwem-dpy) xwin))
           (setq rhook t))

          ((and (= atom-id (X-Atom-id XA-wm-class))
                (= state X-PropertyNewValue))
           ;; WM_CLASS changed
           (multiple-value-bind (ci cn)
               (values-list (XGetWMClass (xwem-dpy) xwin))
             (setf (xwem-cl-wm-class cl) (cons ci cn)))
           (setq rhook t))

          ((and (= atom-id (X-Atom-id XA-wm-command))
                (= state X-PropertyNewValue))
           ;; WM_COMMAND changed
           (setf (xwem-cl-wm-command cl) (XGetWMCommand (xwem-dpy) xwin))
           (setq rhook t))

          ((and (= atom-id (X-Atom-id XA-wm-name))
                (= state X-PropertyNewValue))
           ;; WM_NAME changed
           (setf (xwem-cl-wm-name cl) (XGetWMName (xwem-dpy) xwin))
           (when (string= "" (xwem-cl-wm-name cl))
             (setf (xwem-cl-wm-name cl) xwem-cl-noname-name))
           (unless (and (stringp (xwem-cl-get-sys-prop cl 'saved-name))
                        (string= (xwem-cl-wm-name cl)
                                 (xwem-cl-get-sys-prop cl 'saved-name)))
             (xwem-cl-put-sys-prop cl 'saved-name (xwem-cl-wm-name cl))
             (setq rhook t)))

          ((and (= atom-id (X-Atom-id XA-wm-icon-name))
                (= state X-PropertyNewValue))
           ;; WM_ICON_NAME changed
           (setf (xwem-cl-wm-icon-name cl)
                 (XGetPropertyString (xwem-dpy) (xwem-cl-xwin cl)
                                     XA-wm-icon-name))
           (when (string= "" (xwem-cl-wm-icon-name cl))
             (setf (xwem-cl-wm-icon-name cl) xwem-cl-noicon-name))
           (unless (and (stringp (xwem-cl-get-sys-prop cl 'saved-icon-name))
                        (string= (xwem-cl-wm-icon-name cl)
                                 (xwem-cl-get-sys-prop cl 'saved-icon-name)))
             (xwem-cl-put-sys-prop cl 'saved-icon-name
               (xwem-cl-wm-icon-name cl))
             (setq rhook t)))
          )

    (when rhook
      (run-hook-with-args 'xwem-cl-change-hook cl))
    ))

(defun xwem-cl-hclient-message (cl xev)
  "ClientMessage event XEV."
  (let ((type (length (X-Event-xclient-msg xev)))) ; 5 -> 32, 10 -> 16, 20 -> 8

    (xwem-debug 'xwem-cl "XWEM-CLIENT: in ClientMessage: type=%S msg(0)=%S"
                'type  '(car (nth 0 (X-Event-xclient-msg xev))))

    (cond ((and (= type 5)
                (= (car (nth 0 (X-Event-xclient-msg xev))) X-IconicState))
           ;; Iconify request from client
           (xwem-iconify cl))
          )))

(defun xwem-cl-events-handler (xdpy xwin xev)
  "Events handler for root window."
  (xwem-debug 'xwem-cl "CLIENT HANDLER: xev type=%S, win=%S"
              '(X-Event-name xev) '(X-Win-id (X-Event-win xev)))

  (X-Event-CASE xev
    ((:X-KeyPress :X-KeyRelease :X-ButtonPress :X-ButtonRelease)
     ;; Normal command event proccessing
     (xwem-dispatch-command-xevent xev))

    ;; Focusing mode
    (:X-FocusIn (xwem-focus-mode-invoke (xwem-xwin-cl xwin) 'focus-in xev))
    (:X-FocusOut (xwem-focus-mode-invoke (xwem-xwin-cl xwin) 'focus-out xev))
    (:X-EnterNotify (xwem-focus-mode-invoke (xwem-xwin-cl xwin) 'enter xev))
    (:X-LeaveNotify (xwem-focus-mode-invoke (xwem-xwin-cl xwin) 'leave xev))

    ;; Various events
    (:X-MapRequest (xwem-ev-mapreq xdpy xwin xev))
    (:X-ResizeRequest (xwem-ev-resize xdpy xwin xev))
    (:X-ConfigureRequest (xwem-ev-reconfig xdpy xwin xev))
    (:X-DestroyNotify (xwem-ev-destroy xdpy xwin xev))
    (:X-UnmapNotify (xwem-ev-unmap xdpy xwin xev))

    (:X-PropertyNotify
     (when (xwem-cl-p (xwem-xwin-cl xwin))
       (xwem-cl-hproperty (xwem-xwin-cl xwin) xev)))
    (:X-ClientMessage
     (when (xwem-cl-p (xwem-xwin-cl xwin))
       (xwem-cl-hclient-message (xwem-xwin-cl xwin) xev)))
    ))

;;;###autoload(autoload 'xwem-client-imove "xwem-clients" nil t)
(define-xwem-command xwem-client-imove ()
  "Interactively move client clicked by button."
  (xwem-interactive "_")

  (let ((cl (xwem-misc-xbutton-cl xwem-last-xevent))
        (x-clic (X-Event-xbutton-root-x xwem-last-xevent))
        (y-clic (X-Event-xbutton-root-y xwem-last-xevent))
        tpnt cl-xwin xev done)

    ;; Check CL
    (unless (xwem-cl-alive-p cl)
      (error 'xwem-error "Invalid client .."))

    (setq cl-xwin (xwem-cl-xwin cl)
          tpnt (car (XTranslateCoordinates
                     (xwem-dpy)
                     (X-Event-xbutton-root xwem-last-xevent)
                     cl-xwin x-clic y-clic))
          x-clic (+ (X-Point-x tpnt) (X-Geom-border-width (xwem-cl-xgeom cl)))
          y-clic (+ (X-Point-y tpnt) (X-Geom-border-width (xwem-cl-xgeom cl))))

    (XGrabPointer (xwem-dpy) cl-xwin
                  (Xmask-or XM-ButtonMotion XM-ButtonRelease XM-ButtonPress)
                  xwem-cursor-move)
    (xwem-unwind-protect
        (while (not done)
          (X-Event-CASE (setq xev (xwem-next-event))
            (:X-ButtonRelease (setq done t))

            (:X-MotionNotify
             (xwem-client-move cl (- (X-Event-xmotion-root-x xev) x-clic)
                               (- (X-Event-xmotion-root-y xev) y-clic))
             (when xwem-imove-visible
               (xwem-message 'nolog "New position %+d%+d"
                             (X-Geom-x (xwem-cl-xgeom cl))
                             (X-Geom-y (xwem-cl-xgeom cl)))))))
      (XUngrabPointer (xwem-dpy)))))

;;;###autoload(autoload 'xwem-client-iresize "xwem-clients" nil t)
(define-xwem-command xwem-client-iresize ()
  "Interactively resize clicked client."
  (xwem-interactive "_")

  (let ((cl (xwem-misc-xbutton-cl xwem-last-xevent))
        (x-clic (X-Event-xbutton-root-x xwem-last-xevent))
        (y-clic (X-Event-xbutton-root-y xwem-last-xevent))
        tpnt cl-xwin done xev)

    (unless (xwem-cl-alive-p cl)
      (error 'xwem-error "Invalid client"))

    (setq cl-xwin (xwem-cl-xwin cl)
          tpnt (car (XTranslateCoordinates
                     (xwem-dpy) (X-Event-xbutton-root xwem-last-xevent)
                     cl-xwin x-clic y-clic))
          x-clic (+ (X-Point-x tpnt) (X-Geom-border-width (xwem-cl-xgeom cl)))
          y-clic (+ (X-Point-y tpnt) (X-Geom-border-width (xwem-cl-xgeom cl))))

    (XGrabPointer (xwem-dpy) cl-xwin
                  (Xmask-or XM-ButtonMotion XM-ButtonRelease XM-ButtonPress)
                  xwem-cursor-resize)
    (xwem-unwind-protect
        (progn
          (xwem-client-resize cl x-clic y-clic)
          (when xwem-iresize-visible
            (let ((psize (xwem-cl-get-psize cl))
                  (usize (xwem-cl-get-usize cl)))
              (xwem-message 'nolog "New size %dx%d/%dx%d"
                            (car psize) (cdr psize) (car usize) (cdr usize))))
          (while (not done)
            (X-Event-CASE (setq xev (xwem-next-event))
              (:X-ButtonRelease (setq done t))
              (:X-MotionNotify
               (let ((xoff (X-Event-xmotion-event-x xev))
                     (yoff (X-Event-xmotion-event-y xev)))
                 (when (and (< xoff 40000) (< yoff 40000))
                   (xwem-client-resize cl xoff yoff)
                   (when xwem-iresize-visible
                     (let ((psize (xwem-cl-get-psize cl))
                           (usize (xwem-cl-get-usize cl)))
                       (xwem-message 'nolog "New size %dx%d/%dx%d"
                                     (car psize) (cdr psize)
                                     (car usize) (cdr usize))))
                   ))))))
      (XUngrabPointer (xwem-dpy)))))

;;;###autoload(autoload 'xwem-client-idestroy "xwem-clients" nil t)
(define-xwem-command xwem-client-idestroy (arg)
  "Interactively destroy clicked client.
If used with prefix ARG, force destroyence."
  (xwem-interactive "_P")

  (let ((cl (xwem-misc-xbutton-cl xwem-last-xevent)))
    (unless (xwem-cl-alive-p cl)
      (error 'xwem-error "Invalid client" cl))

    (xwem-client-kill cl arg)))

;;; Applications navigation
(defun xwem-client-application (&optional cl)
  "Retun CL's application entry from `xwem-applications-alist'."
  (unless cl
    (setq cl (xwem-cl-selected)))
  (xwem-manda-find-match-1 cl xwem-applications-alist 'cdr))

;;;###autoload(autoload 'xwem-forward-application "xwem-clients" "Select ARGs next application." t)
(define-xwem-command xwem-forward-application (arg)
  "Select ARGs next client of same application as selected client."
  (xwem-interactive "p")

  (let* ((cl (xwem-cl-selected))
         (app (xwem-client-application cl))
         app-clients)
    (unless app
      (error 'xwem-error "No corresponding application entry in `xwem-applications-alist'"))

    (setq app-clients
          (xwem-clients-list `(lambda (client)
                                (xwem-cl-match-p client (cdr (quote ,app))))))
    (when (< arg 0)
      (setq app-clients (nreverse app-clients))
      (setq arg (- arg)))
    (while (> arg 0)
      (setq cl (or (cadr (memq cl app-clients))
                   (car app-clients)))
      (decf arg))

    (when (xwem-cl-alive-p cl)
      (xwem-select-client cl))))

;;;###autoload(autoload 'xwem-backward-application "xwem-clients" "Select previous application." t)
(define-xwem-command xwem-backward-application (arg)
  "Select ARGs previous client of same application as selected client."
  (xwem-interactive "p")
  (xwem-forward-application (- arg)))

;;;###xwem-autoload
(defun xwem-client-change-manage-type (cl manage-spec)
  "Change CL's manage type to type specified in MANAGE-SPEC."
  (unless (eq (xwem-cl-manage-type cl) (car manage-spec))
    (let ((state (xwem-cl-state cl))
          (selp (xwem-cl-selected-p cl)))

      ;; If client's window was having always on top rank - unset it
      (xwem-misc-unset-always-on-top (xwem-cl-xwin cl))

      ;; Reparent client to root window.  The reparenting leaves unchanged the
      ;; absolute coordinates (with respect to the root window) of the
      ;; upper-left outer corner.
      (let ((tpnt (car (XTranslateCoordinates (xwem-dpy) (xwem-cl-xwin cl)
                                              (xwem-rootwin) 0 0))))
        (XReparentWindow (xwem-dpy) (xwem-cl-xwin cl)
                         (xwem-rootwin) (X-Point-x tpnt) (X-Point-y tpnt)))
      (XUnmapWindow (xwem-dpy) (xwem-cl-xwin cl))

      (xwem-method-on-type-change cl manage-spec)

      ;; Set match spec, update plist
      (setf (xwem-cl-manage-spec cl) manage-spec)
      (xwem-cl-apply-plist cl (cadr manage-spec))

      (xwem-manage cl)

      ;; Keep CL's state
      (when (eq state 'active)
        (xwem-activate cl))
      (when selp
        (xwem-select-client cl)))))

;;;; --- Frontends to methods ---

;;;###xwem-autoload
(defun xwem-cl-honour-init-state (cl)
  ;; Honour CL's initial-state (ICCM 4.1.4)
  (let ((istate (xwem-cl-get-init-state cl)))
    (cond ((eql istate X-IconicState)
           (xwem-iconify cl))
          ((or (eql istate X-NormalState)
               t)                       ; default
           (xwem-activate cl)))))

;;;###xwem-autoload
(defun xwem-manage (cl)
  "Manage client CL."
  (xwem-method-manage cl)

  ;; Save new manage spec into X property
  (xwem-cl-XProperty-manage-spec-export cl)

  (run-hook-with-args 'xwem-cl-manage-hook cl))

;;;###xwem-autoload
(defun xwem-activate (cl &optional type)
  "Activate client CL in its context.
TYPE is one of:

  `activate' - Client is non-active and activation required.

  `select' - Client is about to be selected, so activation required.
             Client may be already activated.

Default TYPE is `activate'."
  (if (and xwem-client-strict-activation
           (not (xwem-misc-xwin-valid-p (xwem-cl-xwin cl))))
      ;; CL suddenly died
      (xwem-cl-destroy cl)

    (unless type (setq type 'activate))

    (unless (eq (xwem-cl-state cl) 'active)
      (xwem-client-change-state cl 'active)
      (xwem-method-activate cl 'activate))

    (unless (eq type 'activate)
      (xwem-method-activate cl type))

    (run-hook-with-args 'xwem-cl-activate-hook cl type)))

;;;###xwem-autoload
(defun xwem-deactivate (cl &optional type)
  "Deactivate client CL in its context.
NOTE that only active client can be deactivated!
TYPE is one of:

   `deactivate' - Client must be deactivate.
 
   `deselect' - Client is deselecting.

Default TYPE is `deactivate'."
  (unless type (setq type 'deactivate))

  (cond ((eq type 'deselect)
         (xwem-method-deactivate cl type))

        ((eq (xwem-cl-state cl) 'active)
         (xwem-client-change-state cl 'inactive)
         (xwem-method-deactivate cl type)
         (xwem-select-some-client))

        ((not (eq (xwem-cl-state cl) 'inactive))
         (xwem-method-deactivate cl type)
         (xwem-select-some-client)))
  
  (run-hook-with-args 'xwem-cl-deactivate-hook cl type))

;;;###xwem-autoload
(defun xwem-iconify (cl)
  "Function to iconify client CL.
ARGS - arguments."
  (unless (eq (xwem-cl-state cl) 'iconified)
    (xwem-client-change-state cl 'iconified)
    (xwem-method-iconify cl))

  (xwem-select-some-client))

;;;###xwem-autoload
(defun xwem-refit (cl)
  "Function to refit client CL.
ARGS - arguments."
  ;; Reguard  border width change
  (when (and (xwem-cl-new-xgeom cl)
             (xwem-manage-property (xwem-cl-manage-type cl)
                                   'reguard-x-border-width)
             (X-Geom-border-width (xwem-cl-new-xgeom cl)))
    (setf (X-Geom-border-width (xwem-cl-xgeom cl))
          (X-Geom-border-width (xwem-cl-new-xgeom cl))))

  (xwem-method-refit cl)

  ;; Apply (new) CL geometry to life
  (xwem-cl-apply-xgeom cl)

  ;; Finally run hooks
  (run-hook-with-args 'xwem-cl-refit-hook cl))

;;;###xwem-autoload
(defun xwem-withdraw (cl)
  "Withdraw client CL."
  (xwem-client-change-state cl 'withdrawn)
  (xwem-method-withdraw cl)

  (xwem-select-some-client)
  (run-hook-with-args 'xwem-cl-withdraw-hook cl))

;;;; ---- Default manage methods ----

(define-xwem-deffered xwem-default-apply-state (cl)
  "Apply CL's state to life."
  (cond ((eq (xwem-cl-state cl) 'active)
         (XMapWindow (xwem-dpy) (xwem-cl-xwin cl)))
        ((memq (xwem-cl-state cl) '(inactive iconified))
         (XUnmapWindow (xwem-dpy) (xwem-cl-xwin cl)))))

(define-xwem-method activate default (cl &optional type)
  "Default method to activate client CL."
  (cond ((eq type 'select)
         (xwem-deffered-funcall 'xwem-misc-raise-xwin (xwem-cl-xwin cl)))
        ((eq type 'activate)
         (xwem-default-apply-state cl))))

(define-xwem-method deactivate default (cl &optional type)
  "Default method to deactivate client CL."
  (cond ((eq type 'deactivate)
         (xwem-default-apply-state cl))))

(define-xwem-method iconify default (cl)
  "Default method to iconify CL."
  (xwem-default-apply-state cl))

(define-xwem-method refit default (cl)
  "Default method to refit CL."
  (xwem-cl-apply-new-xgeom cl)
  (xwem-cl-apply-xgeom cl))

;; New method to select other client
(defun xwem-method-other-client (cl)
  "Return xwem client other then CL."
  (xwem-execute-method 'other-client (xwem-cl-manage-type cl) cl))

(define-xwem-method other-client default (cl)
  "Default other-client method."
  (xwem-cl-other cl))


;;; Dummy client, used, when selecting `nil' client.
(defvar xwem-dummy-client nil
  "Internal variable.")

(define-xwem-client-property dummy-client-p nil
  "Non-nil for dummy clients."
  :type 'boolean)

;;;###xwem-autoload
(defun xwem-dummy-client-p (cl)
  "Return non-nil if CL is dummy client."
  (xwem-client-property cl 'dummy-client-p))

;;;###xwem-autoload
(defun xwem-non-dummy-client-p (cl)
  "Opposit to `xwem-dummy-client-p'."
  (not (xwem-dummy-client-p cl)))

;;;###xwem-autoload
(defun xwem-dummy-client ()
  "Return dummy client."
  (or xwem-dummy-client
      (progn (xwem-dummy-client-init) xwem-dummy-client)))

(defun xwem-dummy-client-init ()
  "Create dummy client"
  (unless xwem-dummy-client
    ;; Set `xwem-dummy-client' to some garbage before creating, to
    ;; avoid infinite loop if `xwem-make-client' will use
    ;; `xwem-dummy-client' somehow --lg
    (setq xwem-dummy-client 'invalid-dummy-client
          xwem-dummy-client
          (xwem-make-client
           (XCreateWindow (xwem-dpy) nil 0 0 1 1 0 nil nil nil
                          (make-X-Attr :override-redirect t))
           '(dummy-client-p t ignore-has-input-p t)))
    (setf (xwem-cl-manage-type xwem-dummy-client) 'dummy)

    (XSelectInput (xwem-dpy) (xwem-cl-xwin xwem-dummy-client)
                  (Xmask-or XM-KeyPress XM-KeyRelease
                            XM-ButtonPress XM-ButtonRelease))
    (XMapWindow (xwem-dpy) (xwem-cl-xwin xwem-dummy-client))

    ;; First selected client is dummy client
    (setf (xwem-cl-selected) xwem-dummy-client)))

;;;###xwem-autoload
(defun xwem-dummy-selected-p ()
  "Return non-nil if dummy client is currently selected."
  (xwem-cl-selected-p xwem-dummy-client))

(define-xwem-method manage dummy (cl))
(define-xwem-method activate dummy (cl &optional type))
(define-xwem-method deactivate dummy (cl &optional type))
(define-xwem-method withdraw dummy (cl))
(define-xwem-method refit dummy (cl))
(define-xwem-method iconify dummy (cl))

;;; Dedicated managing model
(defun xwem-manage-dedicated (cl)
  "Manage method for dedicated CL."
  (let* ((frame (xwem-make-frame-1 'dedicated
                                   :props '(initially-unmapped t)
                                   :noselect t))
         (sw (xwem-frame-selwin frame))
         (qp (XQueryPointer (xwem-dpy) (xwem-rootwin))))

    (xwem-cl-set-win cl sw)
    (xwem-win-set-cl sw cl)

    (xwem-frame-set-pos frame (nth 5 qp) (nth 6 qp))
    (setf (X-Geom-x (xwem-cl-xgeom cl)) (xwem-win-x sw))
    (setf (X-Geom-y (xwem-cl-xgeom cl)) (xwem-win-y sw))
    (xwem-window-set-size sw (X-Geom-width-with-borders (xwem-cl-xgeom cl))
                          (X-Geom-height-with-borders (xwem-cl-xgeom cl)))

    (XReparentWindow (xwem-dpy) (xwem-cl-xwin cl)
                     (xwem-frame-xwin frame)
                     (xwem-win-x sw) (xwem-win-y sw))
    (XMapWindow (xwem-dpy) (xwem-cl-xwin cl))

    (xwem-frame-imove-internal frame (xwem-frame-x frame) (xwem-frame-y frame))
    (xwem-frame-map frame)

    ;; Select client
    (xwem-select-client cl)))

(defun xwem-refit-dedicated (cl)
  "Refit method for dedicated CL."
  (cond ((xwem-cl-new-xgeom cl)
         (xwem-cl-apply-new-xgeom cl nil t)
         (xwem-cl-apply-xgeom cl)
         (xwem-window-set-size
          (xwem-cl-win cl)
          (X-Geom-width-with-borders (xwem-cl-xgeom cl))
          (X-Geom-height-with-borders (xwem-cl-xgeom cl))))

        (t 
         (let ((win (xwem-cl-win cl))
               (clg (xwem-cl-xgeom cl)))
           (when (or (not (= (X-Geom-width-with-borders clg)
                             (xwem-win-width win)))
                     (not (= (X-Geom-height-with-borders clg)
                             (xwem-win-height win))))
             (xwem-cl-correct-size-for-size
              cl
              (make-X-Geom :x (xwem-win-x win)
                           :y (xwem-win-y win)
                           :width (xwem-win-width win)
                           :height (xwem-win-height win)
                           :border-width (X-Geom-border-width clg))
              'left 'top)
             (xwem-window-set-size
              (xwem-cl-win cl)
              (X-Geom-width-with-borders (xwem-cl-xgeom cl))
              (X-Geom-height-with-borders (xwem-cl-xgeom cl)))
             (xwem-cl-apply-xgeom cl))))))

(define-xwem-deffered xwem-cldedic-apply-state (cl)
  "Apply CL's state to life."
  ;; Nothing actually to do here
  nil)

(defun xwem-activate-dedicated (cl &optional type)
  "Activate method for dedicated CL."
  (cond  ((eq type 'select)
          (xwem-select-window (xwem-cl-win cl)))
         
         ((eq type 'activate)
          (xwem-cldedic-apply-state cl))))

(defun xwem-deactivate-dedicated (cl &optional type)
  "Deactivate method for dedicated CL."
  (cond ((eq type 'deselect)
         ;; Hmm, select some other client?
         )
        ((eq type 'deactivate)
         )))

(defun xwem-iconify-dedicated (cl)
  "Iconify method for dedicated CL."
  (xwem-frame-hide (xwem-cl-frame cl)))

(defun xwem-clded-disassociate-frame (cl)
  "Dissassociate dedicated frame from CL."
  (let ((frm (xwem-cl-frame cl)))
    (when (xwem-win-p (xwem-cl-win cl))
      (setf (xwem-win-cl (xwem-cl-win cl)) nil))
    (setf (xwem-cl-win cl) nil)

    (xwem-frame-destroy frm)))
  
(defun xwem-withdraw-dedicated (cl)
  "Withdraw method for dedicated CL."
  (setf (xwem-frame-state (xwem-cl-frame cl)) 'noselect)
  (XUnmapWindow (xwem-dpy) (xwem-frame-xwin (xwem-cl-frame cl))))

;; Additional methods
(define-xwem-method on-type-change dedicated (cl &optional new)
  (xwem-clded-disassociate-frame cl))

(define-xwem-method on-kill dedicated (cl)
  (xwem-clded-disassociate-frame cl))

(define-xwem-manage-model dedicated
  "Dedicated managing model.
Manage clients in dedicated frame."
  :match-spec '(eval nil)

  :manage-properties '(win-support t)
  :manage-method 'xwem-manage-dedicated
  :activate-method 'xwem-activate-dedicated
  :deactivate-method 'xwem-deactivate-dedicated
  :refit-method 'xwem-refit-dedicated
  :iconify-method 'xwem-iconify-dedicated
  :withdraw-method 'xwem-withdraw-dedicated)

;;; Testing:
;(progn
;  (xwem-manda-add-expectance '(dedicated nil (eval t)))
;  (xwem-launch-xterm 4)
;  nil)

;;; Client local variables
(defvar xwem-client-local-variables nil
  "List of client local variables.")

;;;###autoload
(defun xwem-set-default (var val)
  "Set default VAR's value to VAL.
If client does not have its own value, default value will be used."
  (put var 'xwem-default-value val))

;;;###autoload
(defun xwem-make-variable-client-local (var)
  "Make variable symbol VAR to be client local."
  (setq xwem-client-local-variables
        (cons var xwem-client-local-variables))

  (when (boundp var)
    (xwem-set-default var (symbol-value var))))

;;;###xwem-autoload
(defun xwem-client-local-variable-p (var)
  "Return non-nil if VAL is client local variable."
  (memq var xwem-client-local-variables))

;;;###xwem-autoload
(defun xwem-client-local-variable-set (client variable value)
  "Set CLIENT local VARIABLE to VALUE."
  (setf (xwem-cl-local-variables client)
        (put-alist variable value (xwem-cl-local-variables client)))
  (when (xwem-cl-selected-p client)
    (set variable value)))

;;;###xwem-autoload
(defun xwem-client-local-variable-value (client variable)
  "Return CLINEN's local VARIABLE value.
Or global VARIABLE value if CLIENT does not have local value."
  (let ((lval (assq variable (xwem-cl-local-variables client))))
    (if lval
        (cdr lval)
      (get variable 'xwem-default-value))))

(defun xwem-client-local-variables-import (cl)
  "Set client local variables in CL."
  (when (xwem-cl-p cl)
    (setf (xwem-cl-local-variables cl)
          (mapcar #'(lambda (var)
                      (cons var (symbol-value var)))
                  xwem-client-local-variables))))

(defun xwem-client-local-variables-export (cl)
  "Set variables using CL's client local variables."
  (when (xwem-cl-p cl)
    (mapc #'(lambda (var)
              (let ((val (assq var (xwem-cl-local-variables cl))))
                (if val
                    (set var (cdr val))
                  (set var (get var 'xwem-default-value)))))
          xwem-client-local-variables)))

;;; Clients configurations
(defun xwem-client-configuration ()
  "Return current clients configuration."
  )

(defun xwem-set-client-configuration (config)
  "Set client configuration to CONFIG."
  )


(provide 'xwem-clients)

;;;; On-load actions:
;; Define dummy manage type
(define-xwem-manage-model dummy
  "Managing model for dummy clients.
Dummy client is client which can't do anything."
  :match-spec '(function xwem-dummy-client-p))

(if xwem-started
    (xwem-clients-init)
  (add-hook 'xwem-before-init-wins-hook 'xwem-clients-init))

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