This file is indexed.

/usr/lib/python2.7/dist-packages/Xlib/protocol/rq.py is in python-xlib 0.14+20091101-5.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# Xlib.protocol.rq -- structure primitives for request, events and errors
#
#    Copyright (C) 2000-2002 Peter Liljenberg <petli@ctrl-c.liu.se>
#
#    This program 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 of the License, or
#    (at your option) any later version.
#
#    This program 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 this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import types

# Standard modules
import sys
import traceback
import struct
from array import array
import types

# Xlib modules
from Xlib import X
from Xlib.support import lock


_PY3 = sys.version[0] >= '3'

# in Python 3, bytes are an actual array; in python 2, bytes are still
# string-like, so in order to get an array element we need to call ord()
if _PY3:
    def _bytes_item(x):
        return x
else:
    def _bytes_item(x):
        return ord(x)

class BadDataError(Exception): pass

# These are struct codes, we know their byte sizes

signed_codes = { 1: 'b', 2: 'h', 4: 'l' }
unsigned_codes = { 1: 'B', 2: 'H', 4: 'L' }


# Unfortunately, we don't know the array sizes of B, H and L, since
# these use the underlying architecture's size for a char, short and
# long.  Therefore we probe for their sizes, and additionally create
# a mapping that translates from struct codes to array codes.
#
# Bleah.

array_unsigned_codes = { }
struct_to_array_codes = { }

for c in 'bhil':
    size = array(c).itemsize

    array_unsigned_codes[size] = c.upper()
    try:
        struct_to_array_codes[signed_codes[size]] = c
        struct_to_array_codes[unsigned_codes[size]] = c.upper()
    except KeyError:
        pass

# print array_unsigned_codes, struct_to_array_codes


class Field:
    """Field objects represent the data fields of a Struct.

    Field objects must have the following attributes:

       name         -- the field name, or None
       structcode   -- the struct codes representing this field
       structvalues -- the number of values encodes by structcode

    Additionally, these attributes should either be None or real methods:

       check_value  -- check a value before it is converted to binary
       parse_value  -- parse a value after it has been converted from binary

    If one of these attributes are None, no check or additional
    parsings will be done one values when converting to or from binary
    form.  Otherwise, the methods should have the following behaviour:

       newval = check_value(val)
         Check that VAL is legal when converting to binary form.  The
         value can also be converted to another Python value.  In any
         case, return the possibly new value.  NEWVAL should be a
         single Python value if structvalues is 1, a tuple of
         structvalues elements otherwise.

       newval = parse_value(val, display)
         VAL is an unpacked Python value, which now can be further
         refined.  DISPLAY is the current Display object.  Return the
         new value.  VAL will be a single value if structvalues is 1,
         a tuple of structvalues elements otherwise.

    If `structcode' is None the Field must have the method
    f.parse_binary_value() instead.  See its documentation string for
    details.

    """

    name = None
    default = None

    structcode = None
    structvalues = 0

    check_value = None
    parse_value = None

    keyword_args = 0

    def __init__(self):
        pass

    def parse_binary_value(self, data, display, length, format):
        """value, remaindata = f.parse_binary_value(data, display, length, format)

        Decode a value for this field from the binary string DATA.
        If there are a LengthField and/or a FormatField connected to this
        field, their values will be LENGTH and FORMAT, respectively.  If
        there are no such fields the parameters will be None.

        DISPLAY is the display involved, which is really only used by
        the Resource fields.

        The decoded value is returned as VALUE, and the remaining part
        of DATA shold be returned as REMAINDATA.
        """

        raise RuntimeError('Neither structcode or parse_binary_value provided for %s'
                           % self)


class Pad(Field):
    def __init__(self, size):
        self.size = size
        self.value = b'\0' * size
        self.structcode = '%dx' % size
        self.structvalues = 0


class ConstantField(Field):
    def __init__(self, value):
        self.value = value


class Opcode(ConstantField):
    structcode = 'B'
    structvalues = 1

class ReplyCode(ConstantField):
    structcode = 'B'
    structvalues = 1

    def __init__(self):
        self.value = 1

class LengthField(Field):
    """A LengthField stores the length of some other Field whose size
    may vary, e.g. List and String8.

    Its name should be the same as the name of the field whose size
    it stores.

    The lf.get_binary_value() method of LengthFields is not used, instead
    a lf.get_binary_length() should be provided.

    Unless LengthField.get_binary_length() is overridden in child classes,
    there should also be a lf.calc_length().
    """

    structcode = 'L'
    structvalues = 1

    def calc_length(self, length):
        """newlen = lf.calc_length(length)

        Return a new length NEWLEN based on the provided LENGTH.
        """

        return length


class TotalLengthField(LengthField):
    pass

class RequestLength(TotalLengthField):
    structcode = 'H'
    structvalues = 1

    def calc_length(self, length):
        return length // 4

