aboutsummaryrefslogtreecommitdiff
path: root/xorg-server/dix/events.c
blob: e3f5e237240cef321f57801f17268e6a85e572e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
/************************************************************

Copyright 1987, 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 1987 by Digital Equipment Corporation, Maynard, Massachusetts.

                        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 Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL 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.

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

/* The panoramix components contained the following notice */
/*****************************************************************

Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software.

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
DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING,
BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL 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 Digital Equipment Corporation
shall not be used in advertising or otherwise to promote the sale, use or other
dealings in this Software without prior written authorization from Digital
Equipment Corporation.

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

/*
 * Copyright (c) 2003-2005, Oracle and/or its affiliates. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) 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 AUTHORS OR COPYRIGHT HOLDERS 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.
 */

/** @file events.c
 * This file handles event delivery and a big part of the server-side protocol
 * handling (the parts for input devices).
 */

#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif

#include <X11/X.h>
#include "misc.h"
#include "resource.h"
#include <X11/Xproto.h>
#include "windowstr.h"
#include "inputstr.h"
#include "inpututils.h"
#include "scrnintstr.h"
#include "cursorstr.h"

#include "dixstruct.h"
#ifdef PANORAMIX
#include "panoramiX.h"
#include "panoramiXsrv.h"
#endif
#include "globals.h"

#include <X11/extensions/XKBproto.h>
#include "xkbsrv.h"
#include "xace.h"

#ifdef XSERVER_DTRACE
#include <sys/types.h>
typedef const char *string;

#include "Xserver-dtrace.h"
#endif

#include <X11/extensions/XIproto.h>
#include <X11/extensions/XI2proto.h>
#include <X11/extensions/XI.h>
#include <X11/extensions/XI2.h>
#include "exglobals.h"
#include "exevents.h"
#include "extnsionst.h"

#include "dixevents.h"
#include "dixgrabs.h"
#include "dispatch.h"

#include <X11/extensions/ge.h>
#include "geext.h"
#include "geint.h"

#include "eventstr.h"
#include "enterleave.h"
#include "eventconvert.h"
#include "mi.h"

/* Extension events type numbering starts at EXTENSION_EVENT_BASE.  */
#define NoSuchEvent 0x80000000  /* so doesn't match NoEventMask */
#define StructureAndSubMask ( StructureNotifyMask | SubstructureNotifyMask )
#define AllButtonsMask ( \
	Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask )
#define MotionMask ( \
	PointerMotionMask | Button1MotionMask | \
	Button2MotionMask | Button3MotionMask | Button4MotionMask | \
	Button5MotionMask | ButtonMotionMask )
#define PropagateMask ( \
	KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | \
	MotionMask )
#define PointerGrabMask ( \
	ButtonPressMask | ButtonReleaseMask | \
	EnterWindowMask | LeaveWindowMask | \
	PointerMotionHintMask | KeymapStateMask | \
	MotionMask )
#define AllModifiersMask ( \
	ShiftMask | LockMask | ControlMask | Mod1Mask | Mod2Mask | \
	Mod3Mask | Mod4Mask | Mod5Mask )
#define LastEventMask OwnerGrabButtonMask
#define AllEventMasks (LastEventMask|(LastEventMask-1))

/* @return the core event type or 0 if the event is not a core event */
static inline int
core_get_type(const xEvent *event)
{
    int type = event->u.u.type;

    return ((type & EXTENSION_EVENT_BASE) || type == GenericEvent) ? 0 : type;
}

/* @return the XI2 event type or 0 if the event is not a XI2 event */
static inline int
xi2_get_type(const xEvent *event)
{
    const xGenericEvent *e = (const xGenericEvent *) event;

    return (e->type != GenericEvent ||
            e->extension != IReqCode) ? 0 : e->evtype;
}

/**
 * Used to indicate a implicit passive grab created by a ButtonPress event.
 * See DeliverEventsToWindow().
 */
#define ImplicitGrabMask (1 << 7)

#define WID(w) ((w) ? ((w)->drawable.id) : 0)

#define XE_KBPTR (xE->u.keyButtonPointer)

CallbackListPtr EventCallback;
CallbackListPtr DeviceEventCallback;

#define DNPMCOUNT 8

Mask DontPropagateMasks[DNPMCOUNT];
static int DontPropagateRefCnts[DNPMCOUNT];

static void CheckVirtualMotion(DeviceIntPtr pDev, QdEventPtr qe,
                               WindowPtr pWin);
static void CheckPhysLimits(DeviceIntPtr pDev, CursorPtr cursor,
                            Bool generateEvents, Bool confineToScreen,
                            ScreenPtr pScreen);
static Bool IsWrongPointerBarrierClient(ClientPtr client,
                                        DeviceIntPtr dev,
                                        xEvent *event);

/** Key repeat hack. Do not use but in TryClientEvents */
extern BOOL EventIsKeyRepeat(xEvent *event);

/**
 * Main input device struct.
 *     inputInfo.pointer
 *     is the core pointer. Referred to as "virtual core pointer", "VCP",
 *     "core pointer" or inputInfo.pointer. The VCP is the first master
 *     pointer device and cannot be deleted.
 *
 *     inputInfo.keyboard
 *     is the core keyboard ("virtual core keyboard", "VCK", "core keyboard").
 *     See inputInfo.pointer.
 *
 *     inputInfo.devices
 *     linked list containing all devices including VCP and VCK.
 *
 *     inputInfo.off_devices
 *     Devices that have not been initialized and are thus turned off.
 *
 *     inputInfo.numDevices
 *     Total number of devices.
 *
 *     inputInfo.all_devices
 *     Virtual device used for XIAllDevices passive grabs. This device is
 *     not part of the inputInfo.devices list and mostly unset except for
 *     the deviceid. It exists because passivegrabs need a valid device
 *     reference.
 *
 *     inputInfo.all_master_devices
 *     Virtual device used for XIAllMasterDevices passive grabs. This device
 *     is not part of the inputInfo.devices list and mostly unset except for
 *     the deviceid. It exists because passivegrabs need a valid device
 *     reference.
 */
InputInfo inputInfo;

EventSyncInfoRec syncEvents;

static struct DeviceEventTime {
    Bool reset;
    TimeStamp time;
} lastDeviceEventTime[MAXDEVICES];

/**
 * The root window the given device is currently on.
 */
#define RootWindow(sprite) sprite->spriteTrace[0]

static xEvent *swapEvent = NULL;
static int swapEventLen = 0;

void
NotImplemented(xEvent *from, xEvent *to)
{
    FatalError("Not implemented");
}

/**
 * Convert the given event type from an XI event to a core event.
 * @param[in] The XI 1.x event type.
 * @return The matching core event type or 0 if there is none.
 */
int
XItoCoreType(int xitype)
{
    int coretype = 0;

    if (xitype == DeviceMotionNotify)
        coretype = MotionNotify;
    else if (xitype == DeviceButtonPress)
        coretype = ButtonPress;
    else if (xitype == DeviceButtonRelease)
        coretype = ButtonRelease;
    else if (xitype == DeviceKeyPress)
        coretype = KeyPress;
    else if (xitype == DeviceKeyRelease)
        coretype = KeyRelease;

    return coretype;
}

/**
 * @return true if the device owns a cursor, false if device shares a cursor
 * sprite with another device.
 */
Bool
DevHasCursor(DeviceIntPtr pDev)
{
    return pDev->spriteInfo->spriteOwner;
}

/*
 * @return true if a device is a pointer, check is the same as used by XI to
 * fill the 'use' field.
 */
Bool
IsPointerDevice(DeviceIntPtr dev)
{
    return (dev->type == MASTER_POINTER) ||
        (dev->valuator && dev->button) || (dev->valuator && !dev->key);
}

/*
 * @return true if a device is a keyboard, check is the same as used by XI to
 * fill the 'use' field.
 *
 * Some pointer devices have keys as well (e.g. multimedia keys). Try to not
 * count them as keyboard devices.
 */
Bool
IsKeyboardDevice(DeviceIntPtr dev)
{
    return (dev->type == MASTER_KEYBOARD) ||
        ((dev->key && dev->kbdfeed) && !IsPointerDevice(dev));
}

Bool
IsMaster(DeviceIntPtr dev)
{
    return dev->type == MASTER_POINTER || dev->type == MASTER_KEYBOARD;
}

Bool
IsFloating(DeviceIntPtr dev)
{
    return !IsMaster(dev) && GetMaster(dev, MASTER_KEYBOARD) == NULL;
}

/**
 * Max event opcode.
 */
extern int lastEvent;

#define CantBeFiltered NoEventMask
/**
 * Event masks for each event type.
 *
 * One set of filters for each device, initialized by memcpy of
 * default_filter in InitEvents.
 *
 * Filters are used whether a given event may be delivered to a client,
 * usually in the form of if (window-event-mask & filter); then deliver event.
 *
 * One notable filter is for PointerMotion/DevicePointerMotion events. Each
 * time a button is pressed, the filter is modified to also contain the
 * matching ButtonXMotion mask.
 */
Mask event_filters[MAXDEVICES][MAXEVENTS];

static const Mask default_filter[MAXEVENTS] = {
    NoSuchEvent,                /* 0 */
    NoSuchEvent,                /* 1 */
    KeyPressMask,               /* KeyPress */
    KeyReleaseMask,             /* KeyRelease */
    ButtonPressMask,            /* ButtonPress */
    ButtonReleaseMask,          /* ButtonRelease */
    PointerMotionMask,          /* MotionNotify (initial state) */
    EnterWindowMask,            /* EnterNotify */
    LeaveWindowMask,            /* LeaveNotify */
    FocusChangeMask,            /* FocusIn */
    FocusChangeMask,            /* FocusOut */
    KeymapStateMask,            /* KeymapNotify */
    ExposureMask,               /* Expose */
    CantBeFiltered,             /* GraphicsExpose */
    CantBeFiltered,             /* NoExpose */
    VisibilityChangeMask,       /* VisibilityNotify */
    SubstructureNotifyMask,     /* CreateNotify */
    StructureAndSubMask,        /* DestroyNotify */
    StructureAndSubMask,        /* UnmapNotify */
    StructureAndSubMask,        /* MapNotify */
    SubstructureRedirectMask,   /* MapRequest */
    StructureAndSubMask,        /* ReparentNotify */
    StructureAndSubMask,        /* ConfigureNotify */
    SubstructureRedirectMask,   /* ConfigureRequest */
    StructureAndSubMask,        /* GravityNotify */
    ResizeRedirectMask,         /* ResizeRequest */
    StructureAndSubMask,        /* CirculateNotify */
    SubstructureRedirectMask,   /* CirculateRequest */
    PropertyChangeMask,         /* PropertyNotify */
    CantBeFiltered,             /* SelectionClear */
    CantBeFiltered,             /* SelectionRequest */
    CantBeFiltered,             /* SelectionNotify */
    ColormapChangeMask,         /* ColormapNotify */
    CantBeFiltered,             /* ClientMessage */
    CantBeFiltered              /* MappingNotify */
};

/**
 * For the given event, return the matching event filter. This filter may then
 * be AND'ed with the selected event mask.
 *
 * For XI2 events, the returned filter is simply the byte containing the event
 * mask we're interested in. E.g. for a mask of (1 << 13), this would be
 * byte[1].
 *
 * @param[in] dev The device the event belongs to, may be NULL.
 * @param[in] event The event to get the filter for. Only the type of the
 *                  event matters, or the extension + evtype for GenericEvents.
 * @return The filter mask for the given event.
 *
 * @see GetEventMask
 */
Mask
GetEventFilter(DeviceIntPtr dev, xEvent *event)
{
    int evtype = 0;

    if (event->u.u.type != GenericEvent)
        return event_get_filter_from_type(dev, event->u.u.type);
    else if ((evtype = xi2_get_type(event)))
        return event_get_filter_from_xi2type(evtype);
    ErrorF("[dix] Unknown event type %d. No filter\n", event->u.u.type);
    return 0;
}

/**
 * Return the single byte of the device's XI2 mask that contains the mask
 * for the event_type.
 */
int
GetXI2MaskByte(XI2Mask *mask, DeviceIntPtr dev, int event_type)
{
    /* we just return the matching filter because that's the only use
     * for this mask anyway.
     */
    if (xi2mask_isset(mask, dev, event_type))
        return event_get_filter_from_xi2type(event_type);
    else
        return 0;
}

/**
 * @return TRUE if the mask is set for this event from this device on the
 * window, or FALSE otherwise.
 */
Bool
WindowXI2MaskIsset(DeviceIntPtr dev, WindowPtr win, xEvent *ev)
{
    OtherInputMasks *inputMasks = wOtherInputMasks(win);
    int evtype;

    if (!inputMasks || xi2_get_type(ev) == 0)
        return 0;

    evtype = ((xGenericEvent *) ev)->evtype;

    return xi2mask_isset(inputMasks->xi2mask, dev, evtype);
}

Mask
GetEventMask(DeviceIntPtr dev, xEvent *event, InputClients * other)
{
    int evtype;

    /* XI2 filters are only ever 8 bit, so let's return a 8 bit mask */
    if ((evtype = xi2_get_type(event))) {
        return GetXI2MaskByte(other->xi2mask, dev, evtype);
    }
    else if (core_get_type(event) != 0)
        return other->mask[XIAllDevices];
    else
        return other->mask[dev->id];
}

static CARD8 criticalEvents[32] = {
    0x7c, 0x30, 0x40            /* key, button, expose, and configure events */
};

static void
SyntheticMotion(DeviceIntPtr dev, int x, int y)
{
    int screenno = 0;

#ifdef PANORAMIX
    if (!noPanoramiXExtension)
        screenno = dev->spriteInfo->sprite->screen->myNum;
#endif
    PostSyntheticMotion(dev, x, y, screenno,
                        (syncEvents.playingEvents) ? syncEvents.time.
                        milliseconds : currentTime.milliseconds);

}

#ifdef PANORAMIX
static void PostNewCursor(DeviceIntPtr pDev);

static Bool
XineramaSetCursorPosition(DeviceIntPtr pDev, int x, int y, Bool generateEvent)
{
    ScreenPtr pScreen;
    int i;
    SpritePtr pSprite = pDev->spriteInfo->sprite;

    /* x,y are in Screen 0 coordinates.  We need to decide what Screen
       to send the message too and what the coordinates relative to
       that screen are. */

    pScreen = pSprite->screen;
    x += screenInfo.screens[0]->x;
    y += screenInfo.screens[0]->y;

    if (!point_on_screen(pScreen, x, y)) {
        FOR_NSCREENS(i) {
            if (i == pScreen->myNum)
                continue;
            if (point_on_screen(screenInfo.screens[i], x, y)) {
                pScreen = screenInfo.screens[i];
                break;
            }
        }
    }

    pSprite->screen = pScreen;
    pSprite->hotPhys.x = x - screenInfo.screens[0]->x;
    pSprite->hotPhys.y = y - screenInfo.screens[0]->y;
    x -= pScreen->x;
    y -= pScreen->y;

    return (*pScreen->SetCursorPosition) (pDev, pScreen, x, y, generateEvent);
}

static void
XineramaConstrainCursor(DeviceIntPtr pDev)
{
    SpritePtr pSprite = pDev->spriteInfo->sprite;
    ScreenPtr pScreen;
    BoxRec newBox;

    pScreen = pSprite->screen;
    newBox = pSprite->physLimits;

    /* Translate the constraining box to the screen
       the sprite is actually on */
    newBox.x1 += screenInfo.screens[0]->x - pScreen->x;
    newBox.x2 += screenInfo.screens[0]->x - pScreen->x;
    newBox.y1 += screenInfo.screens[0]->y - pScreen->y;
    newBox.y2 += screenInfo.screens[0]->y - pScreen->y;

    (*pScreen->ConstrainCursor) (pDev, pScreen, &newBox);
}

static Bool
XineramaSetWindowPntrs(DeviceIntPtr pDev, WindowPtr pWin)
{
    SpritePtr pSprite = pDev->spriteInfo->sprite;

    if (pWin == screenInfo.screens[0]->root) {
        int i;

        FOR_NSCREENS(i)
            pSprite->windows[i] = screenInfo.screens[i]->root;
    }
    else {
        PanoramiXRes *win;
        int rc, i;

        rc = dixLookupResourceByType((void **) &win, pWin->drawable.id,
                                     XRT_WINDOW, serverClient, DixReadAccess);
        if (rc != Success)
            return FALSE;

        FOR_NSCREENS(i) {
            rc = dixLookupWindow(pSprite->windows + i, win->info[i].id,
                                 serverClient, DixReadAccess);
            if (rc != Success)  /* window is being unmapped */
                return FALSE;
        }
    }
    return TRUE;
}

static void
XineramaConfineCursorToWindow(DeviceIntPtr pDev,
                              WindowPtr pWin, Bool generateEvents)
{
    SpritePtr pSprite = pDev->spriteInfo->sprite;

    int x, y, off_x, off_y, i;

    if (!XineramaSetWindowPntrs(pDev, pWin))
        return;

    i = PanoramiXNumScreens - 1;

    RegionCopy(&pSprite->Reg1, &pSprite->windows[i]->borderSize);
    off_x = screenInfo.screens[i]->x;
    off_y = screenInfo.screens[i]->y;

    while (i--) {
        x = off_x - screenInfo.screens[i]->x;
        y = off_y - screenInfo.screens[i]->y;

        if (x || y)
            RegionTranslate(&pSprite->Reg1, x, y);

        RegionUnion(&pSprite->Reg1, &pSprite->Reg1,
                    &pSprite->windows[i]->borderSize);

        off_x = screenInfo.screens[i]->x;
        off_y = screenInfo.screens[i]->y;
    }

    pSprite->hotLimits = *RegionExtents(&pSprite->Reg1);

    if (RegionNumRects(&pSprite->Reg1) > 1)
        pSprite->hotShape = &pSprite->Reg1;
    else
        pSprite->hotShape = NullRegion;

    pSprite->confined = FALSE;
    pSprite->confineWin =
        (pWin == screenInfo.screens[0]->root) ? NullWindow : pWin;

    CheckPhysLimits(pDev, pSprite->current, generateEvents, FALSE, NULL);
}

#endif                          /* PANORAMIX */

/**
 * Modifies the filter for the given protocol event type to the given masks.
 *
 * There's only two callers: UpdateDeviceState() and XI's SetMaskForExtEvent().
 * The latter initialises masks for the matching XI events, it's a once-off
 * setting.
 * UDS however changes the mask for MotionNotify and DeviceMotionNotify each
 * time a button is pressed to include the matching ButtonXMotion mask in the
 * filter.
 *
 * @param[in] deviceid The device to modify the filter for.
 * @param[in] mask The new filter mask.
 * @param[in] event Protocol event type.
 */
void
SetMaskForEvent(int deviceid, Mask mask, int event)
{
    if (deviceid < 0 || deviceid >= MAXDEVICES)
        FatalError("SetMaskForEvent: bogus device id");
    event_filters[deviceid][event] = mask;
}

void
SetCriticalEvent(int event)
{
    if (event >= MAXEVENTS)
        FatalError("SetCriticalEvent: bogus event number");
    criticalEvents[event >> 3] |= 1 << (event & 7);
}

void
ConfineToShape(DeviceIntPtr pDev, RegionPtr shape, int *px, int *py)
{
    BoxRec box;
    int x = *px, y = *py;
    int incx = 1, incy = 1;

    if (RegionContainsPoint(shape, x, y, &box))
        return;
    box = *RegionExtents(shape);
    /* this is rather crude */
    do {
        x += incx;
        if (x >= box.x2) {
            incx = -1;
            x = *px - 1;
        }
        else if (x < box.x1) {
            incx = 1;
            x = *px;
            y += incy;
            if (y >= box.y2) {
                incy = -1;
                y = *py - 1;
            }
            else if (y < box.y1)
                return;         /* should never get here! */
        }
    } while (!RegionContainsPoint(shape, x, y, &box));
    *px = x;
    *py = y;
}

static void
CheckPhysLimits(DeviceIntPtr pDev, CursorPtr cursor, Bool generateEvents,
                Bool confineToScreen, /* unused if PanoramiX on */
                ScreenPtr pScreen)    /* unused if PanoramiX on */
{
    HotSpot new;
    SpritePtr pSprite = pDev->spriteInfo->sprite;

    if (!cursor)
        return;
    new = pSprite->hotPhys;
#ifdef PANORAMIX
    if (!noPanoramiXExtension)
        /* I don't care what the DDX has to say about it */
        pSprite->physLimits = pSprite->hotLimits;
    else
#endif
    {
        if (pScreen)
            new.pScreen = pScreen;
        else
            pScreen = new.pScreen;
        (*pScreen->CursorLimits) (pDev, pScreen, cursor, &pSprite->hotLimits,
                                  &pSprite->physLimits);
        pSprite->confined = confineToScreen;
        (*pScreen->ConstrainCursor) (pDev, pScreen, &pSprite->physLimits);
    }

    /* constrain the pointer to those limits */
    if (new.x < pSprite->physLimits.x1)
        new.x = pSprite->physLimits.x1;
    else if (new.x >= pSprite->physLimits.x2)
        new.x = pSprite->physLimits.x2 - 1;
    if (new.y < pSprite->physLimits.y1)
        new.y = pSprite->physLimits.y1;
    else if (new.y >= pSprite->physLimits.y2)
        new.y = pSprite->physLimits.y2 - 1;
    if (pSprite->hotShape)
        ConfineToShape(pDev, pSprite->hotShape, &new.x, &new.y);
    if ((
#ifdef PANORAMIX
            noPanoramiXExtension &&
#endif
            (pScreen != pSprite->hotPhys.pScreen)) ||
        (new.x != pSprite->hotPhys.x) || (new.y != pSprite->hotPhys.y)) {
#ifdef PANORAMIX
        if (!noPanoramiXExtension)
        {
            if (pScreen && ((new.x != pSprite->hotPhys.x) || (new.y != pSprite->hotPhys.y)))
                XineramaSetCursorPosition(pDev, new.x, new.y, generateEvents);
        }
        else
#endif
        {
            if (pScreen != pSprite->hotPhys.pScreen)
                pSprite->hotPhys = new;
            (*pScreen->SetCursorPosition)
                (pDev, pScreen, new.x, new.y, generateEvents);
        }
        if (!generateEvents)
            SyntheticMotion(pDev, new.x, new.y);
    }

#ifdef PANORAMIX
    /* Tell DDX what the limits are */
    if (!noPanoramiXExtension)
        XineramaConstrainCursor(pDev);
#endif
}

static void
CheckVirtualMotion(DeviceIntPtr pDev, QdEventPtr qe, WindowPtr pWin)
{
    SpritePtr pSprite = pDev->spriteInfo->sprite;
    RegionPtr reg = NULL;
    DeviceEvent *ev = NULL;

    if (qe) {
        ev = &qe->event->device_event;
        switch (ev->type) {
        case ET_Motion:
        case ET_ButtonPress:
        case ET_ButtonRelease:
        case ET_KeyPress:
        case ET_KeyRelease:
        case ET_ProximityIn:
        case ET_ProximityOut:
            pSprite->hot.pScreen = qe->pScreen;
            pSprite->hot.x = ev->root_x;
            pSprite->hot.y = ev->root_y;
            pWin =
                pDev->deviceGrab.grab ? pDev->deviceGrab.grab->
                confineTo : NullWindow;
            break;
        default:
            break;
        }
    }
    if (pWin) {
        BoxRec lims;

#ifdef PANORAMIX
        if (!noPanoramiXExtension) {
            int x, y, off_x, off_y, i;

            if (!XineramaSetWindowPntrs(pDev, pWin))
                return;

            i = PanoramiXNumScreens - 1;

            RegionCopy(&pSprite->Reg2, &pSprite->windows[i]->borderSize);
            off_x = screenInfo.screens[i]->x;
            off_y = screenInfo.screens[i]->y;

            while (i--) {
                x = off_x - screenInfo.screens[i]->x;
                y = off_y - screenInfo.screens[i]->y;

                if (x || y)
                    RegionTranslate(&pSprite->Reg2, x, y);

                RegionUnion(&pSprite->Reg2, &pSprite->Reg2,
                            &pSprite->windows[i]->borderSize);

                off_x = screenInfo.screens[i]->x;
                off_y = screenInfo.screens[i]->y;
            }
        }
        else
#endif
        {
            if (pSprite->hot.pScreen != pWin->drawable.pScreen) {
                pSprite->hot.pScreen = pWin->drawable.pScreen;
                pSprite->hot.x = pSprite->hot.y = 0;
            }
        }

        lims = *RegionExtents(&pWin->borderSize);
        if (pSprite->hot.x < lims.x1)
            pSprite->hot.x = lims.x1;
        else if (pSprite->hot.x >= lims.x2)
            pSprite->hot.x = lims.x2 - 1;
        if (pSprite->hot.y < lims.y1)
            pSprite->hot.y = lims.y1;
        else if (pSprite->hot.y >= lims.y2)
            pSprite->hot.y = lims.y2 - 1;

#ifdef PANORAMIX
        if (!noPanoramiXExtension) {
            if (RegionNumRects(&pSprite->Reg2) > 1)
                reg = &pSprite->Reg2;

        }
        else
#endif
        {
            if (wBoundingShape(pWin))
                reg = &pWin->borderSize;
        }

        if (reg)
            ConfineToShape(pDev, reg, &pSprite->hot.x, &pSprite->hot.y);

        if (qe && ev) {
            qe->pScreen = pSprite->hot.pScreen;
            ev->root_x = pSprite->hot.x;
            ev->root_y = pSprite->hot.y;
        }
    }
#ifdef PANORAMIX
    if (noPanoramiXExtension)   /* No typo. Only set the root win if disabled */
#endif
        RootWindow(pDev->spriteInfo->sprite) = pSprite->hot.pScreen->root;
}

