File: XExtInt.c

package info (click to toggle)
libxi 2:1.3-8
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 2,476 kB
  • ctags: 906
  • sloc: sh: 10,500; ansic: 6,600; makefile: 454
file content (1732 lines) | stat: -rw-r--r-- 57,865 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
/************************************************************

Copyright 1989, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.

Copyright 1989 by Hewlett-Packard Company, Palo Alto, California.

			All Rights Reserved

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Hewlett-Packard not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.

HEWLETT-PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
HEWLETT-PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

********************************************************/

/***********************************************************************
 *
 * Input Extension library internal functions.
 *
 */

#define NEED_EVENTS
#define NEED_REPLIES
#include <stdio.h>
#include <stdint.h>
#include <X11/extensions/XI.h>
#include <X11/extensions/XI2.h>
#include <X11/extensions/XIproto.h>
#include <X11/extensions/XI2proto.h>
#include <X11/Xlibint.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <X11/extensions/extutil.h>
#include <X11/extensions/geproto.h>
#include <X11/extensions/ge.h>
#include <X11/extensions/Xge.h>
#include "XIint.h"

#define ENQUEUE_EVENT	True
#define DONT_ENQUEUE	False
#define FP1616toDBL(x) ((x) * 1.0 / (1 << 16))

extern void _xibaddevice(
    Display *		/* dpy */,
    int *		/* error */
);

extern void _xibadclass(
    Display *		/* dpy */,
    int *		/* error */
);

extern void _xibadevent(
    Display *		/* dpy */,
    int *		/* error */
);

extern void _xibadmode(
    Display *		/* dpy */,
    int *		/* error */
);

extern void _xidevicebusy(
    Display *		/* dpy */,
    int *		/* error */
);

extern int _XiGetDevicePresenceNotifyEvent(
    Display *		/* dpy */
);

int copy_classes(XIDeviceInfo *to, xXIAnyInfo* from, int *nclasses);
int size_classes(xXIAnyInfo* from, int nclasses);

static XExtensionInfo *xinput_info;
static /* const */ char *xinput_extension_name = INAME;

static int XInputClose(
    Display *		/* dpy */,
    XExtCodes *		/* codes */
);

static char *XInputError(
    Display *		/* dpy */,
    int			/* code */,
    XExtCodes *		/* codes */,
    char *		/* buf */,
    int			/* n */
);

static Bool XInputWireToEvent(
    Display *		/* dpy */,
    XEvent *		/* re */,
    xEvent *		/* event */
);
static Bool XInputWireToCookie(
    Display*	        /* display */,
    XGenericEventCookie*	/* re */,
    xEvent*	        /* event */
);

static Bool XInputCopyCookie(
    Display*	        /* display */,
    XGenericEventCookie*	/* in */,
    XGenericEventCookie*	/* out */
);

static int
wireToDeviceEvent(xXIDeviceEvent *in, XGenericEventCookie* out);
static int
wireToDeviceChangedEvent(xXIDeviceChangedEvent *in, XGenericEventCookie *cookie);
static int
wireToHierarchyChangedEvent(xXIHierarchyEvent *in, XGenericEventCookie *cookie);
static int
wireToRawEvent(xXIRawEvent *in, XGenericEventCookie *cookie);
static int
wireToEnterLeave(xXIEnterEvent *in, XGenericEventCookie *cookie);
static int
wireToPropertyEvent(xXIPropertyEvent *in, XGenericEventCookie *cookie);

static /* const */ XEvent emptyevent;

static /* const */ XExtensionHooks xinput_extension_hooks = {
    NULL,	/* create_gc */
    NULL,	/* copy_gc */
    NULL,	/* flush_gc */
    NULL,	/* free_gc */
    NULL,	/* create_font */
    NULL,	/* free_font */
    XInputClose,	/* close_display */
    XInputWireToEvent,	/* wire_to_event */
    _XiEventToWire,	/* event_to_wire */
    NULL,	/* error */
    XInputError,	/* error_string */
};

static char *XInputErrorList[] = {
    "BadDevice, invalid or uninitialized input device",	/* BadDevice */
    "BadEvent, invalid event type",	/* BadEvent */
    "BadMode, invalid mode parameter",	/* BadMode  */
    "DeviceBusy, device is busy",	/* DeviceBusy */
    "BadClass, invalid event class",	/* BadClass */
};

/* Get the version supported by the server to know which number of
* events are support. Otherwise, a wrong number of events may smash
* the Xlib-internal event processing vector.
*
* Since the extension hasn't been initialized yet, we need to
* manually get the opcode, then the version.
*/
static int
_XiFindEventsSupported(Display *dpy)
{
    XExtCodes codes;
    XExtensionVersion *extversion = NULL;
    int nevents = 0;

    if (!XQueryExtension(dpy, INAME, &codes.major_opcode,
                         &codes.first_event, &codes.first_error))
        goto out;

    LockDisplay(dpy);
    extversion = _XiGetExtensionVersionRequest(dpy, INAME, codes.major_opcode);
    UnlockDisplay(dpy);
    SyncHandle();

    if (!extversion || !extversion->present)
        goto out;

    if (extversion->major_version >= 2)
        nevents = IEVENTS; /* number is fixed, XI2 adds GenericEvents only */
    else if (extversion->major_version <= 0)
    {
        printf("XInput_find_display: invalid extension version %d.%d\n",
                extversion->major_version, extversion->minor_version);
        goto out;
    }
    else
    {
        switch(extversion->minor_version)
        {
            case XI_Add_DeviceProperties_Minor:
                nevents = XI_DevicePropertyNotify + 1;
                break;
            case  XI_Add_DevicePresenceNotify_Minor:
                nevents = XI_DevicePresenceNotify + 1;
                break;
            default:
                nevents = XI_DeviceButtonstateNotify + 1;
                break;
        }
    }

out:
    if (extversion)
        XFree(extversion);
    return nevents;
}


_X_HIDDEN
XExtDisplayInfo *XInput_find_display (Display *dpy)
{
    XExtDisplayInfo *dpyinfo;
    if (!xinput_info) { if (!(xinput_info = XextCreateExtension())) return NULL; }
    if (!(dpyinfo = XextFindDisplay (xinput_info, dpy)))
    {
      int nevents = _XiFindEventsSupported(dpy);

      dpyinfo = XextAddDisplay (xinput_info, dpy,
                                xinput_extension_name,
                                &xinput_extension_hooks,
                                nevents, NULL);
      if (dpyinfo->codes) /* NULL if XI doesn't exist on the server */
      {
          XESetWireToEventCookie(dpy, dpyinfo->codes->major_opcode, XInputWireToCookie);
          XESetCopyEventCookie(dpy, dpyinfo->codes->major_opcode, XInputCopyCookie);
      }
    }
    return dpyinfo;
}

static XEXT_GENERATE_ERROR_STRING(XInputError, xinput_extension_name,
                                  IERRORS, XInputErrorList)