class ReplyLength(TotalLengthField):
    structcode = 'L'
    structvalues = 1

    def calc_length(self, length):
        return (length - 32) // 4


class LengthOf(LengthField):
    def __init__(self, name, size):
        self.name = name
        self.structcode = unsigned_codes[size]


class OddLength(LengthField):
    structcode = 'B'
    structvalues = 1

    def __init__(self, name):
        self.name = name

    def calc_length(self, length):
        return length % 2

    def parse_value(self, value, display):
        if value == 0:
            return 'even'
        else:
            return 'odd'


class FormatField(Field):
    """A FormatField encodes the format of some other field, in a manner
    similar to LengthFields.

    The ff.get_binary_value() method is not used, replaced by
    ff.get_binary_format().
    """

    structvalues = 1

    def __init__(self, name, size):
        self.name = name
        self.structcode = unsigned_codes[size]

Format = FormatField


class ValueField(Field):
    def __init__(self, name, default = None):
        self.name = name
        self.default = default


class Int8(ValueField):
    structcode = 'b'
    structvalues = 1

class Int16(ValueField):
    structcode = 'h'
    structvalues = 1

class Int32(ValueField):
    structcode = 'l'
    structvalues = 1

class Card8(ValueField):
    structcode = 'B'
    structvalues = 1

class Card16(ValueField):
    structcode = 'H'
    structvalues = 1

class Card32(ValueField):
    structcode = 'L'
    structvalues = 1


class Resource(Card32):
    cast_function = '__resource__'
    class_name = 'resource'

    def __init__(self, name, codes = (), default = None):
        Card32.__init__(self, name, default)
        self.codes = codes

    def check_value(self, value):
        try:
            return getattr(value, self.cast_function)()
        except AttributeError:
            return value

    def parse_value(self, value, display):
        # if not display:
        #    return value
        if value in self.codes:
            return value

        c = display.get_resource_class(self.class_name)
        if c:
            return c(display, value)
        else:
            return value

class Window(Resource):
    cast_function = '__window__'
    class_name = 'window'

class Pixmap(Resource):
    cast_function = '__pixmap__'
    class_name = 'pixmap'

class Drawable(Resource):
    cast_function = '__drawable__'
    class_name = 'drawable'

class Fontable(Resource):
    cast_function = '__fontable__'
    class_name = 'fontable'

class Font(Resource):
    cast_function = '__font__'
    class_name = 'font'

class GC(Resource):
    cast_function = '__gc__'
    class_name = 'gc'

class Colormap(Resource):
    cast_function = '__colormap__'
    class_name = 'colormap'

class Cursor(Resource):
    cast_function = '__cursor__'
    class_name = 'cursor'


class Bool(ValueField):
    structvalues = 1
    structcode = 'B'

    def check_value(self, value):
        return not not value

class Set(ValueField):
    structvalues = 1

    def __init__(self, name, size, values, default = None):
        ValueField.__init__(self, name, default)
        self.structcode = unsigned_codes[size]
        self.values = values

    def check_value(self, val):
        if val not in self.values:
            raise ValueError('field %s: argument %s not in %s'
                             % (self.name, val, self.values))

        return val

class Gravity(Set):
    def __init__(self, name):
        Set.__init__(self, name, 1, (X.ForgetGravity, X.StaticGravity,
                                    X.NorthWestGravity, X.NorthGravity,
                                    X.NorthEastGravity, X.WestGravity,
                                    X.CenterGravity, X.EastGravity,
                                    X.SouthWestGravity, X.SouthGravity,
                                    X.SouthEastGravity))


class FixedString(ValueField):
    structvalues = 1

    def __init__(self, name, size):
        ValueField.__init__(self, name)
        self.structcode = '%ds' % size


class String8(ValueField):
    structcode = None

    def __init__(self, name, pad = 1):
        ValueField.__init__(self, name)
        self.pad = pad

    def pack_value(self, val):
        slen = len(val)

        if _PY3 and type(val) is str:
            val = val.encode('UTF-8')

        if self.pad:
            return val + b'\0' * ((4 - slen % 4) % 4), slen, None
        else:
            return val, slen, None

    def parse_binary_value(self, data, display, length, format):
        if length is None:
            try:
                return data.decode('UTF-8'), b''
            except UnicodeDecodeError:
                return data, b''

        if self.pad:
            slen = length + ((4 - length % 4) % 4)
        else:
            slen = length

        s = data[:length]
        try:
            s = s.decode('UTF-8')
        except UnicodeDecodeError:
            pass  # return as bytes
        return s, data[slen:]