static void
ConfineCursorToWindow(DeviceIntPtr pDev, WindowPtr pWin, Bool generateEvents,
                      Bool confineToScreen)
{
    SpritePtr pSprite = pDev->spriteInfo->sprite;

    if (syncEvents.playingEvents) {
        CheckVirtualMotion(pDev, (QdEventPtr) NULL, pWin);
        SyntheticMotion(pDev, pSprite->hot.x, pSprite->hot.y);
    }
    else {
#ifdef PANORAMIX
        if (!noPanoramiXExtension) {
            XineramaConfineCursorToWindow(pDev, pWin, generateEvents);
            return;
        }
#endif
        pSprite->hotLimits = *RegionExtents(&pWin->borderSize);
        pSprite->hotShape = wBoundingShape(pWin) ? &pWin->borderSize
            : NullRegion;
        CheckPhysLimits(pDev, pSprite->current, generateEvents,
                        confineToScreen, pWin->drawable.pScreen);
    }
}

Bool
PointerConfinedToScreen(DeviceIntPtr pDev)
{
    return pDev->spriteInfo->sprite->confined;
}

/**
 * Update the sprite cursor to the given cursor.
 *
 * ChangeToCursor() will display the new cursor and free the old cursor (if
 * applicable). If the provided cursor is already the updated cursor, nothing
 * happens.
 */
static void
ChangeToCursor(DeviceIntPtr pDev, CursorPtr cursor)
{
    SpritePtr pSprite = pDev->spriteInfo->sprite;
    ScreenPtr pScreen;

    if (cursor != pSprite->current) {
        if ((pSprite->current->bits->xhot != cursor->bits->xhot) ||
            (pSprite->current->bits->yhot != cursor->bits->yhot))
            CheckPhysLimits(pDev, cursor, FALSE, pSprite->confined,
                            (ScreenPtr) NULL);
#ifdef PANORAMIX
        /* XXX: is this really necessary?? (whot) */
        if (!noPanoramiXExtension)
            pScreen = pSprite->screen;
        else
#endif
            pScreen = pSprite->hotPhys.pScreen;

        (*pScreen->DisplayCursor) (pDev, pScreen, cursor);
        FreeCursor(pSprite->current, (Cursor) 0);
        pSprite->current = RefCursor(cursor);
    }
}

/**
 * @returns true if b is a descendent of a
 */
Bool
IsParent(WindowPtr a, WindowPtr b)
{
    for (b = b->parent; b; b = b->parent)
        if (b == a)
            return TRUE;
    return FALSE;
}

/**
 * Update the cursor displayed on the screen.
 *
 * Called whenever a cursor may have changed shape or position.
 */
static void
PostNewCursor(DeviceIntPtr pDev)
{
    WindowPtr win;
    GrabPtr grab = pDev->deviceGrab.grab;
    SpritePtr pSprite = pDev->spriteInfo->sprite;
    CursorPtr pCursor;

    if (syncEvents.playingEvents)
        return;
    if (grab) {
        if (grab->cursor) {
            ChangeToCursor(pDev, grab->cursor);
            return;
        }
        if (IsParent(grab->window, pSprite->win))
            win = pSprite->win;
        else
            win = grab->window;
    }
    else
        win = pSprite->win;
    for (; win; win = win->parent) {
        if (win->optional) {
            pCursor = WindowGetDeviceCursor(win, pDev);
            if (!pCursor && win->optional->cursor != NullCursor)
                pCursor = win->optional->cursor;
            if (pCursor) {
                ChangeToCursor(pDev, pCursor);
                return;
            }
        }
    }
}

/**
 * @param dev device which you want to know its current root window
 * @return root window where dev's sprite is located
 */
WindowPtr
GetCurrentRootWindow(DeviceIntPtr dev)
{
    return RootWindow(dev->spriteInfo->sprite);
}

/**
 * @return window underneath the cursor sprite.
 */
WindowPtr
GetSpriteWindow(DeviceIntPtr pDev)
{
    return pDev->spriteInfo->sprite->win;
}

/**
 * @return current sprite cursor.
 */
CursorPtr
GetSpriteCursor(DeviceIntPtr pDev)
{
    return pDev->spriteInfo->sprite->current;
}

/**
 * Set x/y current sprite position in screen coordinates.
 */
void
GetSpritePosition(DeviceIntPtr pDev, int *px, int *py)
{
    SpritePtr pSprite = pDev->spriteInfo->sprite;

    *px = pSprite->hotPhys.x;
    *py = pSprite->hotPhys.y;
}

#ifdef PANORAMIX
int
XineramaGetCursorScreen(DeviceIntPtr pDev)
{
    if (!noPanoramiXExtension) {
        return pDev->spriteInfo->sprite->screen->myNum;
    }
    else {
        return 0;
    }
}
#endif                          /* PANORAMIX */

#define TIMESLOP (5 * 60 * 1000)        /* 5 minutes */

static void
MonthChangedOrBadTime(CARD32 *ms)
{
    /* If the ddx/OS is careless about not processing timestamped events from
     * different sources in sorted order, then it's possible for time to go
     * backwards when it should not.  Here we ensure a decent time.
     */
    if ((currentTime.milliseconds - *ms) > TIMESLOP)
        currentTime.months++;
    else
        *ms = currentTime.milliseconds;
}

void
NoticeTime(const DeviceIntPtr dev, TimeStamp time)
{
    lastDeviceEventTime[XIAllDevices].time = currentTime;
    lastDeviceEventTime[dev->id].time = currentTime;

    LastEventTimeToggleResetFlag(dev->id, TRUE);
    LastEventTimeToggleResetFlag(XIAllDevices, TRUE);
}

static void
NoticeTimeMillis(const DeviceIntPtr dev, CARD32 *ms)
{
    TimeStamp time;
    if (*ms < currentTime.milliseconds)
        MonthChangedOrBadTime(ms);
    time.months = currentTime.months;
    time.milliseconds = *ms;
    NoticeTime(dev, time);
}

void
NoticeEventTime(InternalEvent *ev, DeviceIntPtr dev)
{
    if (!syncEvents.playingEvents)
        NoticeTimeMillis(dev, &ev->any.time);
}

TimeStamp
LastEventTime(int deviceid)
{
    return lastDeviceEventTime[deviceid].time;
}

Bool
LastEventTimeWasReset(int deviceid)
{
    return lastDeviceEventTime[deviceid].reset;
}

void
LastEventTimeToggleResetFlag(int deviceid, Bool state)
{
    lastDeviceEventTime[deviceid].reset = state;
}

void
LastEventTimeToggleResetAll(Bool state)
{
    DeviceIntPtr dev;
    nt_list_for_each_entry(dev, inputInfo.devices, next) {
        LastEventTimeToggleResetFlag(dev->id, FALSE);
    }
    LastEventTimeToggleResetFlag(XIAllDevices, FALSE);
    LastEventTimeToggleResetFlag(XIAllMasterDevices, FALSE);
}

/**************************************************************************
 *            The following procedures deal with synchronous events       *
 **************************************************************************/

/**
 * EnqueueEvent is a device's processInputProc if a device is frozen.
 * Instead of delivering the events to the client, the event is tacked onto a
 * linked list for later delivery.
 */
void
EnqueueEvent(InternalEvent *ev, DeviceIntPtr device)
{
    QdEventPtr tail = NULL;
    QdEventPtr qe;
    SpritePtr pSprite = device->spriteInfo->sprite;
    int eventlen;
    DeviceEvent *event = &ev->device_event;

    if (!xorg_list_is_empty(&syncEvents.pending))
        tail = xorg_list_last_entry(&syncEvents.pending, QdEventRec, next);

    NoticeTimeMillis(device, &ev->any.time);

    /* Fix for key repeating bug. */
    if (device->key != NULL && device->key->xkbInfo != NULL &&
        event->type == ET_KeyRelease)
        AccessXCancelRepeatKey(device->key->xkbInfo, event->detail.key);

    if (DeviceEventCallback) {
        DeviceEventInfoRec eventinfo;

        /*  The RECORD spec says that the root window field of motion events
         *  must be valid.  At this point, it hasn't been filled in yet, so
         *  we do it here.  The long expression below is necessary to get
         *  the current root window; the apparently reasonable alternative
         *  GetCurrentRootWindow()->drawable.id doesn't give you the right
         *  answer on the first motion event after a screen change because
         *  the data that GetCurrentRootWindow relies on hasn't been
         *  updated yet.
         */
        if (ev->any.type == ET_Motion)
            ev->device_event.root = pSprite->hotPhys.pScreen->root->drawable.id;

        eventinfo.event = ev;
        eventinfo.device = device;
        CallCallbacks(&DeviceEventCallback, (void *) &eventinfo);
    }

    if (event->type == ET_Motion) {
#ifdef PANORAMIX
        if (!noPanoramiXExtension) {
            event->root_x += pSprite->screen->x - screenInfo.screens[0]->x;
            event->root_y += pSprite->screen->y - screenInfo.screens[0]->y;
        }
#endif
        pSprite->hotPhys.x = event->root_x;
        pSprite->hotPhys.y = event->root_y;
        /* do motion compression, but not if from different devices */
        if (tail &&
            (tail->event->any.type == ET_Motion) &&
            (tail->device == device) &&
            (tail->pScreen == pSprite->hotPhys.pScreen)) {
            DeviceEvent *tailev = &tail->event->device_event;

            tailev->root_x = pSprite->hotPhys.x;
            tailev->root_y = pSprite->hotPhys.y;
            tailev->time = event->time;
            tail->months = currentTime.months;
            return;
        }
    }

    eventlen = event->length;

    qe = malloc(sizeof(QdEventRec) + eventlen);
    if (!qe)
        return;
    xorg_list_init(&qe->next);
    qe->device = device;
    qe->pScreen = pSprite->hotPhys.pScreen;
    qe->months = currentTime.months;
    qe->event = (InternalEvent *) (qe + 1);
    memcpy(qe->event, event, eventlen);
    xorg_list_append(&qe->next, &syncEvents.pending);
}

/**
 * Run through the list of events queued up in syncEvents.
 * For each event do:
 * If the device for this event is not frozen anymore, take it and process it
 * as usually.
 * After that, check if there's any devices in the list that are not frozen.
 * If there is none, we're done. If there is at least one device that is not
 * frozen, then re-run from the beginning of the event queue.
 */
void
PlayReleasedEvents(void)
{
    QdEventPtr tmp;
    QdEventPtr qe=NULL;
    DeviceIntPtr dev;
    DeviceIntPtr pDev;

 restart:
    xorg_list_for_each_entry_safe(qe, tmp, &syncEvents.pending, next) {
        if (!qe->device->deviceGrab.sync.frozen) {
            xorg_list_del(&qe->next);
            pDev = qe->device;
            if (qe->event->any.type == ET_Motion)
                CheckVirtualMotion(pDev, qe, NullWindow);
            syncEvents.time.months = qe->months;
            syncEvents.time.milliseconds = qe->event->any.time;
#ifdef PANORAMIX
            /* Translate back to the sprite screen since processInputProc
               will translate from sprite screen to screen 0 upon reentry
               to the DIX layer */
            if (!noPanoramiXExtension) {
                DeviceEvent *ev = &qe->event->device_event;

                switch (ev->type) {
                case ET_Motion:
                case ET_ButtonPress:
                case ET_ButtonRelease:
                case ET_KeyPress:
                case ET_KeyRelease:
                case ET_ProximityIn:
                case ET_ProximityOut:
                case ET_TouchBegin:
                case ET_TouchUpdate:
                case ET_TouchEnd:
                    ev->root_x += screenInfo.screens[0]->x -
                        pDev->spriteInfo->sprite->screen->x;
                    ev->root_y += screenInfo.screens[0]->y -
                        pDev->spriteInfo->sprite->screen->y;
                    break;
                default:
                    break;
                }

            }
#endif
            (*qe->device->public.processInputProc) (qe->event, qe->device);
            free(qe);
            for (dev = inputInfo.devices; dev && dev->deviceGrab.sync.frozen;
                 dev = dev->next);
            if (!dev)
                break;

            /* Playing the event may have unfrozen another device. */
            /* So to play it safe, restart at the head of the queue */
            goto restart;
        }
    }
}

/**
 * Freeze or thaw the given devices. The device's processing proc is
 * switched to either the real processing proc (in case of thawing) or an
 * enqueuing processing proc (usually EnqueueEvent()).
 *
 * @param dev The device to freeze/thaw
 * @param frozen True to freeze or false to thaw.
 */
static void
FreezeThaw(DeviceIntPtr dev, Bool frozen)
{
    dev->deviceGrab.sync.frozen = frozen;
    if (frozen)
        dev->public.processInputProc = dev->public.enqueueInputProc;
    else
        dev->public.processInputProc = dev->public.realInputProc;
}

/**
 * Unfreeze devices and replay all events to the respective clients.
 *
 * ComputeFreezes takes the first event in the device's frozen event queue. It
 * runs up the sprite tree (spriteTrace) and searches for the window to replay
 * the events from. If it is found, it checks for passive grabs one down from
 * the window or delivers the events.
 */
static void
ComputeFreezes(void)
{
    DeviceIntPtr replayDev = syncEvents.replayDev;
    WindowPtr w;
    GrabPtr grab;
    DeviceIntPtr dev;

    for (dev = inputInfo.devices; dev; dev = dev->next)
        FreezeThaw(dev, dev->deviceGrab.sync.other ||
                   (dev->deviceGrab.sync.state >= FROZEN));
    if (syncEvents.playingEvents ||
        (!replayDev && xorg_list_is_empty(&syncEvents.pending)))
        return;
    syncEvents.playingEvents = TRUE;
    if (replayDev) {
        DeviceEvent *event = replayDev->deviceGrab.sync.event;

        syncEvents.replayDev = (DeviceIntPtr) NULL;

        w = XYToWindow(replayDev->spriteInfo->sprite,
                       event->root_x, event->root_y);
        if (!CheckDeviceGrabs(replayDev, event, syncEvents.replayWin)) {
            if (IsTouchEvent((InternalEvent *) event)) {
                TouchPointInfoPtr ti =
                    TouchFindByClientID(replayDev, event->touchid);
                BUG_WARN(!ti);

                TouchListenerAcceptReject(replayDev, ti, 0, XIRejectTouch);
            }
            else if (replayDev->focus &&
                     !IsPointerEvent((InternalEvent *) event))
                DeliverFocusedEvent(replayDev, (InternalEvent *) event, w);
            else
                DeliverDeviceEvents(w, (InternalEvent *) event, NullGrab,
                                    NullWindow, replayDev);
        }
    }
    for (dev = inputInfo.devices; dev; dev = dev->next) {
        if (!dev->deviceGrab.sync.frozen) {
            PlayReleasedEvents();
            break;
        }
    }
    syncEvents.playingEvents = FALSE;
    for (dev = inputInfo.devices; dev; dev = dev->next) {
        if (DevHasCursor(dev)) {
            /* the following may have been skipped during replay,
               so do it now */
            if ((grab = dev->deviceGrab.grab) && grab->confineTo) {
                if (grab->confineTo->drawable.pScreen !=
                    dev->spriteInfo->sprite->hotPhys.pScreen)
                    dev->spriteInfo->sprite->hotPhys.x =
                        dev->spriteInfo->sprite->hotPhys.y = 0;
                ConfineCursorToWindow(dev, grab->confineTo, TRUE, TRUE);
            }
            else
                ConfineCursorToWindow(dev,
                                      dev->spriteInfo->sprite->hotPhys.pScreen->
                                      root, TRUE, FALSE);
            PostNewCursor(dev);
        }
    }
}

#ifdef RANDR
void
ScreenRestructured(ScreenPtr pScreen)
{
    GrabPtr grab;
    DeviceIntPtr pDev;

    for (pDev = inputInfo.devices; pDev; pDev = pDev->next) {
        if (!IsFloating(pDev) && !DevHasCursor(pDev))
            continue;

        /* GrabDevice doesn't have a confineTo field, so we don't need to
         * worry about it. */
        if ((grab = pDev->deviceGrab.grab) && grab->confineTo) {
            if (grab->confineTo->drawable.pScreen
                != pDev->spriteInfo->sprite->hotPhys.pScreen)
                pDev->spriteInfo->sprite->hotPhys.x =
                    pDev->spriteInfo->sprite->hotPhys.y = 0;
            ConfineCursorToWindow(pDev, grab->confineTo, TRUE, TRUE);
        }
        else
            ConfineCursorToWindow(pDev,
                                  pDev->spriteInfo->sprite->hotPhys.pScreen->
                                  root, TRUE, FALSE);
    }
}
#endif

static void
CheckGrabForSyncs(DeviceIntPtr thisDev, Bool thisMode, Bool otherMode)
{
    GrabPtr grab = thisDev->deviceGrab.grab;
    DeviceIntPtr dev;

    if (thisMode == GrabModeSync)
        thisDev->deviceGrab.sync.state = FROZEN_NO_EVENT;
    else {                      /* free both if same client owns both */
        thisDev->deviceGrab.sync.state = THAWED;
        if (thisDev->deviceGrab.sync.other &&
            (CLIENT_BITS(thisDev->deviceGrab.sync.other->resource) ==
             CLIENT_BITS(grab->resource)))
            thisDev->deviceGrab.sync.other = NullGrab;
    }

    if (IsMaster(thisDev)) {
        dev = GetPairedDevice(thisDev);
        if (otherMode == GrabModeSync)
            dev->deviceGrab.sync.other = grab;
        else {                  /* free both if same client owns both */
            if (dev->deviceGrab.sync.other &&
                (CLIENT_BITS(dev->deviceGrab.sync.other->resource) ==
                 CLIENT_BITS(grab->resource)))
                dev->deviceGrab.sync.other = NullGrab;
        }
    }
    ComputeFreezes();
}

/**
 * Save the device's master device id. This needs to be done
 * if a client directly grabs a slave device that is attached to a master. For
 * the duration of the grab, the device is detached, ungrabbing re-attaches it
 * though.
 *
 * We store the ID of the master device only in case the master disappears
 * while the device has a grab.
 */
static void
DetachFromMaster(DeviceIntPtr dev)
{
    if (IsFloating(dev))
        return;

    dev->saved_master_id = GetMaster(dev, MASTER_ATTACHED)->id;

    AttachDevice(NULL, dev, NULL);
}

static void
ReattachToOldMaster(DeviceIntPtr dev)
{
    DeviceIntPtr master = NULL;

    if (IsMaster(dev))
        return;

    dixLookupDevice(&master, dev->saved_master_id, serverClient, DixUseAccess);

    if (master) {
        AttachDevice(serverClient, dev, master);
        dev->saved_master_id = 0;
    }
}

/**
 * Update touch records when an explicit grab is activated. Any touches owned by
 * the grabbing client are updated so the listener state reflects the new grab.
 */
static void
UpdateTouchesForGrab(DeviceIntPtr mouse)
{
    int i;

    if (!mouse->touch || mouse->deviceGrab.fromPassiveGrab)
        return;

    for (i = 0; i < mouse->touch->num_touches; i++) {
        TouchPointInfoPtr ti = mouse->touch->touches + i;
        TouchListener *listener = &ti->listeners[0];
        GrabPtr grab = mouse->deviceGrab.grab;

        if (ti->active &&
            CLIENT_BITS(listener->listener) == grab->resource) {
            listener->listener = grab->resource;
            listener->level = grab->grabtype;
            listener->state = LISTENER_IS_OWNER;
            listener->window = grab->window;

            if (grab->grabtype == CORE || grab->grabtype == XI ||
                !xi2mask_isset(grab->xi2mask, mouse, XI_TouchBegin))
                listener->type = LISTENER_POINTER_GRAB;
            else
                listener->type = LISTENER_GRAB;
            if (listener->grab)
                FreeGrab(listener->grab);
            listener->grab = AllocGrab(grab);
        }
    }
}

/**
 * Activate a pointer grab on the given device. A pointer grab will cause all
 * core pointer events of this device to be delivered to the grabbing client only.
 * No other device will send core events to the grab client while the grab is
 * on, but core events will be sent to other clients.
 * Can cause the cursor to change if a grab cursor is set.
 *
 * Note that parameter autoGrab may be (True & ImplicitGrabMask) if the grab
 * is an implicit grab caused by a ButtonPress event.
 *
 * @param mouse The device to grab.
 * @param grab The grab structure, needs to be setup.
 * @param autoGrab True if the grab was caused by a button down event and not
 * explicitely by a client.
 */
void
ActivatePointerGrab(DeviceIntPtr mouse, GrabPtr grab,
                    TimeStamp time, Bool autoGrab)
{
    GrabInfoPtr grabinfo = &mouse->deviceGrab;
    GrabPtr oldgrab = grabinfo->grab;
    WindowPtr oldWin = (grabinfo->grab) ?
        grabinfo->grab->window : mouse->spriteInfo->sprite->win;
    Bool isPassive = autoGrab & ~ImplicitGrabMask;

    /* slave devices need to float for the duration of the grab. */
    if (grab->grabtype == XI2 &&
        !(autoGrab & ImplicitGrabMask) && !IsMaster(mouse))
        DetachFromMaster(mouse);

    if (grab->confineTo) {
        if (grab->confineTo->drawable.pScreen
            != mouse->spriteInfo->sprite->hotPhys.pScreen)
            mouse->spriteInfo->sprite->hotPhys.x =
                mouse->spriteInfo->sprite->hotPhys.y = 0;
        ConfineCursorToWindow(mouse, grab->confineTo, FALSE, TRUE);
    }
    DoEnterLeaveEvents(mouse, mouse->id, oldWin, grab->window, NotifyGrab);
    mouse->valuator->motionHintWindow = NullWindow;
    if (syncEvents.playingEvents)
        grabinfo->grabTime = syncEvents.time;
    else
        grabinfo->grabTime = time;
    grabinfo->grab = AllocGrab(grab);
    grabinfo->fromPassiveGrab = isPassive;
    grabinfo->implicitGrab = autoGrab & ImplicitGrabMask;
    PostNewCursor(mouse);
    UpdateTouchesForGrab(mouse);
    CheckGrabForSyncs(mouse, (Bool) grab->pointerMode,
                      (Bool) grab->keyboardMode);
    if (oldgrab)
        FreeGrab(oldgrab);
}

/**
 * Delete grab on given device, update the sprite.
 *
 * Extension devices are set up for ActivateKeyboardGrab().
 */
void
DeactivatePointerGrab(DeviceIntPtr mouse)
{
    GrabPtr grab = mouse->deviceGrab.grab;
    DeviceIntPtr dev=mouse;
    Bool wasPassive = mouse->deviceGrab.fromPassiveGrab;
    Bool wasImplicit = (mouse->deviceGrab.fromPassiveGrab &&
                        mouse->deviceGrab.implicitGrab);
    XID grab_resource = grab->resource;
    int i;

    /* If an explicit grab was deactivated, we must remove it from the head of
     * all the touches' listener lists. */
    for (i = 0; !wasPassive && mouse->touch && i < mouse->touch->num_touches; i++) {
        TouchPointInfoPtr ti = mouse->touch->touches + i;
        if (ti->active && TouchResourceIsOwner(ti, grab_resource)) {
            int mode = XIRejectTouch;
            /* Rejecting will generate a TouchEnd, but we must not
               emulate a ButtonRelease here. So pretend the listener
               already has the end event */
            if (grab->grabtype == CORE || grab->grabtype == XI ||
                    !xi2mask_isset(mouse->deviceGrab.grab->xi2mask, mouse, XI_TouchBegin)) {
                mode = XIAcceptTouch;
                /* NOTE: we set the state here, but
                 * ProcessTouchOwnershipEvent() will still call
                 * TouchEmitTouchEnd for this listener. The other half of
                 * this hack is in DeliverTouchEndEvent */
                ti->listeners[0].state = LISTENER_HAS_END;
            }
            TouchListenerAcceptReject(mouse, ti, 0, mode);
        }
    }

    TouchRemovePointerGrab(mouse);

    mouse->valuator->motionHintWindow = NullWindow;
    mouse->deviceGrab.grab = NullGrab;
    mouse->deviceGrab.sync.state = NOT_GRABBED;
    mouse->deviceGrab.fromPassiveGrab = FALSE;

    for (dev = inputInfo.devices; dev; dev = dev->next) {
        if (dev->deviceGrab.sync.other == grab)
            dev->deviceGrab.sync.other = NullGrab;
    }
    DoEnterLeaveEvents(mouse, mouse->id, grab->window,
                       mouse->spriteInfo->sprite->win, NotifyUngrab);
    if (grab->confineTo)
        ConfineCursorToWindow(mouse, GetCurrentRootWindow(mouse), FALSE, FALSE);
    PostNewCursor(mouse);

    if (!wasImplicit && grab->grabtype == XI2)
        ReattachToOldMaster(mouse);

    ComputeFreezes();

    FreeGrab(grab);
}