/*******************************************************************
*
* Input extension versions.
*
*/
static XExtensionVersion versions[] = { {XI_Absent, 0, 0},
{XI_Present, XI_Initial_Release_Major, XI_Initial_Release_Minor},
{XI_Present, XI_Add_XDeviceBell_Major, XI_Add_XDeviceBell_Minor},
{XI_Present, XI_Add_XSetDeviceValuators_Major,
 XI_Add_XSetDeviceValuators_Minor},
{XI_Present, XI_Add_XChangeDeviceControl_Major,
 XI_Add_XChangeDeviceControl_Minor},
{XI_Present, XI_Add_DevicePresenceNotify_Major,
 XI_Add_DevicePresenceNotify_Minor},
{XI_Present, XI_Add_DeviceProperties_Major,
 XI_Add_DeviceProperties_Minor},
{XI_Present, XI_2_Major, XI_2_Minor}
};

/***********************************************************************
 *
 * Return errors reported by this extension.
 *
 */

void
_xibaddevice(
    Display	*dpy,
    int		*error)
{
    XExtDisplayInfo *info = XInput_find_display(dpy);

    *error = info->codes->first_error + XI_BadDevice;
}

void
_xibadclass(
    Display	*dpy,
    int		*error)
{
    XExtDisplayInfo *info = XInput_find_display(dpy);

    *error = info->codes->first_error + XI_BadClass;
}

void
_xibadevent(
    Display	*dpy,
    int		*error)
{
    XExtDisplayInfo *info = XInput_find_display(dpy);

    *error = info->codes->first_error + XI_BadEvent;
}

void
_xibadmode(
    Display	*dpy,
    int		*error)
{
    XExtDisplayInfo *info = XInput_find_display(dpy);

    *error = info->codes->first_error + XI_BadMode;
}

void
_xidevicebusy(
    Display	*dpy,
    int		*error)
{
    XExtDisplayInfo *info = XInput_find_display(dpy);

    *error = info->codes->first_error + XI_DeviceBusy;
}

static int XInputCheckExtension(Display *dpy, XExtDisplayInfo *info)
{
    XextCheckExtension (dpy, info, xinput_extension_name, 0);
    return 1;
}

/***********************************************************************
 *
 * Check to see if the input extension is installed in the server.
 * Also check to see if the version is >= the requested version.
 *
 */

_X_HIDDEN int
_XiCheckExtInit(
    register Display	*dpy,
    register int	 version_index,
    XExtDisplayInfo	*info)
{
    XExtensionVersion *ext;

    if (!XInputCheckExtension(dpy, info)) {
	UnlockDisplay(dpy);
	return (-1);
    }

    if (info->data == NULL) {
	info->data = (XPointer) Xmalloc(sizeof(XInputData));
	if (!info->data) {
	    UnlockDisplay(dpy);
	    return (-1);
	}
	((XInputData *) info->data)->vers =
	    _XiGetExtensionVersion(dpy, "XInputExtension", info);
    }

    if (versions[version_index].major_version > Dont_Check) {
	ext = ((XInputData *) info->data)->vers;
	if ((ext->major_version < versions[version_index].major_version) ||
	    ((ext->major_version == versions[version_index].major_version) &&
	     (ext->minor_version < versions[version_index].minor_version))) {
	    UnlockDisplay(dpy);
	    return (-1);
	}
    }
    return (0);
}

/***********************************************************************
 *
 * Close display routine.
 *
 */

static int
XInputClose(
    Display	*dpy,
    XExtCodes	*codes)
{
    XExtDisplayInfo *info = XInput_find_display(dpy);

    if (info->data != NULL) {
	XFree((char *)((XInputData *) info->data)->vers);
	XFree((char *)info->data);
    }
    return XextRemoveDisplay(xinput_info, dpy);
}

static int
Ones(Mask mask)
{
    register Mask y;

    y = (mask >> 1) & 033333333333;
    y = mask - y - ((y >> 1) & 033333333333);
    return (((y + (y >> 3)) & 030707070707) % 077);
}

static int count_bits(unsigned char* ptr, int len)
{
    int bits = 0;
    unsigned int i;
    unsigned char x;

    for (i = 0; i < len; i++)
    {
        x = ptr[i];
        while(x > 0)
        {
            bits += (x & 0x1);
            x >>= 1;
        }
    }
    return bits;
}

int
_XiGetDevicePresenceNotifyEvent(Display * dpy)
{
    XExtDisplayInfo *info = XInput_find_display(dpy);

    return info->codes->first_event + XI_DevicePresenceNotify;
}

/***********************************************************************
 *
 * Handle Input extension events.
 * Reformat a wire event into an XEvent structure of the right type.
 *
 */