class String16(ValueField):
    structcode = None

    def __init__(self, name, pad = 1):
        ValueField.__init__(self, name)
        self.pad = pad

    def pack_value(self, val):
        # Convert 8-byte string into 16-byte list
        if type(val) is str:
            val = list(map(lambda c: ord(c), val))

        slen = len(val)

        if self.pad:
            pad = b'\0\0' * (slen % 2)
        else:
            pad = b''

        return struct.pack(*('>' + 'H' * slen, ) + tuple(val)) + pad, slen, None

    def parse_binary_value(self, data, display, length, format):
        if length == 'odd':
            length = len(data) // 2 - 1
        elif length == 'even':
            length = len(data) // 2

        if self.pad:
            slen = length + (length % 2)
        else:
            slen = length

        return struct.unpack('>' + 'H' * length, data[:length * 2]), data[slen * 2:]



class List(ValueField):
    """The List, FixedList and Object fields store compound data objects.
    The type of data objects must be provided as an object with the
    following attributes and methods:

    ...

    """

    structcode = None

    def __init__(self, name, type, pad = 1):
        ValueField.__init__(self, name)
        self.type = type
        self.pad = pad

    def parse_binary_value(self, data, display, length, format):
        if length is None:
            ret = []
            if self.type.structcode is None:
                while data:
                    val, data = self.type.parse_binary(data, display)
                    ret.append(val)
            else:
                scode = '=' + self.type.structcode
                slen = struct.calcsize(scode)
                pos = 0
                while pos + slen <= len(data):
                    v = struct.unpack(scode, data[pos: pos + slen])

                    if self.type.structvalues == 1:
                        v = v[0]

                    if self.type.parse_value is None:
                        ret.append(v)
                    else:
                        ret.append(self.type.parse_value(v, display))

                    pos = pos + slen

                data = data[pos:]

        else:
            ret = [None] * int(length)

            if self.type.structcode is None:
                for i in range(0, length):
                    ret[i], data = self.type.parse_binary(data, display)
            else:
                scode = '=' + self.type.structcode
                slen = struct.calcsize(scode)
                pos = 0
                for i in range(0, length):
                    v = struct.unpack(scode, data[pos: pos + slen])

                    if self.type.structvalues == 1:
                        v = v[0]

                    if self.type.parse_value is None:
                        ret[i] = v
                    else:
                        ret[i] = self.type.parse_value(v, display)

                    pos = pos + slen

                data = data[pos:]

        if self.pad:
            data = data[len(data) % 4:]

        return ret, data

    def pack_value(self, val):
        # Single-char values, we'll assume that means integer lists.
        if self.type.structcode and len(self.type.structcode) == 1:
            data = array(struct_to_array_codes[self.type.structcode],
                               val).tostring()
        else:
            data = []
            for v in val:
                data.append(self.type.pack_value(v))

            data = b''.join(data)

        if self.pad:
            dlen = len(data)
            data = data + b'\0' * ((4 - dlen % 4) % 4)

        return data, len(val), None


class FixedList(List):
    def __init__(self, name, size, type, pad = 1):
        List.__init__(self, name, type, pad)
        self.size = size

    def parse_binary_value(self, data, display, length, format):
        return List.parse_binary_value(self, data, display, self.size, format)

    def pack_value(self, val):
        if len(val) != self.size:
            raise BadDataError('length mismatch for FixedList %s' % self.name)
        return List.pack_value(self, val)


class Object(ValueField):
    structcode = None

    def __init__(self, name, type, default = None):
        ValueField.__init__(self, name, default)
        self.type = type
        self.structcode = self.type.structcode
        self.structvalues = self.type.structvalues

    def parse_binary_value(self, data, display, length, format):
        if self.type.structcode is None:
            return self.type.parse_binary(data, display)

        else:
            scode = '=' + self.type.structcode
            slen = struct.calcsize(scode)

            v = struct.unpack(scode, data[:slen])
            if self.type.structvalues == 1:
                v = v[0]

            if self.type.parse_value is not None:
                v = self.type.parse_value(v, display)

            return v, data[slen:]

    def parse_value(self, val, display):
        if self.type.parse_value is None:
            return val
        else:
            return self.type.parse_value(val, display)

    def pack_value(self, val):
        # Single-char values, we'll assume that mean an integer
        if self.type.structcode and len(self.type.structcode) == 1:
            return struct.pack('=' + self.type.structcode, val), None, None
        else:
            return self.type.pack_value(val)

    def check_value(self, val):
        if self.type.structcode is None:
            return val

        if type(val) is tuple:
            return val

        if type(val) is dict:
            data = val
        elif isinstance(val, DictWrapper):
            data = val._data
        else:
            raise TypeError('Object value must be tuple, dictionary or DictWrapper: %s' % val)

        vals = []
        for f in self.type.fields:
            if f.name:
                vals.append(data[f.name])

        return vals