/**
 * Activate a keyboard grab on the given device.
 *
 * Extension devices have ActivateKeyboardGrab() set as their grabbing proc.
 */
void
ActivateKeyboardGrab(DeviceIntPtr keybd, GrabPtr grab, TimeStamp time,
                     Bool passive)
{
    GrabInfoPtr grabinfo = &keybd->deviceGrab;
    GrabPtr oldgrab = grabinfo->grab;
    WindowPtr oldWin;

    /* slave devices need to float for the duration of the grab. */
    if (grab->grabtype == XI2 && keybd->enabled &&
        !(passive & ImplicitGrabMask) && !IsMaster(keybd))
        DetachFromMaster(keybd);

    if (!keybd->enabled)
        oldWin = NULL;
    else if (grabinfo->grab)
        oldWin = grabinfo->grab->window;
    else if (keybd->focus)
        oldWin = keybd->focus->win;
    else
        oldWin = keybd->spriteInfo->sprite->win;
    if (oldWin == FollowKeyboardWin)
        oldWin = keybd->focus->win;
    if (keybd->valuator)
        keybd->valuator->motionHintWindow = NullWindow;
    if (oldWin)
        DoFocusEvents(keybd, oldWin, grab->window, NotifyGrab);
    if (syncEvents.playingEvents)
        grabinfo->grabTime = syncEvents.time;
    else
        grabinfo->grabTime = time;
    grabinfo->grab = AllocGrab(grab);
    grabinfo->fromPassiveGrab = passive;
    grabinfo->implicitGrab = passive & ImplicitGrabMask;
    CheckGrabForSyncs(keybd, (Bool) grab->keyboardMode,
                      (Bool) grab->pointerMode);
    if (oldgrab)
        FreeGrab(oldgrab);
}

/**
 * Delete keyboard grab for the given device.
 */
void
DeactivateKeyboardGrab(DeviceIntPtr keybd)
{
    GrabPtr grab = keybd->deviceGrab.grab;
    DeviceIntPtr dev;
    WindowPtr focusWin;
    Bool wasImplicit = (keybd->deviceGrab.fromPassiveGrab &&
                        keybd->deviceGrab.implicitGrab);

    if (keybd->valuator)
        keybd->valuator->motionHintWindow = NullWindow;
    keybd->deviceGrab.grab = NullGrab;
    keybd->deviceGrab.sync.state = NOT_GRABBED;
    keybd->deviceGrab.fromPassiveGrab = FALSE;

    for (dev = inputInfo.devices; dev; dev = dev->next) {
        if (dev->deviceGrab.sync.other == grab)
            dev->deviceGrab.sync.other = NullGrab;
    }

    if (keybd->focus)
        focusWin = keybd->focus->win;
    else if (keybd->spriteInfo->sprite)
        focusWin = keybd->spriteInfo->sprite->win;
    else
        focusWin = NullWindow;

    if (focusWin == FollowKeyboardWin)
        focusWin = inputInfo.keyboard->focus->win;

    DoFocusEvents(keybd, grab->window, focusWin, NotifyUngrab);

    if (!wasImplicit && grab->grabtype == XI2)
        ReattachToOldMaster(keybd);

    ComputeFreezes();

    FreeGrab(grab);
}

void
AllowSome(ClientPtr client, TimeStamp time, DeviceIntPtr thisDev, int newState)
{
    Bool thisGrabbed, otherGrabbed, othersFrozen, thisSynced;
    TimeStamp grabTime;
    DeviceIntPtr dev;
    GrabInfoPtr devgrabinfo, grabinfo = &thisDev->deviceGrab;

    thisGrabbed = grabinfo->grab && SameClient(grabinfo->grab, client);
    thisSynced = FALSE;
    otherGrabbed = FALSE;
    othersFrozen = FALSE;
    grabTime = grabinfo->grabTime;
    for (dev = inputInfo.devices; dev; dev = dev->next) {
        devgrabinfo = &dev->deviceGrab;

        if (dev == thisDev)
            continue;
        if (devgrabinfo->grab && SameClient(devgrabinfo->grab, client)) {
            if (!(thisGrabbed || otherGrabbed) ||
                (CompareTimeStamps(devgrabinfo->grabTime, grabTime) == LATER))
                grabTime = devgrabinfo->grabTime;
            otherGrabbed = TRUE;
            if (grabinfo->sync.other == devgrabinfo->grab)
                thisSynced = TRUE;
            if (devgrabinfo->sync.state >= FROZEN)
                othersFrozen = TRUE;
        }
    }
    if (!((thisGrabbed && grabinfo->sync.state >= FROZEN) || thisSynced))
        return;
    if ((CompareTimeStamps(time, currentTime) == LATER) ||
        (CompareTimeStamps(time, grabTime) == EARLIER))
        return;
    switch (newState) {
    case THAWED:               /* Async */
        if (thisGrabbed)
            grabinfo->sync.state = THAWED;
        if (thisSynced)
            grabinfo->sync.other = NullGrab;
        ComputeFreezes();
        break;
    case FREEZE_NEXT_EVENT:    /* Sync */
        if (thisGrabbed) {
            grabinfo->sync.state = FREEZE_NEXT_EVENT;
            if (thisSynced)
                grabinfo->sync.other = NullGrab;
            ComputeFreezes();
        }
        break;
    case THAWED_BOTH:          /* AsyncBoth */
        if (othersFrozen) {
            for (dev = inputInfo.devices; dev; dev = dev->next) {
                devgrabinfo = &dev->deviceGrab;
                if (devgrabinfo->grab && SameClient(devgrabinfo->grab, client))
                    devgrabinfo->sync.state = THAWED;
                if (devgrabinfo->sync.other &&
                    SameClient(devgrabinfo->sync.other, client))
                    devgrabinfo->sync.other = NullGrab;
            }
            ComputeFreezes();
        }
        break;
    case FREEZE_BOTH_NEXT_EVENT:       /* SyncBoth */
        if (othersFrozen) {
            for (dev = inputInfo.devices; dev; dev = dev->next) {
                devgrabinfo = &dev->deviceGrab;
                if (devgrabinfo->grab && SameClient(devgrabinfo->grab, client))
                    devgrabinfo->sync.state = FREEZE_BOTH_NEXT_EVENT;
                if (devgrabinfo->sync.other
                    && SameClient(devgrabinfo->sync.other, client))
                    devgrabinfo->sync.other = NullGrab;
            }
            ComputeFreezes();
        }
        break;
    case NOT_GRABBED:          /* Replay */
        if (thisGrabbed && grabinfo->sync.state == FROZEN_WITH_EVENT) {
            if (thisSynced)
                grabinfo->sync.other = NullGrab;
            syncEvents.replayDev = thisDev;
            syncEvents.replayWin = grabinfo->grab->window;
            (*grabinfo->DeactivateGrab) (thisDev);
            syncEvents.replayDev = (DeviceIntPtr) NULL;
        }
        break;
    case THAW_OTHERS:          /* AsyncOthers */
        if (othersFrozen) {
            for (dev = inputInfo.devices; dev; dev = dev->next) {
                if (dev == thisDev)
                    continue;
                devgrabinfo = &dev->deviceGrab;
                if (devgrabinfo->grab && SameClient(devgrabinfo->grab, client))
                    devgrabinfo->sync.state = THAWED;
                if (devgrabinfo->sync.other
                    && SameClient(devgrabinfo->sync.other, client))
                    devgrabinfo->sync.other = NullGrab;
            }
            ComputeFreezes();
        }
        break;
    }

    /* We've unfrozen the grab. If the grab was a touch grab, we're now the
     * owner and expected to accept/reject it. Reject == ReplayPointer which
     * we've handled in ComputeFreezes() (during DeactivateGrab) above,
     * anything else is accept.
     */
    if (newState != NOT_GRABBED /* Replay */ &&
        IsTouchEvent((InternalEvent*)grabinfo->sync.event)) {
        TouchAcceptAndEnd(thisDev, grabinfo->sync.event->touchid);
    }
}

/**
 * Server-side protocol handling for AllowEvents request.
 *
 * Release some events from a frozen device.
 */
int
ProcAllowEvents(ClientPtr client)
{
    TimeStamp time;
    DeviceIntPtr mouse = NULL;
    DeviceIntPtr keybd = NULL;

    REQUEST(xAllowEventsReq);

    REQUEST_SIZE_MATCH(xAllowEventsReq);
    time = ClientTimeToServerTime(stuff->time);

    mouse = PickPointer(client);
    keybd = PickKeyboard(client);

    switch (stuff->mode) {
    case ReplayPointer:
        AllowSome(client, time, mouse, NOT_GRABBED);
        break;
    case SyncPointer:
        AllowSome(client, time, mouse, FREEZE_NEXT_EVENT);
        break;
    case AsyncPointer:
        AllowSome(client, time, mouse, THAWED);
        break;
    case ReplayKeyboard:
        AllowSome(client, time, keybd, NOT_GRABBED);
        break;
    case SyncKeyboard:
        AllowSome(client, time, keybd, FREEZE_NEXT_EVENT);
        break;
    case AsyncKeyboard:
        AllowSome(client, time, keybd, THAWED);
        break;
    case SyncBoth:
        AllowSome(client, time, keybd, FREEZE_BOTH_NEXT_EVENT);
        break;
    case AsyncBoth:
        AllowSome(client, time, keybd, THAWED_BOTH);
        break;
    default:
        client->errorValue = stuff->mode;
        return BadValue;
    }
    return Success;
}

/**
 * Deactivate grabs from any device that has been grabbed by the client.
 */
void
ReleaseActiveGrabs(ClientPtr client)
{
    DeviceIntPtr dev;
    Bool done;

    /* XXX CloseDownClient should remove passive grabs before
     * releasing active grabs.
     */
    do {
        done = TRUE;
        for (dev = inputInfo.devices; dev; dev = dev->next) {
            if (dev->deviceGrab.grab &&
                SameClient(dev->deviceGrab.grab, client)) {
                (*dev->deviceGrab.DeactivateGrab) (dev);
                done = FALSE;
            }
        }
    } while (!done);
}

/**************************************************************************
 *            The following procedures deal with delivering events        *
 **************************************************************************/

/**
 * Deliver the given events to the given client.
 *
 * More than one event may be delivered at a time. This is the case with
 * DeviceMotionNotifies which may be followed by DeviceValuator events.
 *
 * TryClientEvents() is the last station before actually writing the events to
 * the socket. Anything that is not filtered here, will get delivered to the
 * client.
 * An event is only delivered if
 *   - mask and filter match up.
 *   - no other client has a grab on the device that caused the event.
 *
 *
 * @param client The target client to deliver to.
 * @param dev The device the event came from. May be NULL.
 * @param pEvents The events to be delivered.
 * @param count Number of elements in pEvents.
 * @param mask Event mask as set by the window.
 * @param filter Mask based on event type.
 * @param grab Possible grab on the device that caused the event.
 *
 * @return 1 if event was delivered, 0 if not or -1 if grab was not set by the
 * client.
 */
int
TryClientEvents(ClientPtr client, DeviceIntPtr dev, xEvent *pEvents,
                int count, Mask mask, Mask filter, GrabPtr grab)
{
    int type;

#ifdef DEBUG_EVENTS
    ErrorF("[dix] Event([%d, %d], mask=0x%lx), client=%d%s",
           pEvents->u.u.type, pEvents->u.u.detail, mask,
           client ? client->index : -1,
           (client && client->clientGone) ? " (gone)" : "");
#endif

    if (!client || client == serverClient || client->clientGone) {
#ifdef DEBUG_EVENTS
        ErrorF(" not delivered to fake/dead client\n");
#endif
        return 0;
    }

    if (filter != CantBeFiltered && !(mask & filter)) {
#ifdef DEBUG_EVENTS
        ErrorF(" filtered\n");
#endif
        return 0;
    }

    if (grab && !SameClient(grab, client)) {
#ifdef DEBUG_EVENTS
        ErrorF(" not delivered due to grab\n");
#endif
        return -1;              /* don't send, but notify caller */
    }

    type = pEvents->u.u.type;
    if (type == MotionNotify) {
        if (mask & PointerMotionHintMask) {
            if (WID(dev->valuator->motionHintWindow) ==
                pEvents->u.keyButtonPointer.event) {
#ifdef DEBUG_EVENTS
                ErrorF("[dix] \n");
                ErrorF("[dix] motionHintWindow == keyButtonPointer.event\n");
#endif
                return 1;       /* don't send, but pretend we did */
            }
            pEvents->u.u.detail = NotifyHint;
        }
        else {
            pEvents->u.u.detail = NotifyNormal;
        }
    }
    else if (type == DeviceMotionNotify) {
        if (MaybeSendDeviceMotionNotifyHint((deviceKeyButtonPointer *) pEvents,
                                            mask) != 0)
            return 1;
    }
    else if (type == KeyPress) {
        if (EventIsKeyRepeat(pEvents)) {
            if (!_XkbWantsDetectableAutoRepeat(client)) {
                xEvent release = *pEvents;

                release.u.u.type = KeyRelease;
                WriteEventsToClient(client, 1, &release);
#ifdef DEBUG_EVENTS
                ErrorF(" (plus fake core release for repeat)");
#endif
            }
            else {
#ifdef DEBUG_EVENTS
                ErrorF(" (detectable autorepeat for core)");
#endif
            }
        }

    }
    else if (type == DeviceKeyPress) {
        if (EventIsKeyRepeat(pEvents)) {
            if (!_XkbWantsDetectableAutoRepeat(client)) {
                deviceKeyButtonPointer release =
                    *(deviceKeyButtonPointer *) pEvents;
                release.type = DeviceKeyRelease;
#ifdef DEBUG_EVENTS
                ErrorF(" (plus fake xi1 release for repeat)");
#endif
                WriteEventsToClient(client, 1, (xEvent *) &release);
            }
            else {
#ifdef DEBUG_EVENTS
                ErrorF(" (detectable autorepeat for core)");
#endif
            }
        }
    }

    if (BitIsOn(criticalEvents, type)) {
        if (client->smart_priority < SMART_MAX_PRIORITY)
            client->smart_priority++;
        SetCriticalOutputPending();
    }

    WriteEventsToClient(client, count, pEvents);
#ifdef DEBUG_EVENTS
    ErrorF("[dix]  delivered\n");
#endif
    return 1;
}

static BOOL
ActivateImplicitGrab(DeviceIntPtr dev, ClientPtr client, WindowPtr win,
                     xEvent *event, Mask deliveryMask)
{
    GrabPtr tempGrab;
    OtherInputMasks *inputMasks;
    CARD8 type = event->u.u.type;
    enum InputLevel grabtype;

    if (type == ButtonPress)
        grabtype = CORE;
    else if (type == DeviceButtonPress)
        grabtype = XI;
    else if ((type = xi2_get_type(event)) == XI_ButtonPress)
        grabtype = XI2;
    else
        return FALSE;

    tempGrab = AllocGrab(NULL);
    if (!tempGrab)
        return FALSE;
    tempGrab->next = NULL;
    tempGrab->device = dev;
    tempGrab->resource = client->clientAsMask;
    tempGrab->window = win;
    tempGrab->ownerEvents = (deliveryMask & OwnerGrabButtonMask) ? TRUE : FALSE;
    tempGrab->eventMask = deliveryMask;
    tempGrab->keyboardMode = GrabModeAsync;
    tempGrab->pointerMode = GrabModeAsync;
    tempGrab->confineTo = NullWindow;
    tempGrab->cursor = NullCursor;
    tempGrab->type = type;
    tempGrab->grabtype = grabtype;

    /* get the XI and XI2 device mask */
    inputMasks = wOtherInputMasks(win);
    tempGrab->deviceMask = (inputMasks) ? inputMasks->inputEvents[dev->id] : 0;

    if (inputMasks)
        xi2mask_merge(tempGrab->xi2mask, inputMasks->xi2mask);

    (*dev->deviceGrab.ActivateGrab) (dev, tempGrab,
                                     currentTime, TRUE | ImplicitGrabMask);
    FreeGrab(tempGrab);
    return TRUE;
}

/**
 * Attempt event delivery to the client owning the window.
 */
static enum EventDeliveryState
DeliverToWindowOwner(DeviceIntPtr dev, WindowPtr win,
                     xEvent *events, int count, Mask filter, GrabPtr grab)
{
    /* if nobody ever wants to see this event, skip some work */
    if (filter != CantBeFiltered &&
        !((wOtherEventMasks(win) | win->eventMask) & filter))
        return EVENT_SKIP;

    if (IsInterferingGrab(wClient(win), dev, events))
        return EVENT_SKIP;

    if (!XaceHook(XACE_RECEIVE_ACCESS, wClient(win), win, events, count)) {
        int attempt = TryClientEvents(wClient(win), dev, events,
                                      count, win->eventMask,
                                      filter, grab);

        if (attempt > 0)
            return EVENT_DELIVERED;
        if (attempt < 0)
            return EVENT_REJECTED;
    }

    return EVENT_NOT_DELIVERED;
}

/**
 * Get the list of clients that should be tried for event delivery on the
 * given window.
 *
 * @return 1 if the client list should be traversed, zero if the event
 * should be skipped.
 */
static Bool
GetClientsForDelivery(DeviceIntPtr dev, WindowPtr win,
                      xEvent *events, Mask filter, InputClients ** iclients)
{
    int rc = 0;

    if (core_get_type(events) != 0)
        *iclients = (InputClients *) wOtherClients(win);
    else if (xi2_get_type(events) != 0) {
        OtherInputMasks *inputMasks = wOtherInputMasks(win);

        /* Has any client selected for the event? */
        if (!WindowXI2MaskIsset(dev, win, events))
            goto out;
        *iclients = inputMasks->inputClients;
    }
    else {
        OtherInputMasks *inputMasks = wOtherInputMasks(win);

        /* Has any client selected for the event? */
        if (!inputMasks || !(inputMasks->inputEvents[dev->id] & filter))
            goto out;

        *iclients = inputMasks->inputClients;
    }

    rc = 1;
 out:
    return rc;
}

/**
 * Try delivery on each client in inputclients, provided the event mask
 * accepts it and there is no interfering core grab..
 */
static enum EventDeliveryState
DeliverEventToInputClients(DeviceIntPtr dev, InputClients * inputclients,
                           WindowPtr win, xEvent *events,
                           int count, Mask filter, GrabPtr grab,
                           ClientPtr *client_return, Mask *mask_return)
{
    int attempt;
    enum EventDeliveryState rc = EVENT_NOT_DELIVERED;
    Bool have_device_button_grab_class_client = FALSE;

    for (; inputclients; inputclients = inputclients->next) {
        Mask mask;
        ClientPtr client = rClient(inputclients);

        if (IsInterferingGrab(client, dev, events))
            continue;

        if (IsWrongPointerBarrierClient(client, dev, events))
            continue;

        mask = GetEventMask(dev, events, inputclients);

        if (XaceHook(XACE_RECEIVE_ACCESS, client, win, events, count))
            /* do nothing */ ;
        else if ((attempt = TryClientEvents(client, dev,
                                            events, count,
                                            mask, filter, grab))) {
            if (attempt > 0) {
                /*
                 * The order of clients is arbitrary therefore if one
                 * client belongs to DeviceButtonGrabClass make sure to
                 * catch it.
                 */
                if (!have_device_button_grab_class_client) {
                    rc = EVENT_DELIVERED;
                    *client_return = client;
                    *mask_return = mask;
                    /* Success overrides non-success, so if we've been
                     * successful on one client, return that */
                    if (mask & DeviceButtonGrabMask)
                        have_device_button_grab_class_client = TRUE;
                }
            } else if (rc == EVENT_NOT_DELIVERED)
                rc = EVENT_REJECTED;
        }
    }

    return rc;
}

/**
 * Deliver events to clients registered on the window.
 *
 * @param client_return On successful delivery, set to the recipient.
 * @param mask_return On successful delivery, set to the recipient's event
 * mask for this event.
 */
static enum EventDeliveryState
DeliverEventToWindowMask(DeviceIntPtr dev, WindowPtr win, xEvent *events,
                         int count, Mask filter, GrabPtr grab,
                         ClientPtr *client_return, Mask *mask_return)
{
    InputClients *iclients;

    if (!GetClientsForDelivery(dev, win, events, filter, &iclients))
        return EVENT_SKIP;

    return DeliverEventToInputClients(dev, iclients, win, events, count, filter,
                                      grab, client_return, mask_return);

}

/**
 * Deliver events to a window. At this point, we do not yet know if the event
 * actually needs to be delivered. May activate a grab if the event is a
 * button press.
 *
 * Core events are always delivered to the window owner. If the filter is
 * something other than CantBeFiltered, the event is also delivered to other
 * clients with the matching mask on the window.
 *
 * More than one event may be delivered at a time. This is the case with
 * DeviceMotionNotifies which may be followed by DeviceValuator events.
 *
 * @param pWin The window that would get the event.
 * @param pEvents The events to be delivered.
 * @param count Number of elements in pEvents.
 * @param filter Mask based on event type.
 * @param grab Possible grab on the device that caused the event.
 *
 * @return a positive number if at least one successful delivery has been
 * made, 0 if no events were delivered, or a negative number if the event
 * has not been delivered _and_ rejected by at least one client.
 */
int
DeliverEventsToWindow(DeviceIntPtr pDev, WindowPtr pWin, xEvent
                      *pEvents, int count, Mask filter, GrabPtr grab)
{
    int deliveries = 0, nondeliveries = 0;
    ClientPtr client = NullClient;
    Mask deliveryMask = 0;      /* If a grab occurs due to a button press, then
                                   this mask is the mask of the grab. */
    int type = pEvents->u.u.type;

    /* Deliver to window owner */
    if ((filter == CantBeFiltered) || core_get_type(pEvents) != 0) {
        enum EventDeliveryState rc;

        rc = DeliverToWindowOwner(pDev, pWin, pEvents, count, filter, grab);

        switch (rc) {
        case EVENT_SKIP:
            return 0;
        case EVENT_REJECTED:
            nondeliveries--;
            break;
        case EVENT_DELIVERED:
            /* We delivered to the owner, with our event mask */
            deliveries++;
            client = wClient(pWin);
            deliveryMask = pWin->eventMask;
            break;
        case EVENT_NOT_DELIVERED:
            break;
        }
    }

    /* CantBeFiltered means only window owner gets the event */
    if (filter != CantBeFiltered) {
        enum EventDeliveryState rc;

        rc = DeliverEventToWindowMask(pDev, pWin, pEvents, count, filter,
                                      grab, &client, &deliveryMask);

        switch (rc) {
        case EVENT_SKIP:
            return 0;
        case EVENT_REJECTED:
            nondeliveries--;
            break;
        case EVENT_DELIVERED:
            deliveries++;
            break;
        case EVENT_NOT_DELIVERED:
            break;
        }
    }

    if (deliveries) {
        /*
         * Note that since core events are delivered first, an implicit grab may
         * be activated on a core grab, stopping the XI events.
         */
        if (!grab &&
            ActivateImplicitGrab(pDev, client, pWin, pEvents, deliveryMask))
            /* grab activated */ ;
        else if (type == MotionNotify)
            pDev->valuator->motionHintWindow = pWin;
        else if (type == DeviceMotionNotify || type == DeviceButtonPress)
            CheckDeviceGrabAndHintWindow(pWin, type,
                                         (deviceKeyButtonPointer *) pEvents,
                                         grab, client, deliveryMask);
        return deliveries;
    }
    return nondeliveries;
}

/**
 * Filter out raw events for XI 2.0 and XI 2.1 clients.
 *
 * If there is a grab on the device, 2.0 clients only get raw events if they
 * have the grab. 2.1+ clients get raw events in all cases.
 *
 * @return TRUE if the event should be discarded, FALSE otherwise.
 */
static BOOL
FilterRawEvents(const ClientPtr client, const GrabPtr grab, WindowPtr root)
{
    XIClientPtr client_xi_version;
    int cmp;

    /* device not grabbed -> don't filter */
    if (!grab)
        return FALSE;

    client_xi_version =
        dixLookupPrivate(&client->devPrivates, XIClientPrivateKey);

    cmp = version_compare(client_xi_version->major_version,
                          client_xi_version->minor_version, 2, 0);
    /* XI 2.0: if device is grabbed, skip
       XI 2.1: if device is grabbed by us, skip, we've already delivered */
    if (cmp == 0)
        return TRUE;

    return (grab->window != root) ? FALSE : SameClient(grab, client);
}