static Bool
XInputWireToEvent(
    Display	*dpy,
    XEvent	*re,
    xEvent	*event)
{
    unsigned int type, reltype;
    unsigned int i, j;
    XExtDisplayInfo *info = XInput_find_display(dpy);
    XEvent *save = (XEvent *) info->data;

    type = event->u.u.type & 0x7f;
    reltype = (type - info->codes->first_event);

    if (type == GenericEvent || 
        (reltype != XI_DeviceValuator &&
	reltype != XI_DeviceKeystateNotify &&
	reltype != XI_DeviceButtonstateNotify)) {
	*save = emptyevent;
	save->type = type;
	((XAnyEvent *) save)->serial = _XSetLastRequestRead(dpy,
							    (xGenericReply *)
							    event);
	((XAnyEvent *) save)->send_event = ((event->u.u.type & 0x80) != 0);
	((XAnyEvent *) save)->display = dpy;
    }

    /* Process traditional events */
    if (type != GenericEvent)
    {
        switch (reltype) {
            case XI_DeviceMotionNotify:
                {
                    register XDeviceMotionEvent *ev = (XDeviceMotionEvent *) save;
                    deviceKeyButtonPointer *ev2 = (deviceKeyButtonPointer *) event;

                    ev->root = ev2->root;
                    ev->window = ev2->event;
                    ev->subwindow = ev2->child;
                    ev->time = ev2->time;
                    ev->x_root = ev2->root_x;
                    ev->y_root = ev2->root_y;
                    ev->x = ev2->event_x;
                    ev->y = ev2->event_y;
                    ev->state = ev2->state;
                    ev->same_screen = ev2->same_screen;
                    ev->is_hint = ev2->detail;
                    ev->deviceid = ev2->deviceid & DEVICE_BITS;
                    return (DONT_ENQUEUE);
                }
                break;
            case XI_DeviceKeyPress:
            case XI_DeviceKeyRelease:
                {
                    register XDeviceKeyEvent *ev = (XDeviceKeyEvent *) save;
                    deviceKeyButtonPointer *ev2 = (deviceKeyButtonPointer *) event;

                    ev->root = ev2->root;
                    ev->window = ev2->event;
                    ev->subwindow = ev2->child;
                    ev->time = ev2->time;
                    ev->x_root = ev2->root_x;
                    ev->y_root = ev2->root_y;
                    ev->x = ev2->event_x;
                    ev->y = ev2->event_y;
                    ev->state = ev2->state;
                    ev->same_screen = ev2->same_screen;
                    ev->keycode = ev2->detail;
                    ev->deviceid = ev2->deviceid & DEVICE_BITS;
                    if (ev2->deviceid & MORE_EVENTS)
                        return (DONT_ENQUEUE);
                    else {
                        *re = *save;
                        return (ENQUEUE_EVENT);
                    }
                }
                break;
            case XI_DeviceButtonPress:
            case XI_DeviceButtonRelease:
                {
                    register XDeviceButtonEvent *ev = (XDeviceButtonEvent *) save;
                    deviceKeyButtonPointer *ev2 = (deviceKeyButtonPointer *) event;

                    ev->root = ev2->root;
                    ev->window = ev2->event;
                    ev->subwindow = ev2->child;
                    ev->time = ev2->time;
                    ev->x_root = ev2->root_x;
                    ev->y_root = ev2->root_y;
                    ev->x = ev2->event_x;
                    ev->y = ev2->event_y;
                    ev->state = ev2->state;
                    ev->same_screen = ev2->same_screen;
                    ev->button = ev2->detail;
                    ev->deviceid = ev2->deviceid & DEVICE_BITS;
                    if (ev2->deviceid & MORE_EVENTS)
                        return (DONT_ENQUEUE);
                    else {
                        *re = *save;
                        return (ENQUEUE_EVENT);
                    }
                }
                break;
            case XI_ProximityIn:
            case XI_ProximityOut:
                {
                    register XProximityNotifyEvent *ev = (XProximityNotifyEvent *) save;
                    deviceKeyButtonPointer *ev2 = (deviceKeyButtonPointer *) event;

                    ev->root = ev2->root;
                    ev->window = ev2->event;
                    ev->subwindow = ev2->child;
                    ev->time = ev2->time;
                    ev->x_root = ev2->root_x;
                    ev->y_root = ev2->root_y;
                    ev->x = ev2->event_x;
                    ev->y = ev2->event_y;
                    ev->state = ev2->state;
                    ev->same_screen = ev2->same_screen;
                    ev->deviceid = ev2->deviceid & DEVICE_BITS;
                    if (ev2->deviceid & MORE_EVENTS)
                        return (DONT_ENQUEUE);
                    else {
                        *re = *save;
                        return (ENQUEUE_EVENT);
                    }
                }
                break;
            case XI_DeviceValuator:
                {
                    deviceValuator *xev = (deviceValuator *) event;
                    int save_type = save->type - info->codes->first_event;

                    if (save_type == XI_DeviceKeyPress || save_type == XI_DeviceKeyRelease) {
                        XDeviceKeyEvent *kev = (XDeviceKeyEvent *) save;

                        kev->device_state = xev->device_state;
                        kev->axes_count = xev->num_valuators;
                        kev->first_axis = xev->first_valuator;
                        i = xev->num_valuators;
                        if (i > 6)
                            i = 6;
                        switch (i) {
                            case 6:
                                kev->axis_data[5] = xev->valuator5;
                            case 5:
                                kev->axis_data[4] = xev->valuator4;
                            case 4:
                                kev->axis_data[3] = xev->valuator3;
                            case 3:
                                kev->axis_data[2] = xev->valuator2;
                            case 2:
                                kev->axis_data[1] = xev->valuator1;
                            case 1:
                                kev->axis_data[0] = xev->valuator0;
                        }
                    } else if (save_type == XI_DeviceButtonPress ||
                            save_type == XI_DeviceButtonRelease) {
                        XDeviceButtonEvent *bev = (XDeviceButtonEvent *) save;

                        bev->device_state = xev->device_state;
                        bev->axes_count = xev->num_valuators;
                        bev->first_axis = xev->first_valuator;
                        i = xev->num_valuators;
                        if (i > 6)
                            i = 6;
                        switch (i) {
                            case 6:
                                bev->axis_data[5] = xev->valuator5;
                            case 5:
                                bev->axis_data[4] = xev->valuator4;
                            case 4:
                                bev->axis_data[3] = xev->valuator3;
                            case 3:
                                bev->axis_data[2] = xev->valuator2;
                            case 2:
                                bev->axis_data[1] = xev->valuator1;
                            case 1:
                                bev->axis_data[0] = xev->valuator0;
                        }
                    } else if (save_type == XI_DeviceMotionNotify) {
                        XDeviceMotionEvent *mev = (XDeviceMotionEvent *) save;

                        mev->device_state = xev->device_state;
                        mev->axes_count = xev->num_valuators;
                        mev->first_axis = xev->first_valuator;
                        i = xev->num_valuators;
                        if (i > 6)
                            i = 6;
                        switch (i) {
                            case 6:
                                mev->axis_data[5] = xev->valuator5;
                            case 5:
                                mev->axis_data[4] = xev->valuator4;
                            case 4:
                                mev->axis_data[3] = xev->valuator3;
                            case 3:
                                mev->axis_data[2] = xev->valuator2;
                            case 2:
                                mev->axis_data[1] = xev->valuator1;
                            case 1:
                                mev->axis_data[0] = xev->valuator0;
                        }
                    } else if (save_type == XI_ProximityIn || save_type == XI_ProximityOut) {
                        XProximityNotifyEvent *pev = (XProximityNotifyEvent *) save;

                        pev->device_state = xev->device_state;
                        pev->axes_count = xev->num_valuators;
                        pev->first_axis = xev->first_valuator;
                        i = xev->num_valuators;
                        if (i > 6)
                            i = 6;
                        switch (i) {
                            case 6:
                                pev->axis_data[5] = xev->valuator5;
                            case 5:
                                pev->axis_data[4] = xev->valuator4;
                            case 4:
                                pev->axis_data[3] = xev->valuator3;
                            case 3:
                                pev->axis_data[2] = xev->valuator2;
                            case 2:
                                pev->axis_data[1] = xev->valuator1;
                            case 1:
                                pev->axis_data[0] = xev->valuator0;
                        }
                    } else if (save_type == XI_DeviceStateNotify) {
                        XDeviceStateNotifyEvent *sev = (XDeviceStateNotifyEvent *) save;
                        XInputClass *any = (XInputClass *) & sev->data[0];
                        XValuatorStatus *v;

                        for (i = 0; i < sev->num_classes; i++)
                            if (any->class != ValuatorClass)
                                any = (XInputClass *) ((char *)any + any->length);
                        v = (XValuatorStatus *) any;
                        i = v->num_valuators;
                        j = xev->num_valuators;
                        if (j > 3)
                            j = 3;
                        switch (j) {
                            case 3:
                                v->valuators[i + 2] = xev->valuator2;
                            case 2:
                                v->valuators[i + 1] = xev->valuator1;
                            case 1:
                                v->valuators[i + 0] = xev->valuator0;
                        }
                        v->num_valuators += j;

                    }
                    *re = *save;
                    return (ENQUEUE_EVENT);
                }
                break;
            case XI_DeviceFocusIn:
            case XI_DeviceFocusOut:
                {
                    register XDeviceFocusChangeEvent *ev = (XDeviceFocusChangeEvent *) re;
                    deviceFocus *fev = (deviceFocus *) event;

                    *ev = *((XDeviceFocusChangeEvent *) save);
                    ev->window = fev->window;
                    ev->time = fev->time;
                    ev->mode = fev->mode;
                    ev->detail = fev->detail;
                    ev->deviceid = fev->deviceid & DEVICE_BITS;
                    return (ENQUEUE_EVENT);
                }
                break;
            case XI_DeviceStateNotify:
                {
                    XDeviceStateNotifyEvent *stev = (XDeviceStateNotifyEvent *) save;
                    deviceStateNotify *sev = (deviceStateNotify *) event;
                    char *data;

                    stev->window = None;
                    stev->deviceid = sev->deviceid & DEVICE_BITS;
                    stev->time = sev->time;
                    stev->num_classes = Ones((Mask) sev->classes_reported & InputClassBits);
                    data = (char *)&stev->data[0];
                    if (sev->classes_reported & (1 << KeyClass)) {
                        register XKeyStatus *kstev = (XKeyStatus *) data;

                        kstev->class = KeyClass;
                        kstev->length = sizeof(XKeyStatus);
                        kstev->num_keys = sev->num_keys;
                        memcpy((char *)&kstev->keys[0], (char *)&sev->keys[0], 4);
                        data += sizeof(XKeyStatus);
                    }
                    if (sev->classes_reported & (1 << ButtonClass)) {
                        register XButtonStatus *bev = (XButtonStatus *) data;

                        bev->class = ButtonClass;
                        bev->length = sizeof(XButtonStatus);
                        bev->num_buttons = sev->num_buttons;
                        memcpy((char *)bev->buttons, (char *)sev->buttons, 4);
                        data += sizeof(XButtonStatus);
                    }
                    if (sev->classes_reported & (1 << ValuatorClass)) {
                        register XValuatorStatus *vev = (XValuatorStatus *) data;

                        vev->class = ValuatorClass;
                        vev->length = sizeof(XValuatorStatus);
                        vev->num_valuators = sev->num_valuators;
                        vev->mode = sev->classes_reported >> ModeBitsShift;
                        j = sev->num_valuators;
                        if (j > 3)
                            j = 3;
                        switch (j) {
                            case 3:
                                vev->valuators[2] = sev->valuator2;
                            case 2:
                                vev->valuators[1] = sev->valuator1;
                            case 1:
                                vev->valuators[0] = sev->valuator0;
                        }
                        data += sizeof(XValuatorStatus);
                    }
                    if (sev->deviceid & MORE_EVENTS)
                        return (DONT_ENQUEUE);
                    else {
                        *re = *save;
                        stev = (XDeviceStateNotifyEvent *) re;
                        return (ENQUEUE_EVENT);
                    }
                }
                break;
            case XI_DeviceKeystateNotify:
                {
                    int i;
                    XInputClass *anyclass;
                    register XKeyStatus *kv;
                    deviceKeyStateNotify *ksev = (deviceKeyStateNotify *) event;
                    XDeviceStateNotifyEvent *kstev = (XDeviceStateNotifyEvent *) save;

                    anyclass = (XInputClass *) & kstev->data[0];
                    for (i = 0; i < kstev->num_classes; i++)
                        if (anyclass->class == KeyClass)
                            break;
                        else
                            anyclass = (XInputClass *) ((char *)anyclass +
                                    anyclass->length);

                    kv = (XKeyStatus *) anyclass;
                    kv->num_keys = 256;
                    memcpy((char *)&kv->keys[4], (char *)ksev->keys, 28);
                    if (ksev->deviceid & MORE_EVENTS)
                        return (DONT_ENQUEUE);
                    else {
                        *re = *save;
                        kstev = (XDeviceStateNotifyEvent *) re;
                        return (ENQUEUE_EVENT);
                    }
                }
                break;
            case XI_DeviceButtonstateNotify:
                {
                    int i;
                    XInputClass *anyclass;
                    register XButtonStatus *bv;
                    deviceButtonStateNotify *bsev = (deviceButtonStateNotify *) event;
                    XDeviceStateNotifyEvent *bstev = (XDeviceStateNotifyEvent *) save;

                    anyclass = (XInputClass *) & bstev->data[0];
                    for (i = 0; i < bstev->num_classes; i++)
                        if (anyclass->class == ButtonClass)
                            break;
                        else
                            anyclass = (XInputClass *) ((char *)anyclass +
                                    anyclass->length);

                    bv = (XButtonStatus *) anyclass;
                    bv->num_buttons = 256;
                    memcpy((char *)&bv->buttons[4], (char *)bsev->buttons, 28);
                    if (bsev->deviceid & MORE_EVENTS)
                        return (DONT_ENQUEUE);
                    else {
                        *re = *save;
                        bstev = (XDeviceStateNotifyEvent *) re;
                        return (ENQUEUE_EVENT);
                    }
                }
                break;
            case XI_DeviceMappingNotify:
                {
                    register XDeviceMappingEvent *ev = (XDeviceMappingEvent *) re;
                    deviceMappingNotify *ev2 = (deviceMappingNotify *) event;

                    *ev = *((XDeviceMappingEvent *) save);
                    ev->window = 0;
                    ev->first_keycode = ev2->firstKeyCode;
                    ev->request = ev2->request;
                    ev->count = ev2->count;
                    ev->time = ev2->time;
                    ev->deviceid = ev2->deviceid & DEVICE_BITS;
                    return (ENQUEUE_EVENT);
                }
                break;
            case XI_ChangeDeviceNotify:
                {
                    register XChangeDeviceNotifyEvent *ev = (XChangeDeviceNotifyEvent *) re;
                    changeDeviceNotify *ev2 = (changeDeviceNotify *) event;

                    *ev = *((XChangeDeviceNotifyEvent *) save);
                    ev->window = 0;
                    ev->request = ev2->request;
                    ev->time = ev2->time;
                    ev->deviceid = ev2->deviceid & DEVICE_BITS;
                    return (ENQUEUE_EVENT);
                }
                break;

            case XI_DevicePresenceNotify:
                {
                    XDevicePresenceNotifyEvent *ev = (XDevicePresenceNotifyEvent *) re;
                    devicePresenceNotify *ev2 = (devicePresenceNotify *) event;

                    *ev = *(XDevicePresenceNotifyEvent *) save;
                    ev->window = 0;
                    ev->time = ev2->time;
                    ev->devchange = ev2->devchange;
                    ev->deviceid = ev2->deviceid;
                    ev->control = ev2->control;
                    return (ENQUEUE_EVENT);
                }
                break;
            case XI_DevicePropertyNotify:
                {
                    XDevicePropertyNotifyEvent* ev = (XDevicePropertyNotifyEvent*)re;
                    devicePropertyNotify *ev2 = (devicePropertyNotify*)event;

                    *ev = *(XDevicePropertyNotifyEvent*)save;
                    ev->time = ev2->time;
                    ev->deviceid = ev2->deviceid;
                    ev->atom = ev2->atom;
                    ev->state = ev2->state;
                    return ENQUEUE_EVENT;
                }
                break;
            default:
                printf("XInputWireToEvent: UNKNOWN WIRE EVENT! type=%d\n", type);
                break;
        }
    }
    return (DONT_ENQUEUE);
}