class PropertyData(ValueField):
    structcode = None

    def parse_binary_value(self, data, display, length, format):
        if length is None:
            length = len(data) // (format // 8)
        else:
            length = int(length)

        if format == 0:
            ret = None
            return ret, data

        elif format == 8:
            ret = (8, data[:length])
            data = data[length + ((4 - length % 4) % 4):]

        elif format == 16:
            ret = (16, array(array_unsigned_codes[2], data[:2 * length]))
            data = data[2 * (length + length % 2):]

        elif format == 32:
            ret = (32, array(array_unsigned_codes[4], data[:4 * length]))
            data = data[4 * length:]

        if type(ret[1]) is bytes:
            try:
                ret = (ret[0], ret[1].decode('UTF-8'))
            except UnicodeDecodeError:
                pass  # return as bytes

        return ret, data

    def pack_value(self, value):
        fmt, val = value

        if fmt not in (8, 16, 32):
            raise BadDataError('Invalid property data format %d' % fmt)

        if _PY3 and type(val) is str:
            val = val.encode('UTF-8')

        if type(val) is bytes:
            size = fmt // 8
            vlen = len(val)
            if vlen % size:
                vlen = vlen - vlen % size
                data = val[:vlen]
            else:
                data = val

            dlen = vlen // size

        else:
            if type(val) is tuple:
                val = list(val)

            size = fmt // 8
            data =  array(array_unsigned_codes[size], val).tostring()
            dlen = len(val)

        dl = len(data)
        data = data + b'\0' * ((4 - dl % 4) % 4)

        return data, dlen, fmt