/**
 * Deliver a raw event to the grab owner (if any) and to all root windows.
 *
 * Raw event delivery differs between XI 2.0 and XI 2.1.
 * XI 2.0: events delivered to the grabbing client (if any) OR to all root
 * windows
 * XI 2.1: events delivered to all root windows, regardless of grabbing
 * state.
 */
void
DeliverRawEvent(RawDeviceEvent *ev, DeviceIntPtr device)
{
    GrabPtr grab = device->deviceGrab.grab;
    xEvent *xi;
    int i, rc;
    int filter;

    rc = EventToXI2((InternalEvent *) ev, (xEvent **) &xi);
    if (rc != Success) {
        ErrorF("[Xi] %s: XI2 conversion failed in %s (%d)\n",
               __FUNCTION__, device->name, rc);
        return;
    }

    if (grab)
        DeliverGrabbedEvent((InternalEvent *) ev, device, FALSE);

    filter = GetEventFilter(device, xi);

    for (i = 0; i < screenInfo.numScreens; i++) {
        WindowPtr root;
        InputClients *inputclients;

        root = screenInfo.screens[i]->root;
        if (!GetClientsForDelivery(device, root, xi, filter, &inputclients))
            continue;

        for (; inputclients; inputclients = inputclients->next) {
            ClientPtr c;        /* unused */
            Mask m;             /* unused */
            InputClients ic = *inputclients;

            /* Because we run through the list manually, copy the actual
             * list, shorten the copy to only have one client and then pass
             * that down to DeliverEventToInputClients. This way we avoid
             * double events on XI 2.1 clients that have a grab on the
             * device.
             */
            ic.next = NULL;

            if (!FilterRawEvents(rClient(&ic), grab, root))
                DeliverEventToInputClients(device, &ic, root, xi, 1,
                                           filter, NULL, &c, &m);
        }
    }

    free(xi);
}

/* If the event goes to dontClient, don't send it and return 0.  if
   send works,  return 1 or if send didn't work, return 2.
   Only works for core events.
*/

#ifdef PANORAMIX
static int
XineramaTryClientEventsResult(ClientPtr client,
                              GrabPtr grab, Mask mask, Mask filter)
{
    if ((client) && (client != serverClient) && (!client->clientGone) &&
        ((filter == CantBeFiltered) || (mask & filter))) {
        if (grab && !SameClient(grab, client))
            return -1;
        else
            return 1;
    }
    return 0;
}
#endif

/**
 * Try to deliver events to the interested parties.
 *
 * @param pWin The window that would get the event.
 * @param pEvents The events to be delivered.
 * @param count Number of elements in pEvents.
 * @param filter Mask based on event type.
 * @param dontClient Don't deliver to the dontClient.
 */
int
MaybeDeliverEventsToClient(WindowPtr pWin, xEvent *pEvents,
                           int count, Mask filter, ClientPtr dontClient)
{
    OtherClients *other;

    if (pWin->eventMask & filter) {
        if (wClient(pWin) == dontClient)
            return 0;
#ifdef PANORAMIX
        if (!noPanoramiXExtension && pWin->drawable.pScreen->myNum)
            return XineramaTryClientEventsResult(wClient(pWin), NullGrab,
                                                 pWin->eventMask, filter);
#endif
        if (XaceHook(XACE_RECEIVE_ACCESS, wClient(pWin), pWin, pEvents, count))
            return 1;           /* don't send, but pretend we did */
        return TryClientEvents(wClient(pWin), NULL, pEvents, count,
                               pWin->eventMask, filter, NullGrab);
    }
    for (other = wOtherClients(pWin); other; other = other->next) {
        if (other->mask & filter) {
            if (SameClient(other, dontClient))
                return 0;
#ifdef PANORAMIX
            if (!noPanoramiXExtension && pWin->drawable.pScreen->myNum)
                return XineramaTryClientEventsResult(rClient(other), NullGrab,
                                                     other->mask, filter);
#endif
            if (XaceHook(XACE_RECEIVE_ACCESS, rClient(other), pWin, pEvents,
                         count))
                return 1;       /* don't send, but pretend we did */
            return TryClientEvents(rClient(other), NULL, pEvents, count,
                                   other->mask, filter, NullGrab);
        }
    }
    return 2;
}

static Window
FindChildForEvent(SpritePtr pSprite, WindowPtr event)
{
    WindowPtr w = DeepestSpriteWin(pSprite);
    Window child = None;

    /* If the search ends up past the root should the child field be
       set to none or should the value in the argument be passed
       through. It probably doesn't matter since everyone calls
       this function with child == None anyway. */
    while (w) {
        /* If the source window is same as event window, child should be
           none.  Don't bother going all all the way back to the root. */

        if (w == event) {
            child = None;
            break;
        }

        if (w->parent == event) {
            child = w->drawable.id;
            break;
        }
        w = w->parent;
    }
    return child;
}

/**
 * Adjust event fields to comply with the window properties.
 *
 * @param xE Event to be modified in place
 * @param pWin The window to get the information from.
 * @param child Child window setting for event (if applicable)
 * @param calcChild If True, calculate the child window.
 */
void
FixUpEventFromWindow(SpritePtr pSprite,
                     xEvent *xE, WindowPtr pWin, Window child, Bool calcChild)
{
    int evtype;

    if (calcChild)
        child = FindChildForEvent(pSprite, pWin);

    if ((evtype = xi2_get_type(xE))) {
        xXIDeviceEvent *event = (xXIDeviceEvent *) xE;

        switch (evtype) {
        case XI_RawKeyPress:
        case XI_RawKeyRelease:
        case XI_RawButtonPress:
        case XI_RawButtonRelease:
        case XI_RawMotion:
        case XI_RawTouchBegin:
        case XI_RawTouchUpdate:
        case XI_RawTouchEnd:
        case XI_DeviceChanged:
        case XI_HierarchyChanged:
        case XI_PropertyEvent:
        case XI_BarrierHit:
        case XI_BarrierLeave:
            return;
        default:
            break;
        }

        event->root = RootWindow(pSprite)->drawable.id;
        event->event = pWin->drawable.id;

        if (evtype == XI_TouchOwnership) {
            event->child = child;
            return;
        }

        if (pSprite->hot.pScreen == pWin->drawable.pScreen) {
            event->event_x = event->root_x - double_to_fp1616(pWin->drawable.x);
            event->event_y = event->root_y - double_to_fp1616(pWin->drawable.y);
            event->child = child;
        }
        else {
            event->event_x = 0;
            event->event_y = 0;
            event->child = None;
        }

        if (event->evtype == XI_Enter || event->evtype == XI_Leave ||
            event->evtype == XI_FocusIn || event->evtype == XI_FocusOut)
            ((xXIEnterEvent *) event)->same_screen =
                (pSprite->hot.pScreen == pWin->drawable.pScreen);

    }
    else {
        XE_KBPTR.root = RootWindow(pSprite)->drawable.id;
        XE_KBPTR.event = pWin->drawable.id;
        if (pSprite->hot.pScreen == pWin->drawable.pScreen) {
            XE_KBPTR.sameScreen = xTrue;
            XE_KBPTR.child = child;
            XE_KBPTR.eventX = XE_KBPTR.rootX - pWin->drawable.x;
            XE_KBPTR.eventY = XE_KBPTR.rootY - pWin->drawable.y;
        }
        else {
            XE_KBPTR.sameScreen = xFalse;
            XE_KBPTR.child = None;
            XE_KBPTR.eventX = 0;
            XE_KBPTR.eventY = 0;
        }
    }
}

/**
 * Check if a given event is deliverable at all on a given window.
 *
 * This function only checks if any client wants it, not for a specific
 * client.
 *
 * @param[in] dev The device this event is being sent for.
 * @param[in] evtype The event type of the event that is to be sent.
 * @param[in] win The current event window.
 *
 * @return Bitmask of ::EVENT_XI2_MASK, ::EVENT_XI1_MASK, ::EVENT_CORE_MASK, and
 *         ::EVENT_DONT_PROPAGATE_MASK.
 */
int
EventIsDeliverable(DeviceIntPtr dev, int evtype, WindowPtr win)
{
    int rc = 0;
    int filter = 0;
    int type;
    OtherInputMasks *inputMasks = wOtherInputMasks(win);

    if ((type = GetXI2Type(evtype)) != 0) {
        if (inputMasks && xi2mask_isset(inputMasks->xi2mask, dev, type))
            rc |= EVENT_XI2_MASK;
    }

    if ((type = GetXIType(evtype)) != 0) {
        filter = event_get_filter_from_type(dev, type);

        /* Check for XI mask */
        if (inputMasks &&
            (inputMasks->deliverableEvents[dev->id] & filter) &&
            (inputMasks->inputEvents[dev->id] & filter))
            rc |= EVENT_XI1_MASK;

        /* Check for XI DontPropagate mask */
        if (inputMasks && (inputMasks->dontPropagateMask[dev->id] & filter))
            rc |= EVENT_DONT_PROPAGATE_MASK;

    }

    if ((type = GetCoreType(evtype)) != 0) {
        filter = event_get_filter_from_type(dev, type);

        /* Check for core mask */
        if ((win->deliverableEvents & filter) &&
            ((wOtherEventMasks(win) | win->eventMask) & filter))
            rc |= EVENT_CORE_MASK;

        /* Check for core DontPropagate mask */
        if (filter & wDontPropagateMask(win))
            rc |= EVENT_DONT_PROPAGATE_MASK;
    }

    return rc;
}

static int
DeliverEvent(DeviceIntPtr dev, xEvent *xE, int count,
             WindowPtr win, Window child, GrabPtr grab)
{
    SpritePtr pSprite = dev->spriteInfo->sprite;
    Mask filter;
    int deliveries = 0;

    if (XaceHook(XACE_SEND_ACCESS, NULL, dev, win, xE, count) == Success) {
        filter = GetEventFilter(dev, xE);
        FixUpEventFromWindow(pSprite, xE, win, child, FALSE);
        deliveries = DeliverEventsToWindow(dev, win, xE, count, filter, grab);
    }

    return deliveries;
}

static int
DeliverOneEvent(InternalEvent *event, DeviceIntPtr dev, enum InputLevel level,
                WindowPtr win, Window child, GrabPtr grab)
{
    xEvent *xE = NULL;
    int count = 0;
    int deliveries = 0;
    int rc;

    switch (level) {
    case XI2:
        rc = EventToXI2(event, &xE);
        count = 1;
        break;
    case XI:
        rc = EventToXI(event, &xE, &count);
        break;
    case CORE:
        rc = EventToCore(event, &xE, &count);
        break;
    default:
        rc = BadImplementation;
        break;
    }

    if (rc == Success) {
        deliveries = DeliverEvent(dev, xE, count, win, child, grab);
        free(xE);
    }
    else
        BUG_WARN_MSG(rc != BadMatch,
                     "%s: conversion to level %d failed with rc %d\n",
                     dev->name, level, rc);
    return deliveries;
}

/**
 * Deliver events caused by input devices.
 *
 * For events from a non-grabbed, non-focus device, DeliverDeviceEvents is
 * called directly from the processInputProc.
 * For grabbed devices, DeliverGrabbedEvent is called first, and _may_ call
 * DeliverDeviceEvents.
 * For focused events, DeliverFocusedEvent is called first, and _may_ call
 * DeliverDeviceEvents.
 *
 * @param pWin Window to deliver event to.
 * @param event The events to deliver, not yet in wire format.
 * @param grab Possible grab on a device.
 * @param stopAt Don't recurse up to the root window.
 * @param dev The device that is responsible for the event.
 *
 * @see DeliverGrabbedEvent
 * @see DeliverFocusedEvent
 */
int
DeliverDeviceEvents(WindowPtr pWin, InternalEvent *event, GrabPtr grab,
                    WindowPtr stopAt, DeviceIntPtr dev)
{
    Window child = None;
    int deliveries = 0;
    int mask;

    verify_internal_event(event);

    while (pWin) {
        if ((mask = EventIsDeliverable(dev, event->any.type, pWin))) {
            /* XI2 events first */
            if (mask & EVENT_XI2_MASK) {
                deliveries =
                    DeliverOneEvent(event, dev, XI2, pWin, child, grab);
                if (deliveries > 0)
                    break;
            }

            /* XI events */
            if (mask & EVENT_XI1_MASK) {
                deliveries = DeliverOneEvent(event, dev, XI, pWin, child, grab);
                if (deliveries > 0)
                    break;
            }

            /* Core event */
            if ((mask & EVENT_CORE_MASK) && IsMaster(dev) && dev->coreEvents) {
                deliveries =
                    DeliverOneEvent(event, dev, CORE, pWin, child, grab);
                if (deliveries > 0)
                    break;
            }

        }

        if ((deliveries < 0) || (pWin == stopAt) ||
            (mask & EVENT_DONT_PROPAGATE_MASK)) {
            deliveries = 0;
            break;
        }

        child = pWin->drawable.id;
        pWin = pWin->parent;
    }

    return deliveries;
}

/**
 * Deliver event to a window and it's immediate parent. Used for most window
 * events (CreateNotify, ConfigureNotify, etc.). Not useful for events that
 * propagate up the tree or extension events
 *
 * In case of a ReparentNotify event, the event will be delivered to the
 * otherParent as well.
 *
 * @param pWin Window to deliver events to.
 * @param xE Events to deliver.
 * @param count number of events in xE.
 * @param otherParent Used for ReparentNotify events.
 */
int
DeliverEvents(WindowPtr pWin, xEvent *xE, int count, WindowPtr otherParent)
{
    DeviceIntRec dummy;
    int deliveries;

#ifdef PANORAMIX
    if (!noPanoramiXExtension && pWin->drawable.pScreen->myNum)
        return count;
#endif

    if (!count)
        return 0;

    dummy.id = XIAllDevices;

    switch (xE->u.u.type) {
    case DestroyNotify:
    case UnmapNotify:
    case MapNotify:
    case MapRequest:
    case ReparentNotify:
    case ConfigureNotify:
    case ConfigureRequest:
    case GravityNotify:
    case CirculateNotify:
    case CirculateRequest:
        xE->u.destroyNotify.event = pWin->drawable.id;
        break;
    }

    switch (xE->u.u.type) {
    case DestroyNotify:
    case UnmapNotify:
    case MapNotify:
    case ReparentNotify:
    case ConfigureNotify:
    case GravityNotify:
    case CirculateNotify:
        break;
    default:
    {
        Mask filter;

        filter = GetEventFilter(&dummy, xE);
        return DeliverEventsToWindow(&dummy, pWin, xE, count, filter, NullGrab);
    }
    }

    deliveries = DeliverEventsToWindow(&dummy, pWin, xE, count,
                                       StructureNotifyMask, NullGrab);
    if (pWin->parent) {
        xE->u.destroyNotify.event = pWin->parent->drawable.id;
        deliveries += DeliverEventsToWindow(&dummy, pWin->parent, xE, count,
                                            SubstructureNotifyMask, NullGrab);
        if (xE->u.u.type == ReparentNotify) {
            xE->u.destroyNotify.event = otherParent->drawable.id;
            deliveries += DeliverEventsToWindow(&dummy,
                                                otherParent, xE, count,
                                                SubstructureNotifyMask,
                                                NullGrab);
        }
    }
    return deliveries;
}

Bool
PointInBorderSize(WindowPtr pWin, int x, int y)
{
    BoxRec box;

    if (RegionContainsPoint(&pWin->borderSize, x, y, &box))
        return TRUE;

#ifdef PANORAMIX
    if (!noPanoramiXExtension &&
        XineramaSetWindowPntrs(inputInfo.pointer, pWin)) {
        SpritePtr pSprite = inputInfo.pointer->spriteInfo->sprite;
        int i;

        FOR_NSCREENS_FORWARD_SKIP(i) {
            if (RegionContainsPoint(&pSprite->windows[i]->borderSize,
                                    x + screenInfo.screens[0]->x -
                                    screenInfo.screens[i]->x,
                                    y + screenInfo.screens[0]->y -
                                    screenInfo.screens[i]->y, &box))
                return TRUE;
        }
    }
#endif
    return FALSE;
}

/**
 * Traversed from the root window to the window at the position x/y. While
 * traversing, it sets up the traversal history in the spriteTrace array.
 * After completing, the spriteTrace history is set in the following way:
 *   spriteTrace[0] ... root window
 *   spriteTrace[1] ... top level window that encloses x/y
 *       ...
 *   spriteTrace[spriteTraceGood - 1] ... window at x/y
 *
 * @returns the window at the given coordinates.
 */
WindowPtr
XYToWindow(SpritePtr pSprite, int x, int y)
{
    ScreenPtr pScreen = RootWindow(pSprite)->drawable.pScreen;

    return (*pScreen->XYToWindow)(pScreen, pSprite, x, y);
}

/**
 * Ungrab a currently FocusIn grabbed device and grab the device on the
 * given window. If the win given is the NoneWin, the device is ungrabbed if
 * applicable and FALSE is returned.
 *
 * @returns TRUE if the device has been grabbed, or FALSE otherwise.
 */
BOOL
ActivateFocusInGrab(DeviceIntPtr dev, WindowPtr old, WindowPtr win)
{
    BOOL rc = FALSE;
    DeviceEvent event;

    if (dev->deviceGrab.grab) {
        if (!dev->deviceGrab.fromPassiveGrab ||
            dev->deviceGrab.grab->type != XI_Enter ||
            dev->deviceGrab.grab->window == win ||
            IsParent(dev->deviceGrab.grab->window, win))
            return FALSE;
        DoEnterLeaveEvents(dev, dev->id, old, win, XINotifyPassiveUngrab);
        (*dev->deviceGrab.DeactivateGrab) (dev);
    }

    if (win == NoneWin || win == PointerRootWin)
        return FALSE;

    memset(&event, 0, sizeof(DeviceEvent));
    event.header = ET_Internal;
    event.type = ET_FocusIn;
    event.length = sizeof(DeviceEvent);
    event.time = GetTimeInMillis();
    event.deviceid = dev->id;
    event.sourceid = dev->id;
    event.detail.button = 0;
    rc = (CheckPassiveGrabsOnWindow(win, dev, (InternalEvent *) &event, FALSE,
                                    TRUE) != NULL);
    if (rc)
        DoEnterLeaveEvents(dev, dev->id, old, win, XINotifyPassiveUngrab);
    return rc;
}

/**
 * Ungrab a currently Enter grabbed device and grab the device for the given
 * window.
 *
 * @returns TRUE if the device has been grabbed, or FALSE otherwise.
 */
static BOOL
ActivateEnterGrab(DeviceIntPtr dev, WindowPtr old, WindowPtr win)
{
    BOOL rc = FALSE;
    DeviceEvent event;

    if (dev->deviceGrab.grab) {
        if (!dev->deviceGrab.fromPassiveGrab ||
            dev->deviceGrab.grab->type != XI_Enter ||
            dev->deviceGrab.grab->window == win ||
            IsParent(dev->deviceGrab.grab->window, win))
            return FALSE;
        DoEnterLeaveEvents(dev, dev->id, old, win, XINotifyPassiveUngrab);
        (*dev->deviceGrab.DeactivateGrab) (dev);
    }

    memset(&event, 0, sizeof(DeviceEvent));
    event.header = ET_Internal;
    event.type = ET_Enter;
    event.length = sizeof(DeviceEvent);
    event.time = GetTimeInMillis();
    event.deviceid = dev->id;
    event.sourceid = dev->id;
    event.detail.button = 0;
    rc = (CheckPassiveGrabsOnWindow(win, dev, (InternalEvent *) &event, FALSE,
                                    TRUE) != NULL);
    if (rc)
        DoEnterLeaveEvents(dev, dev->id, old, win, XINotifyPassiveGrab);
    return rc;
}

/**
 * Update the sprite coordinates based on the event. Update the cursor
 * position, then update the event with the new coordinates that may have been
 * changed. If the window underneath the sprite has changed, change to new
 * cursor and send enter/leave events.
 *
 * CheckMotion() will not do anything and return FALSE if the event is not a
 * pointer event.
 *
 * @return TRUE if the sprite has moved or FALSE otherwise.
 */
Bool
CheckMotion(DeviceEvent *ev, DeviceIntPtr pDev)
{
    WindowPtr prevSpriteWin, newSpriteWin;
    SpritePtr pSprite = pDev->spriteInfo->sprite;

    verify_internal_event((InternalEvent *) ev);

    if (!pSprite)
      return FALSE;

    prevSpriteWin = pSprite->win;

    if (ev && !syncEvents.playingEvents) {
        /* GetPointerEvents() guarantees that pointer events have the correct
           rootX/Y set already. */
        switch (ev->type) {
        case ET_ButtonPress:
        case ET_ButtonRelease:
        case ET_Motion:
        case ET_TouchBegin:
        case ET_TouchUpdate:
        case ET_TouchEnd:
            break;
        default:
            /* all other events return FALSE */
            return FALSE;
        }

#ifdef PANORAMIX
        if (!noPanoramiXExtension) {
            /* Motion events entering DIX get translated to Screen 0
               coordinates.  Replayed events have already been
               translated since they've entered DIX before */
            ev->root_x += pSprite->screen->x - screenInfo.screens[0]->x;
            ev->root_y += pSprite->screen->y - screenInfo.screens[0]->y;
        }
        else
#endif
        {
            if (pSprite->hot.pScreen != pSprite->hotPhys.pScreen) {
                pSprite->hot.pScreen = pSprite->hotPhys.pScreen;
                RootWindow(pDev->spriteInfo->sprite) =
                    pSprite->hot.pScreen->root;
            }
        }

        pSprite->hot.x = ev->root_x;
        pSprite->hot.y = ev->root_y;
        if (pSprite->hot.x < pSprite->physLimits.x1)
            pSprite->hot.x = pSprite->physLimits.x1;
        else if (pSprite->hot.x >= pSprite->physLimits.x2)
            pSprite->hot.x = pSprite->physLimits.x2 - 1;
        if (pSprite->hot.y < pSprite->physLimits.y1)
            pSprite->hot.y = pSprite->physLimits.y1;
        else if (pSprite->hot.y >= pSprite->physLimits.y2)
            pSprite->hot.y = pSprite->physLimits.y2 - 1;
        if (pSprite->hotShape)
            ConfineToShape(pDev, pSprite->hotShape, &pSprite->hot.x,
                           &pSprite->hot.y);
        pSprite->hotPhys = pSprite->hot;

        if ((pSprite->hotPhys.x != ev->root_x) ||
            (pSprite->hotPhys.y != ev->root_y)) {
#ifdef PANORAMIX
            if (!noPanoramiXExtension) {
                XineramaSetCursorPosition(pDev, pSprite->hotPhys.x,
                                          pSprite->hotPhys.y, FALSE);
            }
            else
#endif
            {
                (*pSprite->hotPhys.pScreen->SetCursorPosition) (pDev,
                                                                pSprite->
                                                                hotPhys.pScreen,
                                                                pSprite->
                                                                hotPhys.x,
                                                                pSprite->
                                                                hotPhys.y,
                                                                FALSE);
            }
        }

        ev->root_x = pSprite->hot.x;
        ev->root_y = pSprite->hot.y;
    }

    newSpriteWin = XYToWindow(pSprite, pSprite->hot.x, pSprite->hot.y);

    if (newSpriteWin != prevSpriteWin) {
        int sourceid;

        if (!ev) {
            UpdateCurrentTimeIf();
            sourceid = pDev->id;        /* when from WindowsRestructured */
        }
        else
            sourceid = ev->sourceid;

        if (prevSpriteWin != NullWindow) {
            if (!ActivateEnterGrab(pDev, prevSpriteWin, newSpriteWin))
                DoEnterLeaveEvents(pDev, sourceid, prevSpriteWin,
                                   newSpriteWin, NotifyNormal);
        }
        /* set pSprite->win after ActivateEnterGrab, otherwise
           sprite window == grab_window and no enter/leave events are
           sent. */
        pSprite->win = newSpriteWin;
        PostNewCursor(pDev);
        return FALSE;
    }
    return TRUE;
}

/**
 * Windows have restructured, we need to update the sprite position and the
 * sprite's cursor.
 */
void
WindowsRestructured(void)
{
    DeviceIntPtr pDev = inputInfo.devices;

    while (pDev) {
        if (IsMaster(pDev) || IsFloating(pDev))
            CheckMotion(NULL, pDev);
        pDev = pDev->next;
    }
}

#ifdef PANORAMIX
/* This was added to support reconfiguration under Xdmx.  The problem is
 * that if the 0th screen (i.e., screenInfo.screens[0]) is moved to an origin
 * other than 0,0, the information in the private sprite structure must
 * be updated accordingly, or XYToWindow (and other routines) will not
 * compute correctly. */