static void xge_copy_to_cookie(xGenericEvent* ev,
                               XGenericEventCookie *cookie)
{
    cookie->type = ev->type;
    cookie->evtype = ev->evtype;
    cookie->extension = ev->extension;
}

static Bool
XInputWireToCookie(
    Display	*dpy,
    XGenericEventCookie *cookie,
    xEvent	*event)
{
    XExtDisplayInfo *info = XInput_find_display(dpy);
    XEvent *save = (XEvent *) info->data;
    xGenericEvent* ge = (xGenericEvent*)event;

    if (ge->extension != info->codes->major_opcode)
    {
        printf("XInputWireToCookie: wrong extension opcode %d\n",
                ge->extension);
        return DONT_ENQUEUE;
    }

    *save = emptyevent;
    save->type = event->u.u.type;
    ((XAnyEvent*)save)->serial = _XSetLastRequestRead(dpy, (xGenericReply *) event);
    ((XAnyEvent*)save)->send_event = ((event->u.u.type & 0x80) != 0);
    ((XAnyEvent*)save)->display = dpy;

    xge_copy_to_cookie((xGenericEvent*)event, (XGenericEventCookie*)save);
    switch(ge->evtype)
    {
        case XI_Motion:
        case XI_ButtonPress:
        case XI_ButtonRelease:
        case XI_KeyPress:
        case XI_KeyRelease:
            *cookie = *(XGenericEventCookie*)save;
            if (!wireToDeviceEvent((xXIDeviceEvent*)event, cookie))
            {
                printf("XInputWireToCookie: CONVERSION FAILURE!  evtype=%d\n",
                        ge->evtype);
                break;
            }
            return ENQUEUE_EVENT;
        case XI_DeviceChanged:
            *cookie = *(XGenericEventCookie*)save;
            if (!wireToDeviceChangedEvent((xXIDeviceChangedEvent*)event, cookie))
            {
                printf("XInputWireToCookie: CONVERSION FAILURE!  evtype=%d\n",
                        ge->evtype);
                break;
            }
            return ENQUEUE_EVENT;
        case XI_HierarchyChanged:
            *cookie = *(XGenericEventCookie*)save;
            if (!wireToHierarchyChangedEvent((xXIHierarchyEvent*)event, cookie))
            {
                printf("XInputWireToCookie: CONVERSION FAILURE!  evtype=%d\n",
                        ge->evtype);
                break;
            }
            return ENQUEUE_EVENT;

        case XI_RawKeyPress:
        case XI_RawKeyRelease:
        case XI_RawButtonPress:
        case XI_RawButtonRelease:
        case XI_RawMotion:
            *cookie = *(XGenericEventCookie*)save;
            if (!wireToRawEvent((xXIRawEvent*)event, cookie))
            {
                printf("XInputWireToCookie: CONVERSION FAILURE!  evtype=%d\n",
                        ge->evtype);
                break;
            }
            return ENQUEUE_EVENT;
        case XI_Enter:
        case XI_Leave:
        case XI_FocusIn:
        case XI_FocusOut:
            *cookie = *(XGenericEventCookie*)save;
            if (!wireToEnterLeave((xXIEnterEvent*)event, cookie))
            {
                printf("XInputWireToCookie: CONVERSION FAILURE!  evtype=%d\n",
                        ge->evtype);
                break;
            }
            return ENQUEUE_EVENT;
        case XI_PropertyEvent:
            *cookie = *(XGenericEventCookie*)save;
            if (!wireToPropertyEvent((xXIPropertyEvent*)event, cookie))
            {
                printf("XInputWireToCookie: CONVERSION FAILURE!  evtype=%d\n",
                        ge->evtype);
                break;
            }
            return ENQUEUE_EVENT;
        default:
            printf("XInputWireToCookie: Unknown generic event. type %d\n", ge->evtype);

    }
    return DONT_ENQUEUE;
}

