xwem / lisp / xwem-misc.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
;;; xwem-misc.el --- Misc stuff for XWEM.

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

;; Author: Zajcev Evgeny <zevlg@yandex.ru>
;; Created: 21 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 misc purposes.
;;
;; If you have troubles with C-g key in Emacs, try to eval:
;;
;;    (set-input-mode nil nil nil ?\xff)
;;
;; I dont know where is bug, but sometimes my XEmacs behaves very
;; strange.  Especially after M-x C-h k.

;;; Code:
;;

(require 'xlib-xlib)
(require 'xlib-img)

(require 'xwem-load)
(require 'advice)

(eval-and-compile
  (defvar iswitchb-buflist nil)         ; shutup compiler
  (defvar x-emacs-application-class nil)
  (autoload 'iswitchb-read-buffer "iswitchb") ; shutup compiler

  (defvar elp-function-list nil)        ; shut up compiler
  (autoload 'elp-instrument-list "elp" nil t)
  (autoload 'elp-results "elp" nil t)
  
  (autoload 'calc-eval "calc"))

(defmacro xwem-gc-function-choice ()
  "Return choice dialog to select GC function."
  `(`(choice (const :tag "None" nil)
             (const :tag "Clear" X-GXClear)
             (const :tag "And" X-GXAnd)
             (const :tag "Reverse And" X-GXAndReverse)
             (const :tag "Inverted And" X-GXAndInverted)
             (const :tag "Xor" X-GXXor)
             (const :tag "Or" X-GXOr)
             (const :tag "Reverse Or" X-GXOrReverse)
             (const :tag "Inverted Or" X-GXOrInverted)
             (const :tag "Nor" X-GXNor)
             (const :tag "Equive" X-GXEquiv)
             (const :tag "Invert" X-GXInvert)
             (const :tag "Copy" X-GXCopy)
             (const :tag "Inverted Copy" X-GXCopyInverted)
             (const :tag "Set" X-GXSet))))

(defmacro xwem-cursor-shape-choice ()
  "Return choice dialog to select cursor shape."
  `(`(choice (const :tag "Left" X-XC-left_ptr)
             (const :tag "Left w/mask" (X-XC-left_ptr))
             (const :tag "Right" X-XC-right_ptr )
             (const :tag "Right w/mask" (X-XC-right_ptr ))
             (const :tag "Cross" X-XC-cross)
             (const :tag "Cross w/mask" (X-XC-cross))
             (const :tag "Reverse Cross" X-XC-cross_reverse)
             (const :tag "Reverse Cross w/mask" (X-XC-cross_reverse))
             (const :tag "Crosshair" X-XC-crosshair)
             (const :tag "Crosshair w/mask" (X-XC-crosshair))
             (const :tag "Daimond cross" X-XC-diamond_cross)
             (const :tag "Daimond cross w/mask" (X-XC-diamond_cross))
             ;; TODO: add more, take a look at Cursors section in
             ;; xlib-const.el
             (const :tag "Dot" X-XC-dot)
             (const :tag "Dot w/mask" (X-XC-dot))
             (const :tag "Square Icon" X-XC-icon)
             (const :tag "Square Icon w/mask" (X-XC-icon))
             (const :tag "Fluer" X-XC-fleur)
             (const :tag "Fluer w/mask" (X-XC-fleur))
             
             ;; Arrows
             (const :tag "Down Arrow" X-XC-sb_down_arrow)
             (const :tag "Down Arrow w/mask" (X-XC-sb_down_arrow))
             (const :tag "Question Arrow" X-XC-question_arrow)
             (const :tag "Question Arrow w/mask" (X-XC-question_arrow))

             (const :tag "TopLeft Arrow" X-XC-top_left_arrow)
             (const :tag "TopLeft Arrow w/mask" (X-XC-top_left_arrow))
             (const :tag "Draft large" X-XC-draft_large)
             (const :tag "Draft large w/mask" (X-XC-draft_large))
             (const :tag "Draft small" X-XC-draft_small)
             (const :tag "Draft small w/mask" (X-XC-draft_small))

             ;; Corners
             (const :tag "Bottom Left corner" X-XC-bottom_left_corner)
             (const :tag "Bottom Left corner w/mask" (X-XC-bottom_left_corner))
             (const :tag "Bottom Right corner" X-XC-bottom_right_corner)
             (const :tag "Bottom Right corner w/mask" (X-XC-bottom_right_corner))
             (const :tag "Top Left corner" X-XC-top_left_corner)
             (const :tag "Top Left corner w/mask" (X-XC-top_left_corner))
             (const :tag "Top Right corner" X-XC-top_right_corner)
             (const :tag "Top Right corner w/mask" (X-XC-top_right_corner))

             (const :tag "Gumby guy" X-XC-gumby)
             (const :tag "Gumby guy w/mask" (X-XC-gumby))
             )))

(defmacro xwem-cus-set-cursor-foreground (cursor)
  "Generate :set function to change CURSOR's foreground"
  `(lambda (sym val)
     (set sym val)
     (when ,cursor
       (xwem-cursor-recolorize ,cursor val))))

(defmacro xwem-cus-set-cursor-background (cursor)
  "Generate :set function to change CURSOR's background"
  `(lambda (sym val)
     (set sym val)
     (when ,cursor
       (xwem-cursor-recolorize ,cursor nil val))))

(defmacro xwem-cus-set-cursor-shape (cursor &optional xwin)
  "Generate :set function to change CURSOR's background"
  `(lambda (sym val)
     (set sym val)
     (when ,cursor
       (let ((ncur (copy-X-Cursor ,cursor))
             src-char msk-char)
         (cond ((listp val)
                (setq src-char (eval (car val))
                      msk-char (1+ src-char)))
               (t (setq src-char (eval val)
                        msk-char src-char)))
         (setf (X-Cursor-id ncur) (X-Dpy-get-id (X-Cursor-dpy ,cursor)))
         (setf (X-Cursor-src-char ncur) src-char)
         (setf (X-Cursor-msk-char ncur) msk-char)
         (XFreeCursor (X-Cursor-dpy ,cursor) ,cursor)
         (XCreateGlyphCursor (X-Cursor-dpy ncur) ncur)
         (setq ,cursor ncur)))
     (if (listp ,xwin)
         (mapc #'(lambda (xw)
                   (when (and xw (X-Win-p xw))
                     (XSetWindowCursor (X-Win-dpy xw) xw ,cursor)))
               ,xwin)
       (when (and ,xwin (X-Win-p ,xwin))
         (XSetWindowCursor (X-Win-dpy ,xwin) ,xwin ,cursor)))))

(define-error 'xwem-internal-error
  "Internal XWEM error.")

(defgroup xwem-misc nil
  "Group to customize miscellaneous options."
  :prefix "xwem-"
  :group 'xwem)

(defcustom xwem-messages-buffer-name " *xwem-messages*"
  "*Buffer name for xwem messages."
  :type 'string
  :group 'xwem-misc)

(defcustom xwem-messages-buffer-lines 1000
  "*Maximum lines in xwem messages buffer."
  :type 'number
  :group 'xwem-misc)

(defconst xwem-messages-builtin-labels
  '(info note error warning alarm todo prompt progress nolog asis)
  "List of builtin labels.")

;;;###autoload
(defcustom xwem-messages-ignore-labels
  '(prompt progress nolog)
  "*List of message labels to ignore putting them into xwem message log buffer."
  :type '(repeat (choice (symbol :tag "Custom label")
                         (const :tag "Alarm" alarm)
                         (const :tag "Error" error)
                         (const :tag "Warning" warning)
                         (const :tag "Info" info)
                         (const :tag "Note" note)
                         (const :tag "TODO" todo)
                         (const :tag "Prompt" prompt)
                         (const :tag "Progress" progress)
                         (const :tag "NoLog" nolog)))
  :group 'xwem-misc)

(defcustom xwem-messages-beeps-alist
  '((warning . warning)
    (error . error)
    (alarm . alarm))
  "*Alist in form (MSG-LABEL . SOUND).
Where SOUND is element of `xwem-sound-alist'."
  :type `(repeat (cons (symbol :tag "Message Label")
                       ,(nconc '(choice)
                               (mapcar #'(lambda (ss)
                                           (list 'const :tag (symbol-name (car ss)) (car ss)))
                                       xwem-sound-alist)
                               '((symbol :tag "Sound type")))))
  :group 'xwem-misc)

(defcustom xwem-messages-label-prefixes
  '((warning "Warning" (red))
    (error "Erorr" (red bold))
    (alarm "Alarm" (red bold italic))
    (note "Note" (yellow))
    (info "Info" (default))
    (todo "TODO" (bold)))
  "List of prefixes for certain labels.
CAR is label."
  :type '(list (symbol :tag "Message label") string (repeat face))
  :group 'xwem-misc)

;;;###xwem-autoload
(defcustom xwem-misc-turbo-mode nil
  "*Non-nil mean xwem will work as fast as it can.
In this case, some color related customizations may not apply on fly.
So on-fly theming will not work, etc.
However seting its value to non-nil is most convinient for most users."
  :type 'boolean
  :group 'xwem-misc)

(defcustom xwem-misc-functions-to-profile nil
  "List of functions to profile using xwem profiler."
  :type (list
         'repeat
         (cons 'choice
               (delq nil
                     (mapcar
                      #'(lambda (fun)
                          (and (symbolp fun)
                               (fboundp fun)
                               (> (length (symbol-name fun)) 4)
                               (string= "xwem" (substring (symbol-name fun) 0 4))
                               (list 'function-item fun)))
                      obarray))))
  :group 'xwem-misc)

;;; Cursors
(defgroup xwem-cursor nil
  "Group to customize cursors in XWEM."
  :prefix "xwem-cursor-"
  :group 'xwem)

;; Default cursor
(defcustom xwem-cursor-default-shape 'X-XC-left_ptr
  "*Shape of default xwem cursor."
  :type (xwem-cursor-shape-choice)
  :set (xwem-cus-set-cursor-shape xwem-cursor-default)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-default-foreground-color "#002800"
  "*Default cursor's foreground color."
  :type 'color
  :set (xwem-cus-set-cursor-foreground xwem-cursor-default)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-default-background-color "#000000"
  "*Default cursor's background color."
  :type 'color
  :set (xwem-cus-set-cursor-background xwem-cursor-default)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

;; wait cursor
(defcustom xwem-cursor-wait-shape 'X-XC-icon
  "*Shape of cursor, when XWEM wait for something."
  :type (xwem-cursor-shape-choice)
  :set (xwem-cus-set-cursor-shape xwem-cursor-wait)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-wait-foreground-color "#ea0000"
  "*Cursor's foreground color when XWEM wait for something."
  :type 'color
  :set (xwem-cus-set-cursor-foreground xwem-cursor-wait)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-wait-background-color "#280000"
  "*Cursor's background color when XWEM waiit for something."
  :type 'color
  :set (xwem-cus-set-cursor-background xwem-cursor-wait)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

;; move cursor
(defcustom xwem-cursor-move-shape 'X-XC-fleur
  "*Shape of cursor, when moving something."
  :type (xwem-cursor-shape-choice)
  :set (xwem-cus-set-cursor-shape xwem-cursor-move)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-move-foreground-color "#777777"
  "*Cursor's foreground color when moving something."
  :type 'color
  :set (xwem-cus-set-cursor-foreground xwem-cursor-move)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-move-background-color "#280000"
  "*Cursor's background color when moving something."
  :type 'color
  :set (xwem-cus-set-cursor-background xwem-cursor-move)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

;; Resize cursor
(defcustom xwem-cursor-resize-shape 'X-XC-sizing
  "*Shape of cursor, when resizing something."
  :type (xwem-cursor-shape-choice)
  :set (xwem-cus-set-cursor-shape xwem-cursor-resize)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-resize-foreground-color "#777777"
  "*Cursor's foreground color when resizing something."
  :type 'color
  :set (xwem-cus-set-cursor-foreground xwem-cursor-resize)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-resize-background-color "#280000"
  "*Cursor's background color when resizing something."
  :type 'color
  :set (xwem-cus-set-cursor-background xwem-cursor-resize)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

;; quote cursor
(defcustom xwem-cursor-quote-shape 'X-XC-sb_down_arrow
  "*Shape of cursor, when XWEM quoting keyboard or mouse."
  :type (xwem-cursor-shape-choice)
  :set (xwem-cus-set-cursor-shape xwem-cursor-quote)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-quote-foreground-color "#0000BB"
  "*Cursor's foreground color when XWEM quoting keyboard/mouse."
  :type 'color
  :set (xwem-cus-set-cursor-foreground xwem-cursor-quote)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-quote-background-color "#000099"
  "*Cursor's background color when XWEM quoting keyboard/mouse."
  :type 'color
  :set (xwem-cus-set-cursor-background xwem-cursor-quote)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

;; help cursor
(defcustom xwem-cursor-help-shape '(X-XC-question_arrow)
  "*Shape of cursor, when getting help with XWEM."
  :type (xwem-cursor-shape-choice)
  :set (xwem-cus-set-cursor-shape xwem-cursor-help)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-help-foreground-color "#00BB00"
  "*Cursor's foreground color when quering XWEM for help."
  :type 'color
  :set (xwem-cus-set-cursor-foreground xwem-cursor-help)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

(defcustom xwem-cursor-help-background-color "#009900"
  "*Cursor's background color when quering XWEM for help."
  :type 'color
  :set (xwem-cus-set-cursor-background xwem-cursor-help)
  :initialize 'custom-initialize-default
  :group 'xwem-cursor)

;;; Internal variables

;; cursor storages
(defvar xwem-cursor-fnt nil "Font for \"cursor\" series.")

(defvar xwem-cursor-default nil "Default cursor.")
(defvar xwem-cursor-left nil "Left cursor.")
(defvar xwem-cursor-right nil "Right cursor.")
(defvar xwem-cursor-wait nil "Cursor when we are wait.")
(defvar xwem-cursor-drag nil "Cursor when we drag.  Drug is a bad idea.")
(defvar xwem-cursor-move nil "Cursor when we move something.")
(defvar xwem-cursor-rsz-vert nil)
(defvar xwem-cursor-rsz-horz nil)
(defvar xwem-cursor-resize nil "Cursor when we resize.")
(defvar xwem-cursor-quote nil "Cursor when quoting key.")
(defvar xwem-cursor-help nil "Cursor when in help mode.")

(defvar xwem-misc-mask-pixmap nil "Pixmap with depth 1.")
;;;###xwem-autoload
(defvar xwem-misc-mask-fgc nil
  "X-Gc with foreground 1.0 destination drawable has depth 1.")
;;;###xwem-autoload
(defvar xwem-misc-mask-bgc nil
  "X-Gc with foreground 1.0 destination drawable has depth 1.")

;;; Macros
(defmacro xwem-xwin-frame (xwin)
  "Return XWEM frame, which X window is XWIN."
  `(X-Win-get-prop ,xwin 'xwem-frame))

;;;###xwem-autoload
(defmacro xwem-xwin-cl (xwin)
  "Return CL, which X window is XWIN."
  `(X-Win-get-prop ,xwin 'xwem-cl))
(defsetf xwem-xwin-cl (xwin) (cl)
  `(if (not ,cl)
       (X-Win-rem-prop ,xwin 'xwem-cl)
     (X-Win-put-prop ,xwin 'xwem-cl ,cl)))

(defadvice XCreateWindow (after xwin-created-by-xwem activate)
  "Mark window's created on xwem-dpy as window created by xwem."
  (let ((dpy (ad-get-arg 0))
        (xwin ad-return-value))
    (when (eq dpy (xwem-dpy))
      (X-Win-put-prop xwin 'xwin-created-by-xwem t))))

;;; Functions
;;;###xwem-autoload
(defun xwem-misc-colorspec->rgb-vector (colspec)
  "Conver color specification COLSPEC to internal representation.
COLSPEC maybe in form: #RRGGBB or name like 'green4'."
  (let ((col (color-instance-rgb-components
	      (make-color-instance colspec (default-x-device)))))
    (and col (vconcat col))))

;;;###xwem-autoload
(defun xwem-misc-colorspec->rgb-vector-safe (colspec &optional defret)
  "Validate COLSPEC to be color specification in safe manner.
Return DEFRET or [0 0 0] if there was error."
  (condition-case nil
      (xwem-misc-colorspec->rgb-vector colspec)
    (t (or defret [0 0 0]))))

;;;###xwem-autoload
(defun xwem-misc-colorspec-valid-p (colspec)
  "Return non-nil if COLSPEC is valid color specification.
Valid colorspecification is spec in form: #RRGGBB or name like 'green4'."
  (condition-case nil
      (xwem-misc-colorspec->rgb-vector colspec)
    (t nil)))

;;;###xwem-autoload
(defun xwem-make-color (colorspec &optional cmap)
  "Create X-Color according to COLORSPEC."
  (let ((ccol (xwem-misc-colorspec->rgb-vector-safe colorspec [0 0 0])))
    (make-X-Color :red (aref ccol 0)
                  :green (aref ccol 1)
                  :blue (aref ccol 2))))
  
;;;###xwem-autoload
(defun xwem-make-cursor (type &optional fgcol bgcol)
  "Make new cursor of TYPE and store it in WHERE-STORE.
BGCOL maybe nil, that mean masking will not be done."
  (xwem-cursors-init)                   ; make sure cursor font loaded

  (let ((fgc (xwem-misc-colorspec->rgb-vector-safe fgcol [0 0 0]))
        (bgc (xwem-misc-colorspec->rgb-vector-safe bgcol 'invalid-bgcol))
        src-char msk-char cursor)
    (cond ((listp type)
           (setq src-char (eval (car type))
                 msk-char (1+ src-char)))
          (t (setq src-char (eval type)
                   msk-char src-char)))
    (setq cursor (make-X-Cursor
                  :dpy (xwem-dpy) :id (X-Dpy-get-id (xwem-dpy))
                  :source xwem-cursor-fnt
                  :mask xwem-cursor-fnt
                  :src-char src-char
                  :msk-char msk-char
                  :fgred (aref fgc 0)
                  :fggreen (aref fgc 1)
                  :fgblue (aref fgc 2)))
    (unless (eq bgc 'invalid-bgcol)
      (setf (X-Cursor-bgred cursor) (aref bgc 0))
      (setf (X-Cursor-bggreen cursor) (aref bgc 1))
      (setf (X-Cursor-bgblue cursor) (aref bgc 2)))

    (XCreateGlyphCursor (xwem-dpy) cursor)
    cursor))

;;;###xwem-autoload
(defun xwem-cursor-recolorize (cursor new-fg &optional new-bg)
  "Recolorize CURSOR to use NEW-FG foreground and NEW-BG background."
  (let ((fgc (xwem-misc-colorspec->rgb-vector-safe
              new-fg (vector (X-Cursor-fgred cursor)
                             (X-Cursor-fggreen cursor)
                             (X-Cursor-fgblue cursor))))
        (bgc (xwem-misc-colorspec->rgb-vector-safe
              new-bg (vector (X-Cursor-bgred cursor)
                             (X-Cursor-bggreen cursor)
                             (X-Cursor-bgblue cursor)))))
    (XRecolorCursor (xwem-dpy) cursor
                    (aref fgc 0) (aref fgc 1) (aref fgc 2)
                    (aref bgc 0) (aref bgc 1) (aref bgc 2))))

(defun xwem-cursors-init ()
  "Initialize cursors."
  (unless xwem-cursor-fnt
    ;; Make cursors
    (xwem-message 'init "Initializing cursors ...")

    (setq xwem-cursor-fnt (make-X-Font :dpy (xwem-dpy) :id (X-Dpy-get-id (xwem-dpy))
                                       :name "cursor"))
    (XOpenFont (xwem-dpy) xwem-cursor-fnt)

    (setq xwem-cursor-default (xwem-make-cursor
                               xwem-cursor-default-shape
                               xwem-cursor-default-foreground-color
                               xwem-cursor-default-background-color)
          xwem-cursor-left (xwem-make-cursor
                            X-XC-left_ptr
                            xwem-cursor-default-foreground-color
                            xwem-cursor-default-background-color)
          xwem-cursor-right (xwem-make-cursor
                             X-XC-right_ptr
                             xwem-cursor-default-foreground-color
                             xwem-cursor-default-background-color)
          xwem-cursor-wait (xwem-make-cursor
                            xwem-cursor-wait-shape
                            xwem-cursor-wait-foreground-color
                            xwem-cursor-wait-background-color)
          xwem-cursor-move (xwem-make-cursor
                            xwem-cursor-move-shape
                            xwem-cursor-move-foreground-color
                            xwem-cursor-move-background-color)
          xwem-cursor-resize (xwem-make-cursor
                              xwem-cursor-resize-shape
                              xwem-cursor-resize-foreground-color
                              xwem-cursor-resize-background-color)
          xwem-cursor-quote (xwem-make-cursor
                             xwem-cursor-quote-shape
                             xwem-cursor-quote-foreground-color
                             xwem-cursor-quote-background-color)
          xwem-cursor-help (xwem-make-cursor
                            xwem-cursor-help-shape
                            xwem-cursor-help-foreground-color
                            xwem-cursor-help-background-color))

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

;;; Misc drawing
;;;###xwem-autoload
(defun xwem-misc-draw-shadow (dpy win gc1 gc2 x y w h thick)
  "Draw shadow."
  (let ((offset 0)
        s1 s2)
    (if (or (> (* thick 2) h) (> (* thick 2) w))
        nil                             ; undrawable
      (while (not (= thick offset))
        (setq s1 (cons (cons (make-X-Point :xx (+ x offset)
                                           :yy (+ y offset))
                             (make-X-Point :xx (+ x offset)
                                           :yy (- (+ y h) offset 1)))
                       s1))
        (setq s1 (cons (cons (make-X-Point :xx (+ x offset)
                                           :yy (+ y offset))
                             (make-X-Point :xx (- (+ x w) offset 1)
                                           :yy (+ y offset)))
                       s1))

        (setq s2 (cons (cons (make-X-Point :xx (+ x offset)
                                           :yy (- (+ y h) offset 1))
                             (make-X-Point :xx (- (+ x w) offset 1)
                                           :yy (- (+ y h) offset 1)))
                       s2))
        (setq s2 (cons (cons (make-X-Point :xx (- (+ x w) offset 1)
                                           :yy (+ y offset 1))
                             (make-X-Point :xx (- (+ x w) offset 1)
                                           :yy (- (+ y h) offset 1)))
                       s2))

        (setq offset (+ offset 1)))

      (when s1
        (XDrawSegments dpy win gc1 s1))
      (when s2
        (XDrawSegments dpy win gc2 s2))
      )))

;;;###xwem-autoload
(defun xwem-misc-draw-bar (dpy win gc1 gc2 gc3 x y w h th)
  "Draw shadowed bar.
Bar filled with GC1.
Shadow thickness is TH and it is drawed with GC2 and GC3."
  (xwem-debug 'xwem-misc "Draw bar .. x=%d y=%d w=%d h=%d" 'x 'y 'w 'h)
  
  (xwem-misc-draw-shadow dpy win gc2 gc3 x y w h th)
  (XFillRectangle dpy win gc1 (+ x th) (+ y th)
                  (- w (* th 2)) (- h (* th 2))))

;;;###xwem-autoload
(defun xwem-misc-find-frame (name &optional frames-list)
  "Find Emacs frame by its NAME."
  (let ((fl (or frames-list (frame-list)))
        (rf nil))

    (while fl
      (when (string= (frame-name (car fl)) name)
        ;; Found
        (setq rf (car fl))
        (setq fl nil))
      (setq fl (cdr fl)))
    rf))

;;;###xwem-autoload
(defun xwem-misc-find-emacs-frame (cl)
  "Return Emacs frame that corresponds CL.
HACK, DO NOT USE."
  (let ((fr (xwem-cl-get-sys-prop cl 'emacs-frame)))
    (if fr
        (if (framep fr) fr nil)

      ;; Not yet in cl's plist
      (let ((frames (frame-list))
            xtr)

        (setq xtr (XQueryTree (xwem-dpy) (xwem-cl-xwin cl)))
        (if (car xtr)
            (setq xtr (mapcar 'X-Win-id (cdr (cdr (cdr (cdr xtr))))))
          (setq xtr nil))

        (while (and frames
                    (not (member 
                          (float (- (string-to-int
                                     (or (frame-property
                                          (car frames) 'window-id) "0")) 2))
                          xtr)))
          (setq frames (cdr frames)))

        (if (framep (car frames))
            (xwem-cl-put-sys-prop cl 'emacs-frame (car frames))
          (xwem-cl-put-sys-prop cl 'emacs-frame 'no-emacs-frame))
        (car frames)))))

(defun xwem-misc-find-cl-by-emacs-frame (frame)
  "Return xwem client that holds Emacs FRAME."
  (let ((fid (float (- (string-to-int
                        (or (frame-property frame 'window-id) "0"))
                       2)))
        (clients xwem-clients)
        wm-class xtr rcl)
    (while clients
      (setq wm-class (xwem-hints-wm-class (xwem-cl-hints (car clients))))
      (when (string= (cdr wm-class) x-emacs-application-class)
        (setq xtr (XQueryTree (xwem-dpy) (xwem-cl-xwin (car clients))))
        (if (car xtr)
            (setq xtr (mapcar 'X-Win-id (cdr (cdr (cdr (cdr xtr))))))
          (setq xtr nil))

        (when (member fid xtr)
          (setq rcl (car clients))
          (setq clients nil)))

      (setq clients (cdr clients)))
    rcl))

;;;###xwem-autoload
(defun xwem-misc-xwin-valid-p (xwin)
  "Return non-nil if XWIN is valid X window.
Do it in safe manner."
  (let (attrs)
    (X-Dpy-put-property (X-Win-dpy xwin) 'xwem-ignore-bad-win t)
    (xwem-unwind-protect
        (setq attrs (XGetWindowAttributes (X-Win-dpy xwin) xwin))
      (X-Dpy-put-property (X-Win-dpy xwin) 'xwem-ignore-bad-win nil))
    attrs))

(defun xwem-misc-xerr-hook (xdpy xev)
  "Display X errors in `xwem-minibuffer'.
Error hook must not performe any interaction with X server!
XDPY - X-Dpy.
XEV  - X-Event of error type."
  (let* ((err (X-Event-xerror-code xev))
         (badth (X-Event-xerror-resourceid xev))
         (seq (X-Event-seq xev))
         (maj (X-Event-xerror-maj-op xev))
         (opfun (cdr (assq maj xlib-opcodes-alist)))
         (min (X-Event-xerror-min-op xev))
         (bstr (cond ((= err 1) "Request")
                     ((= err 2) "Value")
                     ((= err 3) "Window")
                     ((= err 4) "Pixmap")
                     ((= err 5) "Atom")
                     ((= err 6) "Cursor")
                     ((= err 7) "Font")
                     ((= err 8) "Match")
                     ((= err 9) "Drawable")
                     ((= err 10) "Access")
                     ((= err 11) "Alloc")
                     ((= err 12) "Color")
                     ((= err 13) "GC")
                     ((= err 14) "IDChoice")
                     ((= err 15) "Name")
                     ((= err 16) "Length")
                     ((= err 17) "Implementation")
                     ((= err 128) "FirstExtension")
                     ((= err 255) "LastExtension")
                     (t "Unknown"))))
    (unless (and (X-Dpy-get-property xdpy 'xwem-ignore-bad-win)
                 (eq err 3))
      (xwem-message 'error "X error - Bad %s %f seq=%f:%d ops=%d:%d/%S"
                    bstr badth seq (X-Dpy-rseq-id (xwem-dpy)) maj min opfun)
    )))

(defun xwem-misc-init ()
  "Miscellaneous initializations."
  (pushnew 'xwem-misc-xerr-hook (X-Dpy-error-hooks (xwem-dpy)))
  (xwem-cursors-init)

  (xwem-message 'init "Initializing masking ...")
  ;; Depth 1 pixmap, gcs
  (setq xwem-misc-mask-pixmap
        (XCreatePixmap (xwem-dpy)
                       (make-X-Pixmap :dpy (xwem-dpy)
                                      :id (X-Dpy-get-id (xwem-dpy)))
                       (xwem-rootwin) 1 1 1)
        xwem-misc-mask-fgc
        (XCreateGC (xwem-dpy) xwem-misc-mask-pixmap
                   (make-X-Gc :dpy (xwem-dpy)
                              :id (X-Dpy-get-id (xwem-dpy))
                              :foreground 1.0
                              :background 0.0))
        xwem-misc-mask-bgc
        (XCreateGC (xwem-dpy) xwem-misc-mask-pixmap
                   (make-X-Gc :dpy (xwem-dpy)
                              :id (X-Dpy-get-id (xwem-dpy))
                              :foreground 0.0
                              :background 1.0)))
  (xwem-message 'init "Initializing masking ... done"))

;;; Stuff for debugging
(defun xwem-misc-str2hexstr (str)
  "Convert STR to hexidecimal string representation."
  (substring (mapconcat #'(lambda (el) (format "%x " el)) str "") 0 -1))

;;; Messaging
(defun xwem-str-with-faces (str face-list)
  "Return STR with applied FACE-LIST."
  (let ((ext (make-extent 0 (length str) str)))

    (set-extent-property ext 'duplicable t)
    (set-extent-property ext 'unique t)
    (set-extent-property ext 'start-open t)
    (set-extent-property ext 'end-open t)
    (set-extent-property ext 'face face-list))
  str)

(defun xwem-format-faces (fmt def-face &rest args)
  "Accepts format FMT and ARGS in form `((arg . face) ...)'.
DEF-FACE is default face. Returns string with faces."
  (let ((flst (string-to-list fmt))
        (chr nil)
        (rstr ""))
    (while flst
      (setq chr (car flst))
      (cond ((= chr ?%)
             (setq flst (cdr flst))
             (setq chr (car flst))
             (let ((arg (if (consp (car args)) (caar args) (car args)))
                   (fcs (if (consp (car args)) (cdr (car args)) nil)))
               (cond ((= chr ?s)
                      (setq rstr (concat
                                  rstr
                                  (xwem-str-with-faces
                                   arg
                                   (if fcs
                                       (list fcs def-face)
                                     (list def-face)))))
                      (setq args (cdr args)))

                     ((= chr ?d)
                      (setq rstr (concat
                                  rstr
                                  (xwem-str-with-faces
                                   (int-to-string arg)
                                   (if fcs
                                       (list fcs def-face)
                                     (list def-face)))))
                      (setq args (cdr args)))
                     (t nil))))
            (t
             (setq rstr
                   (concat rstr
                           (xwem-str-with-faces
                            (char-to-string chr) (list def-face))))))
      (setq flst (cdr flst)))
    rstr))

(defun xwem-message-log (label message)
  "Log MESSAGE in `xwem-messages-buffer-name' buffer."
  (unless (memq label xwem-messages-ignore-labels)
    (with-current-buffer (get-buffer-create xwem-messages-buffer-name)
      (let ((inhibit-read-only t))
        ;; Remove all messages from buffer if it exided maximum value
        (when (> (count-lines (point-min) (point-max))
                 xwem-messages-buffer-lines)
          (delete-region (point-min) (point-max)))

        (goto-char (point-max))
        (insert (format-time-string "%D %T: "))
        (insert message)
        (insert "\n")))))

;;;###xwem-autoload
(defun xwem-clear-message (&optional label)
  "Clear xwem minibuffer's buffer."
  (clear-message label (xwem-minib-frame xwem-minibuffer)))

(defun xwem-message-insert (label msg &optional append-p)
  "Insert message MSG into xwem minibuffer's buffer."
  ;; Workaround XEmacs ''feature''.  When minibuffer is activated,
  ;; and someone uses echo are, XEmacs will wait 2 seconds, so we
  ;; will got lag! (see DEFUN `command-loop-1' in cmdloop.c) --lg
  ;; 
  ;;   However in newer XEmacsen there is
  ;;   `minibuffer-echo-wait-function' variable, which controls
  ;;   behaviour. --lg
  (when (zerop (minibuffer-depth))
    ;; Activate minibuffer, if not ignoring this label
    (when (and xwem-minibuffer
               (xwem-minib-cl xwem-minibuffer)
               (not (memq label xwem-messages-ignore-labels)))
      (xwem-activate (xwem-minib-cl xwem-minibuffer)))
    (add-to-list 'log-message-ignore-labels label) ; avoid logging in *Messages*
    (if append-p
        (append-message label msg
                        (and xwem-minibuffer
                             (xwem-minib-frame xwem-minibuffer)))
      (display-message label msg
                       (and xwem-minibuffer
                            (xwem-minib-frame xwem-minibuffer))))))

(defun xwem-message-label-prefix (label)
  "Return prefix string, according to LABEL.
Return nil if no prefix required for label."
  (let ((lp (assq label xwem-messages-label-prefixes)))
    (when lp
        (concat "XWEM" (if (and (stringp (cadr lp))
                                (not (zerop (length (cadr lp)))))
                           "-" "")
                (funcall 'xwem-str-with-faces (cadr lp) (caddr lp))
                ": "))))

(defun xwem-message-maybe-beep (label)
  "If LABEL is beepable, then beep."
  ;; Beep if needed
  (let ((snd (assq label xwem-messages-beeps-alist)))
    (when snd
      (xwem-play-sound (cdr snd)))))

(defun xwem-message-1 (label fmt append-p &rest args)
  (let* ((print-level 3)                ; XXX limit print level
         (msg (if (eq label 'asis) fmt (apply 'format fmt args)))
        (lp (xwem-message-label-prefix label)))
    (when lp
      (setq msg (concat lp msg)))
    (xwem-message-log label msg)
    (xwem-message-maybe-beep label)
    
    (xwem-message-insert label msg append-p)))
    
(defun xwem-message-append (label fmt &rest args)
  "Append message of LABEL type.
Message formatted using FTM and ARGS."
  (apply 'xwem-message-1 label fmt t args))

;;;###xwem-autoload
(defun xwem-message (label fmt &rest args)
  "Display xwem message of TYPE using FMT format."
  (apply 'xwem-message-1 label fmt nil args))

;;;###autoload(autoload 'xwem-show-message-log "xwem-misc" nil t)
(define-xwem-command xwem-show-message-log (arg)
  "Show `xwem-messages-buffer-name'.
If prefix ARG is given, than behaviour is undefined."
  (xwem-interactive "P")

  (let ((mbuf (get-buffer-create xwem-messages-buffer-name)))
    (xwem-special-popup-frame mbuf)
    (with-current-buffer mbuf
      (setq mode-name "XWEM-log")
      (local-set-key (kbd "q") 'delete-frame)
      (xwem-message 'msg "Press `q' to eliminate buffer.")
      )))

(defun xwem-list-to-string (list len)
  "Convert LIST of characterters to string with length LEN."
  (let ((rstr ""))
    (while (and list (> len 0))
      (setq rstr (concat rstr (string (car list))))
      (setq list (cdr list))
      (setq len (1- len)))
    rstr))

;;;; Misc commands.
;;;###autoload(autoload 'xwem-ignore-command "xwem-misc" nil t)
(define-xwem-command xwem-ignore-command (&rest args)
  "Generic ignore command."
  (xwem-interactive))
  
(defvar xwem-read-expression-history nil
  "*History of expressions evaled using `xwem-eval-expression'.")

;;;###autoload(autoload 'xwem-eval-expression "xwem-misc" nil t)
(define-xwem-command xwem-eval-expression (expr &optional arg)
  "Eval Lisp expression interactively.
When used with prefix ARG, then insert the result into selected client."
  (xwem-interactive
   (list
    (xwem-read-from-minibuffer (if xwem-prefix-arg
                                   "XWEM (insert) Eval: "
                                 "XWEM Eval: ")
                               nil read-expression-map
                               t 'xwem-read-expression-history)
    xwem-prefix-arg))

  (setq values (cons (eval expr) values))
  (if arg
      (xwem-kbd-add-pending-keys (prin1-to-string (car values)))
    (xwem-deffered-funcall
     'xwem-message 'info "%S => %S" expr (car values))))

;;;###autoload(autoload 'xwem-execute-extended-command "xwem-misc" nil t)
(define-xwem-command xwem-execute-extended-command (arg)
  "Execute Emacs command.
Prefix ARG is passed to extended command."
  (xwem-interactive "P")

  (with-xwem-read-from-minibuffer
   (let ((xwem-prefix-arg arg))
     (execute-extended-command arg))))

;;;###autoload(autoload 'xwem-shell-command "xwem-misc" nil t)
(define-xwem-command xwem-shell-command (command arg)
  "Execute shell command, just as `shell-command' do.
If prefix ARG is given insert result to current client.
If output of COMMAND fits to one string it is displayed in
`xwem-minibuffer', if not Emacs special frame will be poped up with
contents of COMMAND output.
If double prefix ARG \(i.e. \\<xwem-global-map>\\[xwem-universal-argument] \\<xwem-global-map>\\[xwem-universal-argument]\) supplied, then last
'\\n' character will be cuted in output to current client."
  (xwem-interactive (list (xwem-read-external-command 
                           (if xwem-prefix-arg
                               (if (> (prefix-numeric-value xwem-prefix-arg) 4)
                                   "XWEM (insert-nonl) shell command: "
                                 "XWEM (insert) shell command: ")
                             "XWEM shell command: "))
                          xwem-prefix-arg))

  ;; Create temporary buffer for shell command output
  (let ((tbuf (get-buffer-create (generate-new-buffer-name " *temp-buf*")))
        (dontkill nil)
        status)
    (unwind-protect
        (with-current-buffer tbuf
          (setq status (call-process shell-file-name nil tbuf nil
                                     shell-command-switch command))
          (cond (arg
                 (xwem-kbd-add-pending-keys
                  (buffer-substring
                   (point-min) (- (point-max)
                                  (if (> (prefix-numeric-value arg) 4) 1 0)))))
                ((= (point-max) (point-min))
                 (xwem-message 'info "Process exit status: %d" status))
                ((= 1 (count-lines (point-min) (point-max)))
                 (xwem-message 'info (buffer-substring (point-min) (point-max))))
                (t
                 (xwem-special-popup-frame tbuf)
                 (setq dontkill t))))
      (unless dontkill
        (kill-buffer tbuf)))))

;;;###autoload(autoload 'xwem-mini-calc "xwem-misc" nil t)
(define-xwem-command xwem-mini-calc (expr &optional arg)
  "Calculate expression EXPR.
If prefix ARG is given, insert the result to current client."
  (xwem-interactive
   (list (xwem-read-from-minibuffer (if xwem-prefix-arg
                                        "XWEM (insert) Calc: "
                                      "XWEM Calc: "))
         xwem-prefix-arg))

  (let ((result (calc-eval expr)))
    (if arg
        (xwem-kbd-add-pending-keys result)
      (xwem-message 'info "%s = %s" expr result))))

;;;###autoload(autoload 'xwem-misc-make-screenshot "xwem-misc" nil t)
(define-xwem-command xwem-misc-make-screenshot (file-name &optional arg)
  "Make screen screenshot and save it to file with NAME.
If used with prefix ARG - import screenshot of current client window.

With double ARG (H-u H-u) - import screenshot of current client with
frame included.

NOTE: `xwem-misc-make-screenshot' uses \"import\" utility from
ImageMagic package, which you can obtain at
http://imagemagick.sourceforge.net/."
  (xwem-interactive "FImport screen to file: \nP")

  (flet ((message (fmt &rest args) nil)) ; XXX shutup messaging
    (xwem-message 'info
                  (format "Importing screenshot to %s." file-name))
    (xwem-add-hook-post-deffering
     `(lambda ()
        (xwem-execute-program
         (format "import -window 0x%x %s %s"
                 ,(X-Win-id (if arg
                                (xwem-cl-xwin (xwem-cl-selected))
                              (xwem-rootwin)))
                 ,(if (equal arg '(16)) "-frame" "")
                 ,(expand-file-name file-name)))))))

;;;###autoload(autoload 'xwem-misc-pause "xwem-misc" nil t)
(define-xwem-command xwem-misc-pause (arg)
  "Pause for ARG decaseconds(0.1 sec).
This command is usefull, when recording keyboard macro, and there need
to wait for something, f.e. window mapping."
  (xwem-interactive "p")

  (add-timeout (* 0.1 arg) (lambda (&rest args) (exit-recursive-edit)) nil)
  (recursive-edit))

;;; Some useful operations on lists
(defun xwem-insert-after (list aft-el el)
  "In LIST after AFT-EL insert EL."
  (push el (cdr (member aft-el list)))
  list)

(defun xwem-insert-before (list bef-el el)
  "In LIST before BEF-EL insert EL."
  (nreverse (xwem-insert-after (nreverse list) bef-el el)))

(defun xwem-list-set-element (list old-el new-el)
  "In LIST set OLD-EL to NEW-EL."
  (setcar (memq old-el list) new-el)
  list)

;;;###xwem-autoload
(defun xwem-list-exchange-els (list el1 el2)
  "In LIST exchange places of EL1 and EL2."
  (when (and (memq el1 list)
             (memq el2 list)
             (not (eq el1 el2)))
    (xwem-list-set-element list el1 'this-fake-name1-should-not-be-in-list)
    (xwem-list-set-element list el2 el1)
    (xwem-list-set-element list 'this-fake-name1-should-not-be-in-list el2))
  list)

;;; Profiling support
;;;###autoload
(defun xwem-misc-start-profiling ()
  "Start profiling critical xlib/xwem functions."
  (interactive)

  (setq elp-function-list
        (or xwem-misc-functions-to-profile
            ;; Profile all X-Dpy-XXX functions
            (delq nil (mapcar #'(lambda (el)
                                  (when (and (symbolp el)
                                             (functionp el)
                                             (string-match "X-Dpy-"
                                                           (symbol-name el)))
                                    el))
                              obarray))))
  (elp-instrument-list))

;;;###autoload
(defun xwem-misc-profiling-results ()
  "Show xlib/xwem profiling results."
  (interactive)

  (elp-results))

;;;###xwem-autoload
(defun xwem-recursive-edit ()
  "Enter recursive edit."
  (recursive-edit))

;;;###xwem-autoload
(defun xwem-exit-recursive-edit ()
  "Exit from recursive edit."
  (if (> (recursion-depth) 0)
      (throw 'exit nil))
  (xwem-message 'warning "No recursive edit is in progress"))


;;; Text Specifications operations

;; TextSpec is list of vectors:
;; - vectors elements is cons cells in form (face . "text")
;; - each vector specifies line
;; - empty vector specifies newline

(defun xwem-misc-line->linesp (default-face)
  "Convert current line in selected buffer to element of text spec - line spec.
DEFAULT-FACE is the default face."
  (let (tsp cpnt npnt face str)
    (save-excursion
      (narrow-to-region (point-at-bol) (point-at-eol))
      (goto-char (point-at-bol))
      (while (not (eolp))
        (setq cpnt (point)
              npnt (or (next-single-property-change cpnt 'face) (point-at-eol))
              face (or (get-char-property cpnt 'face) default-face)
              str (buffer-substring cpnt npnt))
        (when (consp face)
          (setq face (car face)))       ; XXX need face merging
        
        ;; XXX Untabify
        (setq str (replace-in-string str "\t" (make-string tab-width ?\x20)))

        (setq tsp (cons (cons face str) tsp))
        (goto-char npnt))
      (widen))
    (vconcat (nreverse (or tsp (list (cons default-face "")))))))

(defun xwem-misc-buffer->textsp (default-face &optional buffer start end)
  "Convert BUFFER to text specification.
DEFAULT-FACE is the default face.
If BUFFER is omitted, selected buffer assumed."
  (let (rlst)
    (save-excursion
      (when buffer
        (set-buffer buffer))

      (goto-char (or start (point-min)))
      (while (and (not (eobp))
                  (< (point) (or end (point-max))))
        (setq rlst (cons (xwem-misc-line->linesp default-face) rlst))
        (forward-line 1))
      )
    (nreverse rlst)))

(defun xwem-misc-linesp-width (linesp)
  "Return width of line spec LINESP."
  (apply '+ (mapcar #'(lambda (el)
                        (X-Text-width
                         (xwem-dpy) (X-Gc-font (xwem-face-get-gc (car el)))
                         (cdr el)))
                    linesp)))

(defun xwem-misc-linesp-height (linesp)
  "Return height of line spec LINESP."
  (apply 'max (mapcar #'(lambda (el)
                          (X-Text-height
                           (xwem-dpy) (X-Gc-font (xwem-face-get-gc (car el)))
                           (cdr el)))
                      linesp)))

(defun xwem-misc-linesp-show (d x y linesp &optional type default-background)
  "In X drawable D at X and Y coordinates show line spec LINESP.
TYPE is one of XImageString or XDrawString, default is XImageString."
  (let ((cxoff 0))
    (mapc #'(lambda (el)
              (funcall (cond ((and (eq type 'XDrawString)
                                   (stringp default-background)
                                   (not (string= default-background
                                                 (face-background-name (car el)))))
                              'XImageString)
                             ((not (null type)) type)
                             (t 'XImageString))
                       (X-Drawable-dpy d) d
                       (xwem-face-get-gc (car el))
                       (+ x cxoff) y (cdr el))
              (setq cxoff (+ cxoff (X-Text-width
                                    (X-Drawable-dpy d)
                                    (X-Gc-font (xwem-face-get-gc (car el)))
                                    (cdr el)))))
          linesp)))

(defun xwem-misc-textsp-show (xwin x y textsp &optional type default-background)
  "In x window XWIN at X and Y coordinates show text spec TEXTSP.
TYPE is one of XImageString or XDrawString, default is XImageString.
If TYPE is XDrawString and DEFAULT-BACKGROUND is specifed, characters
that have different than DEFAULT-BACKGROUND baground color are drawed
using XImageString."
  (let ((yoff 0))
    (mapc #'(lambda (el)
              (xwem-misc-linesp-show xwin x (+ y yoff) el type default-background)
              (setq yoff (+ yoff (xwem-misc-linesp-height el))))
          textsp)
    ))

;;; Outlining
(define-xwem-face xwem-misc-outline-face1
  `((t (:foreground "white" :background "black"
        :function X-GXXor :subwindow-mode X-IncludeInferiors
        :line-width 4)))
  "Face used to outline something."
  :group 'xwem-misc
  :group 'xwem-faces)

(define-xwem-face xwem-misc-outline-face2
  `((t (:foreground "white" :background "black"
        :function X-GXXor :subwindow-mode X-IncludeInferiors
        :line-width 2)))
  "Face used to outline something."
  :group 'xwem-misc
  :group 'xwem-faces)

(defun xwem-misc-outline (xrect how &optional xwin)
  "Outline XRECT using HOW method in XWIN.
Valid HOW is 'normal, ...
If XWIN is not specified, X root window is used."
  (unless xwin
    (setq xwin (xwem-rootwin)))

  (let ((x (X-Rect-x xrect))
        (y (X-Rect-y xrect))
        (w (X-Rect-width xrect))
        (h (X-Rect-height xrect)))
    (cond ((eq how 'normal)
           (XDrawRectangles
            (xwem-dpy) xwin (xwem-face-get-gc 'xwem-misc-outline-face1)
            (list xrect)))

          ((eq how 'contiguous)
           (xwem-misc-outline xrect 'normal)
           (XDrawSegments
            (xwem-dpy) xwin (xwem-face-get-gc 'xwem-misc-outline-face2)
            (list (cons (cons x 0)
                        (cons x (X-Geom-height (xwem-rootgeom))))
                  (cons (cons (+ x w) 0)
                        (cons (+ x w) (X-Geom-height (xwem-rootgeom))))
                  (cons (cons 0 y)
                        (cons (X-Geom-width (xwem-rootgeom)) y))
                  (cons (cons 0 (+ y h))
                        (cons (X-Geom-width (xwem-rootgeom)) (+ y h)))
                  )))

          ((eq how 'corners)
           (let* ((cornw (/ w 8))
                  (cornh (/ h 8))
                  (crw (/ (+ cornh cornw) 2)))
             (XDrawSegments
              (xwem-dpy) xwin (xwem-face-get-gc 'xwem-misc-outline-face1)
              (list 
               ;; Top left
               (cons (cons x y) (cons (+ x cornw) y))
               (cons (cons x y) (cons x (+ y cornh)))

               ;; Top right
               (cons (cons (+ x w) y) (cons (+ x w (- cornw)) y))
               (cons (cons (+ x w) y) (cons (+ x w) (+ y cornh)))

               ;; Bottom left
               (cons (cons x (+ y h)) (cons (+ x cornw) (+ y h)))
               (cons (cons x (+ y h)) (cons x (+ y h (- cornh))))
                                
               ;; Bottom right
               (cons (cons (+ x w) (+ y h)) (cons (+ x w (- cornw)) (+ y h)))
               (cons (cons (+ x w) (+ y h)) (cons (+ x w) (+ y h (- cornh))))

               ;; Crosshair
               (cons (cons (+ x (/ (- w crw) 2)) (+ y (/ h 2)))
                     (cons (+ x (/ (+ w crw) 2)) (+ y (/ h 2))))
               (cons (cons (+ x (/ w 2)) (+ y (/ (- h crw) 2)))
                     (cons (+ x (/ w 2)) (+ y (/ (+ h crw) 2))))
               ))))

          ((eq how 'grid)
           (xwem-misc-outline xrect 'normal)
           (XDrawSegments
            (xwem-dpy) xwin (xwem-face-get-gc 'xwem-misc-outline-face2)
            (nconc (funcall
                    #'(lambda ()
                        (let ((off 0) rl)
                          (while (< off (+ x w))
                            (when (> off x)
                              (setq rl (cons (cons (cons off y)
                                                   (cons off (+ y h)))
                                             rl)))
                            (setq off (+ off 64)))
                          rl)))
                   (funcall #'(lambda ()
                                (let ((off 0)
                                      rl)
                                  (while (< off (+ y h))
                                    (when (> off y)
                                      (setq rl (cons (cons (cons x off)
                                                           (cons (+ x w) off))
                                                     rl)))
                                    (setq off (+ off 64)))
                                  rl)))))
           )

          ;; TODO: add others
          )))

(defun xwem-misc-move-outline (rect1 rect2 &optional steps)
  "Move RECT1 to RECT2 by STEPS redraws.
Somekind of animation.  XEmacs will block while moving.
Default STEPS is 40."
  (unless steps
    (setq steps 40))

  (xwem-misc-outline rect1 'normal)
  (let ((crect rect1) tcrect
        factor x-step y-step w-step h-step
        done)
    
    ;; Setup steps
    (setq x-step (/ (- (X-Rect-x rect2) (X-Rect-x rect1))
                    steps)
          y-step (/ (- (X-Rect-y rect2) (X-Rect-y rect1))
                    steps)
          w-step (/ (- (X-Rect-width rect2) (X-Rect-width rect1))
                    steps)
          h-step (/ (- (X-Rect-height rect2) (X-Rect-height rect1))
                    steps)
          factor (max x-step y-step w-step h-step))

    (while (not done)
      ;; Remember CRECT before modification
      (setq tcrect (copy-X-Rect crect))

      ;; Transforme CRECT
      (incf (X-Rect-x crect) x-step)
      (incf (X-Rect-width crect) w-step)
      (incf (X-Rect-y crect) y-step)
      (incf (X-Rect-height crect) h-step)

      ;; break condition
      (when (and (<= (abs (- (X-Rect-width crect)
                             (X-Rect-width rect2))) factor))
        (setq done t))

      ;; Outline CRECT
      (xwem-misc-outline tcrect 'normal)
      (xwem-misc-outline crect 'normal))
    (xwem-misc-outline crect 'normal)))

;;;###xwem-autoload
(defun xwem-misc-xwin-background-mode (xwin x y &optional width height)
  "Return XWIN's background mode in rectange WIDTHxHEIGHT+X+y.
Background mode is one of `light' or `dark'."
  (let ((xgeom (XGetGeometry (xwem-dpy) xwin)))
    ;; Adjust x/y/width/height
    (when (< x 0)
      (setq x 0))
    (when (< y 0)
      (setq y 0))
    (when (and width (< width 0))
      (setq width nil))
    (when (and height (< height 0))
      (setq height nil))

    (unless width
      (setq width 10))
    (unless height
      (setq height 10))
    (when (> width (X-Geom-width xgeom))
      (setq width (X-Geom-width xgeom)))
    (when (> height (X-Geom-height xgeom))
      (setq height (X-Geom-height xgeom)))
    (when (> x (X-Geom-width xgeom))
      (setq x (- (X-Geom-width xgeom) width)))
    (when (> y (X-Geom-height xgeom))
      (setq y (- (X-Geom-height xgeom) height))))

  (let* ((ximg (XImageGet (xwem-dpy) xwin x y width height))
         (cv (nth 3 (XQueryColors (xwem-dpy) (XDefaultColormap (xwem-dpy))
                                  (mapcan 'identity (X-Image-get-prop ximg 'px-layout)))))
         (vv (/ (apply '+ (apply 'nconc cv)) (length cv))))

    (XDestroyImage ximg)
    (if (< vv xwem-background-mode-bound)
        'dark 'light)))

;;;###xwem-autoload
(defun xwem-misc-completing-read-using-iswitchb
  (prompt table &optional predicate require-match)
  "Read a string in the xwem minibuffer using iswitchb package.
PROMPT is a string to prompt with.
TABLE is a list of strings to select.
PREDICATE is a function that limits completion to a subset of TABLE."
  (require 'iswitchb)

  (flet ((iswitchb-make-buflist
           (default)
           (setq iswitchb-buflist table)))
    (iswitchb-read-buffer prompt)))

;;;###xwem-autoload
(defun xwem-misc-xbutton-cl (xev)
  "Return client where button event XEV occured."
  (or (xwem-xwin-cl (X-Event-xbutton-event xev))
      (and (X-Win-p (X-Event-xbutton-child xwem-last-xevent))
           (xwem-xwin-cl (X-Event-xbutton-child xwem-last-xevent)))))


(defun xwem-misc-iresize-or-imove (xwin xevent function argument)
  "Interactively resize of move window XWIN according to X event XEVENT.
FUNCTION called each time with three
arguments - ARGUMENT, NEW-X, NEW-Y."
  (let* ((nh (XGetWMNormalHints (xwem-dpy) xwin))
         (min-pnt (or (and (X-WMSize-pminsize-p nh)
                           (cons (X-WMSize-min-width nh)
                                 (X-WMSize-min-height nh)))
                      (cons 0 0)))
         (base-pnt (or (and (X-WMSize-pbasesize-p nh)
                            (cons (X-WMSize-base-width nh)
                                  (X-WMSize-base-height nh)))
                       min-pnt))
         (step-pnt (or (and (X-WMSize-presizeinc-p nh)
                            (cons (X-WMSize-width-inc nh)
                                  (X-WMSize-height-inc nh)))
                       (cons 1 1)))
        
         (srx (X-Event-xbutton-root-x xevent))
         (sry (X-Event-xbutton-root-y xevent))
         
         (done nil)
         need-call xev
         last-x last-y new-x new-y)

    (xwem-mouse-grab xwem-cursor-move xwin
                     (Xmask-or XM-ButtonRelease XM-ButtonMotion))
    (xwem-unwind-protect
        (while (not done)
          (setq need-call nil)
          (X-Event-CASE (setq xev (xwem-next-event))
            (:X-ButtonRelease (setq done t))
        
            (:X-MotionNotify
             ;; Update curr-xrect
             (setq new-x (X-Event-xmotion-root-x xev)
                   new-y (X-Event-xmotion-root-y xev))

             (when (zerop (% (- (- new-x srx)
                                (car base-pnt))
                             (car step-pnt)))
               ;; Can resize
               (setq last-x (- new-x srx)
                     need-call t))

             (when (zerop (% (- (- new-y sry)
                                (cdr base-pnt))
                             (cdr step-pnt)))
               (setq last-y (- new-y sry)
                     need-call t))

             ;; Call function
             (when need-call
               (funcall function argument last-x last-y)))))
      (xwem-mouse-ungrab))))

;;;###xwem-autoload
(defun xwem-misc-fixup-string (str &optional max-width)
  "Fixup STR to be no-more than MAX-WIDTH chars."
  (if (and max-width (> (length str) max-width))
      (substring str 0 max-width)
    str))

;;;###xwem-autoload
(defun xwem-misc-merge-plists (plist1 merg-plist)
  "Merge plist entries on MERG-PLIST to PLIST1 and return resulting plist."
  (while merg-plist
    (setq plist1 (plist-put plist1 (car merg-plist) (cadr merg-plist)))
    (setq merg-plist (cddr merg-plist)))
  plist1)


;;; Huge hack, since non-mule XEmacs 21.4 does not know anything about
;;; UTF-8 :(
(defvar xwem-misc-utf8-koi8-table
 (list [#x10 ?] [#x11 ?] [#x12 ?] [#x13 ?] [#x14 ?] [#x15 ?]
       [#x16 ?] [#x17 ?] [#x18 ?] [#x19 ?] [#x1A ?] [#x1B ?]
       [#x1C ?] [#x1D ?] [#x1E ?] [#x1F ?]

       [#x20 ?] [#x21 ?] [#x22 ?] [#x23 ?] [#x24 ?] [#x25 ?]
       [#x26 ?] [#x27 ?] [#x28 ?] [#x29 ?] [#x2A ??] [#x2B ?]
       [#x2C ?] [#x2D ?] [#x2E ?] [#x2F ?]

       [#x30 ?] [#x31 ?] [#x32 ?] [#x33 ?] [#x34 ?] [#x35 ?]
       [#x36 ?] [#x37 ?] [#x38 ?] [#x39 ?] [#x3A ?] [#x3B ?]
       [#x3C ?] [#x3D ?] [#x3E ?] [#x3F ?]

       [#x40 ?] [#x41 ?] [#x42 ?] [#x43 ?] [#x44 ?] [#x45 ?]
       [#x46 ?] [#x47 ?] [#x48 ?] [#x49 ?] [#x4A ??] [#x4B ?]
       [#x4C ?] [#x4D ?] [#x4E ?] [#x4F ?]))

(defun xwem-misc-utf8-to-koi8-char (utf8-char)
  (let  ((ukl xwem-misc-utf8-koi8-table))
    (while (and ukl
                (not (= (aref (car ukl) 0) utf8-char)))
      (setq ukl (cdr ukl)))
    (or (and ukl
             (aref (car ukl) 1))
        ??)))

(defun xwem-misc-utf8-to-koi8 (utf8-string)
  "Convert UTF8-STRING to KOI8 string.

Here is how UTF-8 looks like

1:  0xxxxxxx
2:  110xxxxx 10xxxxxx
3:  1110xxxx 10xxxxxx 10xxxxxx
4:  11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
5:  111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
6:  1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx

Supported types:

1:  0xxxxxxx
2:  110000xx 10xxxxxx

\\0400 - cyrillic
"
  (let ((rstr "") fc ulen)
    (while (not (string= utf8-string ""))
      (setq fc (aref utf8-string 0))
      (when (= (logand #xa0 fc) #xa0)
        (error "unsupported utf8 character type %d" fc))
      (setq ulen (if (zerop (logand #x80 fc)) 1 2))

      (if (= ulen 1)
          (setq rstr (concat rstr (char-to-string fc))
                utf8-string (substring utf8-string 1))
        (setq rstr (concat rstr
                           (char-to-string
                            (xwem-misc-utf8-to-koi8-char
                             (logior (lsh (logand #xf fc) 6)
                                     (logand #x3f (aref utf8-string 1))))))
              utf8-string (substring utf8-string 2))))
    rstr))

;;; Image rotator
(defun xwem-misc-rotidx-left (i w h depth)
  (setq i (/ i depth))
  (let* ((y (/ i w))
         (x (% i w))
         (x1 y)
         (y1 (- w x 1)))
    (* (+ (* y1 h) x1) depth)))

(defun xwem-misc-rotidx-right (i w h depth)
  (setq i (/ i depth))
  (let* ((y (/ i w))
         (x (% i w))
         (x1 (- h y 1))
         (y1 x))
    (* (+ (* y1 h) x1) depth)))

;;;###xwem-autoload    
(defun xwem-misc-rotate-data (data w h depth &optional rotate)
  "Rotate DATA obtained from XGetImage for use by XPutImage."
  (unless (member depth '(8 16 24 32))
    (error 'xwem-error (format "Unsupported depth %d, use one of (8 16 24 32)" depth)))
  (setq depth (truncate (/ depth 8)))
  
  (unless rotate
    (setq rotate 'left))
  (setq rotate
        (if (eq rotate 'left)
            'xwem-misc-rotidx-left
          'xwem-misc-rotidx-right))

  (let* ((gc-cons-threshold most-positive-fixnum) ; inhibit GCing
        (dstr (make-string (* w h depth) ?\x00))
        (dlen (length data))
        (i 0)
        off j)
    (while (< i dlen)
      (setq off (funcall rotate i w h depth))
      (setq j 0)
      (while (< j depth)
        (aset dstr (+ off j) (aref data (+ i j)))
        (incf j))
      (setq i (incf i depth)))
    dstr))

;;;###xwem-autoload
(defun xwem-debug (routine fmt &rest fmt-args)
  (let ((print-level 3))                ; XXX Restrict huge output
    (apply 'X-Dpy-log (xwem-dpy) routine fmt fmt-args)))


;;; Raise/lower stuff
(defvar xwem-misc-always-on-top-stack nil
  "List of always-on-top windows.")

(defmacro xwem-xwin-rank (xwin)
  `(X-Win-get-prop ,xwin 'always-on-top-rank))
(defsetf xwem-xwin-rank (xwin) (rank)
  `(xwem-misc-set-xwin-always-on-top ,xwin ,rank))

;;;###xwem-autoload
(defun xwem-misc-set-xwin-always-on-top (xwin &optional rank)
  "Mark xwin as always on top window.
If number RANK is given, it denotes rank of always on top window.
Higher RANK mean XWIN is above windows with lower RANK.
By default RANK is 10."
  (X-Win-put-prop xwin 'always-on-top-rank (or rank 10))

  ;; Sort `xwem-misc-always-on-top-stack' by rank after adding XWIN,
  ;; higher rank are at the end.
  (pushnew xwin xwem-misc-always-on-top-stack :test 'X-Win-equal)
  (setq xwem-misc-always-on-top-stack
        (sort xwem-misc-always-on-top-stack
              #'(lambda (xwin1 xwin2)
                  (< (xwem-xwin-rank xwin1)
                     (xwem-xwin-rank xwin2)))))

  ;; Finnaly apply RANK to life
  (xwem-misc-raise-xwin xwin))

;;;###xwem-autoload
(defun xwem-misc-unset-always-on-top (xwin)
  "Unmark XWIN as always on top window."
  (X-Win-rem-prop xwin 'always-on-top-rank)
  (setq xwem-misc-always-on-top-stack
        (delq xwin xwem-misc-always-on-top-stack)))

(defun xwem-misc-find-below-sibling (operation rank)
  "Select appropriate below sibling from `xwem-misc-always-on-top-stack'."
  (let ((sibs xwem-misc-always-on-top-stack)
        (rsib nil))
    (while sibs
      (unless (X-Win-p (car sibs))
        ;; Remove broken sibling
        (setq xwem-misc-always-on-top-stack
              (delq (car sibs) xwem-misc-always-on-top-stack)
              sibs (cdr sibs)))
      (when (funcall operation (xwem-xwin-rank (car sibs)) rank)
        (setq rsib (car sibs)
              sibs nil))
      (setq sibs (cdr sibs)))
    rsib))
  
;;;###xwem-autoload
(defun xwem-misc-raise-xwin (xwin)
  "Raise XWIN reguarding always on top windows."
  (let* ((rank (or (xwem-xwin-rank xwin) 0))
         (bsib (and rank (xwem-misc-find-below-sibling '> rank))))
    (cond ((not bsib)
           (when (memq xwin xwem-misc-always-on-top-stack)
             (setq xwem-misc-always-on-top-stack
                   (nconc (delq xwin xwem-misc-always-on-top-stack)
                          (list xwin))))
           (XRaiseWindow (xwem-dpy) xwin))
          ((not (X-Win-equal xwin bsib))
           ;; Adjust rank stack in case if ranks are equal
           (when (memq xwin xwem-misc-always-on-top-stack)
             (setq xwem-misc-always-on-top-stack
                   (xwem-insert-before
                    (delq xwin xwem-misc-always-on-top-stack)
                    bsib xwin)))
           (XConfigureWindow (xwem-dpy) xwin
                             (make-X-Conf :stackmode X-Below
                                          :sibling bsib))))))

;;;###xwem-autoload
(defun xwem-misc-lower-xwin (xwin)
  "Lower XWIN according to its always on top rank."
  (let* ((rank (xwem-xwin-rank xwin))
         (bsib (and rank (xwem-misc-find-below-sibling '>= rank))))
    (cond ((not bsib)
           (when (memq xwin xwem-misc-always-on-top-stack)
             (setq xwem-misc-always-on-top-stack
                   (cons xwin (delq xwin xwem-misc-always-on-top-stack))))
           (XLowerWindow (xwem-dpy) xwin))
          ((not (X-Win-equal xwin bsib))
           ;; Adjust rank stack in case if ranks are equal
           (when (and (memq xwin xwem-misc-always-on-top-stack)
                      (= rank (xwem-xwin-rank bsib)))
             (setq xwem-misc-always-on-top-stack
                   (xwem-insert-before
                    (delq xwin xwem-misc-always-on-top-stack)
                    bsib xwin)))
           (XConfigureWindow (xwem-dpy) xwin
                             (make-X-Conf :stackmode X-Below
                                          :sibling bsib))))))


(provide 'xwem-misc)

;;; xwem-misc.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.