void
ReinitializeRootWindow(WindowPtr win, int xoff, int yoff)
{
    GrabPtr grab;
    DeviceIntPtr pDev;
    SpritePtr pSprite;

    if (noPanoramiXExtension)
        return;

    pDev = inputInfo.devices;
    while (pDev) {
        if (DevHasCursor(pDev)) {
            pSprite = pDev->spriteInfo->sprite;
            pSprite->hot.x -= xoff;
            pSprite->hot.y -= yoff;

            pSprite->hotPhys.x -= xoff;
            pSprite->hotPhys.y -= yoff;

            pSprite->hotLimits.x1 -= xoff;
            pSprite->hotLimits.y1 -= yoff;
            pSprite->hotLimits.x2 -= xoff;
            pSprite->hotLimits.y2 -= yoff;

            if (RegionNotEmpty(&pSprite->Reg1))
                RegionTranslate(&pSprite->Reg1, xoff, yoff);
            if (RegionNotEmpty(&pSprite->Reg2))
                RegionTranslate(&pSprite->Reg2, xoff, yoff);

            /* FIXME: if we call ConfineCursorToWindow, must we do anything else? */
            if ((grab = pDev->deviceGrab.grab) && grab->confineTo) {
                if (grab->confineTo->drawable.pScreen
                    != pSprite->hotPhys.pScreen)
                    pSprite->hotPhys.x = pSprite->hotPhys.y = 0;
                ConfineCursorToWindow(pDev, grab->confineTo, TRUE, TRUE);
            }
            else
                ConfineCursorToWindow(pDev,
                                      pSprite->hotPhys.pScreen->root,
                                      TRUE, FALSE);

        }
        pDev = pDev->next;
    }
}
#endif

/**
 * Initialize a sprite for the given device and set it to some sane values. If
 * the device already has a sprite alloc'd, don't realloc but just reset to
 * default values.
 * If a window is supplied, the sprite will be initialized with the window's
 * cursor and positioned in the center of the window's screen. The root window
 * is a good choice to pass in here.
 *
 * It's a good idea to call it only for pointer devices, unless you have a
 * really talented keyboard.
 *
 * @param pDev The device to initialize.
 * @param pWin The window where to generate the sprite in.
 *
 */
void
InitializeSprite(DeviceIntPtr pDev, WindowPtr pWin)
{
    SpritePtr pSprite;
    ScreenPtr pScreen;
    CursorPtr pCursor;

    if (!pDev->spriteInfo->sprite) {
        DeviceIntPtr it;

        pDev->spriteInfo->sprite = (SpritePtr) calloc(1, sizeof(SpriteRec));
        if (!pDev->spriteInfo->sprite)
            FatalError("InitializeSprite: failed to allocate sprite struct");

        /* We may have paired another device with this device before our
         * device had a actual sprite. We need to check for this and reset the
         * sprite field for all paired devices.
         *
         * The VCK is always paired with the VCP before the VCP has a sprite.
         */
        for (it = inputInfo.devices; it; it = it->next) {
            if (it->spriteInfo->paired == pDev)
                it->spriteInfo->sprite = pDev->spriteInfo->sprite;
        }
        if (inputInfo.keyboard->spriteInfo->paired == pDev)
            inputInfo.keyboard->spriteInfo->sprite = pDev->spriteInfo->sprite;
    }

    pSprite = pDev->spriteInfo->sprite;
    pDev->spriteInfo->spriteOwner = TRUE;

    pScreen = (pWin) ? pWin->drawable.pScreen : (ScreenPtr) NULL;
    pSprite->hot.pScreen = pScreen;
    pSprite->hotPhys.pScreen = pScreen;
    if (pScreen) {
        pSprite->hotPhys.x = pScreen->width / 2;
        pSprite->hotPhys.y = pScreen->height / 2;
        pSprite->hotLimits.x2 = pScreen->width;
        pSprite->hotLimits.y2 = pScreen->height;
    }

    pSprite->hot = pSprite->hotPhys;
    pSprite->win = pWin;

    if (pWin) {
        pCursor = wCursor(pWin);
        pSprite->spriteTrace = (WindowPtr *) calloc(1, 32 * sizeof(WindowPtr));
        if (!pSprite->spriteTrace)
            FatalError("Failed to allocate spriteTrace");
        pSprite->spriteTraceSize = 32;

        RootWindow(pDev->spriteInfo->sprite) = pWin;
        pSprite->spriteTraceGood = 1;

        pSprite->pEnqueueScreen = pScreen;
        pSprite->pDequeueScreen = pSprite->pEnqueueScreen;

    }
    else {
        pCursor = NullCursor;
        pSprite->spriteTrace = NULL;
        pSprite->spriteTraceSize = 0;
        pSprite->spriteTraceGood = 0;
        pSprite->pEnqueueScreen = screenInfo.screens[0];
        pSprite->pDequeueScreen = pSprite->pEnqueueScreen;
    }
    pCursor = RefCursor(pCursor);
    if (pSprite->current)
        FreeCursor(pSprite->current, None);
    pSprite->current = pCursor;

    if (pScreen) {
        (*pScreen->RealizeCursor) (pDev, pScreen, pSprite->current);
        (*pScreen->CursorLimits) (pDev, pScreen, pSprite->current,
                                  &pSprite->hotLimits, &pSprite->physLimits);
        pSprite->confined = FALSE;

        (*pScreen->ConstrainCursor) (pDev, pScreen, &pSprite->physLimits);
        (*pScreen->SetCursorPosition) (pDev, pScreen, pSprite->hot.x,
                                       pSprite->hot.y, FALSE);
        (*pScreen->DisplayCursor) (pDev, pScreen, pSprite->current);
    }
#ifdef PANORAMIX
    if (!noPanoramiXExtension) {
        pSprite->hotLimits.x1 = -screenInfo.screens[0]->x;
        pSprite->hotLimits.y1 = -screenInfo.screens[0]->y;
        pSprite->hotLimits.x2 = PanoramiXPixWidth - screenInfo.screens[0]->x;
        pSprite->hotLimits.y2 = PanoramiXPixHeight - screenInfo.screens[0]->y;
        pSprite->physLimits = pSprite->hotLimits;
        pSprite->confineWin = NullWindow;
        pSprite->hotShape = NullRegion;
        pSprite->screen = pScreen;
        /* gotta UNINIT these someplace */
        RegionNull(&pSprite->Reg1);
        RegionNull(&pSprite->Reg2);
    }
#endif
}

void FreeSprite(DeviceIntPtr dev)
{
    if (DevHasCursor(dev) && dev->spriteInfo->sprite) {
        if (dev->spriteInfo->sprite->current)
            FreeCursor(dev->spriteInfo->sprite->current, None);
        free(dev->spriteInfo->sprite->spriteTrace);
        free(dev->spriteInfo->sprite);
    }
    dev->spriteInfo->sprite = NULL;
}


/**
 * Update the mouse sprite info when the server switches from a pScreen to another.
 * Otherwise, the pScreen of the mouse sprite is never updated when we switch
 * from a pScreen to another. Never updating the pScreen of the mouse sprite
 * implies that windows that are in pScreen whose pScreen->myNum >0 will never
 * get pointer events. This is  because in CheckMotion(), sprite.hotPhys.pScreen
 * always points to the first pScreen it has been set by
 * DefineInitialRootWindow().
 *
 * Calling this function is useful for use cases where the server
 * has more than one pScreen.
 * This function is similar to DefineInitialRootWindow() but it does not
 * reset the mouse pointer position.
 * @param win must be the new pScreen we are switching to.
 */
void
UpdateSpriteForScreen(DeviceIntPtr pDev, ScreenPtr pScreen)
{
    SpritePtr pSprite = NULL;
    WindowPtr win = NULL;
    CursorPtr pCursor;

    if (!pScreen)
        return;

    if (!pDev->spriteInfo->sprite)
        return;

    pSprite = pDev->spriteInfo->sprite;

    win = pScreen->root;

    pSprite->hotPhys.pScreen = pScreen;
    pSprite->hot = pSprite->hotPhys;
    pSprite->hotLimits.x2 = pScreen->width;
    pSprite->hotLimits.y2 = pScreen->height;
    pSprite->win = win;
    pCursor = RefCursor(wCursor(win));
    if (pSprite->current)
        FreeCursor(pSprite->current, 0);
    pSprite->current = pCursor;
    pSprite->spriteTraceGood = 1;
    pSprite->spriteTrace[0] = win;
    (*pScreen->CursorLimits) (pDev,
                              pScreen,
                              pSprite->current,
                              &pSprite->hotLimits, &pSprite->physLimits);
    pSprite->confined = FALSE;
    (*pScreen->ConstrainCursor) (pDev, pScreen, &pSprite->physLimits);
    (*pScreen->DisplayCursor) (pDev, pScreen, pSprite->current);

#ifdef PANORAMIX
    if (!noPanoramiXExtension) {
        pSprite->hotLimits.x1 = -screenInfo.screens[0]->x;
        pSprite->hotLimits.y1 = -screenInfo.screens[0]->y;
        pSprite->hotLimits.x2 = PanoramiXPixWidth - screenInfo.screens[0]->x;
        pSprite->hotLimits.y2 = PanoramiXPixHeight - screenInfo.screens[0]->y;
        pSprite->physLimits = pSprite->hotLimits;
        pSprite->screen = pScreen;
    }
#endif
}

/*
 * This does not take any shortcuts, and even ignores its argument, since
 * it does not happen very often, and one has to walk up the tree since
 * this might be a newly instantiated cursor for an intermediate window
 * between the one the pointer is in and the one that the last cursor was
 * instantiated from.
 */
void
WindowHasNewCursor(WindowPtr pWin)
{
    DeviceIntPtr pDev;

    for (pDev = inputInfo.devices; pDev; pDev = pDev->next)
        if (DevHasCursor(pDev))
            PostNewCursor(pDev);
}

void
NewCurrentScreen(DeviceIntPtr pDev, ScreenPtr newScreen, int x, int y)
{
    DeviceIntPtr ptr;
    SpritePtr pSprite;

    ptr =
        IsFloating(pDev) ? pDev :
        GetXTestDevice(GetMaster(pDev, MASTER_POINTER));
    pSprite = ptr->spriteInfo->sprite;

    pSprite->hotPhys.x = x;
    pSprite->hotPhys.y = y;
#ifdef PANORAMIX
    if (!noPanoramiXExtension) {
        pSprite->hotPhys.x += newScreen->x - screenInfo.screens[0]->x;
        pSprite->hotPhys.y += newScreen->y - screenInfo.screens[0]->y;
        if (newScreen != pSprite->screen) {
            pSprite->screen = newScreen;
            /* Make sure we tell the DDX to update its copy of the screen */
            if (pSprite->confineWin)
                XineramaConfineCursorToWindow(ptr, pSprite->confineWin, TRUE);
            else
                XineramaConfineCursorToWindow(ptr, screenInfo.screens[0]->root,
                                              TRUE);
            /* if the pointer wasn't confined, the DDX won't get
               told of the pointer warp so we reposition it here */
            if (!syncEvents.playingEvents)
                (*pSprite->screen->SetCursorPosition) (ptr,
                                                       pSprite->screen,
                                                       pSprite->hotPhys.x +
                                                       screenInfo.screens[0]->
                                                       x - pSprite->screen->x,
                                                       pSprite->hotPhys.y +
                                                       screenInfo.screens[0]->
                                                       y - pSprite->screen->y,
                                                       FALSE);
        }
    }
    else
#endif
    if (newScreen != pSprite->hotPhys.pScreen)
        ConfineCursorToWindow(ptr, newScreen->root, TRUE, FALSE);
}

#ifdef PANORAMIX

static Bool
XineramaPointInWindowIsVisible(WindowPtr pWin, int x, int y)
{
    BoxRec box;
    int i, xoff, yoff;

    if (!pWin->realized)
        return FALSE;

    if (RegionContainsPoint(&pWin->borderClip, x, y, &box))
        return TRUE;

    if (!XineramaSetWindowPntrs(inputInfo.pointer, pWin))
         return FALSE;

    xoff = x + screenInfo.screens[0]->x;
    yoff = y + screenInfo.screens[0]->y;

    FOR_NSCREENS_FORWARD_SKIP(i) {
        pWin = inputInfo.pointer->spriteInfo->sprite->windows[i];

        x = xoff - screenInfo.screens[i]->x;
        y = yoff - screenInfo.screens[i]->y;

        if (RegionContainsPoint(&pWin->borderClip, x, y, &box)
            && (!wInputShape(pWin) ||
                RegionContainsPoint(wInputShape(pWin),
                                    x - pWin->drawable.x,
                                    y - pWin->drawable.y, &box)))
            return TRUE;

    }

    return FALSE;
}

static int
XineramaWarpPointer(ClientPtr client)
{
    WindowPtr dest = NULL;
    int x, y, rc;
    SpritePtr pSprite = PickPointer(client)->spriteInfo->sprite;

    REQUEST(xWarpPointerReq);

    if (stuff->dstWid != None) {
        rc = dixLookupWindow(&dest, stuff->dstWid, client, DixReadAccess);
        if (rc != Success)
            return rc;
    }
    x = pSprite->hotPhys.x;
    y = pSprite->hotPhys.y;

    if (stuff->srcWid != None) {
        int winX, winY;
        XID winID = stuff->srcWid;
        WindowPtr source;

        rc = dixLookupWindow(&source, winID, client, DixReadAccess);
        if (rc != Success)
            return rc;

        winX = source->drawable.x;
        winY = source->drawable.y;
        if (source == screenInfo.screens[0]->root) {
            winX -= screenInfo.screens[0]->x;
            winY -= screenInfo.screens[0]->y;
        }
        if (x < winX + stuff->srcX ||
            y < winY + stuff->srcY ||
            (stuff->srcWidth != 0 &&
             winX + stuff->srcX + (int) stuff->srcWidth < x) ||
            (stuff->srcHeight != 0 &&
             winY + stuff->srcY + (int) stuff->srcHeight < y) ||
            !XineramaPointInWindowIsVisible(source, x, y))
            return Success;
    }
    if (dest) {
        x = dest->drawable.x;
        y = dest->drawable.y;
        if (dest == screenInfo.screens[0]->root) {
            x -= screenInfo.screens[0]->x;
            y -= screenInfo.screens[0]->y;
        }
    }

    x += stuff->dstX;
    y += stuff->dstY;

    if (x < pSprite->physLimits.x1)
        x = pSprite->physLimits.x1;
    else if (x >= pSprite->physLimits.x2)
        x = pSprite->physLimits.x2 - 1;
    if (y < pSprite->physLimits.y1)
        y = pSprite->physLimits.y1;
    else if (y >= pSprite->physLimits.y2)
        y = pSprite->physLimits.y2 - 1;
    if (pSprite->hotShape)
        ConfineToShape(PickPointer(client), pSprite->hotShape, &x, &y);

    XineramaSetCursorPosition(PickPointer(client), x, y, TRUE);

    return Success;
}

#endif

/**
 * Server-side protocol handling for WarpPointer request.
 * Warps the cursor position to the coordinates given in the request.
 */
int
ProcWarpPointer(ClientPtr client)
{
    WindowPtr dest = NULL;
    int x, y, rc;
    ScreenPtr newScreen;
    DeviceIntPtr dev, tmp;
    SpritePtr pSprite;

    REQUEST(xWarpPointerReq);
    REQUEST_SIZE_MATCH(xWarpPointerReq);

    dev = PickPointer(client);

    for (tmp = inputInfo.devices; tmp; tmp = tmp->next) {
        if (GetMaster(tmp, MASTER_ATTACHED) == dev) {
            rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, DixWriteAccess);
            if (rc != Success)
                return rc;
        }
    }

    if (dev->lastSlave)
        dev = dev->lastSlave;
    pSprite = dev->spriteInfo->sprite;

#ifdef PANORAMIX
    if (!noPanoramiXExtension)
        return XineramaWarpPointer(client);
#endif

    if (stuff->dstWid != None) {
        rc = dixLookupWindow(&dest, stuff->dstWid, client, DixGetAttrAccess);
        if (rc != Success)
            return rc;
    }
    x = pSprite->hotPhys.x;
    y = pSprite->hotPhys.y;

    if (stuff->srcWid != None) {
        int winX, winY;
        XID winID = stuff->srcWid;
        WindowPtr source;

        rc = dixLookupWindow(&source, winID, client, DixGetAttrAccess);
        if (rc != Success)
            return rc;

        winX = source->drawable.x;
        winY = source->drawable.y;
        if (source->drawable.pScreen != pSprite->hotPhys.pScreen ||
            x < winX + stuff->srcX ||
            y < winY + stuff->srcY ||
            (stuff->srcWidth != 0 &&
             winX + stuff->srcX + (int) stuff->srcWidth < x) ||
            (stuff->srcHeight != 0 &&
             winY + stuff->srcY + (int) stuff->srcHeight < y) ||
            !PointInWindowIsVisible(source, x, y))
            return Success;
    }
    if (dest) {
        x = dest->drawable.x;
        y = dest->drawable.y;
        newScreen = dest->drawable.pScreen;
    }
    else
        newScreen = pSprite->hotPhys.pScreen;

    x += stuff->dstX;
    y += stuff->dstY;

    if (x < 0)
        x = 0;
    else if (x >= newScreen->width)
        x = newScreen->width - 1;
    if (y < 0)
        y = 0;
    else if (y >= newScreen->height)
        y = newScreen->height - 1;

    if (newScreen == pSprite->hotPhys.pScreen) {
        if (x < pSprite->physLimits.x1)
            x = pSprite->physLimits.x1;
        else if (x >= pSprite->physLimits.x2)
            x = pSprite->physLimits.x2 - 1;
        if (y < pSprite->physLimits.y1)
            y = pSprite->physLimits.y1;
        else if (y >= pSprite->physLimits.y2)
            y = pSprite->physLimits.y2 - 1;
        if (pSprite->hotShape)
            ConfineToShape(dev, pSprite->hotShape, &x, &y);
        (*newScreen->SetCursorPosition) (dev, newScreen, x, y, TRUE);
    }
    else if (!PointerConfinedToScreen(dev)) {
        NewCurrentScreen(dev, newScreen, x, y);
    }
    return Success;
}

static Bool
BorderSizeNotEmpty(DeviceIntPtr pDev, WindowPtr pWin)
{
    if (RegionNotEmpty(&pWin->borderSize))
        return TRUE;

#ifdef PANORAMIX
    if (!noPanoramiXExtension && XineramaSetWindowPntrs(pDev, pWin)) {
        int i;

        FOR_NSCREENS_FORWARD_SKIP(i) {
            if (RegionNotEmpty
                (&pDev->spriteInfo->sprite->windows[i]->borderSize))
                return TRUE;
        }
    }
#endif
    return FALSE;
}

/**
 * Activate the given passive grab. If the grab is activated successfully, the
 * event has been delivered to the client.
 *
 * @param device The device of the event to check.
 * @param grab The grab to check.
 * @param event The current device event.
 * @param real_event The original event, in case of touch emulation. The
 * real event is the one stored in the sync queue.
 *
 * @return Whether the grab has been activated.
 */
Bool
ActivatePassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
                    InternalEvent *real_event)
{
    SpritePtr pSprite = device->spriteInfo->sprite;
    GrabInfoPtr grabinfo = &device->deviceGrab;
    xEvent *xE = NULL;
    int count;
    int rc;

    /* The only consumers of corestate are Xi 1.x and core events, which
     * are guaranteed to come from DeviceEvents. */
    if (grab->grabtype == XI || grab->grabtype == CORE) {
        DeviceIntPtr gdev;

        event->device_event.corestate &= 0x1f00;

        if (grab->grabtype == CORE)
            gdev = GetMaster(device, KEYBOARD_OR_FLOAT);
        else
            gdev = grab->modifierDevice;

        if (gdev && gdev->key && gdev->key->xkbInfo)
            event->device_event.corestate |=
                gdev->key->xkbInfo->state.grab_mods & (~0x1f00);
    }

    if (grab->grabtype == CORE) {
        rc = EventToCore(event, &xE, &count);
        if (rc != Success) {
            BUG_WARN_MSG(rc != BadMatch, "[dix] %s: core conversion failed"
                         "(%d, %d).\n", device->name, event->any.type, rc);
            return FALSE;
        }
    }
    else if (grab->grabtype == XI2) {
        rc = EventToXI2(event, &xE);
        if (rc != Success) {
            if (rc != BadMatch)
                BUG_WARN_MSG(rc != BadMatch, "[dix] %s: XI2 conversion failed"
                             "(%d, %d).\n", device->name, event->any.type, rc);
            return FALSE;
        }
        count = 1;
    }
    else {
        rc = EventToXI(event, &xE, &count);
        if (rc != Success) {
            if (rc != BadMatch)
                BUG_WARN_MSG(rc != BadMatch, "[dix] %s: XI conversion failed"
                             "(%d, %d).\n", device->name, event->any.type, rc);
            return FALSE;
        }
    }

    (*grabinfo->ActivateGrab) (device, grab,
                               ClientTimeToServerTime(event->any.time), TRUE);

    if (xE) {
        FixUpEventFromWindow(pSprite, xE, grab->window, None, TRUE);

        /* XXX: XACE? */
        TryClientEvents(rClient(grab), device, xE, count,
                        GetEventFilter(device, xE),
                        GetEventFilter(device, xE), grab);
    }

    if (grabinfo->sync.state == FROZEN_NO_EVENT)
        grabinfo->sync.state = FROZEN_WITH_EVENT;
    *grabinfo->sync.event = real_event->device_event;

    free(xE);
    return TRUE;
}

static BOOL
CoreGrabInterferes(DeviceIntPtr device, GrabPtr grab)
{
    DeviceIntPtr other;
    BOOL interfering = FALSE;

    for (other = inputInfo.devices; other; other = other->next) {
        GrabPtr othergrab = other->deviceGrab.grab;

        if (othergrab && othergrab->grabtype == CORE &&
            SameClient(grab, rClient(othergrab)) &&
            ((IsPointerDevice(grab->device) &&
              IsPointerDevice(othergrab->device)) ||
             (IsKeyboardDevice(grab->device) &&
              IsKeyboardDevice(othergrab->device)))) {
            interfering = TRUE;
            break;
        }
    }

    return interfering;
}

enum MatchFlags {
    NO_MATCH = 0x0,
    CORE_MATCH = 0x1,
    XI_MATCH = 0x2,
    XI2_MATCH = 0x4,
};

/**
 * Match the grab against the temporary grab on the given input level.
 * Modifies the temporary grab pointer.
 *
 * @param grab The grab to match against
 * @param tmp The temporary grab to use for matching
 * @param level The input level we want to match on
 * @param event_type Wire protocol event type
 *
 * @return The respective matched flag or 0 for no match
 */
static enum MatchFlags
MatchForType(const GrabPtr grab, GrabPtr tmp, enum InputLevel level,
             int event_type)
{
    enum MatchFlags match;
    BOOL ignore_device = FALSE;
    int grabtype;
    int evtype;

    switch (level) {
    case XI2:
        grabtype = XI2;
        evtype = GetXI2Type(event_type);
        BUG_WARN(!evtype);
        match = XI2_MATCH;
        break;
    case XI:
        grabtype = XI;
        evtype = GetXIType(event_type);
        match = XI_MATCH;
        break;
    case CORE:
        grabtype = CORE;
        evtype = GetCoreType(event_type);
        match = CORE_MATCH;
        ignore_device = TRUE;
        break;
    default:
        return NO_MATCH;
    }

    tmp->grabtype = grabtype;
    tmp->type = evtype;

    if (tmp->type && GrabMatchesSecond(tmp, grab, ignore_device))
        return match;

    return NO_MATCH;
}

/**
 * Check an individual grab against an event to determine if a passive grab
 * should be activated.
 *
 * @param device The device of the event to check.
 * @param grab The grab to check.
 * @param event The current device event.
 * @param checkCore Check for core grabs too.
 * @param tempGrab A pre-allocated temporary grab record for matching. This
 *        must have the window and device values filled in.
 *
 * @return Whether the grab matches the event.
 */