/**
 * Calculate length in bytes needed for the device event with the given
 * button mask length, valuator mask length + valuator mask. All parameters
 * in bytes.
 */
static inline int
sizeDeviceEvent(int buttons_len, int valuators_len,
                unsigned char *valuators_mask)
{
    int len;

    len = sizeof(XIDeviceEvent);
    len += sizeof(XIButtonState) + buttons_len;
    len += sizeof(XIValuatorState) + valuators_len;
    len += count_bits(valuators_mask, valuators_len) * sizeof(double);
    len += sizeof(XIModifierState) + sizeof(XIGroupState);

    return len;
}

/**
 * Return the size in bytes required to store the matching class type
 * num_elements is num_buttons for XIButtonClass or num_keycodes for
 * XIKeyClass.
 *
 * Also used from copy_classes in XIQueryDevice.c
 */
static int
sizeDeviceClassType(int type, int num_elements)
{
    int l = 0;
    switch(type)
    {
        case XIButtonClass:
            l = sizeof(XIButtonClassInfo);
            l += num_elements * sizeof(Atom);
            l += ((((num_elements + 7)/8) + 3)/4) * 4;
            break;
        case XIKeyClass:
            l = sizeof(XIKeyClassInfo);
            l += num_elements * sizeof(int);
            break;
        case XIValuatorClass:
            l = sizeof(XIValuatorClassInfo);
            break;
        default:
            printf("sizeDeviceClassType: unknown type %d\n", type);
            break;
    }
    return l;
}

static Bool
copyHierarchyEvent(XGenericEventCookie *cookie_in,
                   XGenericEventCookie *cookie_out)
{
    XIHierarchyEvent *in, *out;
    void *ptr;

    in = cookie_in->data;

    ptr = cookie_out->data = malloc(sizeof(XIHierarchyEvent) +
                                    in->num_info * sizeof(XIHierarchyInfo));
    if (!ptr)
        return False;

    out = next_block(&ptr, sizeof(XIHierarchyEvent));
    *out = *in;
    out->info = next_block(&ptr, in->num_info * sizeof(XIHierarchyInfo));
    memcpy(out->info, in->info, in->num_info * sizeof(XIHierarchyInfo));

    return True;
}