class FixedPropertyData(PropertyData):
    def __init__(self, name, size):
        PropertyData.__init__(self, name)
        self.size = size

    def parse_binary_value(self, data, display, length, format):
        return PropertyData.parse_binary_value(self, data, display,
                                               self.size // (format // 8), format)

    def pack_value(self, value):
        data, dlen, fmt = PropertyData.pack_value(self, value)

        if len(data) != self.size:
            raise BadDataError('Wrong data length for FixedPropertyData: %s'
                               % (value, ))

        return data, dlen, fmt


class ValueList(Field):
    structcode = None
    keyword_args = 1
    default = 'usekeywords'

    def __init__(self, name, mask, pad, *fields):
        self.name = name
        self.maskcode = '=%s%dx' % (unsigned_codes[mask], pad)
        self.maskcodelen = struct.calcsize(self.maskcode)
        self.fields = []

        flag = 1
        for f in fields:
            if f.name:
                self.fields.append((f, flag))
                flag = flag << 1

    def pack_value(self, arg, keys):
        mask = 0
        data = b''

        if arg == self.default:
            arg = keys

        for field, flag in self.fields:
            if field.name in arg:
                mask = mask | flag

                val = arg[field.name]
                if field.check_value is not None:
                    val = field.check_value(val)

                d = struct.pack('=' + field.structcode, val)
                data = data + d + b'\0' * (4 - len(d))

        return struct.pack(self.maskcode, mask) + data, None, None

    def parse_binary_value(self, data, display, length, format):
        r = {}

        mask = int(struct.unpack(self.maskcode, data[:self.maskcodelen])[0])
        data = data[self.maskcodelen:]

        for field, flag in self.fields:
            if mask & flag:
                if field.structcode:
                    vals = struct.unpack('=' + field.structcode,
                                         data[:struct.calcsize('=' + field.structcode)])
                    if field.structvalues == 1:
                        vals = vals[0]

                    if field.parse_value is not None:
                        vals = field.parse_value(vals, display)

                else:
                    vals, d = field.parse_binary_value(data[:4], display, None, None)

                r[field.name] = vals
                data = data[4:]

        return DictWrapper(r), data


class KeyboardMapping(ValueField):
    structcode = None

    def parse_binary_value(self, data, display, length, format):
        if length is None:
            dlen = len(data)
        else:
            dlen = 4 * length * format

        a = array(array_unsigned_codes[4], data[:dlen])

        ret = []
        for i in range(0, len(a), format):
            ret.append(a[i : i + format])

        return ret, data[dlen:]

    def pack_value(self, value):
        keycodes = 0
        for v in value:
            keycodes = max(keycodes, len(v))

        a = array(array_unsigned_codes[4])

        for v in value:
            for k in v:
                a.append(k)
            for i in range(len(v), keycodes):
                a.append(X.NoSymbol)

        return a.tostring(), len(value), keycodes


class ModifierMapping(ValueField):
    structcode = None

    def parse_binary_value(self, data, display, length, format):
        a = array(array_unsigned_codes[1], data[:8 * format])

        ret = []
        for i in range(0, 8):
            ret.append(a[i * format : (i + 1) * format])

        return ret, data[8 * format:]

    def pack_value(self, value):
        if len(value) != 8:
            raise BadDataError('ModifierMapping list should have eight elements')

        keycodes = 0
        for v in value:
            keycodes = max(keycodes, len(v))

        a = array(array_unsigned_codes[1])

        for v in value:
            for k in v:
                a.append(k)
            for i in range(len(v), keycodes):
                a.append(0)

        return a.tostring(), len(value), keycodes

class EventField(ValueField):
    structcode = None

    def pack_value(self, value):
        if not isinstance(value, Event):
            raise BadDataError('%s is not an Event for field %s' % (value, self.name))

        return value._binary, None, None

    def parse_binary_value(self, data, display, length, format):
        from Xlib.protocol import event

        estruct = display.event_classes.get(_bytes_item(data[0]) & 0x7f, event.AnyEvent)

        return estruct(display = display, binarydata = data[:32]), data[32:]


#
# Objects usable for List and FixedList fields.
# Struct is also usable.
#

class ScalarObj:
    def __init__(self, code):
        self.structcode = code
        self.structvalues = 1
        self.parse_value = None

Card8Obj  = ScalarObj('B')
Card16Obj = ScalarObj('H')
Card32Obj = ScalarObj('L')

class ResourceObj:
    structcode = 'L'
    structvalues = 1

    def __init__(self, class_name):
        self.class_name = class_name

    def parse_value(self, value, display):
        # if not display:
        #     return value
        c = display.get_resource_class(self.class_name)
        if c:
            return c(display, value)
        else:
            return value

WindowObj = ResourceObj('window')
ColormapObj = ResourceObj('colormap')

class StrClass:
    structcode = None

    def pack_value(self, val):
        if type(val) is not bytes:
            val = val.encode('UTF-8')
        if _PY3:
            val = bytes([len(val)]) + val
        else:
            val = chr(len(val)) + val
        return val

    def parse_binary(self, data, display):
        slen = _bytes_item(data[0]) + 1
        s = data[1:slen]
        try:
            s = s.decode('UTF-8')
        except UnicodeDecodeError:
            pass  # return as bytes
        return s, data[slen:]

Str = StrClass()


class Struct:

    """Struct objects represents a binary data structure.  It can
    contain both fields with static and dynamic sizes.  However, all
    static fields must appear before all dynamic fields.

    Fields are represented by various subclasses of the abstract base
    class Field.  The fields of a structure are given as arguments
    when instantiating a Struct object.

    Struct objects have two public methods:

      to_binary()    -- build a binary representation of the structure
                        with the values given as arguments
      parse_binary() -- convert a binary (string) representation into
                        a Python dictionary or object.

    These functions will be generated dynamically for each Struct
    object to make conversion as fast as possible.  They are
    generated the first time the methods are called.

    """

    def __init__(self, *fields):
        self.fields = fields

        # Structures for to_binary, parse_value and parse_binary
        self.static_codes = '='
        self.static_values = 0
        self.static_fields = []
        self.static_size = None
        self.var_fields = []

        for f in self.fields:
            # Append structcode if there is one and we haven't
            # got any varsize fields yet.
            if f.structcode is not None:
                assert not self.var_fields

                self.static_codes = self.static_codes + f.structcode

                # Only store fields with values
                if f.structvalues > 0:
                    self.static_fields.append(f)
                    self.static_values = self.static_values + f.structvalues

            # If we have got one varsize field, all the rest must
            # also be varsize fields.
            else:
                self.var_fields.append(f)

        self.static_size = struct.calcsize(self.static_codes)
        if self.var_fields:
            self.structcode = None
            self.structvalues = 0
        else:
            self.structcode = self.static_codes[1:]
            self.structvalues = self.static_values


    # These functions get called only once, as they will override
    # themselves with dynamically created functions in the Struct
    # object

    def to_binary(self, *varargs, **keys):

        """data = s.to_binary(...)

        Convert Python values into the binary representation.  The
        arguments will be all value fields with names, in the order
        given when the Struct object was instantiated.  With one
        exception: fields with default arguments will be last.

        Returns the binary representation as the string DATA.

        """

        code = ''
        total_length = str(self.static_size)
        joins = []
        args = []
        defargs = []
        kwarg = 0

        # First pack all varfields so their lengths and formats are
        # available when we pack their static LengthFields and
        # FormatFields

        i = 0
        for f in self.var_fields:
            if f.keyword_args:
                kwarg = 1
                kw = ', _keyword_args'
            else:
                kw = ''

            # Call pack_value method for each field, storing
            # the return values for later use
            code = code + ('  _%(name)s, _%(name)s_length, _%(name)s_format'
                           ' = self.var_fields[%(fno)d].pack_value(%(name)s%(kw)s)\n'
                           % { 'name': f.name,
                               'fno': i,
                               'kw': kw })

            total_length = total_length + ' + len(_%s)' % f.name
            joins.append('_%s' % f.name)

            i = i + 1


        # Construct argument list for struct.pack call, packing all
        # static fields.  First argument is the structcode, the
        # remaining are values.


        pack_args = ['"%s"' % self.static_codes]

        i = 0
        for f in self.static_fields:
            if isinstance(f, LengthField):

                # If this is a total length field, insert
                # the calculated field value here
                if isinstance(f, TotalLengthField):
                    if self.var_fields:
                        pack_args.append('self.static_fields[%d].calc_length(%s)'
                                         % (i, total_length))
                    else:
                        pack_args.append(str(f.calc_length(self.static_size)))
                else:
                    pack_args.append('self.static_fields[%d].calc_length(_%s_length)'
                                       % (i, f.name))

            # Format field, just insert the value we got previously
            elif isinstance(f, FormatField):
                pack_args.append('_%s_format' % f.name)

            # A constant field, insert its value directly
            elif isinstance(f, ConstantField):
                pack_args.append(str(f.value))

            # Value fields
            else:
                if f.structvalues == 1:

                    # If there's a value check/convert function, call it
                    if f.check_value is not None:
                        pack_args.append('self.static_fields[%d].check_value(%s)'
                                           % (i, f.name))

                    # Else just use the argument as provided
                    else:
                        pack_args.append(f.name)

                # Multivalue field.  Handled like single valuefield,
                # but the value are tuple unpacked into seperate arguments
                # which are appended to pack_args
                else:
                    a = []
                    for j in range(f.structvalues):
                        a.append('_%s_%d' % (f.name, j))

                    if f.check_value is not None:
                        code = code + ('  %s = self.static_fields[%d].check_value(%s)\n'
                                       % (', '.join(a), i, f.name))
                    else:
                        code = code + '  %s = %s\n' % (', '.join(a), f.name)

                    pack_args = pack_args + a

                # Add field to argument list
                if f.name:
                    if f.default is None:
                        args.append(f.name)
                    else:
                        defargs.append('%s = %s' % (f.name, repr(f.default)))

            i = i + 1

        # Construct call to struct.pack
        pack = 'struct.pack(%s)' % ', '.join(pack_args)

        # If there are any varfields, we append the packed strings to build
        # the resulting binary value
        if self.var_fields:
            code = code + '  return %s + %s\n' % (pack, ' + '.join(joins))

        # If there's only static fields, return the packed value
        else:
            code = code + '  return %s\n' % pack

        # Add all varsize fields to argument list.  We do it here
        # to ensure that they appear after the static fields.
        for f in self.var_fields:
            if f.name:
                if f.default is None:
                    args.append(f.name)
                else:
                    defargs.append('%s = %s' % (f.name, repr(f.default)))

        args = args + defargs
        if kwarg:
            args.append('**_keyword_args')

        # Add function header
        code = 'def to_binary(self, %s):\n' % ', '.join(args) + code

        # self._pack_code = code

        # print
        # print code
        # print

        # Finally, compile function by evaluating it.  This will store
        # the function in the local variable to_binary, thanks to the
        # def: line.  Convert it into a instance metod bound to self,
        # and store it in self.

        # Unfortunately, this creates a circular reference.  However,
        # Structs are not really created dynamically so the potential
        # memory leak isn't that serious.  Besides, Python 2.0 has
        # real garbage collect.

        g = globals().copy()
        exec(code, g)
        self.to_binary = types.MethodType(g['to_binary'], self)

        # Finally call it manually
        return self.to_binary(*varargs, **keys)


    def pack_value(self, value):

        """ This function allows Struct objects to be used in List and
        Object fields.  Each item represents the arguments to pass to
        to_binary, either a tuple, a dictionary or a DictWrapper.

        """

        if type(value) is tuple:
            return self.to_binary(*value, **{})
        elif type(value) is dict:
            return self.to_binary(*(), **value)
        elif isinstance(value, DictWrapper):
            return self.to_binary(*(), **value._data)
        else:
            raise BadDataError('%s is not a tuple or a list' % (value))


    def parse_value(self, val, display, rawdict = 0):

        """This function is used by List and Object fields to convert
        Struct objects with no var_fields into Python values.

        """

        code = ('def parse_value(self, val, display, rawdict = 0):\n'
                '  ret = {}\n')

        vno = 0
        fno = 0
        for f in self.static_fields:
            # Fields without names should be ignored, and there should
            # not be any length or format fields if this function
            # ever gets called.  (If there were such fields, there should
            # be a matching field in var_fields and then parse_binary
            # would have been called instead.

            if not f.name:
                pass

            elif isinstance(f, LengthField):
                pass

            elif isinstance(f, FormatField):
                pass

            # Value fields
            else:

                # Get the index or range in val representing this field.

                if f.structvalues == 1:
                    vrange = str(vno)
                else:
                    vrange = '%d:%d' % (vno, vno + f.structvalues)

                # If this field has a parse_value method, call it, otherwise
                # use the unpacked value as is.

                if f.parse_value is None:
                    code = code + '  ret["%s"] = val[%s]\n' % (f.name, vrange)
                else:
                    code = code + ('  ret["%s"] = self.static_fields[%d].'
                                   'parse_value(val[%s], display)\n'
                                   % (f.name, fno, vrange))

            fno = fno + 1
            vno = vno + f.structvalues

        code = code + '  if not rawdict: return DictWrapper(ret)\n'
        code = code + '  return ret\n'

        # print
        # print code
        # print

        # Finally, compile function as for to_binary.

        g = globals().copy()
        exec(code, g)
        self.parse_value = types.MethodType(g['parse_value'], self)

        # Call it manually
        return self.parse_value(val, display, rawdict)


    def parse_binary(self, data, display, rawdict = 0):

        """values, remdata = s.parse_binary(data, display, rawdict = 0)

        Convert a binary representation of the structure into Python values.

        DATA is a string or a buffer containing the binary data.
        DISPLAY should be a Xlib.protocol.display.Display object if
        there are any Resource fields or Lists with ResourceObjs.

        The Python values are returned as VALUES.  If RAWDICT is true,
        a Python dictionary is returned, where the keys are field
        names and the values are the corresponding Python value.  If
        RAWDICT is false, a DictWrapper will be returned where all
        fields are available as attributes.

        REMDATA are the remaining binary data, unused by the Struct object.

        """

        code = ('def parse_binary(self, data, display, rawdict = 0):\n'
                '  ret = {}\n'
                '  val = struct.unpack("%s", data[:%d])\n'
                % (self.static_codes, self.static_size))

        lengths = {}
        formats = {}

        vno = 0
        fno = 0
        for f in self.static_fields:

            # Fields without name should be ignored.  This is typically
            # pad and constant fields

            if not f.name:
                pass

            # Store index in val for Length and Format fields, to be used
            # when treating varfields.

            elif isinstance(f, LengthField):
                if f.parse_value is None:
                    lengths[f.name] = 'val[%d]' % vno
                else:
                    lengths[f.name] = ('self.static_fields[%d].'
                                       'parse_value(val[%d], display)'
                                       % (fno, vno))

            elif isinstance(f, FormatField):
                formats[f.name] = 'val[%d]' % vno

            # Treat value fields the same was as in parse_value.
            else:
                if f.structvalues == 1:
                    vrange = str(vno)
                else:
                    vrange = '%d:%d' % (vno, vno + f.structvalues)

                if f.parse_value is None:
                    code = code + '  ret["%s"] = val[%s]\n' % (f.name, vrange)
                else:
                    code = code + ('  ret["%s"] = self.static_fields[%d].'
                                   'parse_value(val[%s], display)\n'
                                   % (f.name, fno, vrange))

            fno = fno + 1
            vno = vno + f.structvalues

        code = code + '  data = data[%d:]\n' % self.static_size

        # Call parse_binary_value for each var_field, passing the
        # length and format values from the unpacked val.

        fno = 0
        for f in self.var_fields:
            code = code + ('  ret["%s"], data = '
                           'self.var_fields[%d].parse_binary_value'
                           '(data, display, %s, %s)\n'
                           % (f.name, fno,
                              lengths.get(f.name, 'None'),
                              formats.get(f.name, 'None')))
            fno = fno + 1

        code = code + '  if not rawdict: ret = DictWrapper(ret)\n'
        code = code + '  return ret, data\n'

        # print
        # print code
        # print

        # Finally, compile function as for to_binary.

        g = globals().copy()
        exec(code, g)
        self.parse_binary = types.MethodType(g['parse_binary'], self)

        # Call it manually
        return self.parse_binary(data, display, rawdict)


class TextElements8(ValueField):
    string_textitem = Struct( LengthOf('string', 1),
                              Int8('delta'),
                              String8('string', pad = 0) )

    def pack_value(self, value):
        data = b''
        args = {}

        for v in value:
            # Let values be simple strings, meaning a delta of 0
            if _PY3 and type(v) is str:
                v = v.encode('UTF-8')

            if type(v) is bytes:
                v = (0, v)

            # A tuple, it should be (delta, string)
            # Encode it as one or more textitems

            if type(v) in (tuple, dict) or \
               isinstance(v, DictWrapper):

                if type(v) is tuple:
                    delta, s = v
                else:
                    delta = v['delta']
                    s = v['string']

                while delta or s:
                    args['delta'] = delta
                    args['string'] = s[:254]

                    data = data + self.string_textitem.to_binary(*(), **args)

                    delta = 0
                    s = s[254:]

            # Else an integer, i.e. a font change
            else:
                # Use fontable cast function if instance
                if hasattr(v, '__fontable__'):
                    v = v.__fontable__()

                data = data + struct.pack('>BL', 255, v)

        # Pad out to four byte length
        dlen = len(data)
        return data + b'\0' * ((4 - dlen % 4) % 4), None, None

    def parse_binary_value(self, data, display, length, format):
        values = []
        while 1:
            if len(data) < 2:
                break

            # font change
            if _bytes_item(data[0]) == 255:
                values.append(struct.unpack('>L', data[1:5])[0])
                data = data[5:]

            # skip null strings
            elif _bytes_item(data[0]) == 0 and _bytes_item(data[1]) == 0:
                data = data[2:]

            # string with delta
            else:
                v, data = self.string_textitem.parse_binary(data, display)
                values.append(v)

        return values, b''



class TextElements16(TextElements8):
    string_textitem = Struct( LengthOf('string', 1),
                              Int8('delta'),
                              String16('string', pad = 0) )



class GetAttrData(object):
    def __getattr__(self, attr):
        try:
            if self._data:
                return self._data[attr]
            else:
                raise AttributeError(attr)
        except KeyError:
            raise AttributeError(attr)

class DictWrapper(GetAttrData):
    def __init__(self, dict):
        self.__dict__['_data'] = dict

    def __getitem__(self, key):
        return self._data[key]

    def __setitem__(self, key, value):
        self._data[key] = value

    def __delitem__(self, key):
        del self._data[key]

    def __setattr__(self, key, value):
        self._data[key] = value

    def __delattr__(self, key):
        del self._data[key]

    def __str__(self):
        return str(self._data)

    def __repr__(self):
        return '%s(%s)' % (self.__class__, repr(self._data))

    def __eq__(self, other):
        if isinstance(other, DictWrapper):
            return self._data == other._data
        else:
            return self._data == other

    def __ne__(self, other):
        return not self.__eq__(other)

class Request:
    def __init__(self, display, onerror = None, *args, **keys):
        self._errorhandler = onerror
        self._binary = self._request.to_binary(*args, **keys)
        self._serial = None
        display.send_request(self, onerror is not None)

    def _set_error(self, error):
        if self._errorhandler is not None:
            return call_error_handler(self._errorhandler, error, self)
        else:
            return 0

class ReplyRequest(GetAttrData):
    def __init__(self, display, defer = 0, *args, **keys):
        self._display = display
        self._binary = self._request.to_binary(*args, **keys)
        self._serial = None
        self._data = None
        self._error = None

        self._response_lock = lock.allocate_lock()

        self._display.send_request(self, 1)
        if not defer:
            self.reply()

    def reply(self):
        # Send request and wait for reply if we hasn't
        # already got one.  This means that reply() can safely
        # be called more than one time.

        self._response_lock.acquire()
        while self._data is None and self._error is None:
            self._display.send_recv_lock.acquire()
            self._response_lock.release()

            self._display.send_and_recv(request = self._serial)
            self._response_lock.acquire()

        self._response_lock.release()
        self._display = None

        # If error has been set, raise it
        if self._error:
            raise self._error

    def _parse_response(self, data):
        self._response_lock.acquire()
        self._data, d = self._reply.parse_binary(data, self._display, rawdict = 1)
        self._response_lock.release()

    def _set_error(self, error):
        self._response_lock.acquire()
        self._error = error
        self._response_lock.release()
        return 1

    def __repr__(self):
        return '<%s serial = %s, data = %s, error = %s>' % (self.__class__, self._serial, self._data, self._error)


class Event(GetAttrData):
    def __init__(self, binarydata = None, display = None,
                 **keys):
        if binarydata:
            self._binary = binarydata
            self._data, data = self._fields.parse_binary(binarydata, display,
                                                         rawdict = 1)
            # split event type into type and send_event bit
            self._data['send_event'] = not not self._data['type'] & 0x80
            self._data['type'] = self._data['type'] & 0x7f
        else:
            if self._code:
                keys['type'] = self._code

            keys['sequence_number'] = 0

            self._binary = self._fields.to_binary(*(), **keys)

            keys['send_event'] = 0
            self._data = keys

    def __repr__(self):
        kwlist = []
        for kw, val in self._data.items():
            if kw == 'send_event':
                continue
            if kw == 'type' and self._data['send_event']:
                val = val | 0x80
            kwlist.append('%s = %s' % (kw, repr(val)))

        kws = ', '.join(kwlist)
        return '%s(%s)' % (self.__class__, kws)

    def __eq__(self, other):
        if isinstance(other, Event):
            return self._data == other._data
        else:
            return cmp(self._data, other)

def call_error_handler(handler, error, request):
    try:
        return handler(error, request)
    except:
        sys.stderr.write('Exception raised by error handler.\n')
        traceback.print_exc()
        return 0