static Bool
CheckPassiveGrab(DeviceIntPtr device, GrabPtr grab, InternalEvent *event,
                 Bool checkCore, GrabPtr tempGrab)
{
    DeviceIntPtr gdev;
    XkbSrvInfoPtr xkbi = NULL;
    enum MatchFlags match = 0;
    int emulated_type = 0;

    gdev = grab->modifierDevice;
    if (grab->grabtype == CORE) {
        gdev = GetMaster(device, KEYBOARD_OR_FLOAT);
    }
    else if (grab->grabtype == XI2) {
        /* if the device is an attached slave device, gdev must be the
         * attached master keyboard. Since the slave may have been
         * reattached after the grab, the modifier device may not be the
         * same. */
        if (!IsMaster(grab->device) && !IsFloating(device))
            gdev = GetMaster(device, MASTER_KEYBOARD);
    }

    if (gdev && gdev->key)
        xkbi = gdev->key->xkbInfo;
    tempGrab->modifierDevice = grab->modifierDevice;
    tempGrab->modifiersDetail.exact = xkbi ? xkbi->state.grab_mods : 0;

    /* Check for XI2 and XI grabs first */
    match = MatchForType(grab, tempGrab, XI2, event->any.type);

    if (!match && IsTouchEvent(event) &&
        (event->device_event.flags & TOUCH_POINTER_EMULATED)) {
        emulated_type = TouchGetPointerEventType(event);
        match = MatchForType(grab, tempGrab, XI2, emulated_type);
    }

    if (!match)
        match = MatchForType(grab, tempGrab, XI, event->any.type);

    if (!match && emulated_type)
        match = MatchForType(grab, tempGrab, XI, emulated_type);

    if (!match && checkCore) {
        match = MatchForType(grab, tempGrab, CORE, event->any.type);
        if (!match && emulated_type)
            match = MatchForType(grab, tempGrab, CORE, emulated_type);
    }

    if (!match || (grab->confineTo &&
                   (!grab->confineTo->realized ||
                    !BorderSizeNotEmpty(device, grab->confineTo))))
        return FALSE;

    /* In some cases a passive core grab may exist, but the client
     * already has a core grab on some other device. In this case we
     * must not get the grab, otherwise we may never ungrab the
     * device.
     */

    if (grab->grabtype == CORE) {
        /* A passive grab may have been created for a different device
           than it is assigned to at this point in time.
           Update the grab's device and modifier device to reflect the
           current state.
           Since XGrabDeviceButton requires to specify the
           modifierDevice explicitly, we don't override this choice.
         */
        if (grab->type < GenericEvent) {
            grab->device = device;
            grab->modifierDevice = GetMaster(device, MASTER_KEYBOARD);
        }

        if (CoreGrabInterferes(device, grab))
            return FALSE;
    }

    return TRUE;
}

/**
 * "CheckPassiveGrabsOnWindow" checks to see if the event passed in causes a
 * passive grab set on the window to be activated.
 * If activate is true and a passive grab is found, it will be activated,
 * and the event will be delivered to the client.
 *
 * @param pWin The window that may be subject to a passive grab.
 * @param device Device that caused the event.
 * @param event The current device event.
 * @param checkCore Check for core grabs too.
 * @param activate If a grab is found, activate it and deliver the event.
 */

GrabPtr
CheckPassiveGrabsOnWindow(WindowPtr pWin,
                          DeviceIntPtr device,
                          InternalEvent *event, BOOL checkCore, BOOL activate)
{
    GrabPtr grab = wPassiveGrabs(pWin);
    GrabPtr tempGrab;

    if (!grab)
        return NULL;

    tempGrab = AllocGrab(NULL);
    if (tempGrab == NULL)
        return NULL;

    /* Fill out the grab details, but leave the type for later before
     * comparing */
    switch (event->any.type) {
    case ET_KeyPress:
    case ET_KeyRelease:
        tempGrab->detail.exact = event->device_event.detail.key;
        break;
    case ET_ButtonPress:
    case ET_ButtonRelease:
    case ET_TouchBegin:
    case ET_TouchEnd:
        tempGrab->detail.exact = event->device_event.detail.button;
        break;
    default:
        tempGrab->detail.exact = 0;
        break;
    }
    tempGrab->window = pWin;
    tempGrab->device = device;
    tempGrab->detail.pMask = NULL;
    tempGrab->modifiersDetail.pMask = NULL;
    tempGrab->next = NULL;

    for (; grab; grab = grab->next) {
        if (!CheckPassiveGrab(device, grab, event, checkCore, tempGrab))
            continue;

        if (activate && !ActivatePassiveGrab(device, grab, event, event))
            continue;

        break;
    }

    FreeGrab(tempGrab);
    return grab;
}

/**
 * CheckDeviceGrabs handles both keyboard and pointer events that may cause
 * a passive grab to be activated.
 *
 * If the event is a keyboard event, the ancestors of the focus window are
 * traced down and tried to see if they have any passive grabs to be
 * activated.  If the focus window itself is reached and it's descendants
 * contain the pointer, the ancestors of the window that the pointer is in
 * are then traced down starting at the focus window, otherwise no grabs are
 * activated.
 * If the event is a pointer event, the ancestors of the window that the
 * pointer is in are traced down starting at the root until CheckPassiveGrabs
 * causes a passive grab to activate or all the windows are
 * tried. PRH
 *
 * If a grab is activated, the event has been sent to the client already!
 *
 * The event we pass in must always be an XI event. From this, we then emulate
 * the core event and then check for grabs.
 *
 * @param device The device that caused the event.
 * @param xE The event to handle (Device{Button|Key}Press).
 * @param count Number of events in list.
 * @return TRUE if a grab has been activated or false otherwise.
*/

Bool
CheckDeviceGrabs(DeviceIntPtr device, DeviceEvent *event, WindowPtr ancestor)
{
    int i;
    WindowPtr pWin = NULL;
    FocusClassPtr focus =
        IsPointerEvent((InternalEvent *) event) ? NULL : device->focus;
    BOOL sendCore = (IsMaster(device) && device->coreEvents);
    Bool ret = FALSE;

    if (event->type != ET_ButtonPress && event->type != ET_KeyPress)
        return FALSE;

    if (event->type == ET_ButtonPress && (device->button->buttonsDown != 1))
        return FALSE;

    if (device->deviceGrab.grab)
        return FALSE;

    i = 0;
    if (ancestor) {
        while (i < device->spriteInfo->sprite->spriteTraceGood)
            if (device->spriteInfo->sprite->spriteTrace[i++] == ancestor)
                break;
        if (i == device->spriteInfo->sprite->spriteTraceGood)
            goto out;
    }

    if (focus) {
        for (; i < focus->traceGood; i++) {
            pWin = focus->trace[i];
            if (CheckPassiveGrabsOnWindow(pWin, device, (InternalEvent *) event,
                                          sendCore, TRUE)) {
                ret = TRUE;
                goto out;
            }
        }

        if ((focus->win == NoneWin) ||
            (i >= device->spriteInfo->sprite->spriteTraceGood) ||
            (pWin && pWin != device->spriteInfo->sprite->spriteTrace[i - 1]))
            goto out;
    }

    for (; i < device->spriteInfo->sprite->spriteTraceGood; i++) {
        pWin = device->spriteInfo->sprite->spriteTrace[i];
        if (CheckPassiveGrabsOnWindow(pWin, device, (InternalEvent *) event,
                                      sendCore, TRUE)) {
            ret = TRUE;
            goto out;
        }
    }

 out:
    if (ret == TRUE && event->type == ET_KeyPress)
        device->deviceGrab.activatingKey = event->detail.key;
    return ret;
}

/**
 * Called for keyboard events to deliver event to whatever client owns the
 * focus.
 *
 * The event is delivered to the keyboard's focus window, the root window or
 * to the window owning the input focus.
 *
 * @param keybd The keyboard originating the event.
 * @param event The event, not yet in wire format.
 * @param window Window underneath the sprite.
 */
void
DeliverFocusedEvent(DeviceIntPtr keybd, InternalEvent *event, WindowPtr window)
{
    DeviceIntPtr ptr;
    WindowPtr focus = keybd->focus->win;
    BOOL sendCore = (IsMaster(keybd) && keybd->coreEvents);
    xEvent *core = NULL, *xE = NULL, *xi2 = NULL;
    int count, rc;
    int deliveries = 0;

    if (focus == FollowKeyboardWin)
        focus = inputInfo.keyboard->focus->win;
    if (!focus)
        return;
    if (focus == PointerRootWin) {
        DeliverDeviceEvents(window, event, NullGrab, NullWindow, keybd);
        return;
    }
    if ((focus == window) || IsParent(focus, window)) {
        if (DeliverDeviceEvents(window, event, NullGrab, focus, keybd))
            return;
    }

    /* just deliver it to the focus window */
    ptr = GetMaster(keybd, POINTER_OR_FLOAT);

    rc = EventToXI2(event, &xi2);
    if (rc == Success) {
        /* XXX: XACE */
        int filter = GetEventFilter(keybd, xi2);

        FixUpEventFromWindow(ptr->spriteInfo->sprite, xi2, focus, None, FALSE);
        deliveries = DeliverEventsToWindow(keybd, focus, xi2, 1,
                                           filter, NullGrab);
        if (deliveries > 0)
            goto unwind;
    }
    else if (rc != BadMatch)
        ErrorF
            ("[dix] %s: XI2 conversion failed in DFE (%d, %d). Skipping delivery.\n",
             keybd->name, event->any.type, rc);

    rc = EventToXI(event, &xE, &count);
    if (rc == Success &&
        XaceHook(XACE_SEND_ACCESS, NULL, keybd, focus, xE, count) == Success) {
        FixUpEventFromWindow(ptr->spriteInfo->sprite, xE, focus, None, FALSE);
        deliveries = DeliverEventsToWindow(keybd, focus, xE, count,
                                           GetEventFilter(keybd, xE), NullGrab);

        if (deliveries > 0)
            goto unwind;
    }
    else if (rc != BadMatch)
        ErrorF
            ("[dix] %s: XI conversion failed in DFE (%d, %d). Skipping delivery.\n",
             keybd->name, event->any.type, rc);

    if (sendCore) {
        rc = EventToCore(event, &core, &count);
        if (rc == Success) {
            if (XaceHook(XACE_SEND_ACCESS, NULL, keybd, focus, core, count) ==
                Success) {
                FixUpEventFromWindow(keybd->spriteInfo->sprite, core, focus,
                                     None, FALSE);
                deliveries =
                    DeliverEventsToWindow(keybd, focus, core, count,
                                          GetEventFilter(keybd, core),
                                          NullGrab);
            }
        }
        else if (rc != BadMatch)
            ErrorF
                ("[dix] %s: core conversion failed DFE (%d, %d). Skipping delivery.\n",
                 keybd->name, event->any.type, rc);
    }

 unwind:
    free(core);
    free(xE);
    free(xi2);
    return;
}

int
DeliverOneGrabbedEvent(InternalEvent *event, DeviceIntPtr dev,
                       enum InputLevel level)
{
    SpritePtr pSprite = dev->spriteInfo->sprite;
    int rc;
    xEvent *xE = NULL;
    int count = 0;
    int deliveries = 0;
    Mask mask;
    GrabInfoPtr grabinfo = &dev->deviceGrab;
    GrabPtr grab = grabinfo->grab;
    Mask filter;

    if (grab->grabtype != level)
        return 0;

    switch (level) {
    case XI2:
        rc = EventToXI2(event, &xE);
        count = 1;
        if (rc == Success) {
            int evtype = xi2_get_type(xE);

            mask = GetXI2MaskByte(grab->xi2mask, dev, evtype);
            filter = GetEventFilter(dev, xE);
        }
        break;
    case XI:
        if (grabinfo->fromPassiveGrab && grabinfo->implicitGrab)
            mask = grab->deviceMask;
        else
            mask = grab->eventMask;
        rc = EventToXI(event, &xE, &count);
        if (rc == Success)
            filter = GetEventFilter(dev, xE);
        break;
    case CORE:
        rc = EventToCore(event, &xE, &count);
        mask = grab->eventMask;
        if (rc == Success)
            filter = GetEventFilter(dev, xE);
        break;
    default:
        BUG_WARN_MSG(1, "Invalid input level %d\n", level);
        return 0;
    }

    if (rc == Success) {
        FixUpEventFromWindow(pSprite, xE, grab->window, None, TRUE);
        if (XaceHook(XACE_SEND_ACCESS, 0, dev,
                     grab->window, xE, count) ||
            XaceHook(XACE_RECEIVE_ACCESS, rClient(grab),
                     grab->window, xE, count))
            deliveries = 1;     /* don't send, but pretend we did */
        else if (level != CORE || !IsInterferingGrab(rClient(grab), dev, xE)) {
            deliveries = TryClientEvents(rClient(grab), dev,
                                         xE, count, mask, filter, grab);
        }
    }
    else
        BUG_WARN_MSG(rc != BadMatch,
                     "%s: conversion to mode %d failed on %d with %d\n",
                     dev->name, level, event->any.type, rc);

    free(xE);
    return deliveries;
}

/**
 * Deliver an event from a device that is currently grabbed. Uses
 * DeliverDeviceEvents() for further delivery if a ownerEvents is set on the
 * grab. If not, TryClientEvents() is used.
 *
 * @param deactivateGrab True if the device's grab should be deactivated.
 *
 * @return The number of events delivered.
 */
int
DeliverGrabbedEvent(InternalEvent *event, DeviceIntPtr thisDev,
                    Bool deactivateGrab)
{
    GrabPtr grab;
    GrabInfoPtr grabinfo;
    int deliveries = 0;
    DeviceIntPtr dev;
    SpritePtr pSprite = thisDev->spriteInfo->sprite;
    BOOL sendCore = FALSE;

    grabinfo = &thisDev->deviceGrab;
    grab = grabinfo->grab;

    if (grab->ownerEvents) {
        WindowPtr focus;

        /* Hack: Some pointer device have a focus class. So we need to check
         * for the type of event, to see if we really want to deliver it to
         * the focus window. For pointer events, the answer is no.
         */
        if (IsPointerEvent(event))
            focus = PointerRootWin;
        else if (thisDev->focus) {
            focus = thisDev->focus->win;
            if (focus == FollowKeyboardWin)
                focus = inputInfo.keyboard->focus->win;
        }
        else
            focus = PointerRootWin;
        if (focus == PointerRootWin)
            deliveries = DeliverDeviceEvents(pSprite->win, event, grab,
                                             NullWindow, thisDev);
        else if (focus && (focus == pSprite->win ||
                           IsParent(focus, pSprite->win)))
            deliveries = DeliverDeviceEvents(pSprite->win, event, grab, focus,
                                             thisDev);
        else if (focus)
            deliveries = DeliverDeviceEvents(focus, event, grab, focus,
                                             thisDev);
    }
    if (!deliveries) {
        sendCore = (IsMaster(thisDev) && thisDev->coreEvents);
        /* try core event */
        if ((sendCore && grab->grabtype == CORE) || grab->grabtype != CORE)
            deliveries = DeliverOneGrabbedEvent(event, thisDev, grab->grabtype);

        if (deliveries && (event->any.type == ET_Motion))
            thisDev->valuator->motionHintWindow = grab->window;
    }
    if (deliveries && !deactivateGrab &&
        (event->any.type == ET_KeyPress ||
         event->any.type == ET_KeyRelease ||
         event->any.type == ET_ButtonPress ||
         event->any.type == ET_ButtonRelease)) {
        switch (grabinfo->sync.state) {
        case FREEZE_BOTH_NEXT_EVENT:
            dev = GetPairedDevice(thisDev);
            if (dev) {
                FreezeThaw(dev, TRUE);
                if ((dev->deviceGrab.sync.state == FREEZE_BOTH_NEXT_EVENT) &&
                    (CLIENT_BITS(grab->resource) ==
                     CLIENT_BITS(dev->deviceGrab.grab->resource)))
                    dev->deviceGrab.sync.state = FROZEN_NO_EVENT;
                else
                    dev->deviceGrab.sync.other = grab;
            }
            /* fall through */
        case FREEZE_NEXT_EVENT:
            grabinfo->sync.state = FROZEN_WITH_EVENT;
            FreezeThaw(thisDev, TRUE);
            *grabinfo->sync.event = event->device_event;
            break;
        }
    }

    return deliveries;
}

/* This function is used to set the key pressed or key released state -
   this is only used when the pressing of keys does not cause
   the device's processInputProc to be called, as in for example Mouse Keys.
*/
void
FixKeyState(DeviceEvent *event, DeviceIntPtr keybd)
{
    int key = event->detail.key;

    if (event->type == ET_KeyPress) {
        DebugF("FixKeyState: Key %d %s\n", key,
               ((event->type == ET_KeyPress) ? "down" : "up"));
    }

    if (event->type == ET_KeyPress)
        set_key_down(keybd, key, KEY_PROCESSED);
    else if (event->type == ET_KeyRelease)
        set_key_up(keybd, key, KEY_PROCESSED);
    else
        FatalError("Impossible keyboard event");
}

#define AtMostOneClient \
	(SubstructureRedirectMask | ResizeRedirectMask | ButtonPressMask)
#define ManagerMask \
	(SubstructureRedirectMask | ResizeRedirectMask)

/**
 * Recalculate which events may be deliverable for the given window.
 * Recalculated mask is used for quicker determination which events may be
 * delivered to a window.
 *
 * The otherEventMasks on a WindowOptional is the combination of all event
 * masks set by all clients on the window.
 * deliverableEventMask is the combination of the eventMask and the
 * otherEventMask plus the events that may be propagated to the parent.
 *
 * Traverses to siblings and parents of the window.
 */
void
RecalculateDeliverableEvents(WindowPtr pWin)
{
    OtherClients *others;
    WindowPtr pChild;

    pChild = pWin;
    while (1) {
        if (pChild->optional) {
            pChild->optional->otherEventMasks = 0;
            for (others = wOtherClients(pChild); others; others = others->next) {
                pChild->optional->otherEventMasks |= others->mask;
            }
        }
        pChild->deliverableEvents = pChild->eventMask |
            wOtherEventMasks(pChild);
        if (pChild->parent)
            pChild->deliverableEvents |=
                (pChild->parent->deliverableEvents &
                 ~wDontPropagateMask(pChild) & PropagateMask);
        if (pChild->firstChild) {
            pChild = pChild->firstChild;
            continue;
        }
        while (!pChild->nextSib && (pChild != pWin))
            pChild = pChild->parent;
        if (pChild == pWin)
            break;
        pChild = pChild->nextSib;
    }
}

/**
 *
 *  \param value must conform to DeleteType
 */
int
OtherClientGone(void *value, XID id)
{
    OtherClientsPtr other, prev;
    WindowPtr pWin = (WindowPtr) value;

    prev = 0;
    for (other = wOtherClients(pWin); other; other = other->next) {
        if (other->resource == id) {
            if (prev)
                prev->next = other->next;
            else {
                if (!(pWin->optional->otherClients = other->next))
                    CheckWindowOptionalNeed(pWin);
            }
            free(other);
            RecalculateDeliverableEvents(pWin);
            return Success;
        }
        prev = other;
    }
    FatalError("client not on event list");
    return BadValue; // to avoid warning
}

int
EventSelectForWindow(WindowPtr pWin, ClientPtr client, Mask mask)
{
    Mask check;
    OtherClients *others;
    DeviceIntPtr dev;
    int rc;

    if (mask & ~AllEventMasks) {
        client->errorValue = mask;
        return BadValue;
    }
    check = (mask & ManagerMask);
    if (check) {
        rc = XaceHook(XACE_RESOURCE_ACCESS, client, pWin->drawable.id,
                      RT_WINDOW, pWin, RT_NONE, NULL, DixManageAccess);
        if (rc != Success)
            return rc;
    }
    check = (mask & AtMostOneClient);
    if (check & (pWin->eventMask | wOtherEventMasks(pWin))) {
        /* It is illegal for two different clients to select on any of the
           events for AtMostOneClient. However, it is OK, for some client to
           continue selecting on one of those events.  */
        if ((wClient(pWin) != client) && (check & pWin->eventMask))
            return BadAccess;
        for (others = wOtherClients(pWin); others; others = others->next) {
            if (!SameClient(others, client) && (check & others->mask))
                return BadAccess;
        }
    }
    if (wClient(pWin) == client) {
        check = pWin->eventMask;
        pWin->eventMask = mask;
    }
    else {
        for (others = wOtherClients(pWin); others; others = others->next) {
            if (SameClient(others, client)) {
                check = others->mask;
                if (mask == 0) {
                    FreeResource(others->resource, RT_NONE);
                    return Success;
                }
                else
                    others->mask = mask;
                goto maskSet;
            }
        }
        check = 0;
        if (!pWin->optional && !MakeWindowOptional(pWin))
            return BadAlloc;
        others = malloc(sizeof(OtherClients));
        if (!others)
            return BadAlloc;
        others->mask = mask;
        others->resource = FakeClientID(client->index);
        others->next = pWin->optional->otherClients;
        pWin->optional->otherClients = others;
        if (!AddResource(others->resource, RT_OTHERCLIENT, (void *) pWin))
            return BadAlloc;
    }
 maskSet:
    if ((mask & PointerMotionHintMask) && !(check & PointerMotionHintMask)) {
        for (dev = inputInfo.devices; dev; dev = dev->next) {
            if (dev->valuator && dev->valuator->motionHintWindow == pWin)
                dev->valuator->motionHintWindow = NullWindow;
        }
    }
    RecalculateDeliverableEvents(pWin);
    return Success;
}

int
EventSuppressForWindow(WindowPtr pWin, ClientPtr client,
                       Mask mask, Bool *checkOptional)
{
    int i, freed;

    if (mask & ~PropagateMask) {
        client->errorValue = mask;
        return BadValue;
    }
    if (pWin->dontPropagate)
        DontPropagateRefCnts[pWin->dontPropagate]--;
    if (!mask)
        i = 0;
    else {
        for (i = DNPMCOUNT, freed = 0; --i > 0;) {
            if (!DontPropagateRefCnts[i])
                freed = i;
            else if (mask == DontPropagateMasks[i])
                break;
        }
        if (!i && freed) {
            i = freed;
            DontPropagateMasks[i] = mask;
        }
    }
    if (i || !mask) {
        pWin->dontPropagate = i;
        if (i)
            DontPropagateRefCnts[i]++;
        if (pWin->optional) {
            pWin->optional->dontPropagateMask = mask;
            *checkOptional = TRUE;
        }
    }
    else {
        if (!pWin->optional && !MakeWindowOptional(pWin)) {
            if (pWin->dontPropagate)
                DontPropagateRefCnts[pWin->dontPropagate]++;
            return BadAlloc;
        }
        pWin->dontPropagate = 0;
        pWin->optional->dontPropagateMask = mask;
    }
    RecalculateDeliverableEvents(pWin);
    return Success;
}

/**
 * Assembles an EnterNotify or LeaveNotify and sends it event to the client.
 * Uses the paired keyboard to get some additional information.
 */
void
CoreEnterLeaveEvent(DeviceIntPtr mouse,
                    int type,
                    int mode, int detail, WindowPtr pWin, Window child)
{
    xEvent event;
    WindowPtr focus;
    DeviceIntPtr keybd;
    GrabPtr grab = mouse->deviceGrab.grab;
    Mask mask;

    keybd = GetMaster(mouse, KEYBOARD_OR_FLOAT);

    if ((pWin == mouse->valuator->motionHintWindow) &&
        (detail != NotifyInferior))
        mouse->valuator->motionHintWindow = NullWindow;
    if (grab) {
        mask = (pWin == grab->window) ? grab->eventMask : 0;
        if (grab->ownerEvents)
            mask |= EventMaskForClient(pWin, rClient(grab));
    }
    else {
        mask = pWin->eventMask | wOtherEventMasks(pWin);
    }

    memset(&event, 0, sizeof(xEvent));
    event.u.u.type = type;
    event.u.u.detail = detail;
    event.u.enterLeave.time = currentTime.milliseconds;
    event.u.enterLeave.rootX = mouse->spriteInfo->sprite->hot.x;
    event.u.enterLeave.rootY = mouse->spriteInfo->sprite->hot.y;
    /* Counts on the same initial structure of crossing & button events! */
    FixUpEventFromWindow(mouse->spriteInfo->sprite, &event, pWin, None, FALSE);
    /* Enter/Leave events always set child */
    event.u.enterLeave.child = child;
    event.u.enterLeave.flags = event.u.keyButtonPointer.sameScreen ?
        ELFlagSameScreen : 0;
    event.u.enterLeave.state =
        mouse->button ? (mouse->button->state & 0x1f00) : 0;
    if (keybd)
        event.u.enterLeave.state |=
            XkbGrabStateFromRec(&keybd->key->xkbInfo->state);
    event.u.enterLeave.mode = mode;
    focus = (keybd) ? keybd->focus->win : None;
    if ((focus != NoneWin) &&
        ((pWin == focus) || (focus == PointerRootWin) || IsParent(focus, pWin)))
        event.u.enterLeave.flags |= ELFlagFocus;

    if ((mask & GetEventFilter(mouse, &event))) {
        if (grab)
            TryClientEvents(rClient(grab), mouse, &event, 1, mask,
                            GetEventFilter(mouse, &event), grab);
        else
            DeliverEventsToWindow(mouse, pWin, &event, 1,
                                  GetEventFilter(mouse, &event), NullGrab);
    }

    if ((type == EnterNotify) && (mask & KeymapStateMask)) {
        xKeymapEvent ke;
        ClientPtr client = grab ? rClient(grab) : wClient(pWin);
        int rc;

        rc = XaceHook(XACE_DEVICE_ACCESS, client, keybd, DixReadAccess);
        if (rc == Success)
            memcpy((char *) &ke.map[0], (char *) &keybd->key->down[1], 31);
        else
            memset((char *) &ke.map[0], 0, 31);        

        ke.type = KeymapNotify;
        if (grab)
            TryClientEvents(rClient(grab), keybd, (xEvent *) &ke, 1,
                            mask, KeymapStateMask, grab);
        else
            DeliverEventsToWindow(mouse, pWin, (xEvent *) &ke, 1,
                                  KeymapStateMask, NullGrab);
    }
}