static Bool
copyDeviceChangedEvent(XGenericEventCookie *in_cookie,
                       XGenericEventCookie *out_cookie)
{
    int len, i;
    XIDeviceChangedEvent *in, *out;
    XIAnyClassInfo *any;
    void *ptr;

    in = in_cookie->data;

    len = sizeof(XIDeviceChangedEvent);
    len += in->num_classes * sizeof(XIAnyClassInfo*);

    for (i = 0; i < in->num_classes; i++)
    {
        any = in->classes[i];
        switch(any->type)
        {
            case XIButtonClass:
                len += sizeDeviceClassType(XIButtonClass,
                        ((XIButtonClassInfo*)any)->num_buttons);
                break;
            case XIKeyClass:
                len += sizeDeviceClassType(XIKeyClass,
                        ((XIKeyClassInfo*)any)->num_keycodes);
                break;
            case XIValuatorClass:
                len += sizeDeviceClassType(XIValuatorClass, 0);
                break;
            default:
                printf("copyDeviceChangedEvent: unknown type %d\n",
                        any->type);
                break;
        }

    }

    ptr = out_cookie->data = malloc(len);
    if (!ptr)
        return False;
    out = next_block(&ptr, sizeof(XIDeviceChangedEvent));
    *out = *in;

    out->classes = next_block(&ptr,
                              out->num_classes * sizeof(XIAnyClassInfo*));

    for (i = 0; i < in->num_classes; i++)
    {
        any = in->classes[i];

        switch(any->type)
        {
            case XIButtonClass:
                {
                    XIButtonClassInfo *bin, *bout;
                    bin = (XIButtonClassInfo*)any;
                    bout = next_block(&ptr, sizeof(XIButtonClass));

                    *bout = *bin;
                    bout->state.mask = next_block(&ptr, bout->state.mask_len);
                    memcpy(bout->state.mask, bin->state.mask,
                            bout->state.mask_len);

                    bout->labels = next_block(&ptr, bout->num_buttons * sizeof(Atom));
                    memcpy(bout->labels, bin->labels, bout->num_buttons * sizeof(Atom));
                    out->classes[i] = (XIAnyClassInfo*)bout;
                    break;
                }
            case XIKeyClass:
                {
                    XIKeyClassInfo *kin, *kout;
                    kin = (XIKeyClassInfo*)any;

                    kout = next_block(&ptr, sizeof(XIKeyClass));
                    *kout = *kin;
                    kout->keycodes = next_block(&ptr, kout->num_keycodes * sizeof(int));
                    memcpy(kout->keycodes, kin->keycodes, kout->num_keycodes * sizeof(int));
                    out->classes[i] = (XIAnyClassInfo*)kout;
                    break;
                }
            case XIValuatorClass:
                {
                    XIValuatorClassInfo *vin, *vout;
                    vin = (XIValuatorClassInfo*)any;
                    vout = next_block(&ptr, sizeof(XIValuatorClass));
                    *vout = *vin;
                    out->classes[i] = (XIAnyClassInfo*)vout;
                    break;
                }
        }
    }

    return True;
}

static Bool
copyDeviceEvent(XGenericEventCookie *cookie_in,
                XGenericEventCookie *cookie_out)
{
    int len;
    XIDeviceEvent *in, *out;
    int bits; /* valuator bits */
    void *ptr;

    in = cookie_in->data;
    bits = count_bits(in->valuators.mask, in->valuators.mask_len);

    len = sizeDeviceEvent(in->buttons.mask_len, in->valuators.mask_len,
                          in->valuators.mask);

    ptr = cookie_out->data = malloc(len);
    if (!ptr)
        return False;

    out = next_block(&ptr, sizeof(XIDeviceEvent));
    *out = *in;

    out->buttons.mask = next_block(&ptr, in->buttons.mask_len);
    memcpy(out->buttons.mask, in->buttons.mask,
           out->buttons.mask_len);
    out->valuators.mask = next_block(&ptr, in->valuators.mask_len);
    memcpy(out->valuators.mask, in->valuators.mask,
           out->valuators.mask_len);
    out->valuators.values = next_block(&ptr, bits * sizeof(double));
    memcpy(out->valuators.values, in->valuators.values,
           bits * sizeof(double));

    return True;
}

static Bool
copyEnterEvent(XGenericEventCookie *cookie_in,
               XGenericEventCookie *cookie_out)
{
    int len;
    XIEnterEvent *in, *out;
    void *ptr;

    in = cookie_in->data;

    len = sizeof(XIEnterEvent) + in->buttons.mask_len;

    ptr = cookie_out->data = malloc(len);
    if (!ptr)
        return False;

    out = next_block(&ptr, sizeof(XIEnterEvent));
    *out = *in;

    out->buttons.mask = next_block(&ptr, in->buttons.mask_len);
    memcpy(out->buttons.mask, in->buttons.mask, out->buttons.mask_len);

    return True;
}

static Bool
copyPropertyEvent(XGenericEventCookie *cookie_in,
                  XGenericEventCookie *cookie_out)
{
    XIPropertyEvent *in, *out;

    in = cookie_in->data;

    out = cookie_out->data = malloc(sizeof(XIPropertyEvent));
    if (!out)
        return False;

    *out = *in;
    return True;
}

static Bool
copyRawEvent(XGenericEventCookie *cookie_in,
             XGenericEventCookie *cookie_out)
{
    XIRawEvent *in, *out;
    void *ptr;
    int len;
    int bits;

    in = cookie_in->data;

    bits = count_bits(in->valuators.mask, in->valuators.mask_len);
    len = sizeof(XIRawEvent) + in->valuators.mask_len;
    len += bits * sizeof(double) * 2;

    ptr = cookie_out->data = malloc(sizeof(XIRawEvent));
    if (!ptr)
        return False;

    out = next_block(&ptr, sizeof(XIRawEvent));
    *out = *in;
    out->valuators.mask = next_block(&ptr, out->valuators.mask_len);
    memcpy(out->valuators.mask, in->valuators.mask, out->valuators.mask_len);

    out->valuators.values = next_block(&ptr, bits * sizeof(double));
    memcpy(out->valuators.values, in->valuators.values, bits * sizeof(double));

    out->raw_values = next_block(&ptr, bits * sizeof(double));
    memcpy(out->raw_values, in->raw_values, bits * sizeof(double));

    return True;
}



static Bool
XInputCopyCookie(Display *dpy, XGenericEventCookie *in, XGenericEventCookie *out)
{
    int ret = True;

    XExtDisplayInfo *info = XInput_find_display(dpy);

    if (in->extension != info->codes->major_opcode)
    {
        printf("XInputCopyCookie: wrong extension opcode %d\n",
                in->extension);
        return False;
    }

    *out = *in;
    out->data = NULL;
    out->cookie = 0;

    switch(in->evtype) {
        case XI_Motion:
        case XI_ButtonPress:
        case XI_ButtonRelease:
        case XI_KeyPress:
        case XI_KeyRelease:
            ret = copyDeviceEvent(in, out);
            break;
        case XI_DeviceChanged:
            ret = copyDeviceChangedEvent(in, out);
            break;
        case XI_HierarchyChanged:
            ret = copyHierarchyEvent(in, out);
            break;
        case XI_Enter:
        case XI_Leave:
        case XI_FocusIn:
        case XI_FocusOut:
            ret = copyEnterEvent(in, out);
            break;
        case XI_PropertyEvent:
            ret = copyPropertyEvent(in, out);
            break;
        case XI_RawKeyPress:
        case XI_RawKeyRelease:
        case XI_RawButtonPress:
        case XI_RawButtonRelease:
        case XI_RawMotion:
            ret = copyRawEvent(in, out);
            break;
        default:
            printf("XInputCopyCookie: unknown evtype %d\n", in->evtype);
            ret = False;
    }

    if (!ret)
        printf("XInputCopyCookie: Failed to copy evtype %d", in->evtype);
    return ret;
}

static int
wireToDeviceEvent(xXIDeviceEvent *in, XGenericEventCookie* cookie)
{
    int len, i;
    unsigned char *ptr;
    void *ptr_lib;
    FP3232 *values;
    XIDeviceEvent *out;

    ptr = (unsigned char*)&in[1] + in->buttons_len * 4;

    len = sizeDeviceEvent(in->buttons_len * 4, in->valuators_len * 4, ptr);

    cookie->data = ptr_lib = malloc(len);

    out = next_block(&ptr_lib, sizeof(XIDeviceEvent));
    out->display = cookie->display;
    out->type = in->type;
    out->extension = in->extension;
    out->evtype = in->evtype;
    out->send_event = ((in->type & 0x80) != 0);
    out->time = in->time;
    out->deviceid = in->deviceid;
    out->sourceid = in->sourceid;
    out->detail = in->detail;
    out->root = in->root;
    out->event = in->event;
    out->child = in->child;
    out->root_x = FP1616toDBL(in->root_x);
    out->root_y = FP1616toDBL(in->root_y);
    out->event_x = FP1616toDBL(in->event_x);
    out->event_y = FP1616toDBL(in->event_y);
    out->flags = in->flags;
    out->mods.base = in->mods.base_mods;
    out->mods.locked = in->mods.locked_mods;
    out->mods.latched = in->mods.latched_mods;
    out->mods.effective = in->mods.effective_mods;
    out->group.base = in->group.base_group;
    out->group.locked = in->group.locked_group;
    out->group.latched = in->group.latched_group;
    out->group.effective = in->group.effective_group;
    out->buttons.mask_len = in->buttons_len * 4;
    out->valuators.mask_len = in->valuators_len * 4;

    out->buttons.mask = next_block(&ptr_lib, out->buttons.mask_len);

    /* buttons */
    ptr = (unsigned char*)&in[1];
    memcpy(out->buttons.mask, ptr, out->buttons.mask_len);
    ptr += in->buttons_len * 4;

    /* valuators */
    out->valuators.mask = next_block(&ptr_lib, out->valuators.mask_len);
    memcpy(out->valuators.mask, ptr, out->valuators.mask_len);
    ptr += in->valuators_len * 4;

    len = count_bits(out->valuators.mask, out->valuators.mask_len);
    out->valuators.values = next_block(&ptr_lib, len * sizeof(double));

    values = (FP3232*)ptr;
    for (i = 0; i < len; i++, values++)
    {
        out->valuators.values[i] = values->integral;
        out->valuators.values[i] += ((double)values->frac / (1 << 16) / (1 << 16));
    }


    return 1;
}

_X_HIDDEN int
size_classes(xXIAnyInfo* from, int nclasses)
{
    int len, i;
    xXIAnyInfo *any_wire;
    char *ptr_wire;

    len = nclasses * sizeof(XIAnyClassInfo*); /* len for to->classes */
    ptr_wire = (char*)from;
    for (i = 0; i < nclasses; i++)
    {
        int l = 0;
        any_wire = (xXIAnyInfo*)ptr_wire;
        switch(any_wire->type)
        {
            case XIButtonClass:
                l = sizeDeviceClassType(XIButtonClass,
                        ((xXIButtonInfo*)any_wire)->num_buttons);
                break;
            case XIKeyClass:
                l = sizeDeviceClassType(XIKeyClass,
                        ((xXIKeyInfo*)any_wire)->num_keycodes);
                break;
            case XIValuatorClass:
                l = sizeDeviceClassType(XIValuatorClass, 0);
                break;
        }

        len += l;
        ptr_wire += any_wire->length * 4;
    }

    return len;
}

/* Copy classes from any into to->classes and return the number of bytes
 * copied. Memory layout of to->classes is
 * [clsptr][clsptr][clsptr][classinfo][classinfo]...
 *    |________|___________^
 *             |______________________^
 */
_X_HIDDEN int
copy_classes(XIDeviceInfo* to, xXIAnyInfo* from, int *nclasses)
{
    XIAnyClassInfo *any_lib;
    xXIAnyInfo *any_wire;
    void *ptr_lib;
    char *ptr_wire;
    int i, len;
    int cls_idx = 0;

    if (!to->classes)
        return -1;

    ptr_wire = (char*)from;
    ptr_lib = to->classes;
    to->classes = next_block(&ptr_lib, *nclasses * sizeof(XIAnyClassInfo*));
    memset(to->classes, 0, sizeof(*nclasses * sizeof(XIAnyClassInfo*)));
    len = 0; /* count wire length */

    for (i = 0; i < *nclasses; i++)
    {
        any_lib = (XIAnyClassInfo*)ptr_lib;
        any_wire = (xXIAnyInfo*)ptr_wire;

        switch(any_wire->type)
        {
            case XIButtonClass:
                {
                    XIButtonClassInfo *cls_lib;
                    xXIButtonInfo *cls_wire;
                    uint32_t *atoms;
                    int j;

                    cls_lib = next_block(&ptr_lib, sizeof(XIButtonClassInfo));
                    cls_wire = (xXIButtonInfo*)any_wire;

                    cls_lib->type = cls_wire->type;
                    cls_lib->sourceid = cls_wire->sourceid;
                    cls_lib->num_buttons = cls_wire->num_buttons;
                    cls_lib->state.mask_len = ((((cls_wire->num_buttons + 7)/8) + 3)/4) * 4;
                    cls_lib->state.mask = next_block(&ptr_lib, cls_lib->state.mask_len);
                    memcpy(cls_lib->state.mask, &cls_wire[1],
                           cls_lib->state.mask_len);

                    cls_lib->labels = next_block(&ptr_lib, cls_lib->num_buttons * sizeof(Atom));
                    atoms =(uint32_t*)((char*)&cls_wire[1] + cls_lib->state.mask_len);
                    for (j = 0; j < cls_lib->num_buttons; j++)
                        cls_lib->labels[j] = *atoms++;

                    to->classes[cls_idx++] = any_lib;
                    break;
                }
            case XIKeyClass:
                {
                    XIKeyClassInfo *cls_lib;
                    xXIKeyInfo *cls_wire;

                    cls_lib = next_block(&ptr_lib, sizeof(XIKeyClassInfo));
                    cls_wire = (xXIKeyInfo*)any_wire;

                    cls_lib->type = cls_wire->type;
                    cls_lib->sourceid = cls_wire->sourceid;
                    cls_lib->num_keycodes = cls_wire->num_keycodes;
                    cls_lib->keycodes = next_block(&ptr_lib,
                            cls_lib->num_keycodes * sizeof(int));
                    memcpy(cls_lib->keycodes, &cls_wire[1],
                            cls_lib->num_keycodes);

                    to->classes[cls_idx++] = any_lib;
                    break;
                }
            case XIValuatorClass:
                {
                    XIValuatorClassInfo *cls_lib;
                    xXIValuatorInfo *cls_wire;

                    cls_lib = next_block(&ptr_lib, sizeof(XIValuatorClassInfo));
                    cls_wire = (xXIValuatorInfo*)any_wire;

                    cls_lib->type = cls_wire->type;
                    cls_lib->sourceid = cls_wire->sourceid;
                    cls_lib->number = cls_wire->number;
                    cls_lib->label  = cls_wire->label;
                    cls_lib->resolution = cls_wire->resolution;
                    cls_lib->min        = cls_wire->min.integral;
                    cls_lib->max        = cls_wire->max.integral;
                    cls_lib->value      = cls_wire->value.integral;
                    /* FIXME: fractional parts */
                    cls_lib->mode       = cls_wire->mode;

                    to->classes[cls_idx++] = any_lib;
                }
                break;
        }
        len += any_wire->length * 4;
        ptr_wire += any_wire->length * 4;
    }

    /* we may have skipped unknown classes, reset nclasses */
    *nclasses = cls_idx;
    return len;
}