void
DeviceEnterLeaveEvent(DeviceIntPtr mouse,
                      int sourceid,
                      int type,
                      int mode, int detail, WindowPtr pWin, Window child)
{
    GrabPtr grab = mouse->deviceGrab.grab;
    xXIEnterEvent *event;
    WindowPtr focus;
    int filter;
    int btlen, len, i;
    DeviceIntPtr kbd;

    if ((mode == XINotifyPassiveGrab && type == XI_Leave) ||
        (mode == XINotifyPassiveUngrab && type == XI_Enter))
        return;

    btlen = (mouse->button) ? bits_to_bytes(mouse->button->numButtons) : 0;
    btlen = bytes_to_int32(btlen);
    len = sizeof(xXIEnterEvent) + btlen * 4;

    event = calloc(1, len);
    event->type = GenericEvent;
    event->extension = IReqCode;
    event->evtype = type;
    event->length = (len - sizeof(xEvent)) / 4;
    event->buttons_len = btlen;
    event->detail = detail;
    event->time = currentTime.milliseconds;
    event->deviceid = mouse->id;
    event->sourceid = sourceid;
    event->mode = mode;
    event->root_x = double_to_fp1616(mouse->spriteInfo->sprite->hot.x);
    event->root_y = double_to_fp1616(mouse->spriteInfo->sprite->hot.y);

    for (i = 0; mouse && mouse->button && i < mouse->button->numButtons; i++)
        if (BitIsOn(mouse->button->down, i))
            SetBit(&event[1], i);

    kbd = GetMaster(mouse, MASTER_KEYBOARD);
    if (kbd && kbd->key) {
        event->mods.base_mods = kbd->key->xkbInfo->state.base_mods;
        event->mods.latched_mods = kbd->key->xkbInfo->state.latched_mods;
        event->mods.locked_mods = kbd->key->xkbInfo->state.locked_mods;

        event->group.base_group = kbd->key->xkbInfo->state.base_group;
        event->group.latched_group = kbd->key->xkbInfo->state.latched_group;
        event->group.locked_group = kbd->key->xkbInfo->state.locked_group;
    }

    focus = (kbd) ? kbd->focus->win : None;
    if ((focus != NoneWin) &&
        ((pWin == focus) || (focus == PointerRootWin) || IsParent(focus, pWin)))
        event->focus = TRUE;

    FixUpEventFromWindow(mouse->spriteInfo->sprite, (xEvent *) event, pWin,
                         None, FALSE);

    filter = GetEventFilter(mouse, (xEvent *) event);

    if (grab && grab->grabtype == XI2) {
        Mask mask;

        mask = xi2mask_isset(grab->xi2mask, mouse, type);
        TryClientEvents(rClient(grab), mouse, (xEvent *) event, 1, mask, 1,
                        grab);
    }
    else {
        if (!WindowXI2MaskIsset(mouse, pWin, (xEvent *) event))
            goto out;
        DeliverEventsToWindow(mouse, pWin, (xEvent *) event, 1, filter,
                              NullGrab);
    }

 out:
    free(event);
}

void
CoreFocusEvent(DeviceIntPtr dev, int type, int mode, int detail, WindowPtr pWin)
{
    xEvent event; memset(&event, 0, sizeof(xEvent));
    event.u.u.type = type;
    event.u.u.detail = detail;

    event.u.focus.mode = mode;
    event.u.focus.window = pWin->drawable.id;

    DeliverEventsToWindow(dev, pWin, &event, 1,
                          GetEventFilter(dev, &event), NullGrab);
    if ((type == FocusIn) &&
        ((pWin->eventMask | wOtherEventMasks(pWin)) & KeymapStateMask)) {
        xKeymapEvent ke;
        ClientPtr client = wClient(pWin);
        int rc;

        rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, DixReadAccess);
        if (rc == Success)
            memcpy((char *) &ke.map[0], (char *) &dev->key->down[1], 31);
        else
            memset((char *) &ke.map[0], 0, 31);

        ke.type = KeymapNotify;
        DeliverEventsToWindow(dev, pWin, (xEvent *) &ke, 1,
                              KeymapStateMask, NullGrab);
    }
}

/**
 * Set the input focus to the given window. Subsequent keyboard events will be
 * delivered to the given window.
 *
 * Usually called from ProcSetInputFocus as result of a client request. If so,
 * the device is the inputInfo.keyboard.
 * If called from ProcXSetInputFocus as result of a client xinput request, the
 * device is set to the device specified by the client.
 *
 * @param client Client that requested input focus change.
 * @param dev Focus device.
 * @param focusID The window to obtain the focus. Can be PointerRoot or None.
 * @param revertTo Specifies where the focus reverts to when window becomes
 * unviewable.
 * @param ctime Specifies the time.
 * @param followOK True if pointer is allowed to follow the keyboard.
 */
int
SetInputFocus(ClientPtr client,
              DeviceIntPtr dev,
              Window focusID, CARD8 revertTo, Time ctime, Bool followOK)
{
    FocusClassPtr focus;
    WindowPtr focusWin;
    int mode, rc;
    TimeStamp time;
    DeviceIntPtr keybd;         /* used for FollowKeyboard or FollowKeyboardWin */

    UpdateCurrentTime();
    if ((revertTo != RevertToParent) &&
        (revertTo != RevertToPointerRoot) &&
        (revertTo != RevertToNone) &&
        ((revertTo != RevertToFollowKeyboard) || !followOK)) {
        client->errorValue = revertTo;
        return BadValue;
    }
    time = ClientTimeToServerTime(ctime);

    keybd = GetMaster(dev, KEYBOARD_OR_FLOAT);

    if ((focusID == None) || (focusID == PointerRoot))
        focusWin = (WindowPtr) (long) focusID;
    else if ((focusID == FollowKeyboard) && followOK) {
        focusWin = keybd->focus->win;
    }
    else {
        rc = dixLookupWindow(&focusWin, focusID, client, DixSetAttrAccess);
        if (rc != Success)
            return rc;
        /* It is a match error to try to set the input focus to an
           unviewable window. */
        if (!focusWin->realized)
            return BadMatch;
    }
    rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, DixSetFocusAccess);
    if (rc != Success)
        return Success;

    focus = dev->focus;
    if ((CompareTimeStamps(time, currentTime) == LATER) ||
        (CompareTimeStamps(time, focus->time) == EARLIER))
        return Success;
    mode = (dev->deviceGrab.grab) ? NotifyWhileGrabbed : NotifyNormal;
    if (focus->win == FollowKeyboardWin) {
        if (!ActivateFocusInGrab(dev, keybd->focus->win, focusWin))
            DoFocusEvents(dev, keybd->focus->win, focusWin, mode);
    }
    else {
        if (!ActivateFocusInGrab(dev, focus->win, focusWin))
            DoFocusEvents(dev, focus->win, focusWin, mode);
    }
    focus->time = time;
    focus->revert = revertTo;
    if (focusID == FollowKeyboard)
        focus->win = FollowKeyboardWin;
    else
        focus->win = focusWin;
    if ((focusWin == NoneWin) || (focusWin == PointerRootWin))
        focus->traceGood = 0;
    else {
        int depth = 0;
        WindowPtr pWin;

        for (pWin = focusWin; pWin; pWin = pWin->parent)
            depth++;
        if (depth > focus->traceSize) {
            focus->traceSize = depth + 1;
            focus->trace = realloc(focus->trace,
                                   focus->traceSize * sizeof(WindowPtr));
        }
        focus->traceGood = depth;
        for (pWin = focusWin, depth--; pWin; pWin = pWin->parent, depth--)
            focus->trace[depth] = pWin;
    }
    return Success;
}

/**
 * Server-side protocol handling for SetInputFocus request.
 *
 * Sets the input focus for the virtual core keyboard.
 */
int
ProcSetInputFocus(ClientPtr client)
{
    DeviceIntPtr kbd = PickKeyboard(client);

    REQUEST(xSetInputFocusReq);

    REQUEST_SIZE_MATCH(xSetInputFocusReq);

    return SetInputFocus(client, kbd, stuff->focus,
                         stuff->revertTo, stuff->time, FALSE);
}

/**
 * Server-side protocol handling for GetInputFocus request.
 *
 * Sends the current input focus for the client's keyboard back to the
 * client.
 */
int
ProcGetInputFocus(ClientPtr client)
{
    DeviceIntPtr kbd = PickKeyboard(client);
    xGetInputFocusReply rep;
    FocusClassPtr focus = kbd->focus;
    int rc;

    /* REQUEST(xReq); */
    REQUEST_SIZE_MATCH(xReq);

    rc = XaceHook(XACE_DEVICE_ACCESS, client, kbd, DixGetFocusAccess);
    if (rc != Success)
        return rc;

    memset(&rep, 0, sizeof(xGetInputFocusReply));
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.revertTo = focus->revert;

    if (focus->win == NoneWin)
        rep.focus = None;
    else if (focus->win == PointerRootWin)
        rep.focus = PointerRoot;
    else
        rep.focus = focus->win->drawable.id;

    WriteReplyToClient(client, sizeof(xGetInputFocusReply), &rep);
    return Success;
}

/**
 * Server-side protocol handling for GrabPointer request.
 *
 * Sets an active grab on the client's ClientPointer and returns success
 * status to client.
 */
int
ProcGrabPointer(ClientPtr client)
{
    xGrabPointerReply rep;
    DeviceIntPtr device = PickPointer(client);
    GrabPtr grab;
    GrabMask mask;
    WindowPtr confineTo;
    BYTE status;

    REQUEST(xGrabPointerReq);
    int rc;

    REQUEST_SIZE_MATCH(xGrabPointerReq);
    UpdateCurrentTime();

    if (stuff->eventMask & ~PointerGrabMask) {
        client->errorValue = stuff->eventMask;
        return BadValue;
    }

    if (stuff->confineTo == None)
        confineTo = NullWindow;
    else {
        rc = dixLookupWindow(&confineTo, stuff->confineTo, client,
                             DixSetAttrAccess);
        if (rc != Success)
            return rc;
    }

    grab = device->deviceGrab.grab;

    if (grab && grab->confineTo && !confineTo)
        ConfineCursorToWindow(device, GetCurrentRootWindow(device), FALSE, FALSE);

    mask.core = stuff->eventMask;

    rc = GrabDevice(client, device, stuff->pointerMode, stuff->keyboardMode,
                    stuff->grabWindow, stuff->ownerEvents, stuff->time,
                    &mask, CORE, stuff->cursor, stuff->confineTo, &status);
    if (rc != Success)
        return rc;

    memset(&rep, 0, sizeof(xGrabPointerReply));
    rep.type = X_Reply;
    rep.status = status;
    rep.sequenceNumber = client->sequence;
    rep.length = 0;
    WriteReplyToClient(client, sizeof(xGrabPointerReply), &rep);
    return Success;
}

/**
 * Server-side protocol handling for ChangeActivePointerGrab request.
 *
 * Changes properties of the grab hold by the client. If the client does not
 * hold an active grab on the device, nothing happens.
 */
int
ProcChangeActivePointerGrab(ClientPtr client)
{
    DeviceIntPtr device;
    GrabPtr grab;
    CursorPtr newCursor, oldCursor;

    REQUEST(xChangeActivePointerGrabReq);
    TimeStamp time;

    REQUEST_SIZE_MATCH(xChangeActivePointerGrabReq);
    if (stuff->eventMask & ~PointerGrabMask) {
        client->errorValue = stuff->eventMask;
        return BadValue;
    }
    if (stuff->cursor == None)
        newCursor = NullCursor;
    else {
        int rc = dixLookupResourceByType((void **) &newCursor, stuff->cursor,
                                         RT_CURSOR, client, DixUseAccess);

        if (rc != Success) {
            client->errorValue = stuff->cursor;
            return rc;
        }
    }

    device = PickPointer(client);
    grab = device->deviceGrab.grab;

    if (!grab)
        return Success;
    if (!SameClient(grab, client))
        return Success;
    time = ClientTimeToServerTime(stuff->time);
    if ((CompareTimeStamps(time, currentTime) == LATER) ||
        (CompareTimeStamps(time, device->deviceGrab.grabTime) == EARLIER))
        return Success;
    oldCursor = grab->cursor;
    grab->cursor = RefCursor(newCursor);
    PostNewCursor(device);
    if (oldCursor)
        FreeCursor(oldCursor, (Cursor) 0);
    grab->eventMask = stuff->eventMask;
    return Success;
}

/**
 * Server-side protocol handling for UngrabPointer request.
 *
 * Deletes a pointer grab on a device the client has grabbed.
 */
int
ProcUngrabPointer(ClientPtr client)
{
    DeviceIntPtr device = PickPointer(client);
    GrabPtr grab;
    TimeStamp time;

    REQUEST(xResourceReq);

    REQUEST_SIZE_MATCH(xResourceReq);
    UpdateCurrentTime();
    grab = device->deviceGrab.grab;

    time = ClientTimeToServerTime(stuff->id);
    if ((CompareTimeStamps(time, currentTime) != LATER) &&
        (CompareTimeStamps(time, device->deviceGrab.grabTime) != EARLIER) &&
        (grab) && SameClient(grab, client))
        (*device->deviceGrab.DeactivateGrab) (device);
    return Success;
}

/**
 * Sets a grab on the given device.
 *
 * Called from ProcGrabKeyboard to work on the client's keyboard.
 * Called from ProcXGrabDevice to work on the device specified by the client.
 *
 * The parameters this_mode and other_mode represent the keyboard_mode and
 * pointer_mode parameters of XGrabKeyboard().
 * See man page for details on all the parameters
 *
 * @param client Client that owns the grab.
 * @param dev The device to grab.
 * @param this_mode GrabModeSync or GrabModeAsync
 * @param other_mode GrabModeSync or GrabModeAsync
 * @param status Return code to be returned to the caller.
 *
 * @returns Success or BadValue or BadAlloc.
 */
int
GrabDevice(ClientPtr client, DeviceIntPtr dev,
           unsigned pointer_mode, unsigned keyboard_mode, Window grabWindow,
           unsigned ownerEvents, Time ctime, GrabMask *mask,
           int grabtype, Cursor curs, Window confineToWin, CARD8 *status)
{
    WindowPtr pWin, confineTo;
    GrabPtr grab;
    TimeStamp time;
    Mask access_mode = DixGrabAccess;
    int rc;
    GrabInfoPtr grabInfo = &dev->deviceGrab;
    CursorPtr cursor;

    UpdateCurrentTime();
    if ((keyboard_mode != GrabModeSync) && (keyboard_mode != GrabModeAsync)) {
        client->errorValue = keyboard_mode;
        return BadValue;
    }
    if ((pointer_mode != GrabModeSync) && (pointer_mode != GrabModeAsync)) {
        client->errorValue = pointer_mode;
        return BadValue;
    }
    if ((ownerEvents != xFalse) && (ownerEvents != xTrue)) {
        client->errorValue = ownerEvents;
        return BadValue;
    }

    rc = dixLookupWindow(&pWin, grabWindow, client, DixSetAttrAccess);
    if (rc != Success)
        return rc;

    if (confineToWin == None)
        confineTo = NullWindow;
    else {
        rc = dixLookupWindow(&confineTo, confineToWin, client,
                             DixSetAttrAccess);
        if (rc != Success)
            return rc;
    }

    if (curs == None)
        cursor = NullCursor;
    else {
        rc = dixLookupResourceByType((void **) &cursor, curs, RT_CURSOR,
                                     client, DixUseAccess);
        if (rc != Success) {
            client->errorValue = curs;
            return rc;
        }
        access_mode |= DixForceAccess;
    }

    if (keyboard_mode == GrabModeSync || pointer_mode == GrabModeSync)
        access_mode |= DixFreezeAccess;
    rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, access_mode);
    if (rc != Success)
        return rc;

    time = ClientTimeToServerTime(ctime);
    grab = grabInfo->grab;
    if (grab && grab->grabtype != grabtype)
        *status = AlreadyGrabbed;
    else if (grab && !SameClient(grab, client))
        *status = AlreadyGrabbed;
    else if ((!pWin->realized) ||
             (confineTo &&
              !(confineTo->realized && BorderSizeNotEmpty(dev, confineTo))))
        *status = GrabNotViewable;
    else if ((CompareTimeStamps(time, currentTime) == LATER) ||
             (CompareTimeStamps(time, grabInfo->grabTime) == EARLIER))
        *status = GrabInvalidTime;
    else if (grabInfo->sync.frozen &&
             grabInfo->sync.other && !SameClient(grabInfo->sync.other, client))
        *status = GrabFrozen;
    else {
        GrabPtr tempGrab;

        tempGrab = AllocGrab(NULL);
        if (tempGrab == NULL)
            return BadAlloc;

        tempGrab->next = NULL;
        tempGrab->window = pWin;
        tempGrab->resource = client->clientAsMask;
        tempGrab->ownerEvents = ownerEvents;
        tempGrab->keyboardMode = keyboard_mode;
        tempGrab->pointerMode = pointer_mode;
        if (grabtype == CORE)
            tempGrab->eventMask = mask->core;
        else if (grabtype == XI)
            tempGrab->eventMask = mask->xi;
        else
            xi2mask_merge(tempGrab->xi2mask, mask->xi2mask);
        tempGrab->device = dev;
        tempGrab->cursor = RefCursor(cursor);
        tempGrab->confineTo = confineTo;
        tempGrab->grabtype = grabtype;
        (*grabInfo->ActivateGrab) (dev, tempGrab, time, FALSE);
        *status = GrabSuccess;

        FreeGrab(tempGrab);
    }
    return Success;
}

/**
 * Server-side protocol handling for GrabKeyboard request.
 *
 * Grabs the client's keyboard and returns success status to client.
 */
int
ProcGrabKeyboard(ClientPtr client)
{
    xGrabKeyboardReply rep;
    BYTE status;

    REQUEST(xGrabKeyboardReq);
    int result;
    DeviceIntPtr keyboard = PickKeyboard(client);
    GrabMask mask;

    REQUEST_SIZE_MATCH(xGrabKeyboardReq);

    mask.core = KeyPressMask | KeyReleaseMask;

    result = GrabDevice(client, keyboard, stuff->pointerMode,
                        stuff->keyboardMode, stuff->grabWindow,
                        stuff->ownerEvents, stuff->time, &mask, CORE, None,
                        None, &status);

    if (result != Success)
        return result;

    memset(&rep, 0, sizeof(xGrabKeyboardReply));
    rep.type = X_Reply;
    rep.status = status,
    rep.sequenceNumber = client->sequence;
    rep.length = 0;
    WriteReplyToClient(client, sizeof(xGrabKeyboardReply), &rep);
    return Success;
}

/**
 * Server-side protocol handling for UngrabKeyboard request.
 *
 * Deletes a possible grab on the client's keyboard.
 */
int
ProcUngrabKeyboard(ClientPtr client)
{
    DeviceIntPtr device = PickKeyboard(client);
    GrabPtr grab;
    TimeStamp time;

    REQUEST(xResourceReq);

    REQUEST_SIZE_MATCH(xResourceReq);
    UpdateCurrentTime();

    grab = device->deviceGrab.grab;

    time = ClientTimeToServerTime(stuff->id);
    if ((CompareTimeStamps(time, currentTime) != LATER) &&
        (CompareTimeStamps(time, device->deviceGrab.grabTime) != EARLIER) &&
        (grab) && SameClient(grab, client) && grab->grabtype == CORE)
        (*device->deviceGrab.DeactivateGrab) (device);
    return Success;
}

/**
 * Server-side protocol handling for QueryPointer request.
 *
 * Returns the current state and position of the client's ClientPointer to the
 * client.
 */
int
ProcQueryPointer(ClientPtr client)
{
    xQueryPointerReply rep;
    WindowPtr pWin, t;
    DeviceIntPtr mouse = PickPointer(client);
    DeviceIntPtr keyboard;
    SpritePtr pSprite;
    int rc;

    REQUEST(xResourceReq);
    REQUEST_SIZE_MATCH(xResourceReq);

    rc = dixLookupWindow(&pWin, stuff->id, client, DixGetAttrAccess);
    if (rc != Success)
        return rc;
    rc = XaceHook(XACE_DEVICE_ACCESS, client, mouse, DixReadAccess);
    if (rc != Success && rc != BadAccess)
        return rc;

    keyboard = GetMaster(mouse, MASTER_KEYBOARD);

    pSprite = mouse->spriteInfo->sprite;
    if (mouse->valuator->motionHintWindow)
        MaybeStopHint(mouse, client);
    memset(&rep, 0, sizeof(xQueryPointerReply));
    rep.type = X_Reply;
    rep.sequenceNumber = client->sequence;
    rep.length = 0;
    rep.mask = event_get_corestate(mouse, keyboard);
    rep.root = (GetCurrentRootWindow(mouse))->drawable.id;
    rep.rootX = pSprite->hot.x;
    rep.rootY = pSprite->hot.y;
    rep.child = None;
    
    if (pSprite->hot.pScreen == pWin->drawable.pScreen) {
        rep.sameScreen = xTrue;
        rep.winX = pSprite->hot.x - pWin->drawable.x;
        rep.winY = pSprite->hot.y - pWin->drawable.y;
        for (t = pSprite->win; t; t = t->parent)
            if (t->parent == pWin) {
                rep.child = t->drawable.id;
                break;
            }
    }
    else {
        rep.sameScreen = xFalse;
        rep.winX = 0;
        rep.winY = 0;
    }

#ifdef PANORAMIX
    if (!noPanoramiXExtension) {
        rep.rootX += screenInfo.screens[0]->x;
        rep.rootY += screenInfo.screens[0]->y;
        if (stuff->id == rep.root) {
            rep.winX += screenInfo.screens[0]->x;
            rep.winY += screenInfo.screens[0]->y;
        }
    }
#endif

    if (rc == BadAccess) {
        rep.mask = 0;
        rep.child = None;
        rep.rootX = 0;
        rep.rootY = 0;
        rep.winX = 0;
        rep.winY = 0;
    }

    WriteReplyToClient(client, sizeof(xQueryPointerReply), &rep);

    return Success;
}

/**
 * Initializes the device list and the DIX sprite to sane values. Allocates
 * trace memory used for quick window traversal.
 */
void
InitEvents(void)
{
    int i;
    QdEventPtr qe=NULL;
    QdEventPtr tmp;

    inputInfo.numDevices = 0;
    inputInfo.devices = (DeviceIntPtr) NULL;
    inputInfo.off_devices = (DeviceIntPtr) NULL;
    inputInfo.keyboard = (DeviceIntPtr) NULL;
    inputInfo.pointer = (DeviceIntPtr) NULL;

    for (i = 0; i < MAXDEVICES; i++) {
        DeviceIntRec dummy;
        memcpy(&event_filters[i], default_filter, sizeof(default_filter));

        dummy.id = i;
        NoticeTime(&dummy, currentTime);
        LastEventTimeToggleResetFlag(i, FALSE);
    }

    syncEvents.replayDev = (DeviceIntPtr) NULL;
    syncEvents.replayWin = NullWindow;
    if (syncEvents.pending.next)
        xorg_list_for_each_entry_safe(qe, tmp, &syncEvents.pending, next)
            free(qe);
    xorg_list_init(&syncEvents.pending);
    syncEvents.playingEvents = FALSE;
    syncEvents.time.months = 0;
    syncEvents.time.milliseconds = 0;   /* hardly matters */
    currentTime.months = 0;
    currentTime.milliseconds = GetTimeInMillis();
    for (i = 0; i < DNPMCOUNT; i++) {
        DontPropagateMasks[i] = 0;
        DontPropagateRefCnts[i] = 0;
    }

    InputEventList = InitEventList(GetMaximumEventsNum());
    if (!InputEventList)
        FatalError("[dix] Failed to allocate input event list.\n");
}

void
CloseDownEvents(void)
{
    FreeEventList(InputEventList, GetMaximumEventsNum());
    InputEventList = NULL;
}

#define SEND_EVENT_BIT 0x80

/**
 * Server-side protocol handling for SendEvent request.
 *
 * Locates the window to send the event to and forwards the event.
 */
int
ProcSendEvent(ClientPtr client)
{
    WindowPtr pWin;
    WindowPtr effectiveFocus = NullWindow;      /* only set if dest==InputFocus */
    DeviceIntPtr dev = PickPointer(client);
    DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD);
    SpritePtr pSprite = dev->spriteInfo->sprite;

    REQUEST(xSendEventReq);

    REQUEST_SIZE_MATCH(xSendEventReq);

    /* libXext and other extension libraries may set the bit indicating
     * that this event came from a SendEvent request so remove it
     * since otherwise the event type may fail the range checks
     * and cause an invalid BadValue error to be returned.
     *
     * This is safe to do since we later add the SendEvent bit (0x80)
     * back in once we send the event to the client */

    stuff->event.u.u.type &= ~(SEND_EVENT_BIT);

    /* The client's event type must be a core event type or one defined by an
       extension. */

    if (!((stuff->event.u.u.type > X_Reply &&
           stuff->event.u.u.type < LASTEvent) ||
          (stuff->event.u.u.type >= EXTENSION_EVENT_BASE &&
           stuff->event.u.u.type < (unsigned) lastEvent))) {
        client->errorValue = stuff->event.u.u.type;
        return BadValue;
    }
    if (stuff->event.u.u.type == ClientMessage &&
        stuff->event.u.u.detail != 8 &&
        stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) {
        client->errorValue = stuff->event.u.u.detail;
        return BadValue;
    }
    if (stuff->eventMask & ~AllEventMasks) {
        client->errorValue = stuff->eventMask;
        return BadValue;
    }

    if (stuff->destination == PointerWindow)
        pWin = pSprite->win;
    else if (stuff->destination == InputFocus) {
        WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin;

        if (inputFocus == NoneWin)
            return Success;

        /* If the input focus is PointerRootWin, send the event to where
           the pointer is if possible, then perhaps propogate up to root. */
        if (inputFocus == PointerRootWin)
            inputFocus = GetCurrentRootWindow(dev);

        if (IsParent(inputFocus, pSprite->win)) {
            effectiveFocus = inputFocus;
            pWin = pSprite->win;
        }
        else
            effectiveFocus = pWin = inputFocus;
    }
    else
        dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess);

    if (!pWin)
        return BadWindow;
    if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) {
        client->errorValue = stuff->propagate;
        return BadValue;
    }
    stuff->event.u.u.type |= SEND_EVENT_BIT;
    if (stuff->propagate) {
        for (; pWin; pWin = pWin->parent) {
            if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin,
                         &stuff->event, 1))
                return Success;
            if (DeliverEventsToWindow(dev, pWin,
                                      &stuff->event, 1, stuff->eventMask,
                                      NullGrab))
                return Success;
            if (pWin == effectiveFocus)
                return Success;
            stuff->eventMask &= ~wDontPropagateMask(pWin);
            if (!stuff->eventMask)
                break;
        }
    }
    else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1))
        DeliverEventsToWindow(dev, pWin, &stuff->event,
                              1, stuff->eventMask, NullGrab);
    return Success;
}

/**
 * Server-side protocol handling for UngrabKey request.
 *
 * Deletes a passive grab for the given key. Works on the
 * client's keyboard.
 */
int
ProcUngrabKey(ClientPtr client)
{
    REQUEST(xUngrabKeyReq);
    WindowPtr pWin;
    GrabPtr tempGrab;
    DeviceIntPtr keybd = PickKeyboard(client);
    int rc;

    REQUEST_SIZE_MATCH(xUngrabKeyReq);
    rc = dixLookupWindow(&pWin, stuff->grabWindow, client, DixGetAttrAccess);
    if (rc != Success)
        return rc;

    if (((stuff->key > keybd->key->xkbInfo->desc->max_key_code) ||
         (stuff->key < keybd->key->xkbInfo->desc->min_key_code))
        && (stuff->key != AnyKey)) {
        client->errorValue = stuff->key;
        return BadValue;
    }
    if ((stuff->modifiers != AnyModifier) &&
        (stuff->modifiers & ~AllModifiersMask)) {
        client->errorValue = stuff->modifiers;
        return BadValue;
    }
    tempGrab = AllocGrab(NULL);
    if (!tempGrab)
        return BadAlloc;
    tempGrab->resource = client->clientAsMask;
    tempGrab->device = keybd;
    tempGrab->window = pWin;
    tempGrab->modifiersDetail.exact = stuff->modifiers;
    tempGrab->modifiersDetail.pMask = NULL;
    tempGrab->modifierDevice = keybd;
    tempGrab->type = KeyPress;
    tempGrab->grabtype = CORE;
    tempGrab->detail.exact = stuff->key;
    tempGrab->detail.pMask = NULL;
    tempGrab->next = NULL;

    if (!DeletePassiveGrabFromList(tempGrab))
        rc = BadAlloc;

    FreeGrab(tempGrab);

    return rc;
}

/**
 * Server-side protocol handling for GrabKey request.
 *
 * Creates a grab for the client's keyboard and adds it to the list of passive
 * grabs.
 */
int
ProcGrabKey(ClientPtr client)
{
    WindowPtr pWin;

    REQUEST(xGrabKeyReq);
    GrabPtr grab;
    DeviceIntPtr keybd = PickKeyboard(client);
    int rc;
    GrabParameters param;
    GrabMask mask;

    REQUEST_SIZE_MATCH(xGrabKeyReq);

    memset(&param, 0, sizeof(param));
    param.grabtype = CORE;
    param.ownerEvents = stuff->ownerEvents;
    param.this_device_mode = stuff->keyboardMode;
    param.other_devices_mode = stuff->pointerMode;
    param.modifiers = stuff->modifiers;

    rc = CheckGrabValues(client, &param);
    if (rc != Success)
        return rc;

    if (((stuff->key > keybd->key->xkbInfo->desc->max_key_code) ||
         (stuff->key < keybd->key->xkbInfo->desc->min_key_code))
        && (stuff->key != AnyKey)) {
        client->errorValue = stuff->key;
        return BadValue;
    }
    rc = dixLookupWindow(&pWin, stuff->grabWindow, client, DixSetAttrAccess);
    if (rc != Success)
        return rc;

    mask.core = (KeyPressMask | KeyReleaseMask);

    grab = CreateGrab(client->index, keybd, keybd, pWin, CORE, &mask,
                      &param, KeyPress, stuff->key, NullWindow, NullCursor);
    if (!grab)
        return BadAlloc;
    return AddPassiveGrabToList(client, grab);
}

/**
 * Server-side protocol handling for GrabButton request.
 *
 * Creates a grab for the client's ClientPointer and adds it as a passive grab
 * to the list.
 */
int
ProcGrabButton(ClientPtr client)
{
    WindowPtr pWin, confineTo;

    REQUEST(xGrabButtonReq);
    CursorPtr cursor;
    GrabPtr grab;
    DeviceIntPtr ptr, modifierDevice;
    Mask access_mode = DixGrabAccess;
    GrabMask mask;
    GrabParameters param;
    int rc;

    REQUEST_SIZE_MATCH(xGrabButtonReq);
    if ((stuff->pointerMode != GrabModeSync) &&
        (stuff->pointerMode != GrabModeAsync)) {
        client->errorValue = stuff->pointerMode;
        return BadValue;
    }
    if ((stuff->keyboardMode != GrabModeSync) &&
        (stuff->keyboardMode != GrabModeAsync)) {
        client->errorValue = stuff->keyboardMode;
        return BadValue;
    }
    if ((stuff->modifiers != AnyModifier) &&
        (stuff->modifiers & ~AllModifiersMask)) {
        client->errorValue = stuff->modifiers;
        return BadValue;
    }
    if ((stuff->ownerEvents != xFalse) && (stuff->ownerEvents != xTrue)) {
        client->errorValue = stuff->ownerEvents;
        return BadValue;
    }
    if (stuff->eventMask & ~PointerGrabMask) {
        client->errorValue = stuff->eventMask;
        return BadValue;
    }
    rc = dixLookupWindow(&pWin, stuff->grabWindow, client, DixSetAttrAccess);
    if (rc != Success)
        return rc;
    if (stuff->confineTo == None)
        confineTo = NullWindow;
    else {
        rc = dixLookupWindow(&confineTo, stuff->confineTo, client,
                             DixSetAttrAccess);
        if (rc != Success)
            return rc;
    }
    if (stuff->cursor == None)
        cursor = NullCursor;
    else {
        rc = dixLookupResourceByType((void **) &cursor, stuff->cursor,
                                     RT_CURSOR, client, DixUseAccess);
        if (rc != Success) {
            client->errorValue = stuff->cursor;
            return rc;
        }
        access_mode |= DixForceAccess;
    }

    ptr = PickPointer(client);
    modifierDevice = GetMaster(ptr, MASTER_KEYBOARD);
    if (stuff->pointerMode == GrabModeSync ||
        stuff->keyboardMode == GrabModeSync)
        access_mode |= DixFreezeAccess;
    rc = XaceHook(XACE_DEVICE_ACCESS, client, ptr, access_mode);
    if (rc != Success)
        return rc;

    memset(&param, 0, sizeof(param));
    param.grabtype = CORE;
    param.ownerEvents = stuff->ownerEvents;
    param.this_device_mode = stuff->keyboardMode;
    param.other_devices_mode = stuff->pointerMode;
    param.modifiers = stuff->modifiers;

    mask.core = stuff->eventMask;

    grab = CreateGrab(client->index, ptr, modifierDevice, pWin,
                      CORE, &mask, &param, ButtonPress,
                      stuff->button, confineTo, cursor);
    if (!grab)
        return BadAlloc;
    return AddPassiveGrabToList(client, grab);
}

/**
 * Server-side protocol handling for UngrabButton request.
 *
 * Deletes a passive grab on the client's ClientPointer from the list.
 */
int
ProcUngrabButton(ClientPtr client)
{
    REQUEST(xUngrabButtonReq);
    WindowPtr pWin;
    GrabPtr tempGrab;
    int rc;
    DeviceIntPtr ptr;

    REQUEST_SIZE_MATCH(xUngrabButtonReq);
    if ((stuff->modifiers != AnyModifier) &&
        (stuff->modifiers & ~AllModifiersMask)) {
        client->errorValue = stuff->modifiers;
        return BadValue;
    }
    rc = dixLookupWindow(&pWin, stuff->grabWindow, client, DixReadAccess);
    if (rc != Success)
        return rc;

    ptr = PickPointer(client);

    tempGrab = AllocGrab(NULL);
    if (!tempGrab)
        return BadAlloc;
    tempGrab->resource = client->clientAsMask;
    tempGrab->device = ptr;
    tempGrab->window = pWin;
    tempGrab->modifiersDetail.exact = stuff->modifiers;
    tempGrab->modifiersDetail.pMask = NULL;
    tempGrab->modifierDevice = GetMaster(ptr, MASTER_KEYBOARD);
    tempGrab->type = ButtonPress;
    tempGrab->detail.exact = stuff->button;
    tempGrab->grabtype = CORE;
    tempGrab->detail.pMask = NULL;
    tempGrab->next = NULL;

    if (!DeletePassiveGrabFromList(tempGrab))
        rc = BadAlloc;

    FreeGrab(tempGrab);
    return rc;
}

/**
 * Deactivate any grab that may be on the window, remove the focus.
 * Delete any XInput extension events from the window too. Does not change the
 * window mask. Use just before the window is deleted.
 *
 * If freeResources is set, passive grabs on the window are deleted.
 *
 * @param pWin The window to delete events from.
 * @param freeResources True if resources associated with the window should be
 * deleted.
 */
void
DeleteWindowFromAnyEvents(WindowPtr pWin, Bool freeResources)
{
    WindowPtr parent;
    DeviceIntPtr mouse = inputInfo.pointer;
    DeviceIntPtr keybd = inputInfo.keyboard;
    FocusClassPtr focus;
    OtherClientsPtr oc;
    GrabPtr passive;
    GrabPtr grab;

    /* Deactivate any grabs performed on this window, before making any
       input focus changes. */
    grab = mouse->deviceGrab.grab;
    if (grab && ((grab->window == pWin) || (grab->confineTo == pWin)))
        (*mouse->deviceGrab.DeactivateGrab) (mouse);

    /* Deactivating a keyboard grab should cause focus events. */
    grab = keybd->deviceGrab.grab;
    if (grab && (grab->window == pWin))
        (*keybd->deviceGrab.DeactivateGrab) (keybd);

    /* And now the real devices */
    for (mouse = inputInfo.devices; mouse; mouse = mouse->next) {
        grab = mouse->deviceGrab.grab;
        if (grab && ((grab->window == pWin) || (grab->confineTo == pWin)))
            (*mouse->deviceGrab.DeactivateGrab) (mouse);
    }

    for (keybd = inputInfo.devices; keybd; keybd = keybd->next) {
        if (IsKeyboardDevice(keybd)) {
            focus = keybd->focus;

            /* If the focus window is a root window (ie. has no parent)
               then don't delete the focus from it. */

            if ((pWin == focus->win) && (pWin->parent != NullWindow)) {
                int focusEventMode = NotifyNormal;

                /* If a grab is in progress, then alter the mode of focus events. */

                if (keybd->deviceGrab.grab)
                    focusEventMode = NotifyWhileGrabbed;

                switch (focus->revert) {
                case RevertToNone:
                    DoFocusEvents(keybd, pWin, NoneWin, focusEventMode);
                    focus->win = NoneWin;
                    focus->traceGood = 0;
                    break;
                case RevertToParent:
                    parent = pWin;
                    do {
                        parent = parent->parent;
                        focus->traceGood--;
                    } while (!parent->realized
                    /* This would be a good protocol change -- windows being
                       reparented during SaveSet processing would cause the
                       focus to revert to the nearest enclosing window which
                       will survive the death of the exiting client, instead
                       of ending up reverting to a dying window and thence
                       to None */
#ifdef NOTDEF
                             || wClient(parent)->clientGone
#endif
                        );
                    if (!ActivateFocusInGrab(keybd, pWin, parent))
                        DoFocusEvents(keybd, pWin, parent, focusEventMode);
                    focus->win = parent;
                    focus->revert = RevertToNone;
                    break;
                case RevertToPointerRoot:
                    if (!ActivateFocusInGrab(keybd, pWin, PointerRootWin))
                        DoFocusEvents(keybd, pWin, PointerRootWin,
                                      focusEventMode);
                    focus->win = PointerRootWin;
                    focus->traceGood = 0;
                    break;
                }
            }
        }

        if (IsPointerDevice(keybd)) {
            if (keybd->valuator->motionHintWindow == pWin)
                keybd->valuator->motionHintWindow = NullWindow;
        }
    }

    if (freeResources) {
        if (pWin->dontPropagate)
            DontPropagateRefCnts[pWin->dontPropagate]--;
        while ((oc = wOtherClients(pWin)))
            FreeResource(oc->resource, RT_NONE);
        while ((passive = wPassiveGrabs(pWin)))
            FreeResource(passive->resource, RT_NONE);
    }

    DeleteWindowFromAnyExtEvents(pWin, freeResources);
}

/**
 * Call this whenever some window at or below pWin has changed geometry. If
 * there is a grab on the window, the cursor will be re-confined into the
 * window.
 */
void
CheckCursorConfinement(WindowPtr pWin)
{
    GrabPtr grab;
    WindowPtr confineTo;
    DeviceIntPtr pDev;

#ifdef PANORAMIX
    if (!noPanoramiXExtension && pWin->drawable.pScreen->myNum)
        return;
#endif

    for (pDev = inputInfo.devices; pDev; pDev = pDev->next) {
        if (DevHasCursor(pDev)) {
            grab = pDev->deviceGrab.grab;
            if (grab && (confineTo = grab->confineTo)) {
                if (!BorderSizeNotEmpty(pDev, confineTo))
                    (*pDev->deviceGrab.DeactivateGrab) (pDev);
                else if ((pWin == confineTo) || IsParent(pWin, confineTo))
                    ConfineCursorToWindow(pDev, confineTo, TRUE, TRUE);
            }
        }
    }
}

Mask
EventMaskForClient(WindowPtr pWin, ClientPtr client)
{
    OtherClientsPtr other;

    if (wClient(pWin) == client)
        return pWin->eventMask;
    for (other = wOtherClients(pWin); other; other = other->next) {
        if (SameClient(other, client))
            return other->mask;
    }
    return 0;
}

/**
 * Server-side protocol handling for RecolorCursor request.
 */
int
ProcRecolorCursor(ClientPtr client)
{
    CursorPtr pCursor;
    int rc, nscr;
    ScreenPtr pscr;
    Bool displayed;
    SpritePtr pSprite = PickPointer(client)->spriteInfo->sprite;

    REQUEST(xRecolorCursorReq);

    REQUEST_SIZE_MATCH(xRecolorCursorReq);
    rc = dixLookupResourceByType((void **) &pCursor, stuff->cursor, RT_CURSOR,
                                 client, DixWriteAccess);
    if (rc != Success) {
        client->errorValue = stuff->cursor;
        return rc;
    }

    pCursor->foreRed = stuff->foreRed;
    pCursor->foreGreen = stuff->foreGreen;
    pCursor->foreBlue = stuff->foreBlue;

    pCursor->backRed = stuff->backRed;
    pCursor->backGreen = stuff->backGreen;
    pCursor->backBlue = stuff->backBlue;

    for (nscr = 0; nscr < screenInfo.numScreens; nscr++) {
        pscr = screenInfo.screens[nscr];
#ifdef PANORAMIX
        if (!noPanoramiXExtension)
            displayed = (pscr == pSprite->screen);
        else
#endif
            displayed = (pscr == pSprite->hotPhys.pScreen);
        (*pscr->RecolorCursor) (PickPointer(client), pscr, pCursor,
                                (pCursor == pSprite->current) && displayed);
    }
    return Success;
}

/**
 * Write the given events to a client, swapping the byte order if necessary.
 * To swap the byte ordering, a callback is called that has to be set up for
 * the given event type.
 *
 * In the case of DeviceMotionNotify trailed by DeviceValuators, the events
 * can be more than one. Usually it's just one event.
 *
 * Do not modify the event structure passed in. See comment below.
 *
 * @param pClient Client to send events to.
 * @param count Number of events.
 * @param events The event list.
 */
void
WriteEventsToClient(ClientPtr pClient, int count, xEvent *events)
{
#ifdef PANORAMIX
    xEvent eventCopy;
#endif
    xEvent *eventTo, *eventFrom;
    int i, eventlength = sizeof(xEvent);

    if (!pClient || pClient == serverClient || pClient->clientGone)
        return;

    for (i = 0; i < count; i++)
        if ((events[i].u.u.type & 0x7f) != KeymapNotify)
            events[i].u.u.sequenceNumber = pClient->sequence;

    /* Let XKB rewrite the state, as it depends on client preferences. */
    XkbFilterEvents(pClient, count, events);

#ifdef PANORAMIX
    if (!noPanoramiXExtension &&
        (screenInfo.screens[0]->x || screenInfo.screens[0]->y)) {
        switch (events->u.u.type) {
        case MotionNotify:
        case ButtonPress:
        case ButtonRelease:
        case KeyPress:
        case KeyRelease:
        case EnterNotify:
        case LeaveNotify:
            /*
               When multiple clients want the same event DeliverEventsToWindow
               passes the same event structure multiple times so we can't
               modify the one passed to us
             */
            count = 1;          /* should always be 1 */
            memcpy(&eventCopy, events, sizeof(xEvent));
            eventCopy.u.keyButtonPointer.rootX += screenInfo.screens[0]->x;
            eventCopy.u.keyButtonPointer.rootY += screenInfo.screens[0]->y;
            if (eventCopy.u.keyButtonPointer.event ==
                eventCopy.u.keyButtonPointer.root) {
                eventCopy.u.keyButtonPointer.eventX += screenInfo.screens[0]->x;
                eventCopy.u.keyButtonPointer.eventY += screenInfo.screens[0]->y;
            }
            events = &eventCopy;
            break;
        default:
            break;
        }
    }
#endif

    if (EventCallback) {
        EventInfoRec eventinfo;

        eventinfo.client = pClient;
        eventinfo.events = events;
        eventinfo.count = count;
        CallCallbacks(&EventCallback, (void *) &eventinfo);
    }
#ifdef XSERVER_DTRACE
    if (XSERVER_SEND_EVENT_ENABLED()) {
        for (i = 0; i < count; i++) {
            XSERVER_SEND_EVENT(pClient->index, events[i].u.u.type, &events[i]);
        }
    }
#endif
    /* Just a safety check to make sure we only have one GenericEvent, it just
     * makes things easier for me right now. (whot) */
    for (i = 1; i < count; i++) {
        if (events[i].u.u.type == GenericEvent) {
            ErrorF("[dix] TryClientEvents: Only one GenericEvent at a time.\n");
            return;
        }
    }

    if (events->u.u.type == GenericEvent) {
        eventlength += ((xGenericEvent *) events)->length * 4;
    }

    if (pClient->swapped) {
        if (eventlength > swapEventLen) {
            swapEventLen = eventlength;
            swapEvent = realloc(swapEvent, swapEventLen);
            if (!swapEvent) {
                FatalError("WriteEventsToClient: Out of memory.\n");
                return;
            }
        }

        for (i = 0; i < count; i++) {
            eventFrom = &events[i];
            eventTo = swapEvent;

            /* Remember to strip off the leading bit of type in case
               this event was sent with "SendEvent." */
            (*EventSwapVector[eventFrom->u.u.type & 0177])
                (eventFrom, eventTo);

            WriteToClient(pClient, eventlength, eventTo);
        }
    }
    else {
        /* only one GenericEvent, remember? that means either count is 1 and
         * eventlength is arbitrary or eventlength is 32 and count doesn't
         * matter. And we're all set. Woohoo. */
        WriteToClient(pClient, count * eventlength, events);
    }
}

/*
 * Set the client pointer for the given client.
 *
 * A client can have exactly one ClientPointer. Each time a
 * request/reply/event is processed and the choice of devices is ambiguous
 * (e.g. QueryPointer request), the server will pick the ClientPointer (see
 * PickPointer()).
 * If a keyboard is needed, the first keyboard paired with the CP is used.
 */
int
SetClientPointer(ClientPtr client, DeviceIntPtr device)
{
    int rc = XaceHook(XACE_DEVICE_ACCESS, client, device, DixUseAccess);

    if (rc != Success)
        return rc;

    if (!IsMaster(device)) {
        ErrorF("[dix] Need master device for ClientPointer. This is a bug.\n");
        return BadDevice;
    }
    else if (!device->spriteInfo->spriteOwner) {
        ErrorF("[dix] Device %d does not have a sprite. "
               "Cannot be ClientPointer\n", device->id);
        return BadDevice;
    }
    client->clientPtr = device;
    return Success;
}

/* PickPointer will pick an appropriate pointer for the given client.
 *
 * An "appropriate device" is (in order of priority):
 *  1) A device the given client has a core grab on.
 *  2) A device set as ClientPointer for the given client.
 *  3) The first master device.
 */
DeviceIntPtr
PickPointer(ClientPtr client)
{
    DeviceIntPtr it = inputInfo.devices;

    /* First, check if the client currently has a grab on a device. Even
     * keyboards count. */
    for (it = inputInfo.devices; it; it = it->next) {
        GrabPtr grab = it->deviceGrab.grab;

        if (grab && grab->grabtype == CORE && SameClient(grab, client)) {
            it = GetMaster(it, MASTER_POINTER);
            return it;          /* Always return a core grabbed device */
        }
    }

    if (!client->clientPtr) {
        it = inputInfo.devices;
        while (it) {
            if (IsMaster(it) && it->spriteInfo->spriteOwner) {
                client->clientPtr = it;
                break;
            }
            it = it->next;
        }
    }
    return client->clientPtr;
}

/* PickKeyboard will pick an appropriate keyboard for the given client by
 * searching the list of devices for the keyboard device that is paired with
 * the client's pointer.
 */
DeviceIntPtr
PickKeyboard(ClientPtr client)
{
    DeviceIntPtr ptr = PickPointer(client);
    DeviceIntPtr kbd = GetMaster(ptr, MASTER_KEYBOARD);

    if (!kbd) {
        ErrorF("[dix] ClientPointer not paired with a keyboard. This "
               "is a bug.\n");
    }

    return kbd;
}

/* A client that has one or more core grabs does not get core events from
 * devices it does not have a grab on. Legacy applications behave bad
 * otherwise because they are not used to it and the events interfere.
 * Only applies for core events.
 *
 * Return true if a core event from the device would interfere and should not
 * be delivered.
 */
Bool
IsInterferingGrab(ClientPtr client, DeviceIntPtr dev, xEvent *event)
{
    DeviceIntPtr it = inputInfo.devices;

    switch (event->u.u.type) {
    case KeyPress:
    case KeyRelease:
    case ButtonPress:
    case ButtonRelease:
    case MotionNotify:
    case EnterNotify:
    case LeaveNotify:
        break;
    default:
        return FALSE;
    }

    if (dev->deviceGrab.grab && SameClient(dev->deviceGrab.grab, client))
        return FALSE;

    while (it) {
        if (it != dev) {
            if (it->deviceGrab.grab && SameClient(it->deviceGrab.grab, client)
                && !it->deviceGrab.fromPassiveGrab) {
                if ((IsPointerDevice(it) && IsPointerDevice(dev)) ||
                    (IsKeyboardDevice(it) && IsKeyboardDevice(dev)))
                    return TRUE;
            }
        }
        it = it->next;
    }

    return FALSE;
}

/* PointerBarrier events are only delivered to the client that created that
 * barrier */
static Bool
IsWrongPointerBarrierClient(ClientPtr client, DeviceIntPtr dev, xEvent *event)
{
    xXIBarrierEvent *ev = (xXIBarrierEvent*)event;

    if (ev->type != GenericEvent || ev->extension != IReqCode)
        return FALSE;

    if (ev->evtype != XI_BarrierHit && ev->evtype != XI_BarrierLeave)
        return FALSE;

    return client->index != CLIENT_ID(ev->barrier);
}