static int
wireToDeviceChangedEvent(xXIDeviceChangedEvent *in, XGenericEventCookie *cookie)
{
    XIDeviceChangedEvent *out;
    XIDeviceInfo info;
    int len;
    int nclasses = in->num_classes;

    len = size_classes((xXIAnyInfo*)&in[1], in->num_classes);

    cookie->data = out = malloc(sizeof(XIDeviceChangedEvent) + len);

    out->type = in->type;
    out->display = cookie->display;
    out->extension = in->extension;
    out->evtype = in->evtype;
    out->send_event = ((in->type & 0x80) != 0);
    out->time = in->time;
    out->deviceid = in->deviceid;
    out->sourceid = in->sourceid;
    out->reason = in->reason;

    out->classes = (XIAnyClassInfo**)&out[1];

    info.classes = out->classes;

    copy_classes(&info, (xXIAnyInfo*)&in[1], &nclasses);
    out->num_classes = nclasses;

    return 1;
}

static int
wireToHierarchyChangedEvent(xXIHierarchyEvent *in, XGenericEventCookie *cookie)
{
    int i;
    XIHierarchyInfo *info_out;
    xXIHierarchyInfo *info_in;
    XIHierarchyEvent *out;

    cookie->data = out = malloc(sizeof(XIHierarchyEvent) + in->num_info * sizeof(XIHierarchyInfo));;

    out->info           = (XIHierarchyInfo*)&out[1];
    out->display        = cookie->display;
    out->type           = in->type;
    out->extension      = in->extension;
    out->evtype         = in->evtype;
    out->send_event = ((in->type & 0x80) != 0);
    out->time           = in->time;
    out->flags          = in->flags;
    out->num_info       = in->num_info;

    info_out            = out->info;
    info_in             = (xXIHierarchyInfo*)&in[1];

    for (i = 0; i < out->num_info; i++, info_out++, info_in++)
    {
        info_out->deviceid      = info_in->deviceid;
        info_out->attachment    = info_in->attachment;
        info_out->use           = info_in->use;
        info_out->enabled       = info_in->enabled;
        info_out->flags         = info_in->flags;
    }

    return 1;
}

static int
wireToRawEvent(xXIRawEvent *in, XGenericEventCookie *cookie)
{
    int len, i, bits;
    FP3232 *values;
    XIRawEvent *out;
    void *ptr;


    len = sizeof(XIRawEvent) + in->valuators_len * 4;
    bits = count_bits((unsigned char*)&in[1], in->valuators_len * 4);
    len += bits * sizeof(double) * 2; /* raw + normal */

    cookie->data = ptr = calloc(1, len);
    if (!ptr)
        return 0;

    out = next_block(&ptr, sizeof(XIRawEvent));
    out->type           = in->type;
    out->display        = cookie->display;
    out->extension      = in->extension;
    out->evtype         = in->evtype;
    out->send_event = ((in->type & 0x80) != 0);
    out->time           = in->time;
    out->detail         = in->detail;
    out->deviceid       = in->deviceid;
    out->flags          = in->flags;

    out->valuators.mask_len = in->valuators_len * 4;
    out->valuators.mask = next_block(&ptr, out->valuators.mask_len);
    memcpy(out->valuators.mask, &in[1], out->valuators.mask_len);

    out->valuators.values = next_block(&ptr, bits * sizeof(double));
    out->raw_values = next_block(&ptr, bits * sizeof(double));

    values = (FP3232*)(((char*)&in[1]) + in->valuators_len * 4);
    for (i = 0; i < bits; i++)
    {
        out->valuators.values[i] = values->integral;
        out->valuators.values[i] += ((double)values->frac / (1 << 16) / (1 << 16));
        out->raw_values[i] = (values + bits)->integral;
        out->raw_values[i] += ((double)(values + bits)->frac / (1 << 16) / (1 << 16));
        values++;
    }

    return 1;
}

/* Memory layout of XIEnterEvents:
   [event][modifiers][group][button]
 */
static int
wireToEnterLeave(xXIEnterEvent *in, XGenericEventCookie *cookie)
{
    int len;
    XIEnterEvent *out;

    len = sizeof(XIEnterEvent) + in->buttons_len * 4;

    cookie->data = out = malloc(len);
    out->buttons.mask = (unsigned char*)&out[1];

    out->type           = in->type;
    out->display        = cookie->display;
    out->extension      = in->extension;
    out->evtype         = in->evtype;
    out->send_event = ((in->type & 0x80) != 0);
    out->time           = in->time;
    out->detail         = in->detail;
    out->deviceid       = in->deviceid;
    out->root           = in->root;
    out->event          = in->event;
    out->child          = in->child;
    out->sourceid       = in->sourceid;
    out->root_x         = FP1616toDBL(in->root_x);
    out->root_y         = FP1616toDBL(in->root_y);
    out->event_x        = FP1616toDBL(in->event_x);
    out->event_y        = FP1616toDBL(in->event_y);
    out->mode           = in->mode;
    out->focus          = in->focus;
    out->same_screen    = in->same_screen;

    out->mods.base = in->mods.base_mods;
    out->mods.locked = in->mods.locked_mods;
    out->mods.latched = in->mods.latched_mods;
    out->mods.effective = in->mods.effective_mods;
    out->group.base = in->group.base_group;
    out->group.locked = in->group.locked_group;
    out->group.latched = in->group.latched_group;
    out->group.effective = in->group.effective_group;

    out->buttons.mask_len = in->buttons_len * 4;
    memcpy(out->buttons.mask, &in[1], out->buttons.mask_len);

    return 1;
}

static int
wireToPropertyEvent(xXIPropertyEvent *in, XGenericEventCookie *cookie)
{
    XIPropertyEvent *out = malloc(sizeof(XIPropertyEvent));

    cookie->data = out;

    out->type           = in->type;
    out->extension      = in->extension;
    out->evtype         = in->evtype;
    out->send_event = ((in->type & 0x80) != 0);
    out->time           = in->time;
    out->property       = in->property;
    out->what           = in->what;
    out->deviceid       = in->deviceid;

    return 1;
}