summaryrefslogtreecommitdiff
blob: 31648c6561eda756715102285723f451e2f67c5f (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
Index: b/Xi/allowev.c
===================================================================
--- a/Xi/allowev.c	2011-02-28 13:56:41.000000000 +1100
+++ b/Xi/allowev.c	2011-03-09 13:11:48.093384404 +1100
@@ -125,5 +125,24 @@
 	client->errorValue = stuff->mode;
 	return BadValue;
     }
+
+    /* If this is a master pointer with an active touch emulation and the touch
+     * has physically ceased, end the touchpoint state. */
+    if (thisdev->emulate_dev)
+    {
+        DeviceIntPtr sourcedev = thisdev->emulate_dev;
+        TouchPointInfoPtr ti = sourcedev->touch->emulate;
+
+        if (ti->pending_finish && ti->owner < 0)
+            EndTouchPoint(sourcedev, ti);
+        else if (ti->pending_finish)
+        {
+            TouchClientPtr tc = &ti->clients[ti->owner];
+
+            if (tc->type == TOUCH_SELECT || tc->type == TOUCH_SELECT_UNOWNED)
+                EndTouchPoint(sourcedev, ti);
+        }
+    }
+
     return Success;
 }
Index: b/Xi/exevents.c
===================================================================
--- a/Xi/exevents.c	2011-03-09 11:19:12.126789337 +1100
+++ b/Xi/exevents.c	2011-03-09 13:11:48.093384404 +1100
@@ -44,6 +44,31 @@
 
 ********************************************************/
 
+/*
+ * Copyright © 2010 Collabora Ltd.
+ *
+ * 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.
+ *
+ * Author: Daniel Stone <daniel@fooishbar.org>
+ */
+
 /********************************************************************
  *
  *  Routines to register and initialize extension input devices.
@@ -77,6 +102,9 @@
 #include "xiquerydevice.h" /* For List*Info */
 #include "eventconvert.h"
 #include "eventstr.h"
+#include "xserver-properties.h"
+#include "inpututils.h"
+#include "mi.h"
 
 #include <X11/extensions/XKBproto.h>
 #include "xkbsrv.h"
@@ -127,6 +155,20 @@
     return FALSE;
 }
 
+Bool
+IsTouchEvent(InternalEvent* event)
+{
+    switch(event->any.type)
+    {
+        case ET_TouchBegin:
+        case ET_TouchEnd:
+        case ET_TouchMotion:
+            return TRUE;
+        default:
+            return FALSE;
+    }
+}
+
 /**
  * @return the device matching the deviceid of the device set in the event, or
  * NULL if the event is not an XInput event.
@@ -725,6 +767,46 @@
     XISendDeviceChangedEvent(slave, device, dce);
 }
 
+#define DEFAULT 0
+#define DONT_PROCESS 1
+int
+ReleaseButton(DeviceIntPtr device, int button)
+{
+    ButtonClassPtr b = device->button;
+    int i;
+
+    if (IsMaster(device)) {
+        DeviceIntPtr sd;
+
+        /*
+         * Leave the button down if any slave has the
+         * button still down. Note that this depends on the
+         * event being delivered through the slave first
+         */
+        for (sd = inputInfo.devices; sd; sd = sd->next) {
+            if (IsMaster(sd) || sd->u.master != device)
+                continue;
+            if (!sd->button)
+                continue;
+            for (i = 1; i <= sd->button->numButtons; i++)
+                if (sd->button->map[i] == button &&
+                    button_is_down(sd, i, BUTTON_PROCESSED))
+                    return DONT_PROCESS;
+        }
+    }
+    set_button_up(device, button, BUTTON_PROCESSED);
+    if (device->valuator)
+        device->valuator->motionHintWindow = NullWindow;
+    if (!b->map[button])
+        return DONT_PROCESS;
+    if (b->buttonsDown >= 1 && !--b->buttonsDown)
+        b->motionMask = 0;
+    if (b->map[button] <= 5)
+        b->state &= ~((Button1Mask >> 1) << b->map[button]);
+
+    return DEFAULT;
+}
+
 /**
  * Update the device state according to the data in the event.
  *
@@ -732,8 +814,6 @@
  *   DEFAULT ... process as normal
  *   DONT_PROCESS ... return immediately from caller
  */
-#define DEFAULT 0
-#define DONT_PROCESS 1
 int
 UpdateDeviceState(DeviceIntPtr device, DeviceEvent* event)
 {
@@ -857,34 +937,9 @@
 
         if (!button_is_down(device, key, BUTTON_PROCESSED))
             return DONT_PROCESS;
-        if (IsMaster(device)) {
-            DeviceIntPtr sd;
 
-            /*
-             * Leave the button down if any slave has the
-             * button still down. Note that this depends on the
-             * event being delivered through the slave first
-             */
-            for (sd = inputInfo.devices; sd; sd = sd->next) {
-                if (IsMaster(sd) || sd->u.master != device)
-                    continue;
-                if (!sd->button)
-                    continue;
-                for (i = 1; i <= sd->button->numButtons; i++)
-                    if (sd->button->map[i] == key &&
-                        button_is_down(sd, i, BUTTON_PROCESSED))
-                        return DONT_PROCESS;
-            }
-        }
-        set_button_up(device, key, BUTTON_PROCESSED);
-	if (device->valuator)
-	    device->valuator->motionHintWindow = NullWindow;
-        if (!b->map[key])
+        if (ReleaseButton(device, key) == DONT_PROCESS)
             return DONT_PROCESS;
-        if (b->buttonsDown >= 1 && !--b->buttonsDown)
-	    b->motionMask = 0;
-	if (b->map[key] <= 5)
-	    b->state &= ~((Button1Mask >> 1) << b->map[key]);
 
         /* Add state and motionMask to the filter for this event */
         mask = DevicePointerMotionMask | b->state | b->motionMask;
@@ -926,6 +981,939 @@
 }
 
 /**
+ * Add a touch client to the list of clients for the touch point. Return TRUE
+ * if the caller should stop processing touch clients.
+ */
+static Bool
+AddTouchClient(TouchPointInfoPtr ti, int client_id, WindowPtr window,
+               TouchClientType type, DeviceIntPtr dev, DeviceIntPtr sourcedev,
+               GrabPtr grab)
+{
+    TouchClientPtr client;
+
+    ti->active_clients++;
+    if (ti->active_clients > ti->num_clients)
+    {
+        int num_clients = ti->num_clients ? ti->num_clients * 2 : 2;
+
+        TouchClientPtr tmp;
+        tmp = realloc(ti->clients, num_clients * sizeof(TouchClientRec));
+                      
+        if (tmp)
+        {
+            ti->clients = tmp;
+            ti->num_clients = num_clients;
+        } else {
+            LogMessage(X_ERROR, "failed to reallocate touch clients\n");
+            return TRUE;
+        }
+    }
+
+    client = &ti->clients[ti->active_clients - 1];
+    client->client = clients[client_id];
+    client->window = window;
+    client->type = type;
+    client->device = dev;
+    client->source = sourcedev;
+    client->grab = grab;
+
+    return FALSE;
+}
+
+/**
+ * Ensure a list of clients for a touchpoint, constructing one for TouchBegin
+ * events. Returns TRUE if a touch client exists, FALSE if none.
+ */
+static Bool
+EnsureTouchClients(DeviceIntPtr sourcedev, TouchPointInfoPtr ti,
+                   InternalEvent *ev)
+{
+    TouchClassPtr t = sourcedev->touch;
+    SpritePtr sprite = &ti->sprite;
+    DeviceIntPtr masterdev = sourcedev->u.master;
+    int i;
+
+    if (ev->any.type != ET_TouchBegin)
+        return (ti->active_clients > 0);
+
+    if (ti->active_clients > 0)
+        LogMessage(X_ERROR, "Getting touch clients for active touch\n");
+
+    /* Create sprite trace for the touchpoint */
+    if (t->mode == XIDirectTouch)
+    {
+        /* Focus immediately under the touchpoint in direct touch mode.
+         * XXX: Do we need to handle crossing screens here? */
+        sprite->spriteTrace[0] =
+            sourcedev->spriteInfo->sprite->hotPhys.pScreen->root;
+        XYToWindow(sprite, ev->device_event.root_x, ev->device_event.root_y);
+    }
+    else
+    {
+        WindowPtr *trace;
+        SpritePtr srcsprite;
+
+        /* Find and reuse an existing, physically active touch's sprite and 
+         * touch client list if possible, else use the device's pointer sprite
+         * and generate a new list of touch clients. */
+        for (i = 0; i < t->num_touches; i++)
+            if (!t->touches[i].ddx_pending_finish &&
+                t->touches[i].active_clients > 0)
+                break;
+        if (i < t->num_touches) {
+            srcsprite = &t->touches[i].sprite;
+            ti->active_clients = t->touches[i].active_clients;
+
+            if (ti->active_clients > ti->num_clients)
+            {
+                TouchClientPtr tmp;
+
+                tmp = realloc(ti->clients,
+                              ti->active_clients * sizeof(TouchClientRec));
+                if (!tmp)
+                {
+                    ti->active_clients = 0;
+                    ti->owner = -1;
+                    return FALSE;
+                }
+                ti->clients = tmp;
+                ti->num_clients = ti->active_clients;
+            }
+            memcpy(ti->clients, t->touches[i].clients,
+                   ti->active_clients * sizeof(TouchClientRec));
+        }
+        else if (sourcedev->spriteInfo->sprite)
+            srcsprite = sourcedev->spriteInfo->sprite;
+        else
+            return FALSE;
+
+        if (srcsprite->spriteTraceGood > sprite->spriteTraceSize)
+        {   
+            trace = realloc(sprite->spriteTrace,
+                            srcsprite->spriteTraceSize * sizeof(*trace));
+            if (!trace)
+            {   
+                sprite->spriteTraceGood = 0;
+                ti->active_clients = 0;
+                ti->owner = -1;
+                return FALSE;
+            }
+            sprite->spriteTrace = trace;
+            sprite->spriteTraceSize = srcsprite->spriteTraceGood;
+        }
+        memcpy(sprite->spriteTrace, srcsprite->spriteTrace,
+               srcsprite->spriteTraceGood * sizeof(*trace));
+        sprite->spriteTraceGood = srcsprite->spriteTraceGood;
+
+        if (ti->active_clients)
+            return TRUE;
+    }
+
+    if (sprite->spriteTraceGood <= 0)
+        return FALSE;
+
+    /* Search for touch grab clients from root to child windows. */
+    for (i = 0; i < sprite->spriteTraceGood; i++)
+    {
+        WindowPtr win = sprite->spriteTrace[i];
+        GrabPtr grab;
+        InternalEvent ev;
+
+        ev.any.type = ET_TouchBegin;
+        if ((grab = CheckPassiveGrabsOnWindow(win, sourcedev, &ev, FALSE,
+                                              FALSE)))
+        {
+            if (AddTouchClient(ti, CLIENT_ID(grab->resource), win, TOUCH_GRAB,
+                               sourcedev, sourcedev, grab))
+                goto done;
+            continue;
+        }
+        if (masterdev &&
+            (grab = CheckPassiveGrabsOnWindow(win, masterdev, &ev, FALSE,
+                                              FALSE)))
+        {
+            if (AddTouchClient(ti, CLIENT_ID(grab->resource), win, TOUCH_GRAB,
+                               masterdev, sourcedev, grab))
+                goto done;
+            continue;
+        }
+    }
+
+    /* Search for one touch select client from child to root windows. */
+    for (i = sprite->spriteTraceGood - 1; i >= 0; i--)
+    {
+        WindowPtr win = sprite->spriteTrace[i];
+        OtherInputMasks *inputMasks = wOtherInputMasks(win);
+
+        /* Is anyone listening for unowned events on this window? */
+        if (inputMasks &&
+            (BitIsOn(inputMasks->xi2mask[XIAllDevices],
+                     XI_TouchUpdateUnowned) ||
+             BitIsOn(inputMasks->xi2mask[sourcedev->id],
+                     XI_TouchUpdateUnowned) ||
+             (masterdev &&
+              (BitIsOn(inputMasks->xi2mask[XIAllMasterDevices],
+                       XI_TouchUpdateUnowned) ||
+               BitIsOn(inputMasks->xi2mask[masterdev->id],
+                       XI_TouchUpdateUnowned)))))
+        {
+            InputClientsPtr inputClients = inputMasks->inputClients;
+
+            /* Find the one client listening for unowned events. */
+            for (inputClients = inputMasks->inputClients;
+                 inputClients;
+                 inputClients = inputClients->next)
+            {
+                if (BitIsOn(inputClients->xi2mask[XIAllDevices],
+                            XI_TouchUpdateUnowned) ||
+                    BitIsOn(inputClients->xi2mask[sourcedev->id],
+                            XI_TouchUpdateUnowned))
+                {
+                    AddTouchClient(ti, CLIENT_ID(inputClients->resource),
+                                   win, TOUCH_SELECT_UNOWNED, sourcedev,
+                                   sourcedev, NULL);
+                    goto done;
+                }
+                else if (masterdev &&
+                         (BitIsOn(inputClients->xi2mask[XIAllMasterDevices],
+                                  XI_TouchUpdateUnowned) ||
+                          BitIsOn(inputClients->xi2mask[masterdev->id],
+                                  XI_TouchUpdateUnowned)))
+                {
+                    AddTouchClient(ti, CLIENT_ID(inputClients->resource),
+                                   win, TOUCH_SELECT_UNOWNED, masterdev,
+                                   sourcedev, NULL);
+                    goto done;
+                }
+            }
+        }
+
+        /* Is anyone listening for only owned events on this window? */
+        if (inputMasks &&
+            (BitIsOn(inputMasks->xi2mask[XIAllDevices], XI_TouchUpdate) ||
+             BitIsOn(inputMasks->xi2mask[sourcedev->id], XI_TouchUpdate) ||
+             (masterdev &&
+              (BitIsOn(inputMasks->xi2mask[XIAllMasterDevices],
+                       XI_TouchUpdate) ||
+               BitIsOn(inputMasks->xi2mask[masterdev->id],
+                       XI_TouchUpdate)))))
+        {
+            InputClientsPtr inputClients = inputMasks->inputClients;
+
+            /* Find the one client listening for owned events. */
+            for (inputClients = inputMasks->inputClients;
+                 inputClients;
+                 inputClients = inputClients->next)
+            {
+                if (BitIsOn(inputClients->xi2mask[XIAllDevices],
+                            XI_TouchUpdate) ||
+                    BitIsOn(inputClients->xi2mask[sourcedev->id],
+                            XI_TouchUpdate))
+                {
+                    AddTouchClient(ti, CLIENT_ID(inputClients->resource), win,
+                                   TOUCH_SELECT, sourcedev, sourcedev, NULL);
+                    goto done;
+                }
+                else if (masterdev &&
+                         (BitIsOn(inputClients->xi2mask[XIAllMasterDevices],
+                                  XI_TouchUpdate) ||
+                          BitIsOn(inputClients->xi2mask[masterdev->id],
+                                  XI_TouchUpdate)))
+                {
+                    AddTouchClient(ti, CLIENT_ID(inputClients->resource), win,
+                                   TOUCH_SELECT, masterdev, sourcedev, NULL);
+                    goto done;
+                }
+            }
+        }
+    }
+
+done:
+    return (ti->active_clients > 0);
+}
+
+/**
+ * Attempts to deliver a touch event to the given client.
+ */
+static Bool
+DeliverOneTouchEvent(TouchClientPtr client, TouchPointInfoPtr ti,
+                     InternalEvent *ev)
+{
+    int err;
+    xEvent *xi2;
+    Mask filter;
+    Window child = DeepestSpriteWin(&ti->sprite)->drawable.id;
+
+    /* If we fail here, we're going to leave a client hanging. */
+    err = EventToXI2(ev, &xi2);
+    if (err != Success)
+        FatalError("[Xi] %s: XI2 conversion failed in DeliverOneTouchEvent"
+                   " (%d)\n", client->device->name, err);
+
+    FixUpEventFromWindow(&ti->sprite, xi2, client->window, child, FALSE);
+    filter = GetEventFilter(client->device, xi2);
+    if (XaceHook(XACE_RECEIVE_ACCESS, client->client, client->window, xi2, 1)
+        != Success)
+        return FALSE;
+    err = TryClientEvents(client->client, client->device, xi2, 1, filter,
+                          filter, NullGrab);
+    free(xi2);
+
+    /* Returning the value from TryClientEvents isn't useful, since all our
+     * resource-gone cleanups will update the delivery list anyway. */
+    return TRUE;
+}
+
+/**
+ * Deliver touch ownership event directly to client.
+ */
+int
+DeliverTouchOwnershipEvent(TouchClientPtr client, TouchPointInfoPtr ti)
+{
+    TouchOwnershipEvent event;
+
+    memset(&event, 0, sizeof(TouchOwnershipEvent));
+    event.header = ET_Internal;
+    event.type = ET_TouchOwnership;
+    event.length = sizeof(TouchOwnershipEvent);
+    event.time = GetTimeInMillis();
+    event.deviceid = client->device->id;
+    event.sourceid = client->source->id;
+    event.touchid = ti->client_id;
+
+    DeliverOneTouchEvent(client, ti, (InternalEvent *)&event);
+
+    return 1;
+}
+
+/* Add the given event to the history for the touch point. */
+static void
+UpdateTouchHistory(TouchPointInfoPtr ti, InternalEvent *ev)
+{
+    /* Copy begin events off to the side. This prevents the ring buffer
+       overrunning and erasing the begin event. */
+    if (ev->any.type == ET_TouchBegin)
+        memcpy(ti->begin_event, ev, sizeof(InternalEvent));
+    else
+    {
+        memcpy(ti->next_history, ev, sizeof(InternalEvent));
+
+        ti->next_history++;
+        if (ti->next_history == ti->history + ti->history_size)
+            ti->next_history = ti->history;
+
+        /* If the ring overruns, advance the first pointer so we keep as many
+           events as possible. */
+        if (ti->next_history == ti->first_history)
+        {
+            ti->first_history++;
+            if (ti->first_history == ti->history + ti->history_size)
+                ti->first_history = ti->history;
+        }
+    }
+}
+
+/**
+ * Helper to get a static EventList for pointer emulation.
+ */
+static EventList *
+GetEvents(void)
+{
+    static EventList *events = NULL;
+
+    /* Allocate twice the maximum number of events for motion and button
+     * emulation. */
+    if (!events)
+        events = InitEventList(2 * GetMaximumEventsNum());
+
+    return events;
+}
+
+/* Helper function to set up touch pointer emulation. */
+static void
+SetTouchEmulationMask(InternalEvent *ev, ValuatorMask *mask, int x_axis,
+                      int y_axis)
+{
+    valuator_mask_zero(mask);
+    if (BitIsOn(ev->device_event.valuators.mask, x_axis))
+        valuator_mask_set(mask, 0,
+                          ev->device_event.valuators.data[x_axis]);
+    if (BitIsOn(ev->device_event.valuators.mask, y_axis))
+        valuator_mask_set(mask, 1,
+                          ev->device_event.valuators.data[y_axis]);
+}
+
+/* Process touch emulation. */
+static void
+EmulateTouchEvents(DeviceIntPtr dev, TouchPointInfoPtr ti, InternalEvent *ev)
+{
+    EventList *emulationEvents = GetEvents();
+    ValuatorMask mask;
+    InternalEvent mevent;
+    DeviceIntPtr master = dev->u.master;
+    enum EventType evtype = ev->any.type;
+    int nevents = 0;
+    int x_axis = dev->touch->x_axis;
+    int y_axis = dev->touch->y_axis;
+    int i;
+
+    /* Set the emulation touch for the device. Only one touch may be emulated
+     * at a time. */
+    if (dev->touch->emulate != ti)
+        return;
+
+    /* Emulate a normal event. */
+    SetTouchEmulationMask(ev, &mask, x_axis, y_axis);
+
+    if (evtype == ET_TouchBegin)
+    {
+        nevents = GetPointerEvents(emulationEvents, dev,
+                                   MotionNotify, 0, POINTER_ABSOLUTE, &mask);
+        nevents += GetPointerEvents(emulationEvents + nevents, dev,
+                                    ButtonPress, 1, POINTER_ABSOLUTE, &mask);
+    }
+    else if (evtype == ET_TouchMotion)
+        nevents = GetPointerEvents(emulationEvents, dev, MotionNotify, 0,
+                                   POINTER_ABSOLUTE, &mask);
+    else if (evtype == ET_TouchEnd)
+    {
+        nevents = GetPointerEvents(emulationEvents, dev, MotionNotify, 0,
+                                   POINTER_ABSOLUTE, &mask);
+        nevents += GetPointerEvents(emulationEvents + nevents, dev,
+                                    ButtonRelease, 1, POINTER_ABSOLUTE, &mask);
+    }
+
+    if (ti->emulate_pointer)
+    {
+        for (i = 0; i < nevents; i++)
+        {
+            InternalEvent *event = (InternalEvent *)((emulationEvents + i)->event);
+
+            event->device_event.flags |= XIPointerEmulated;
+            event->device_event.touchpoint = ev->device_event.touchpoint;
+
+            if (master)
+            {
+                master->u.lastSlave = dev;
+
+                CopyGetMasterEvent(dev, event, &mevent);
+
+                /* If a grab has been activated but no event has been handled
+                 * yet, then the grab is a touch grab. Store the pointer
+                 * emulation event for now, ready for replay when the touch grab
+                 * is relinquished. */
+                if (master->deviceGrab.sync.state == FROZEN_NO_EVENT)
+                {
+                    GrabInfoPtr grabinfo = &master->deviceGrab;
+
+                    grabinfo->sync.state = FROZEN_WITH_EVENT;
+                    if (!grabinfo->sync.event)
+                        grabinfo->sync.event = calloc(1, sizeof(InternalEvent));
+                    *grabinfo->sync.event = event->device_event;
+                }
+                else
+                    master->public.processInputProc(&mevent, master);
+            }
+        }
+    }
+
+    /* If there are touch clients on a pointer emulated touchpoint, send touch
+     * events through traditional device processing as well. */
+    if (master && ti->active_clients > 0 &&
+        (ev->any.type != ET_TouchEnd ||
+         (ti->clients[ti->active_clients - 1].type == TOUCH_SELECT ||
+          ti->clients[ti->active_clients - 1].type == TOUCH_SELECT_UNOWNED)))
+    {
+        ev->device_event.flags |= XIPointerEmulated;
+        master->u.lastSlave = dev;
+        CopyGetMasterEvent(dev, ev, &mevent);
+        master->process_touch = TRUE;
+        master->public.processInputProc(&mevent, master);
+        master->process_touch = FALSE;
+
+        /* If grabbed by an implicit touch grab from FindFirstGrab, release it
+         * now. */
+        if (master->deviceGrab.grab &&
+            master->deviceGrab.grab->type == ET_TouchBegin &&
+            master->deviceGrab.implicitGrab)
+            master->deviceGrab.DeactivateGrab(master);
+    }
+}
+
+#define ImplicitGrabMask (1 << 7)
+/**
+ * Find the first grab of a new touchpoint. Returns TRUE if a grab was found.
+ */
+static Bool
+FindFirstGrab(DeviceIntPtr dev, TouchPointInfoPtr ti)
+{
+    DeviceIntPtr master = dev->u.master;
+    InternalEvent p_event;
+    InternalEvent t_event;
+    GrabRec tempGrab;
+    int i, j;
+
+    p_event.any.type = ET_ButtonPress;
+    t_event.any.type = ET_TouchBegin;
+
+    j = ti->owner >= 0 ? ti->owner : 0;
+
+    for (i = 0; i < ti->sprite.spriteTraceGood; i++)
+    {
+        WindowPtr win = ti->sprite.spriteTrace[i];
+        TouchClientPtr client = &ti->clients[j];
+        GrabPtr grab;
+
+        /* If master pointer is already grabbed, bypass touch grabs above. */
+        if (ti->emulate_pointer && master->deviceGrab.grab)
+        {
+            if (win == master->deviceGrab.grab->window)
+            {
+                if (j >= ti->active_clients - 1)
+                {
+                    ti->owner = -1;
+                    ti->active_clients = 0;
+                } else
+                    ti->owner = j + 1;
+                return TRUE;
+            } else
+                goto next;
+        }
+
+        /* Check for a touch grab on this window. */
+        if (j < ti->active_clients && win == client->window &&
+            client->type == TOUCH_GRAB)
+        {
+            client->device->deviceGrab.ActivateGrab(client->device,
+                                                    client->grab, currentTime,
+                                                    TRUE);
+            ti->owner = j;
+            return TRUE;
+        }
+
+        if (!ti->emulate_pointer)
+            goto next;
+
+        /* Check for a passive pointer grab on this window. */
+        grab = CheckPassiveGrabsOnWindow(win, dev, &p_event, TRUE, FALSE);
+        if (grab)
+            return TRUE;
+        else if (master)
+        {
+            grab = CheckPassiveGrabsOnWindow(win, master, &p_event, TRUE,
+                                             FALSE);
+            if (grab)
+                return TRUE;
+        }
+
+next:
+        if (j < ti->active_clients && win == client->window)
+            j++;
+    }
+
+    /* Even when there's no grabbing clients, we need to sync events so we can
+     * properly check for touch vs pointer selection in DeliverDeviceEvents.
+     * Create a temporary implicit touch grab here, and deactivate it after
+     * enqueuing emulated pointer events. */
+    if (ti->emulate_pointer)
+    {
+        memset(&tempGrab, 0, sizeof(GrabRec));
+        tempGrab.next = NULL;
+        tempGrab.device = master;
+        tempGrab.resource = 0;
+        tempGrab.window = ti->sprite.spriteTrace[0];
+        tempGrab.ownerEvents = FALSE;
+        tempGrab.eventMask = 0;
+        tempGrab.keyboardMode = GrabModeAsync;
+        tempGrab.pointerMode = GrabModeSync;
+        tempGrab.confineTo = NullWindow;
+        tempGrab.cursor = NullCursor;
+        tempGrab.type = ET_TouchBegin;
+        tempGrab.grabtype = GRABTYPE_XI2;
+        tempGrab.deviceMask = 0;
+
+        master->deviceGrab.ActivateGrab(master, &tempGrab, currentTime,
+                                        TRUE | ImplicitGrabMask);
+    }
+
+    return FALSE;
+}
+
+void
+ProcessTouchOwnership(DeviceIntPtr dev, TouchPointInfoPtr ti, uint8_t reason,
+                      Bool touch_grab)
+{
+    DeviceIntPtr sourcedev = ti->source;
+    DeviceIntPtr masterdev;
+
+    masterdev = dev->u.master;
+
+    if (reason == XITouchOwnerAccept)
+    {
+        TouchClientPtr client;
+        DeviceEvent event;
+        int i;
+
+        init_event(dev, &event, GetTimeInMillis());
+        event.type = ET_TouchEnd;
+        event.detail.touch = ti->client_id;
+        event.touchpoint = ti;
+
+        for (i = ti->owner + 1; i < ti->active_clients; i++)
+        {
+            client = &ti->clients[i];
+
+            if (client->type == TOUCH_GRAB ||
+                client->type == TOUCH_SELECT_UNOWNED)
+            {
+                event.deviceid = client->device->id;
+                event.sourceid = client->source->id;
+
+                DeliverOneTouchEvent(client, ti, (InternalEvent *)&event);
+            }
+        }
+
+        if (!touch_grab)
+        {
+            ti->active_clients = 0;
+            ti->owner = -1;
+            RemoveTouchEventsFromQueue(masterdev, TRUE, FALSE);
+            return;
+        }
+
+        client = &ti->clients[ti->owner];
+        ti->active_clients = ti->owner + 1;
+        ti->accepted = TRUE;
+
+        RemoveTouchEventsFromQueue(masterdev, FALSE, FALSE);
+        RemoveTouchEventsFromQueue(masterdev, TRUE, FALSE);
+        ReleaseButton(masterdev, 1);
+
+        if (ti->emulate_pointer)
+            masterdev->deviceGrab.DeactivateGrab(masterdev);
+
+        ti->emulate_pointer = FALSE;
+
+        if (ti->pending_finish)
+        {
+            event.deviceid = client->device->id;
+            event.sourceid = client->source->id;
+
+            DeliverOneTouchEvent(client, ti, (InternalEvent *)&event);
+            EndTouchPoint(sourcedev, ti);
+        }
+    } else {
+        TouchClientPtr tc = &ti->clients[ti->owner];
+        GrabPtr grab = masterdev->deviceGrab.grab;
+
+        if (touch_grab)
+        {
+            DeviceEvent event;
+
+            tc = &ti->clients[ti->owner];
+
+            init_event(tc->device, &event, GetTimeInMillis());
+            event.type = ET_TouchEnd;
+            event.detail.touch = ti->client_id;
+            event.deviceid = tc->device->id;
+            event.sourceid = tc->source->id;
+            event.touchpoint = ti;
+
+            DeliverOneTouchEvent(tc, ti, (InternalEvent *)&event);
+        
+            ti->owner++;
+        }
+
+        if (ti->owner >= ti->active_clients)
+        {
+            ti->owner = -1;
+            ti->active_clients = 0;
+            tc = NULL;
+        } else {
+            tc = &ti->clients[ti->owner];
+
+            if (tc->type == TOUCH_SELECT && !ti->emulate_pointer)
+            {
+                InternalEvent *ev;
+                Bool ret;
+
+                /* Deliver the saved touch begin event. */
+                ret = DeliverOneTouchEvent(tc, ti, ti->begin_event);
+
+                /* Deliver all the touch motion events in the ring buffer. */
+                ev = ti->first_history;
+                while (ret && ev != ti->next_history)
+                {
+                    ret = DeliverOneTouchEvent(tc, ti, ev);
+
+                    if (ev->any.type == ET_TouchEnd)
+                    {
+                        ti->pending_finish = TRUE;
+                        break;
+                    }
+
+                    ev++;
+                    if (ev == ti->history + ti->history_size)
+                        ev = ti->history;
+                }
+            } else if (tc->type == TOUCH_SELECT_UNOWNED &&
+                       !ti->emulate_pointer) {
+                DeliverTouchOwnershipEvent(tc, ti);
+            }
+        }
+
+        if (ti->emulate_pointer)
+        {
+            if (ti->active_clients &&
+                ti->clients[ti->owner].type == TOUCH_SELECT_UNOWNED)
+                RemoveTouchEventsFromQueue(masterdev, TRUE, TRUE);
+
+            syncEvents.replayDev = masterdev;
+            if (touch_grab)
+                syncEvents.replayWin = grab->window->parent;
+            else
+                syncEvents.replayWin = grab->window;
+            masterdev->deviceGrab.DeactivateGrab(masterdev);
+            syncEvents.replayDev = NULL;
+        }
+
+        if (ti->pending_finish &&
+            (!tc || (tc->type == TOUCH_SELECT ||
+                     tc->type == TOUCH_SELECT_UNOWNED)) &&
+            (!ti->emulate_pointer || !masterdev->deviceGrab.grab))
+            EndTouchPoint(sourcedev, ti);
+    }
+}
+
+/**
+ * Processes and delivers a TouchBegin, TouchMotion, or a TouchEnd event.
+ *
+ * Due to having rather different delivery semantics (see the Xi 2.1 protocol
+ * spec for more information), this implements its own grab and event-selection
+ * delivery logic.
+ */
+static void
+ProcessTouchEvent(InternalEvent *ev, DeviceIntPtr sourcedev)
+{
+    DeviceIntPtr masterdev = sourcedev->u.master;
+    TouchClassPtr t = sourcedev->touch;
+    TouchPointInfoPtr ti;
+    TouchClientPtr client;
+    uint32_t touchid;
+    int i;
+
+    /* We handle deliveries to MDs through the SD, rather than copying
+     * the event and processing it twice. */
+    if (IsMaster(sourcedev))
+        return;
+
+    if (!t)
+        return;
+
+    /* If we hit 50% utilization of touches, double the number of touch
+     * frames. */
+    if (t->active_touches > t->num_touches / 2)
+    {
+        void *tmp;
+
+        tmp = realloc(t->touches, (t->num_touches * 2) * sizeof(*t->touches));
+        if (tmp)
+        {
+            t->touches = tmp;
+            memset(t->touches + t->num_touches, 0,
+                   t->num_touches * sizeof(*t->touches));
+
+            for (i = t->num_touches; i < t->num_touches * 2; i++)
+            {
+                if (!InitTouchPoint(t, i))
+                {
+                    LogMessage(X_ERROR,
+                               "%s: failed to initialize new touchpoint %d\n",
+                               sourcedev->name, i);
+                    break;
+                }
+            }
+            t->num_touches = i;
+
+            LogMessage(X_INFO, "%s: reallocated %d touches\n", sourcedev->name,
+                       t->num_touches);
+        } else
+            LogMessage(X_ERROR, "%s: failed to allocate more touches (%d)\n",
+                       sourcedev->name, t->num_touches * 2);
+    }
+
+    touchid = ev->device_event.detail.touch;
+    ti = FindTouchPointByClientID(sourcedev, touchid);
+    if (!ti)
+    {
+        DebugF("[Xi] %s: Received event for inactive touchpoint %d\n",
+               sourcedev->name, touchid);
+        return;
+    }
+
+    /* Set the emulation touch for a direct touch device. Only one touch may be
+     * emulated per master device at a time. */
+    if (ev->any.type == ET_TouchBegin && t->mode == XIDirectTouch &&
+        masterdev && !masterdev->emulate_dev)
+    {
+        ti->emulate_pointer = TRUE;
+        sourcedev->touch->emulate = ti;
+        masterdev->emulate_dev = sourcedev;
+    }
+
+    /* Make sure we have a valid list of touch clients for event delivery. */
+    if (!EnsureTouchClients(sourcedev, ti, ev))
+    {
+        /* No touch clients, so only attempt to emulate a pointer. */
+        EmulateTouchEvents(sourcedev, ti, ev);
+
+        if (ti->active && ev->any.type == ET_TouchEnd)
+            EndTouchPoint(sourcedev, ti);
+
+        return;
+    }
+
+    if (ev->any.type == ET_TouchBegin)
+    {
+        if (ti->emulate_pointer)
+        {
+            if (!FindFirstGrab(sourcedev, ti))
+            {
+                if (ti->clients[0].type == TOUCH_SELECT)
+                {
+                    ti->owner = 0;
+                    EmulateTouchEvents(sourcedev, ti, ev);
+                    return;
+                }
+                else if (ti->clients[0].type == TOUCH_SELECT_UNOWNED)
+                {
+                    ti->owner = 0;
+                    client = &ti->clients[ti->owner];
+                    ev->device_event.deviceid = client->device->id;
+                    ev->device_event.sourceid = client->source->id;
+                    DeliverOneTouchEvent(client, ti, ev);
+                    EmulateTouchEvents(sourcedev, ti, ev);
+                    return;
+                }
+            } else if (ti->owner < 0)
+                /* Pointer grab found, check touch grab first when replayed. */
+                ev->device_event.check_grab = TRUE;
+        }
+        else
+            ti->owner = 0;
+    }
+
+    /* Update touch history for non-emulated touches. Emulated touch history is
+     * maintained in syncEvents queue. */
+    if (!ti->emulate_pointer && !ti->accepted)
+        UpdateTouchHistory(ti, ev);
+
+    EmulateTouchEvents(sourcedev, ti, ev);
+
+    if (ti->owner >= 0)
+        client = &ti->clients[ti->owner];
+
+    /* Handle the special case where we are ending an emulated touch during an
+     * active pointer grab. */
+    if (ti == t->emulate && masterdev && masterdev->deviceGrab.grab &&
+        !masterdev->deviceGrab.fromPassiveGrab &&
+        !masterdev->deviceGrab.implicitGrab && ev->any.type == ET_TouchEnd)
+    {
+        InternalEvent mevent;
+
+        ev->device_event.flags |= XIPointerEmulated;
+
+        masterdev->u.lastSlave = sourcedev;
+        CopyGetMasterEvent(sourcedev, ev, &mevent);
+        masterdev->process_touch = TRUE;
+        masterdev->public.processInputProc(&mevent, masterdev);
+        masterdev->process_touch = FALSE;
+        if (client && (client->type == TOUCH_SELECT ||
+                       client->type == TOUCH_SELECT_UNOWNED))
+            EndTouchPoint(sourcedev, ti);
+    }
+
+    /* If a touch is owned, deliver to the owning client. */
+    if (ti->owner >= 0 &&
+        (ti != t->emulate || ti->accepted ||
+         ((!client->grab && !sourcedev->deviceGrab.grab &&
+           !masterdev->deviceGrab.grab) ||
+          (client->grab && sourcedev->deviceGrab.grab &&
+           GrabMatchesSecond(sourcedev->deviceGrab.grab, client->grab, FALSE)) ||
+          (client->grab && masterdev && masterdev->deviceGrab.grab &&
+           GrabMatchesSecond(masterdev->deviceGrab.grab, client->grab, FALSE)))))
+    {
+        if (client->type == TOUCH_GRAB)
+        {
+            /* Mutate end event to a pending finish event for further
+             * clients. */
+            if (ev->any.type == ET_TouchEnd && !ti->accepted)
+            {
+                ev->any.type = ET_TouchMotion;
+                ev->device_event.flags |= XITouchPendingEnd;
+                ti->pending_finish = TRUE;
+            }
+
+            ev->device_event.deviceid = client->device->id;
+            ev->device_event.sourceid = client->source->id;
+
+            DeliverOneTouchEvent(client, ti, ev);
+            if (ev->any.type == ET_TouchBegin)
+                DeliverTouchOwnershipEvent(client, ti);
+            else if (ev->any.type == ET_TouchEnd)
+                EndTouchPoint(sourcedev, ti);
+        }
+        else if (client->type == TOUCH_SELECT ||
+                 client->type == TOUCH_SELECT_UNOWNED)
+        {
+            ev->device_event.deviceid = client->device->id;
+            ev->device_event.sourceid = client->source->id;
+
+            if (ev->any.type != ET_TouchEnd)
+                DeliverOneTouchEvent(client, ti, ev);
+
+            else if (client->type == TOUCH_SELECT_UNOWNED &&
+                     ev->any.type == ET_TouchBegin)
+                DeliverTouchOwnershipEvent(client, ti);
+
+            /* An ending emulated touchpoint must release the primary mouse
+             * button. */
+            if (ev->any.type == ET_TouchEnd)
+            {
+                if (ti == sourcedev->touch->emulate)
+                    ReleaseButton(masterdev, 1);
+                else
+                    DeliverOneTouchEvent(client, ti, ev);
+
+                EndTouchPoint(sourcedev, ti);
+            }
+        }
+    }
+
+    /* Deliver to non-owners. */
+    if (ev->any.type == ET_TouchMotion)
+        ev->any.type = ET_TouchMotionUnowned;
+    else if (ev->any.type == ET_TouchEnd)
+    {
+        ev->any.type = ET_TouchMotionUnowned;
+        ev->device_event.flags |= XITouchPendingEnd;
+        ti->pending_finish = TRUE;
+    }
+
+    for (i = ti->owner + 1; i < ti->active_clients; i++)
+    {
+        TouchClientPtr client = &ti->clients[i];
+
+        ev->device_event.deviceid = client->device->id;
+        ev->device_event.sourceid = client->source->id;
+
+        if (client->type == TOUCH_GRAB ||
+            client->type == TOUCH_SELECT_UNOWNED)
+            DeliverOneTouchEvent(client, ti, ev);
+    }
+}
+
+/**
  * Main device event processing function.
  * Called from when processing the events from the event queue.
  *
@@ -954,6 +1942,33 @@
     {
         ProcessRawEvent(&ev->raw_event, device);
         return;
+    } else if ((!syncEvents.playingEvents && !device->process_touch) &&
+               (ev->any.type == ET_TouchBegin ||
+                ev->any.type == ET_TouchMotion ||
+                ev->any.type == ET_TouchMotionUnowned ||
+                ev->any.type == ET_TouchOwnership ||
+                ev->any.type == ET_TouchEnd))
+    {
+        /* The first time through we figure out what to do with the touch.
+         * Further times through (playingEvents or process_touch), we process
+         * the event like any other. */
+        ProcessTouchEvent(ev, device);
+        return;
+    }
+
+    /* Ownership events are smaller than device events, so we must handle them
+     * first or we'll corrupt the heap. */
+    if (ev->any.type == ET_TouchOwnership)
+    {
+        grab = device->deviceGrab.grab;
+
+        if (grab)
+            DeliverGrabbedEvent(ev, device, FALSE);
+        else
+            DeliverDeviceEvents(GetSpriteWindow(device), ev, NullGrab,
+                                NullWindow, device);
+
+        return;
     }
 
     if (IsPointerDevice(device))
@@ -1152,6 +2167,50 @@
         dev->proximity->in_proximity = FALSE;
 }
 
+void
+InitTouchValuatorAxisStruct(DeviceIntPtr dev, int axnum, Atom label, int minval,
+                            int maxval, int resolution)
+{
+    TouchAxisInfoPtr ax;
+
+    if (!dev || !dev->touch || minval > maxval)
+        return;
+    if (axnum >= dev->touch->num_axes)
+        return;
+
+    ax = dev->touch->axes + axnum;
+
+    ax->min_value = minval;
+    ax->max_value = maxval;
+    ax->resolution = resolution;
+    ax->label = label;
+
+    if (ax->label == XIGetKnownProperty(AXIS_LABEL_PROP_ABS_MT_POSITION_X))
+    {
+        dev->touch->x_axis = axnum;
+        if (dev->touch->mode == XIDirectTouch &&
+            (!dev->valuator || dev->valuator->numAxes < 1 ||
+             dev->valuator->axes[0].min_value != minval ||
+             dev->valuator->axes[0].max_value != maxval ||
+             dev->valuator->axes[0].resolution != resolution))
+            LogMessage(X_WARNING, "Touch X valuator does not match pointer X "
+                                  "valuator, pointer emulation may be "
+                                  "incorrect\n");
+    }
+    else if (ax->label == XIGetKnownProperty(AXIS_LABEL_PROP_ABS_MT_POSITION_Y))
+    {
+        dev->touch->y_axis = axnum;
+        if (dev->touch->mode == XIDirectTouch &&
+            (!dev->valuator || dev->valuator->numAxes < 2 ||
+             dev->valuator->axes[1].min_value != minval ||
+             dev->valuator->axes[1].max_value != maxval ||
+             dev->valuator->axes[1].resolution != resolution))
+            LogMessage(X_WARNING, "Touch Y valuator does not match pointer Y "
+                                  "valuator, pointer emulation may be "
+                                  "incorrect\n");
+    }
+}
+
 static void
 FixDeviceStateNotify(DeviceIntPtr dev, deviceStateNotify * ev, KeyClassPtr k,
 		     ButtonClassPtr b, ValuatorClassPtr v, int first)
@@ -1562,6 +2621,38 @@
     return AddPassiveGrabToList(client, grab);
 }
 
+/* Touch grab */
+int
+GrabTouch(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr mod_dev,
+          GrabParameters *param, GrabMask *mask)
+{
+    WindowPtr pWin;
+    GrabPtr grab;
+    int rc;
+
+    rc = CheckGrabValues(client, param);
+    if (rc != Success)
+        return rc;
+
+    rc = dixLookupWindow(&pWin, param->grabWindow, client, DixSetAttrAccess);
+    if (rc != Success)
+	return rc;
+    rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, DixFreezeAccess);
+    if (rc != Success)
+	return rc;
+
+    /* Touch grabs are asynchronous in protocol, but we need to freeze the
+     * pointer device if a touch grab is activated for pointer emulation. */
+    param->other_devices_mode = GrabModeSync;
+
+    grab = CreateGrab(client->index, dev, mod_dev, pWin, GRABTYPE_XI2,
+                      mask, param, XI_TouchBegin, 0, NullWindow, NullCursor);
+    if (!grab)
+        return BadAlloc;
+
+    return AddPassiveGrabToList(client, grab);
+}
+
 int
 SelectForWindow(DeviceIntPtr dev, WindowPtr pWin, ClientPtr client,
 		Mask mask, Mask exclusivemasks)
@@ -1695,10 +2786,65 @@
     }
 }
 
+static void
+RemoveTouchClient(DeviceIntPtr dev, TouchPointInfoPtr ti, int index)
+{
+    TouchClientPtr tc = &ti->clients[index];
+    int i;
+
+    if (index == ti->owner) {
+        if (tc->grab && dev->deviceGrab.grab &&
+            GrabMatchesSecond(tc->grab, dev->deviceGrab.grab,
+                              FALSE))
+            ProcessTouchOwnership(dev, ti, XITouchOwnerRejectEnd, TRUE);
+        else {
+            ti->owner++;
+            if (ti->owner >= ti->active_clients) {
+                ti->owner = -1;
+                ti->active_clients = 0;
+            }
+        }
+        return;
+    }
+
+    for (i = index; i < ti->active_clients - 1; i++)
+        memcpy(ti->clients + i, ti->clients + i + 1,
+               sizeof(TouchClientRec));
+    ti->active_clients--;
+}
+
+
 int
 InputClientGone(WindowPtr pWin, XID id)
 {
     InputClientsPtr other, prev;
+    DeviceIntPtr dev;
+
+    for (dev = inputInfo.devices; dev; dev = dev->next) {
+        TouchClassPtr t = dev->touch;
+        int i;
+
+        if (!t)
+            continue;
+
+        for (i = 0; i < t->num_touches; i++) {
+            TouchPointInfoPtr ti = &t->touches[i];
+            int j;
+
+            if (!ti->active || ti->active_clients == 0)
+                continue;
+
+            j = (ti->owner < 0) ? 0 : ti->owner;
+            while (j < ti->active_clients) {
+                TouchClientPtr tc = &ti->clients[j];
+
+                if (clients[CLIENT_ID(id)] == tc->client)
+                    RemoveTouchClient(dev, ti, j);
+                else
+                    j++;
+            }
+        }
+    }
 
     if (!wOtherInputMasks(pWin))
 	return Success;
@@ -1734,6 +2880,54 @@
     FatalError("client not on device event list");
 }
 
+/**
+ * Search for window in each touch trace for each device. Remove the window
+ * and all its subwindows from the trace when found. The initial window
+ * order is preserved.
+ */
+void WindowGone(WindowPtr win)
+{
+    DeviceIntPtr dev;
+
+    for (dev = inputInfo.devices; dev; dev = dev->next) {
+        TouchClassPtr t = dev->touch;
+        int i;
+
+        if (!t)
+            continue;
+
+        for (i = 0; i < t->num_touches; i++) {
+            SpritePtr sprite = &t->touches[i].sprite;
+            int j;
+
+            for (j = 0; j < sprite->spriteTraceGood; j++) {
+                if (sprite->spriteTrace[j] == win) {
+                    sprite->spriteTraceGood = j;
+                    break;
+                }
+            }
+        }
+
+        for (i = 0; i < t->num_touches; i++) {
+            TouchPointInfoPtr ti = &t->touches[i];
+            int j;
+
+            if (!ti->active || ti->active_clients == 0)
+                continue;
+
+            j = (ti->owner < 0) ? 0 : ti->owner;
+            while (j < ti->active_clients) {
+                TouchClientPtr tc = &ti->clients[j];
+
+                if (win == tc->window)
+                    RemoveTouchClient(dev, ti, j);
+                else
+                    j++;
+            }
+        }
+    }
+}
+
 int
 SendEvent(ClientPtr client, DeviceIntPtr d, Window dest, Bool propagate,
 	  xEvent * ev, Mask mask, int count)
Index: b/Xi/extinit.c
===================================================================
--- a/Xi/extinit.c	2011-02-28 16:57:00.000000000 +1100
+++ b/Xi/extinit.c	2011-03-09 13:11:48.093384404 +1100
@@ -258,7 +258,8 @@
         ProcXIChangeProperty,                   /* 57 */
         ProcXIDeleteProperty,                   /* 58 */
         ProcXIGetProperty,                      /* 59 */
-        ProcXIGetSelectedEvents                 /* 60 */
+        ProcXIGetSelectedEvents,                /* 60 */
+        ProcXIAllowTouchEvents,                 /* 61 */
 };
 
 /* For swapped clients */
@@ -323,7 +324,8 @@
         SProcXIChangeProperty,                   /* 57 */
         SProcXIDeleteProperty,                   /* 58 */
         SProcXIGetProperty,                      /* 59 */
-        SProcXIGetSelectedEvents                 /* 60 */
+        SProcXIGetSelectedEvents,                /* 60 */
+        SProcXIAllowTouchEvents,                 /* 61 */
 };
 
 /*****************************************************************
@@ -854,6 +856,21 @@
     swaps(&to->valuators_len, n);
 }
 
+static void STouchOwnershipEvent(xXITouchOwnershipEvent *from,
+                                 xXITouchOwnershipEvent *to)
+{
+    char n;
+
+    *to = *from;
+    swaps(&to->sequenceNumber, n);
+    swapl(&to->length, n);
+    swaps(&to->evtype, n);
+    swaps(&to->deviceid, n);
+    swapl(&to->time, n);
+    swaps(&to->sourceid, n);
+    swapl(&to->touchid, n);
+    swapl(&to->flags, n);
+}
 
 /** Event swapping function for XI2 events. */
 void
@@ -881,8 +898,16 @@
         case XI_KeyRelease:
         case XI_ButtonPress:
         case XI_ButtonRelease:
+        case XI_TouchBegin:
+        case XI_TouchUpdate:
+        case XI_TouchUpdateUnowned:
+        case XI_TouchEnd:
             SDeviceEvent((xXIDeviceEvent*)from, (xXIDeviceEvent*)to);
             break;
+        case XI_TouchOwnership:
+            STouchOwnershipEvent((xXITouchOwnershipEvent*)from,
+                                 (xXITouchOwnershipEvent*)to);
+            break;
         case XI_RawMotion:
         case XI_RawKeyPress:
         case XI_RawKeyRelease:
Index: b/Xi/xiallowev.c
===================================================================
--- a/Xi/xiallowev.c	2011-02-28 13:56:41.000000000 +1100
+++ b/Xi/xiallowev.c	2011-03-09 13:11:48.093384404 +1100
@@ -35,11 +35,15 @@
 
 #include "inputstr.h"	/* DeviceIntPtr      */
 #include "windowstr.h"	/* window structure  */
+#include "eventstr.h"
+#include "mi.h"
 #include <X11/extensions/XI2.h>
 #include <X11/extensions/XI2proto.h>
 
 #include "exglobals.h" /* BadDevice */
 #include "xiallowev.h"
+#include "exevents.h"
+#include "dixgrabs.h"
 
 int
 SProcXIAllowEvents(ClientPtr client)
@@ -98,6 +102,113 @@
 	ret = BadValue;
     }
 
+    /* If this is a master pointer with an active touch emulation and the touch
+     * has physically ceased, end the touchpoint state. */
+    if (dev->emulate_dev)
+    {  
+        DeviceIntPtr sourcedev = dev->emulate_dev;
+        TouchPointInfoPtr ti = sourcedev->touch->emulate;
+
+        if (ti->pending_finish && ti->owner < 0)
+            EndTouchPoint(sourcedev, ti);
+        else if (ti->pending_finish)
+        {  
+            TouchClientPtr tc = &ti->clients[ti->owner];
+
+            if (tc->type == TOUCH_SELECT || tc->type == TOUCH_SELECT_UNOWNED)
+                EndTouchPoint(sourcedev, ti);
+        }
+    }
+
     return ret;
 }
 
+int
+SProcXIAllowTouchEvents(ClientPtr client)
+{
+    char n;
+
+    REQUEST(xXIAllowTouchEventsReq);
+
+    swaps(&stuff->length, n);
+    swaps(&stuff->deviceid, n);
+    swapl(&stuff->touchid, n);
+
+    return ProcXIAllowTouchEvents(client);
+}
+
+int
+ProcXIAllowTouchEvents(ClientPtr client)
+{
+    DeviceIntPtr dev;
+    TouchClassPtr t;
+    TouchPointInfoPtr ti;
+    TouchClientPtr tc;
+    int ret;
+    EventList *events = InitEventList(GetMaximumEventsNum());
+
+    REQUEST(xXIAllowTouchEventsReq);
+    REQUEST_SIZE_MATCH(xXIAllowTouchEventsReq);
+
+    if (!events)
+        return BadAlloc;
+
+    ret = dixLookupDevice(&dev, stuff->deviceid, client, DixGetAttrAccess);
+    if (ret != Success)
+        return ret;
+
+    if (!dev->touch)
+    {
+        client->errorValue = stuff->deviceid;
+        return BadDevice;
+    }
+
+    t = dev->touch;
+
+    ti = FindTouchPointByClientID(dev, stuff->touchid);
+    if (!ti)
+    {
+        client->errorValue = stuff->touchid;
+        return BadValue;
+    }
+
+    tc = &ti->clients[ti->owner];
+
+    if (client != tc->client || !tc->grab)
+        return BadAccess;
+
+    if (ti == t->emulate)
+    {
+        DeviceIntPtr master = dev->u.master;
+
+        if (!master || !master->deviceGrab.grab ||
+            !GrabMatchesSecond(master->deviceGrab.grab, tc->grab, FALSE))
+        return BadAccess;
+    }
+
+    if (stuff->mode & XITouchOwnerAccept)
+    {
+        if (stuff->mode & ~XITouchOwnerAccept)
+        {
+            client->errorValue = stuff->mode;
+            return BadValue;
+        }
+    }
+    else if (stuff->mode & XITouchOwnerRejectEnd)
+    {
+        if (stuff->mode & ~XITouchOwnerRejectEnd)
+        {
+            client->errorValue = stuff->mode;
+            return BadValue;
+        }
+    }
+    else
+    {
+        client->errorValue = stuff->mode;
+        return BadValue;
+    }
+
+    ProcessTouchOwnership(dev, ti, stuff->mode, TRUE);
+
+    return Success;
+}
Index: b/Xi/xiallowev.h
===================================================================
--- a/Xi/xiallowev.h	2011-02-28 13:56:41.000000000 +1100
+++ b/Xi/xiallowev.h	2011-03-09 13:11:48.093384404 +1100
@@ -32,5 +32,7 @@
 
 int ProcXIAllowEvents(ClientPtr client);
 int SProcXIAllowEvents(ClientPtr client);
+int ProcXIAllowTouchEvents(ClientPtr client);
+int SProcXIAllowTouchEvents(ClientPtr client);
 
 #endif /* XIALLOWEV_H */
Index: b/Xi/xipassivegrab.c
===================================================================
--- a/Xi/xipassivegrab.c	2011-03-09 11:19:12.000000000 +1100
+++ b/Xi/xipassivegrab.c	2011-03-09 13:11:48.093384404 +1100
@@ -105,19 +105,30 @@
     if (stuff->grab_type != XIGrabtypeButton &&
         stuff->grab_type != XIGrabtypeKeycode &&
         stuff->grab_type != XIGrabtypeEnter &&
-        stuff->grab_type != XIGrabtypeFocusIn)
+        stuff->grab_type != XIGrabtypeFocusIn &&
+        stuff->grab_type != XIGrabtypeTouchBegin)
     {
         client->errorValue = stuff->grab_type;
         return BadValue;
     }
 
     if ((stuff->grab_type == XIGrabtypeEnter ||
-         stuff->grab_type == XIGrabtypeFocusIn) && stuff->detail != 0)
+         stuff->grab_type == XIGrabtypeFocusIn ||
+         stuff->grab_type == XIGrabtypeTouchBegin) &&
+        stuff->detail != 0)
     {
         client->errorValue = stuff->detail;
         return BadValue;
     }
 
+    if (stuff->grab_type == XIGrabtypeTouchBegin &&
+        (stuff->grab_mode != GrabModeAsync ||
+         stuff->paired_device_mode != GrabModeAsync))
+    {
+        client->errorValue = GrabModeSync;
+        return BadValue;
+    }
+
     if (XICheckInvalidMaskBits(client, (unsigned char*)&stuff[1],
                                stuff->mask_len * 4) != Success)
         return BadValue;
@@ -185,6 +196,9 @@
                 status = GrabWindow(client, dev, stuff->grab_type,
                                     &param, &mask);
                 break;
+            case XIGrabtypeTouchBegin:
+                status = GrabTouch(client, dev, mod_dev, &param, &mask);
+                break;
         }
 
         if (status != GrabSuccess)
Index: b/Xi/xiquerydevice.c
===================================================================
--- a/Xi/xiquerydevice.c	2011-03-09 11:19:12.000000000 +1100
+++ b/Xi/xiquerydevice.c	2011-03-09 13:11:48.093384404 +1100
@@ -232,6 +232,12 @@
     if (dev->valuator)
         len += sizeof(xXIValuatorInfo) * dev->valuator->numAxes;
 
+    if (dev->touch)
+    {
+        len += sizeof(xXITouchInfo);
+        len += sizeof(xXITouchValuatorInfo) * dev->touch->num_axes;
+    }
+
     return len;
 }
 
@@ -373,6 +379,73 @@
     swaps(&info->sourceid, n);
 }
 
+/**
+ * List multitouch information
+ *
+ * @return The number of bytes written into info.
+ */
+int
+ListTouchInfo(DeviceIntPtr dev, xXITouchInfo *touch)
+{
+    touch->type = XITouchClass;
+    touch->length = sizeof(xXITouchInfo) >> 2;
+    touch->sourceid = dev->id;
+    touch->mode = dev->touch->mode;
+    touch->num_touches = dev->touch->num_touches;
+
+    return touch->length << 2;
+}
+
+static void
+SwapTouchInfo(DeviceIntPtr dev, xXITouchInfo* touch)
+{
+    char n;
+    swaps(&touch->type, n);
+    swaps(&touch->length, n);
+    swaps(&touch->sourceid, n);
+}
+
+/**
+ * List multitouch axis information
+ *
+ * @return The number of bytes written into info.
+ */
+int
+ListTouchValuatorInfo(DeviceIntPtr dev, xXITouchValuatorInfo* val,
+                      int axisnumber)
+{
+    TouchClassPtr t = dev->touch;
+
+    val->type = XITouchValuatorClass;
+    val->length = sizeof(xXITouchValuatorInfo) >> 2;
+    val->sourceid = dev->id;
+    val->number = axisnumber;
+    val->label = t->axes[axisnumber].label;
+    val->min.integral = t->axes[axisnumber].min_value;
+    val->min.frac = 0;
+    val->max.integral = t->axes[axisnumber].max_value;
+    val->max.frac = 0;
+    val->resolution = t->axes[axisnumber].resolution;
+
+    return val->length << 2;
+}
+
+static void
+SwapTouchValuatorInfo(DeviceIntPtr dev, xXITouchValuatorInfo* val)
+{
+    char n;
+    swaps(&val->type, n);
+    swaps(&val->length, n);
+    swaps(&val->sourceid, n);
+    swaps(&val->number, n);
+    swapl(&val->label, n);
+    swapl(&val->min.integral, n);
+    swapl(&val->min.frac, n);
+    swapl(&val->max.integral, n);
+    swapl(&val->max.frac, n);
+    swapl(&val->resolution, n);
+}
+
 int GetDeviceUse(DeviceIntPtr dev, uint16_t *attachment)
 {
     DeviceIntPtr master = dev->u.master;
@@ -462,6 +535,22 @@
         total_len += len;
     }
 
+    if (dev->touch)
+    {
+        (*nclasses)++;
+        len = ListTouchInfo(dev, (xXITouchInfo*)any);
+        any += len;
+        total_len += len;
+
+        for (i = 0; i < dev->touch->num_axes; i++)
+        {
+            (*nclasses)++;
+            len = ListTouchValuatorInfo(dev, (xXITouchValuatorInfo*)any, i);
+            any += len;
+            total_len += len;
+        }
+    }
+
     return total_len;
 }
 
@@ -489,6 +578,12 @@
             case XIValuatorClass:
                 SwapValuatorInfo(dev, (xXIValuatorInfo*)any);
                 break;
+            case XITouchClass:
+                SwapTouchInfo(dev, (xXITouchInfo*)any);
+                break;
+            case XITouchValuatorClass:
+                SwapTouchValuatorInfo(dev, (xXITouchValuatorInfo*)any);
+                break;
         }
 
         any += len * 4;
Index: b/Xi/xiquerydevice.h
===================================================================
--- a/Xi/xiquerydevice.h	2011-02-28 13:56:41.000000000 +1100
+++ b/Xi/xiquerydevice.h	2011-03-09 13:11:48.093384404 +1100
@@ -44,4 +44,7 @@
 int ListKeyInfo(DeviceIntPtr dev, xXIKeyInfo* info);
 int ListValuatorInfo(DeviceIntPtr dev, xXIValuatorInfo* info,
 		     int axisnumber, Bool reportState);
+int ListTouchInfo(DeviceIntPtr dev, xXITouchInfo* info);
+int ListTouchValuatorInfo(DeviceIntPtr dev, xXITouchValuatorInfo* val,
+                          int axisnumber);
 #endif /* QUERYDEV_H */
Index: b/Xi/xiselectev.c
===================================================================
--- a/Xi/xiselectev.c	2011-02-28 13:56:41.000000000 +1100
+++ b/Xi/xiselectev.c	2011-03-09 13:11:48.093384404 +1100
@@ -152,6 +152,60 @@
             }
         }
 
+        if (evmask->mask_len >= 1)
+        {
+            unsigned char *bits = (unsigned char*)&evmask[1];
+
+            /* Check validity of touch selections */
+            if (BitIsOn(bits, XI_TouchBegin) ||
+                 BitIsOn(bits, XI_TouchUpdate) ||
+                 BitIsOn(bits, XI_TouchEnd))
+            {
+                /* All three touch events must be selected at once */
+                if (!BitIsOn(bits, XI_TouchBegin) ||
+                    !BitIsOn(bits, XI_TouchUpdate) ||
+                    !BitIsOn(bits, XI_TouchEnd))
+                {
+                    client->errorValue = XI_TouchBegin;
+                    return BadValue;
+                }
+
+                /* Unowned and ownership events must both be selected */
+                if ((BitIsOn(bits, XI_TouchUpdateUnowned) ||
+                     BitIsOn(bits, XI_TouchOwnership)) &&
+                    (!BitIsOn(bits, XI_TouchUpdateUnowned) ||
+                     !BitIsOn(bits, XI_TouchOwnership)))
+                {
+                    client->errorValue = XI_TouchBegin;
+                    return BadValue;
+                }
+            }
+
+            /* Only one client per window may select for touch events on the
+             * same devices, including master devices.
+             * XXX: This breaks if a device goes from floating to attached. */
+            if (BitIsOn(bits, XI_TouchBegin))
+            {
+                OtherInputMasks *inputMasks = wOtherInputMasks(win);
+                InputClients *iclient = NULL;
+                if (inputMasks)
+                    iclient = inputMasks->inputClients;
+                for (; iclient; iclient = iclient->next)
+                {
+                    if (CLIENT_ID(iclient->resource) == client->index)
+                        continue;
+                    if (BitIsOn(iclient->xi2mask[evmask->deviceid],
+                                XI_TouchBegin) ||
+                        BitIsOn(iclient->xi2mask[XIAllDevices],
+                                XI_TouchBegin) ||
+                        (dev && (IsMaster(dev) || dev->u.master) &&
+                         BitIsOn(iclient->xi2mask[XIAllMasterDevices],
+                                 XI_TouchBegin)))
+                        return BadAccess;
+                }
+            }
+        }
+
         if (XICheckInvalidMaskBits(client, (unsigned char*)&evmask[1],
                                    evmask->mask_len * 4) != Success)
             return BadValue;
Index: b/dix/devices.c
===================================================================
--- a/dix/devices.c	2011-03-09 11:19:13.000000000 +1100
+++ b/dix/devices.c	2011-03-09 13:11:48.103384795 +1100
@@ -754,6 +754,20 @@
                 free((*v));
                 break;
             }
+        case XITouchClass:
+            {
+                TouchClassPtr *t = (TouchClassPtr*)class;
+                int i;
+
+                for (i = 0; i < (*t)->num_touches; i++)
+                {
+                    free((*t)->touches[i].sprite.spriteTrace);
+                    free((*t)->touches[i].clients);
+                }
+
+                free((*t));
+                break;
+            }
         case FocusClass:
             {
                 FocusClassPtr *f = (FocusClassPtr*)class;
@@ -862,6 +876,7 @@
 
     FreeDeviceClass(KeyClass, (pointer)&classes->key);
     FreeDeviceClass(ValuatorClass, (pointer)&classes->valuator);
+    FreeDeviceClass(XITouchClass, (pointer)&classes->touch);
     FreeDeviceClass(ButtonClass, (pointer)&classes->button);
     FreeDeviceClass(FocusClass, (pointer)&classes->focus);
     FreeDeviceClass(ProximityClass, (pointer)&classes->proximity);
@@ -1543,6 +1558,151 @@
 	   InitPtrFeedbackClassDeviceStruct(dev, controlProc));
 }
 
+Bool
+InitTouchPoint(TouchClassPtr t, int index)
+{
+    TouchPointInfoPtr ti;
+
+    if (!index >= t->num_touches)
+        return FALSE;
+    ti = &t->touches[index];
+
+    ti->valuators = calloc(t->num_axes, sizeof(*ti->valuators));
+    if (!ti->valuators)
+        return FALSE;
+    ti->num_valuators = t->num_axes;
+
+    ti->sprite.spriteTrace = calloc(32, sizeof(*ti->sprite.spriteTrace));
+    if (!ti->sprite.spriteTrace)
+    {
+        free(ti->valuators);
+        ti->valuators = NULL;
+        ti->num_valuators = 0;
+        return FALSE;
+    }
+    ti->sprite.spriteTraceSize = 32;
+    ti->sprite.spriteTrace[0] = screenInfo.screens[0]->root;
+    ti->sprite.hot.pScreen = screenInfo.screens[0];
+    ti->sprite.hotPhys.pScreen = screenInfo.screens[0];
+
+    ti->ddx_id = -1;
+    ti->client_id = -1;
+
+    ti->history_size = GetMotionHistorySize();
+    ti->begin_event = malloc((ti->history_size + 1) * sizeof(InternalEvent));
+    if (!ti->begin_event)
+    {
+        free(ti->sprite.spriteTrace);
+        free(ti->valuators);
+        ti->sprite.spriteTrace = NULL;
+        ti->valuators = NULL;
+        ti->num_valuators = 0;
+        return FALSE;
+    }
+    ti->history = ti->begin_event + 1;
+    ti->first_history = ti->history;
+    ti->next_history = ti->history;
+
+    return TRUE;
+}
+
+void
+FreeTouchPoint(DeviceIntPtr device, int index)
+{
+    TouchPointInfoPtr ti;
+
+    if (!device->touch || index >= device->touch->num_touches)
+        return;
+    ti = &device->touch->touches[index];
+
+    if (ti->active)
+        EndTouchPoint(device, ti);
+
+    free(ti->valuators);
+    ti->valuators = NULL;
+    ti->num_valuators = 0;
+    free(ti->sprite.spriteTrace);
+    ti->sprite.spriteTrace = NULL;
+    free(ti->begin_event);
+    ti->begin_event = NULL;
+    free(ti->clients);
+    ti->clients = NULL;
+    ti->num_clients = 0;
+}
+
+/**
+ * Sets up multitouch capabilities on @device.
+ *
+ * @max_touches The maximum number of simultaneous touches, or 0 for unlimited.
+ * @mode The mode of the touch device (XIDirectTouch or XIDependentTouch).
+ * @num_axes The number of touch valuator axes.
+ */
+Bool
+InitTouchClassDeviceStruct(DeviceIntPtr device, unsigned int max_touches,
+                           unsigned int mode, unsigned int num_axes)
+{
+    TouchClassPtr touch;
+    int i;
+
+    if (device->touch)
+        return FALSE;
+
+    /* Check the mode is valid, and at least X and Y axes. */
+    if (mode != XIDirectTouch && mode != XIDependentTouch)
+        return FALSE;
+    if (num_axes < 2)
+        return FALSE;
+
+    if (num_axes > MAX_VALUATORS)
+    {
+        LogMessage(X_WARNING,
+                   "Device '%s' has %d touch axes, only using first %d.\n",
+                   device->name, num_axes, MAX_VALUATORS);
+        num_axes = MAX_VALUATORS;
+    }
+
+    touch = calloc(1, sizeof(*touch));
+    if (!touch)
+        return FALSE;
+
+    touch->axes = calloc(num_axes, sizeof(*touch->axes));
+    if (!touch->axes)
+        goto err;
+    touch->num_axes = num_axes;
+
+    touch->max_touches = max_touches;
+    if (max_touches == 0)
+        max_touches = 5; /* arbitrary number plucked out of the air */
+
+    /* Need cushion for clients who may hold on to touches after they physically
+     * end. So double the initial allocation of touches. */
+    touch->touches = calloc(max_touches * 2, sizeof(*touch->touches));
+    if (!touch->touches)
+        goto err;
+    touch->num_touches = max_touches * 2;
+    for (i = 0; i < touch->num_touches; i++)
+        InitTouchPoint(touch, i);
+
+    touch->mode = mode;
+    touch->x_axis = -1;
+    touch->y_axis = -1;
+    touch->next_client_id = 1;
+
+    device->touch = touch;
+
+    return TRUE;
+
+err:
+    for (i = 0; i < touch->num_touches; i++)
+        FreeTouchPoint(device, i);
+
+    free(touch->touches);
+    free(touch->axes);
+    free(touch);
+
+    return FALSE;
+}
+
 /*
  * Check if the given buffer contains elements between low (inclusive) and
  * high (inclusive) only.
@@ -2375,6 +2535,58 @@
     }
 }
 
+static void
+DropTouchSelectionsOnWindow(DeviceIntPtr dev, WindowPtr win)
+{
+    WindowPtr child;
+
+    if (wOtherInputMasks(win) &&
+        BitIsOn(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchBegin))
+    {
+        InputClientsPtr client = wOtherInputMasks(win)->inputClients;
+
+        /* Don't bother deleting client record if there are no other
+         * selections. The client will likely reselect when it gets the
+         * HierarchyChange event. */
+        while (client)
+        {
+            ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchBegin);
+            ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchEnd);
+            ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchOwnership);
+            ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchUpdate);
+            ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchUpdateUnowned);
+
+            client = client->next;
+        }
+
+        ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchBegin);
+        ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchEnd);
+        ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchOwnership);
+        ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchUpdate);
+        ClearBit(wOtherInputMasks(win)->xi2mask[dev->id], XI_TouchUpdateUnowned);
+    }
+
+    child = win->firstChild;
+    while (child)
+    {
+        DropTouchSelectionsOnWindow(dev, child);
+        child = child->nextSib;
+    }
+}
+
+static void
+DropTouchSelections(DeviceIntPtr dev)
+{
+    int i;
+
+    for (i = 0; i < screenInfo.numScreens; i++)
+    {
+        WindowPtr win = screenInfo.screens[i]->root;
+
+        DropTouchSelectionsOnWindow(dev, win);
+    }
+}
+
 /**
  * Attach device 'dev' to device 'master'.
  * Client is set to the client that issued the request, or NULL if it comes
@@ -2440,6 +2652,12 @@
         dev->spriteInfo->spriteOwner = FALSE;
 
         RecalculateMasterButtons(master);
+
+        /* Only one client may select for touch events from a device on a window
+         * at any time. Reattaching could break this, so drop all touch event
+         * selections for this specific slave device on all windows. */
+        if (dev->touch)
+            DropTouchSelections(dev);
     }
 
     /* XXX: in theory, the MD should change back to its old, original
Index: b/dix/eventconvert.c
===================================================================
--- a/dix/eventconvert.c	2011-03-09 11:39:57.000000000 +1100
+++ b/dix/eventconvert.c	2011-03-09 13:11:48.103384795 +1100
@@ -55,6 +55,7 @@
 static int eventToDeviceChanged(DeviceChangedEvent *ev, xEvent **dcce);
 static int eventToDeviceEvent(DeviceEvent *ev, xEvent **xi);
 static int eventToRawEvent(RawDeviceEvent *ev, xEvent **xi);
+static int eventToTouchOwnershipEvent(TouchOwnershipEvent *ev, xEvent **xi);
 
 /* Do not use, read comments below */
 BOOL EventIsKeyRepeat(xEvent *event);
@@ -139,6 +140,11 @@
         case ET_RawButtonPress:
         case ET_RawButtonRelease:
         case ET_RawMotion:
+        case ET_TouchBegin:
+        case ET_TouchEnd:
+        case ET_TouchMotion:
+        case ET_TouchMotionUnowned:
+        case ET_TouchOwnership:
             return BadMatch;
         default:
             /* XXX: */
@@ -184,6 +190,11 @@
         case ET_RawButtonPress:
         case ET_RawButtonRelease:
         case ET_RawMotion:
+        case ET_TouchBegin:
+        case ET_TouchEnd:
+        case ET_TouchMotion:
+        case ET_TouchMotionUnowned:
+        case ET_TouchOwnership:
             *count = 0;
             *xi = NULL;
             return BadMatch;
@@ -225,7 +236,13 @@
         case ET_ButtonRelease:
         case ET_KeyPress:
         case ET_KeyRelease:
+        case ET_TouchBegin:
+        case ET_TouchMotion:
+        case ET_TouchMotionUnowned:
+        case ET_TouchEnd:
             return eventToDeviceEvent(&ev->device_event, xi);
+        case ET_TouchOwnership:
+            return eventToTouchOwnershipEvent(&ev->touch_ownership_event, xi);
         case ET_ProximityIn:
         case ET_ProximityOut:
             *xi = NULL;
@@ -588,6 +605,7 @@
     xde->root_x         = FP1616(ev->root_x, ev->root_x_frac);
     xde->root_y         = FP1616(ev->root_y, ev->root_y_frac);
 
+    xde->flags          = ev->flags;
     if (ev->key_repeat)
         xde->flags      |= XIKeyRepeat;
 
@@ -625,6 +643,27 @@
 }
 
 static int
+eventToTouchOwnershipEvent(TouchOwnershipEvent *ev, xEvent **xi)
+{
+    int len = sizeof(xXITouchOwnershipEvent);
+    xXITouchOwnershipEvent *xtoe;
+
+    *xi = calloc(1, len);
+    xtoe = (xXITouchOwnershipEvent*)*xi;
+    xtoe->type          = GenericEvent;
+    xtoe->extension     = IReqCode;
+    xtoe->length        = bytes_to_int32(len - sizeof(xEvent));
+    xtoe->evtype        = GetXI2Type((InternalEvent*)ev);
+    xtoe->deviceid      = ev->deviceid;
+    xtoe->time          = ev->time;
+    xtoe->sourceid      = ev->sourceid;
+    xtoe->touchid       = ev->touchid;
+    xtoe->flags         = ev->flags;
+
+    return Success;
+}
+
+static int
 eventToRawEvent(RawDeviceEvent *ev, xEvent **xi)
 {
     xXIRawEvent* raw;
@@ -739,6 +778,11 @@
         case ET_RawMotion:      xi2type = XI_RawMotion;        break;
         case ET_FocusIn:        xi2type = XI_FocusIn;          break;
         case ET_FocusOut:       xi2type = XI_FocusOut;         break;
+        case ET_TouchBegin:     xi2type = XI_TouchBegin;       break;
+        case ET_TouchEnd:       xi2type = XI_TouchEnd;         break;
+        case ET_TouchMotion:    xi2type = XI_TouchUpdate;      break;
+        case ET_TouchMotionUnowned: xi2type = XI_TouchUpdateUnowned; break;
+        case ET_TouchOwnership: xi2type = XI_TouchOwnership;   break;
         default:
             break;
     }
Index: b/dix/events.c
===================================================================
--- a/dix/events.c	2011-03-09 11:19:13.000000000 +1100
+++ b/dix/events.c	2011-03-09 13:11:48.103384795 +1100
@@ -1089,7 +1089,7 @@
 void
 EnqueueEvent(InternalEvent *ev, DeviceIntPtr device)
 {
-    QdEventPtr	tail = *syncEvents.pendtail;
+    QdEventPtr	tail = syncEvents.pendtail;
     QdEventPtr	qe;
     SpritePtr	pSprite = device->spriteInfo->sprite;
     int		eventlen;
@@ -1160,8 +1160,10 @@
     qe->event = (InternalEvent *)(qe + 1);
     memcpy(qe->event, event, eventlen);
     if (tail)
-	syncEvents.pendtail = &tail->next;
-    *syncEvents.pendtail = qe;
+        tail->next = qe;
+    else
+        syncEvents.pending = qe;
+    syncEvents.pendtail = qe;
 }
 
 /**
@@ -1176,18 +1178,19 @@
 static void
 PlayReleasedEvents(void)
 {
-    QdEventPtr *prev, qe;
+    QdEventPtr prev, qe = syncEvents.pending;
     DeviceIntPtr dev;
     DeviceIntPtr pDev;
 
-    prev = &syncEvents.pending;
-    while ( (qe = *prev) )
+    prev = NULL;
+    while (qe)
     {
 	if (!qe->device->deviceGrab.sync.frozen)
 	{
-	    *prev = qe->next;
+            if (syncEvents.pending == qe)
+                syncEvents.pending = qe->next;
             pDev = qe->device;
-	    if (*syncEvents.pendtail == *prev)
+	    if (syncEvents.pendtail == qe)
 		syncEvents.pendtail = prev;
 	    if (qe->event->any.type == ET_Motion)
 		CheckVirtualMotion(pDev, qe, NullWindow);
@@ -1219,6 +1222,7 @@
 
 	    }
 #endif
+
 	    (*qe->device->public.processInputProc)(qe->event, qe->device);
 	    free(qe);
 	    for (dev = inputInfo.devices; dev && dev->deviceGrab.sync.frozen; dev = dev->next)
@@ -1227,10 +1231,14 @@
 		break;
 	    /* Playing the event may have unfrozen another device. */
 	    /* So to play it safe, restart at the head of the queue */
-	    prev = &syncEvents.pending;
+	    qe = syncEvents.pending;
+            prev = NULL;
 	}
 	else
-	    prev = &qe->next;
+        {
+	    prev = qe;
+            qe = qe->next;
+        }
     }
 }
 
@@ -1252,6 +1260,76 @@
 	dev->public.processInputProc = dev->public.realInputProc;
 }
 
+void
+RemoveTouchEventsFromQueue(DeviceIntPtr dev, Bool touch, Bool ignoreOwned)
+{
+    QdEventPtr qe = syncEvents.pending;
+    QdEventPtr prev_qe = NULL;
+    QdEventPtr first = NULL;
+    Bool end = FALSE;
+
+    while (qe && !end)
+    {
+        QdEventPtr tmp;
+
+        if (qe->device != dev)
+            continue;
+
+        if (ignoreOwned && (qe->event->any.type == ET_TouchOwnership ||
+                            qe->event->any.type == ET_TouchEnd))
+            break;
+
+        if (qe->event->any.type == ET_TouchEnd)
+            end = TRUE;
+
+        if ((touch && !IsTouchEvent(qe->event)) ||
+            (!touch && !IsPointerEvent(qe->event)) ||
+            (ignoreOwned && qe->event->any.type == ET_TouchBegin))
+        {
+            if (!first)
+                first = qe;
+            prev_qe = qe;
+            qe = qe->next;
+            continue;
+        }
+
+        tmp = qe;
+        qe = qe->next;
+        if (prev_qe)
+            prev_qe->next = qe;
+        if (syncEvents.pending == tmp)
+            syncEvents.pending = qe;
+
+        free(tmp);
+
+        if (!qe)
+            syncEvents.pendtail = prev_qe;
+    }
+
+    if (qe && !qe->next)
+        syncEvents.pendtail = qe;
+
+    if (dev->deviceGrab.sync.event &&
+        ((touch && IsTouchEvent((InternalEvent *)dev->deviceGrab.sync.event)) ||
+         (!touch &&
+          IsPointerEvent((InternalEvent *)dev->deviceGrab.sync.event))))
+    {
+        free(dev->deviceGrab.sync.event);
+        if (first)
+        {
+            dev->deviceGrab.sync.event = malloc(sizeof(DeviceEvent));
+            memcpy(dev->deviceGrab.sync.event, first->event,
+                   sizeof(DeviceEvent));
+        }
+        else
+            dev->deviceGrab.sync.event = NULL;
+        syncEvents.pending = first->next;
+        free(first);
+        if (!syncEvents.pending)
+            syncEvents.pendtail = NULL;
+    }
+}
+
 /**
  * Unfreeze devices and replay all events to the respective clients.
  *
@@ -1278,6 +1356,14 @@
     {
         DeviceEvent* event = replayDev->deviceGrab.sync.event;
 
+        if (event->type == ET_TouchBegin)
+        {  
+            ProcessTouchOwnership(replayDev, event->touchpoint,
+                                  XITouchOwnerAccept, FALSE);
+            if (!replayDev->deviceGrab.sync.event)
+                goto no_sync;
+        }
+
 	syncEvents.replayDev = (DeviceIntPtr)NULL;
 
         w = XYToWindow(replayDev->spriteInfo->sprite,
@@ -1291,6 +1377,7 @@
                                     NullWindow, replayDev);
         }
     }
+no_sync:
     for (dev = inputInfo.devices; dev; dev = dev->next)
     {
 	if (!dev->deviceGrab.sync.frozen)
@@ -1510,6 +1597,20 @@
     if (!wasImplicit && grab->grabtype == GRABTYPE_XI2)
         ReattachToOldMaster(mouse);
 
+    if (mouse->deviceGrab.sync.event &&
+        (mouse->deviceGrab.sync.event->flags & XIPointerEmulated) &&
+        (grab->grabtype != GRABTYPE_XI2 || grab->type != XI_TouchBegin))
+    {
+        InternalEvent event;
+
+        event.any.type = ET_TouchBegin;
+
+        if (CheckPassiveGrabsOnWindow(grab->window, mouse, &event, FALSE, TRUE))
+            syncEvents.playingEvents = TRUE;
+    }
+    else
+        syncEvents.playingEvents = FALSE;
+
     ComputeFreezes();
 }
 
@@ -1757,6 +1858,25 @@
 	    client->errorValue = stuff->mode;
 	    return BadValue;
     }
+
+    /* If this is a master pointer with an active touch emulation and the touch
+     * has physically ceased, end the touchpoint state. */
+    if (mouse->emulate_dev)
+    {
+        DeviceIntPtr sourcedev = mouse->emulate_dev;
+        TouchPointInfoPtr ti = sourcedev->touch->emulate;
+
+        if (ti->pending_finish && ti->owner < 0)
+            EndTouchPoint(sourcedev, ti);
+        else if (ti->pending_finish)
+        {
+            TouchClientPtr tc = &ti->clients[ti->owner];
+
+            if (tc->type == TOUCH_SELECT || tc->type == TOUCH_SELECT_UNOWNED)
+                EndTouchPoint(sourcedev, ti);
+        }
+    }
+
     return Success;
 }
 
@@ -2174,7 +2294,7 @@
 
 static Window FindChildForEvent(SpritePtr pSprite, WindowPtr event)
 {
-    WindowPtr w = pSprite->spriteTrace[pSprite->spriteTraceGood-1];
+    WindowPtr w = DeepestSpriteWin(pSprite);
     Window child = None;
 
     /* If the search ends up past the root should the child field be
@@ -2232,7 +2352,8 @@
             event->evtype == XI_RawMotion ||
             event->evtype == XI_DeviceChanged ||
             event->evtype == XI_HierarchyChanged ||
-            event->evtype == XI_PropertyEvent)
+            event->evtype == XI_PropertyEvent ||
+            event->evtype == XI_TouchOwnership)
             return;
 
         event->root = RootWindow(pSprite)->drawable.id;
@@ -2369,12 +2490,119 @@
     xEvent core;
     xEvent *xE = NULL;
     int rc, mask, count = 0;
+    InternalEvent touch_dummy;
+    Bool check_touch = FALSE;
 
     CHECKEVENT(event);
 
+    /* If we are replaying a pointer emulated button press event, find the first
+     * pointer or touch selecting client. */
+    if (syncEvents.playingEvents && event->any.type == ET_ButtonPress &&
+        (event->device_event.flags & XIPointerEmulated) &&
+        event->device_event.touchpoint &&
+        event->device_event.touchpoint->active_clients > 0)
+    {
+        QdEventPtr qe;
+        DeviceEvent *te;
+        TouchPointInfoPtr ti;
+        TouchClientPtr tc = NULL;
+
+        for (qe = syncEvents.pending; qe; qe = qe->next)
+            if (qe->device == dev && qe->event->any.type == ET_TouchBegin)
+                break;
+        if (!qe)
+        {
+            LogMessage(X_ERROR, "no touch for emulated button press\n");
+            goto no_touch_event;
+        }
+
+        te = &qe->event->device_event;
+        ti = te->touchpoint;
+
+        if (ti->active_clients > 0)
+        {
+            tc = &ti->clients[ti->active_clients - 1];
+            te->deviceid = tc->device->id;
+        }
+
+        while (pWin)
+        {
+            Bool touch = FALSE;
+            Bool pointer = FALSE;
+
+            if (tc &&
+                EventIsDeliverable(tc->device, (InternalEvent *)te, pWin) &&
+                (tc->type == TOUCH_SELECT || tc->type == TOUCH_SELECT_UNOWNED))
+            {
+                ti->owner = ti->active_clients - 1;
+                if (tc->type == TOUCH_SELECT_UNOWNED)
+                    DeliverTouchOwnershipEvent(tc, ti);
+                touch = TRUE;
+            }
+
+            if (EventIsDeliverable(dev, event, pWin))
+                pointer = TRUE;
+
+            if (touch && pointer)
+                break;
+            else if (touch || pointer)
+            {
+                /* Remove unselected events from queue. */
+                RemoveTouchEventsFromQueue(dev, pointer, FALSE);
+
+                if (touch)
+                {
+                    /* If only touch events are selected, release mouse
+                     * button. */
+                    ReleaseButton(dev, 1);
+                    ti->emulate_pointer = FALSE;
+                    if (IsPointerEvent(event))
+                        return 0;
+                } else {
+                    ti->owner = -1;
+                    ti->active_clients = 0;
+                    if (IsTouchEvent(event))
+                        return 0;
+                }
+
+                break;
+            }
+
+            pWin = pWin->parent;
+        }
+    }
+    else if (IsPointerEvent(event) && !syncEvents.playingEvents &&
+             (event->device_event.flags & XIPointerEmulated) &&
+             event->device_event.touchpoint &&
+             event->device_event.touchpoint->active_clients > 0)
+    {
+        /* Non-grabbed emulated pointer event, so check for touch selections. */
+        check_touch = TRUE;
+        touch_dummy.any.type = ET_TouchBegin;
+    }
+    else if (IsTouchEvent(event))
+    {
+        TouchPointInfoPtr ti = event->device_event.touchpoint;
+        TouchClientPtr tc = &ti->clients[ti->owner];
+
+        pWin = tc->window;
+    }
+
+no_touch_event:
     while (pWin)
     {
-        if ((mask = EventIsDeliverable(dev, event, pWin)))
+        DeviceIntPtr check_dev = dev;
+
+        if (IsTouchEvent(event))
+        {
+            TouchPointInfoPtr ti = event->device_event.touchpoint;
+            TouchClientPtr tc = &ti->clients[ti->owner];
+
+            event->device_event.deviceid = tc->device->id;
+            check_dev = tc->device;
+        }
+
+        if ((mask = EventIsDeliverable(check_dev, event, pWin)))
         {
             /* XI2 events first */
             if (mask & XI2_MASK)
@@ -2383,10 +2611,25 @@
                 rc = EventToXI2(event, &xi2);
                 if (rc == Success)
                 {
+                    if (event->any.type == ET_TouchBegin ||
+                         event->any.type == ET_TouchMotionUnowned)
+                    {
+                        OtherInputMasks *masks = wOtherInputMasks(pWin);
+
+                        if (BitIsOn(masks->xi2mask[XIAllDevices],
+                                    XI_TouchOwnership) ||
+                            BitIsOn(masks->xi2mask[check_dev->id],
+                                    XI_TouchOwnership) ||
+                            (IsMaster(check_dev) &&
+                             BitIsOn(masks->xi2mask[XIAllMasterDevices],
+                                     XI_TouchOwnership)))
+                            goto unwind;
+                    }
+
                     /* XXX: XACE */
-                    filter = GetEventFilter(dev, xi2);
+                    filter = GetEventFilter(check_dev, xi2);
                     FixUpEventFromWindow(pSprite, xi2, pWin, child, FALSE);
-                    deliveries = DeliverEventsToWindow(dev, pWin, xi2, 1,
+                    deliveries = DeliverEventsToWindow(check_dev, pWin, xi2, 1,
                                                        filter, grab);
                     free(xi2);
                     if (deliveries > 0)
@@ -2439,6 +2682,14 @@
                 goto unwind;
             }
         }
+        else if (check_touch && EventIsDeliverable(dev, &touch_dummy, pWin))
+        {
+            /* Only touch events wanted on this window. Skip this event and
+             * stop pointer emulation. Future touch events will be sent
+             * instead. */
+            event->device_event.touchpoint->emulate_pointer = FALSE;
+            goto unwind;
+        }
 
         child = pWin->drawable.id;
         pWin = pWin->parent;
@@ -2591,7 +2842,7 @@
 	else
 	    pWin = pWin->nextSib;
     }
-    return pSprite->spriteTrace[pSprite->spriteTraceGood-1];
+    return DeepestSpriteWin(pSprite);
 }
 
 /**
@@ -2629,7 +2880,8 @@
     event.deviceid = dev->id;
     event.sourceid = dev->id;
     event.detail.button = 0;
-    rc = (CheckPassiveGrabsOnWindow(win, dev, &event, FALSE, TRUE) != NULL);
+    rc = (CheckPassiveGrabsOnWindow(win, dev, (InternalEvent *) &event, FALSE,
+                                    TRUE) != NULL);
     if (rc)
         DoEnterLeaveEvents(dev, dev->id, old, win, XINotifyPassiveUngrab);
     return rc;
@@ -2666,7 +2918,8 @@
     event.deviceid = dev->id;
     event.sourceid = dev->id;
     event.detail.button = 0;
-    rc = (CheckPassiveGrabsOnWindow(win, dev, &event, FALSE, TRUE) != NULL);
+    rc = (CheckPassiveGrabsOnWindow(win, dev, (InternalEvent *) &event, FALSE,
+                                    TRUE) != NULL);
     if (rc)
         DoEnterLeaveEvents(dev, dev->id, old, win, XINotifyPassiveGrab);
     return rc;
@@ -3353,7 +3606,7 @@
 CheckPassiveGrabsOnWindow(
     WindowPtr pWin,
     DeviceIntPtr device,
-    DeviceEvent *event,
+    InternalEvent *event,
     BOOL checkCore,
     BOOL activate)
 {
@@ -3370,9 +3623,22 @@
 	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:
+            tempGrab.detail.exact = event->device_event.detail.button;
+            break;
+        default:
+            tempGrab.detail.exact = 0;
+            break;
+    }
     tempGrab.window = pWin;
     tempGrab.device = device;
-    tempGrab.detail.exact = event->detail.key;
     tempGrab.detail.pMask = NULL;
     tempGrab.modifiersDetail.pMask = NULL;
     tempGrab.next = NULL;
@@ -3380,6 +3646,9 @@
     {
 	DeviceIntPtr	gdev;
 	XkbSrvInfoPtr	xkbi = NULL;
+	int rc, count = 0;
+	xEvent *xE = NULL;
+	xEvent core;
 
 	gdev= grab->modifierDevice;
         if (grab->grabtype == GRABTYPE_CORE)
@@ -3405,16 +3674,15 @@
         tempGrab.modifiersDetail.exact = xkbi ? xkbi->state.grab_mods : 0;
 
         /* Check for XI2 and XI grabs first */
-        tempGrab.type = GetXI2Type((InternalEvent*)event);
+        tempGrab.type = GetXI2Type(event);
         tempGrab.grabtype = GRABTYPE_XI2;
         if (GrabMatchesSecond(&tempGrab, grab, FALSE))
             match = XI2_MATCH;
 
-        tempGrab.detail.exact = event->detail.key;
         if (!match)
         {
             tempGrab.grabtype = GRABTYPE_XI;
-            if ((tempGrab.type = GetXIType((InternalEvent*)event)) &&
+            if ((tempGrab.type = GetXIType(event)) &&
                 (GrabMatchesSecond(&tempGrab, grab, FALSE)))
                 match = XI_MATCH;
         }
@@ -3423,125 +3691,143 @@
         if (!match && checkCore)
         {
             tempGrab.grabtype = GRABTYPE_CORE;
-            if ((tempGrab.type = GetCoreType((InternalEvent*)event)) &&
+            if ((tempGrab.type = GetCoreType(event)) &&
                 (GrabMatchesSecond(&tempGrab, grab, TRUE)))
                 match = CORE_MATCH;
         }
 
-        if (match && (!grab->confineTo ||
-	     (grab->confineTo->realized &&
-				BorderSizeNotEmpty(device, grab->confineTo))))
-	{
-            int rc, count = 0;
-            xEvent *xE = NULL;
-            xEvent core;
+        if (!match || (grab->confineTo &&
+                       (!grab->confineTo->realized ||
+                        !BorderSizeNotEmpty(device, grab->confineTo))))
+            continue;
 
-            event->corestate &= 0x1f00;
-            event->corestate |= tempGrab.modifiersDetail.exact & (~0x1f00);
-            grabinfo = &device->deviceGrab;
-            /* 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 == GRABTYPE_CORE)
-            {
-                DeviceIntPtr other;
-                BOOL interfering = FALSE;
-
-                /* 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 (tempGrab.type < GenericEvent)
-                {
-                    grab->device = device;
-                    grab->modifierDevice = GetPairedDevice(device);
-                }
+        grabinfo = &device->deviceGrab;
+        /* 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 == GRABTYPE_CORE)
+        {
+            DeviceIntPtr other;
+            BOOL interfering = FALSE;
+
+            /* 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 (tempGrab.type < GenericEvent)
+            {
+                grab->device = device;
+                grab->modifierDevice = GetPairedDevice(device);
+            }
 
-                for (other = inputInfo.devices; other; other = other->next)
+            for (other = inputInfo.devices; other; other = other->next)
+            {
+                GrabPtr othergrab = other->deviceGrab.grab;
+                if (othergrab && othergrab->grabtype == GRABTYPE_CORE &&
+                    SameClient(grab, rClient(othergrab)) &&
+                    ((IsPointerDevice(grab->device) &&
+                     IsPointerDevice(othergrab->device)) ||
+                     (IsKeyboardDevice(grab->device) &&
+                      IsKeyboardDevice(othergrab->device))))
                 {
-                    GrabPtr othergrab = other->deviceGrab.grab;
-                    if (othergrab && othergrab->grabtype == GRABTYPE_CORE &&
-                        SameClient(grab, rClient(othergrab)) &&
-                        ((IsPointerDevice(grab->device) &&
-                         IsPointerDevice(othergrab->device)) ||
-                         (IsKeyboardDevice(grab->device) &&
-                          IsKeyboardDevice(othergrab->device))))
-                    {
-                        interfering = TRUE;
-                        break;
-                    }
+                    interfering = TRUE;
+                    break;
                 }
-                if (interfering)
-                    continue;
             }
+            if (interfering)
+                continue;
+        }
 
-            if (!activate)
-                return grab;
+        if (!activate)
+        {
+            return grab;
+        }
+        else if (!GetXIType(event) && !GetCoreType(event))
+        {
+            ErrorF("Event type %d in CheckPassiveGrabsOnWindow is neither"
+                   " XI 1.x nor core\n", event->any.type);
+            return NULL;
+        }
 
-            if (match & CORE_MATCH)
+        /* The only consumers of corestate are Xi 1.x and core events, which
+         * are guaranteed to come from DeviceEvents. */
+        if (match & (XI_MATCH | CORE_MATCH))
+        {
+            event->device_event.corestate &= 0x1f00;
+            event->device_event.corestate |= tempGrab.modifiersDetail.exact &
+                                              (~0x1f00);
+        }
+
+        if (match & CORE_MATCH)
+        {
+            rc = EventToCore(event, &core);
+            if (rc != Success)
             {
-                rc = EventToCore((InternalEvent*)event, &core);
-                if (rc != Success)
-                {
-                    if (rc != BadMatch)
-                        ErrorF("[dix] %s: core conversion failed in CPGFW "
-                                "(%d, %d).\n", device->name, event->type, rc);
-                    continue;
-                }
-                xE = &core;
-                count = 1;
-            } else if (match & XI2_MATCH)
+                if (rc != BadMatch)
+                    ErrorF("[dix] %s: core conversion failed in CPGFW "
+                            "(%d, %d).\n", device->name, event->any.type, rc);
+                continue;
+            }
+            xE = &core;
+            count = 1;
+        } else if (match & XI2_MATCH)
+        {
+            rc = EventToXI2(event, &xE);
+            if (rc != Success)
             {
-                rc = EventToXI2((InternalEvent*)event, &xE);
-                if (rc != Success)
-                {
-                    if (rc != BadMatch)
-                        ErrorF("[dix] %s: XI2 conversion failed in CPGFW "
-                                "(%d, %d).\n", device->name, event->type, rc);
-                    continue;
-                }
-                count = 1;
-            } else
+                if (rc != BadMatch)
+                    ErrorF("[dix] %s: XI2 conversion failed in CPGFW "
+                            "(%d, %d).\n", device->name, event->any.type, rc);
+                continue;
+            }
+            count = 1;
+        } else
+        {
+            rc = EventToXI(event, &xE, &count);
+            if (rc != Success)
             {
-                rc = EventToXI((InternalEvent*)event, &xE, &count);
-                if (rc != Success)
-                {
-                    if (rc != BadMatch)
-                        ErrorF("[dix] %s: XI conversion failed in CPGFW "
-                                "(%d, %d).\n", device->name, event->type, rc);
-                    continue;
-                }
+                if (rc != BadMatch)
+                    ErrorF("[dix] %s: XI conversion failed in CPGFW "
+                            "(%d, %d).\n", device->name, event->any.type, rc);
+                continue;
             }
+        }
 
-	    (*grabinfo->ActivateGrab)(device, grab, currentTime, TRUE);
+        (*grabinfo->ActivateGrab)(device, grab, currentTime, TRUE);
 
-            if (xE)
-            {
-                FixUpEventFromWindow(pSprite, xE, grab->window, None, TRUE);
+        /* Don't send touch events if you activate a touch grab. Touch grabs
+         * are handled separately. */
+        if (xE && grab->type != ET_TouchBegin)
+        {
+            FixUpEventFromWindow(pSprite, xE, grab->window, None, TRUE);
 
-                TryClientEvents(rClient(grab), device, xE, count,
-                                       GetEventFilter(device, xE),
-                                       GetEventFilter(device, xE), grab);
-            }
+            TryClientEvents(rClient(grab), device, xE, count,
+                            GetEventFilter(device, xE),
+                            GetEventFilter(device, xE), grab);
+        }
 
-	    if (grabinfo->sync.state == FROZEN_NO_EVENT)
-	    {
+        if (grabinfo->sync.state == FROZEN_NO_EVENT)
+        {
+            /* Touch events are enqueued differently due to pointer
+             * emulation. */
+            if (grab->type != ET_TouchBegin)
+            {
                 if (!grabinfo->sync.event)
-                    grabinfo->sync.event = calloc(1, sizeof(InternalEvent));
-                *grabinfo->sync.event = *event;
-		grabinfo->sync.state = FROZEN_WITH_EVENT;
+                    grabinfo->sync.event = calloc(1, sizeof(DeviceEvent));
+                *grabinfo->sync.event = event->device_event;
             }
+            grabinfo->sync.state = FROZEN_WITH_EVENT;
+        }
 
-            if (match & (XI_MATCH | XI2_MATCH))
-                free(xE); /* on core match xE == &core */
-	    return grab;
-	}
+        if (match & (XI_MATCH | XI2_MATCH))
+            free(xE); /* on core match xE == &core */
+        return grab;
     }
     return NULL;
 #undef CORE_MATCH
@@ -3580,8 +3866,13 @@
 {
     int i;
     WindowPtr pWin = NULL;
-    FocusClassPtr focus = IsPointerEvent((InternalEvent*)event) ? NULL : device->focus;
+    FocusClassPtr focus = device->focus;
     BOOL sendCore = (IsMaster(device) && device->coreEvents);
+    DeviceEvent *touch_event = NULL;
+
+    if (IsPointerEvent((InternalEvent *)event) ||
+        IsTouchEvent((InternalEvent *)event))
+        focus = NULL;
 
     if (event->type != ET_ButtonPress &&
         event->type != ET_KeyPress)
@@ -3609,7 +3900,8 @@
 	for (; i < focus->traceGood; i++)
 	{
 	    pWin = focus->trace[i];
-	    if (CheckPassiveGrabsOnWindow(pWin, device, event, sendCore, TRUE))
+	    if (CheckPassiveGrabsOnWindow(pWin, device, (InternalEvent *) event,
+	                                  sendCore, TRUE))
 		return TRUE;
 	}
 
@@ -3619,11 +3911,54 @@
 	    return FALSE;
     }
 
+    if (syncEvents.pending && event->type == ET_ButtonPress &&
+        (event->flags & XIPointerEmulated))
+    {
+        QdEventPtr qe;
+
+        for (qe = syncEvents.pending; qe; qe = qe->next)
+            if (qe->device == device && qe->event->any.type == ET_TouchBegin)
+                break;
+        if (qe)
+            touch_event = &qe->event->device_event;
+    }
+
     for (; i < device->spriteInfo->sprite->spriteTraceGood; i++)
     {
-	pWin = device->spriteInfo->sprite->spriteTrace[i];
-	if (CheckPassiveGrabsOnWindow(pWin, device, event, sendCore, TRUE))
-	    return TRUE;
+        pWin = device->spriteInfo->sprite->spriteTrace[i];
+
+        if (!pWin->optional)
+            continue;
+
+        /* Touch grabs are checked before pointer grabs. When a touch grab
+         * should be checked first, check_grab is TRUE. */
+        if (touch_event && touch_event->check_grab)
+        {
+            GrabPtr grab;
+
+            grab = CheckPassiveGrabsOnWindow(pWin, device,
+                                             (InternalEvent *)touch_event,
+                                             FALSE, FALSE);
+            if (grab)
+            {
+                TouchPointInfoPtr ti = touch_event->touchpoint;
+                TouchClientPtr tc = &ti->clients[ti->owner];
+
+                device->deviceGrab.ActivateGrab(device, grab, currentTime,
+                                                TRUE);
+                touch_event->check_grab = FALSE;
+                DeliverTouchOwnershipEvent(tc, ti);
+                return TRUE;
+            }
+        }
+
+        if (touch_event)
+            touch_event->check_grab = TRUE;
+
+        if (pWin->optional &&
+            CheckPassiveGrabsOnWindow(pWin, device, (InternalEvent *)event,
+                                      sendCore, TRUE))
+            return TRUE;
     }
 
     return FALSE;
@@ -3745,6 +4080,17 @@
     grabinfo = &thisDev->deviceGrab;
     grab = grabinfo->grab;
 
+    /* Touch grab deliver is handled in ProcessTouchEvent. */
+    if (event->any.type == ET_TouchBegin ||
+        event->any.type == ET_TouchMotionUnowned)
+    {
+        if (BitIsOn(grab->xi2mask[XIAllDevices], XI_TouchOwnership) ||
+            BitIsOn(grab->xi2mask[thisDev->id], XI_TouchOwnership) ||
+            (IsMaster(thisDev) &&
+             BitIsOn(grab->xi2mask[XIAllMasterDevices], XI_TouchOwnership)))
+            return;
+    }
+
     if (grab->ownerEvents)
     {
 	WindowPtr focus;
@@ -3821,6 +4167,9 @@
                 mask = grab->xi2mask[XIAllDevices][evtype/8] |
                     grab->xi2mask[XIAllMasterDevices][evtype/8] |
                     grab->xi2mask[thisDev->id][evtype/8];
+                if (IsTouchEvent(event))
+                    mask |=
+                        grab->xi2mask[event->device_event.sourceid][evtype/8];
                 /* try XI2 event */
                 FixUpEventFromWindow(pSprite, xi2, grab->window, None, TRUE);
                 /* XXX: XACE */
@@ -4955,7 +5304,7 @@
 	free(syncEvents.pending);
 	syncEvents.pending = next;
     }
-    syncEvents.pendtail = &syncEvents.pending;
+    syncEvents.pendtail = NULL;
     syncEvents.playingEvents = FALSE;
     syncEvents.time.months = 0;
     syncEvents.time.milliseconds = 0;	/* hardly matters */
Index: b/dix/getevents.c
===================================================================
--- a/dix/getevents.c	2011-03-09 11:19:13.000000000 +1100
+++ b/dix/getevents.c	2011-03-09 13:11:48.103384795 +1100
@@ -47,6 +47,7 @@
 #include "eventstr.h"
 #include "eventconvert.h"
 #include "inpututils.h"
+#include "windowstr.h"
 
 #include <X11/extensions/XKBproto.h>
 #include "xkbsrv.h"
@@ -160,7 +161,7 @@
               (1 << (key_code & 7)));
 }
 
-static void
+void
 init_event(DeviceIntPtr dev, DeviceEvent* event, Time ms)
 {
     memset(event, 0, sizeof(DeviceEvent));
@@ -172,6 +173,18 @@
 }
 
 static void
+init_touch_ownership(DeviceIntPtr dev, TouchOwnershipEvent *event, Time ms)
+{
+    memset(event, 0, sizeof(TouchOwnershipEvent));
+    event->header = ET_Internal;
+    event->type = ET_TouchOwnership;
+    event->length = sizeof(TouchOwnershipEvent);
+    event->time = ms;
+    event->deviceid = dev->id;
+    event->sourceid = dev->id;
+}
+
+static void
 init_raw(DeviceIntPtr dev, RawDeviceEvent *event, Time ms, int type, int detail)
 {
     memset(event, 0, sizeof(RawDeviceEvent));
@@ -210,7 +223,8 @@
         if (valuator_mask_isset(mask, i))
         {
             SetBit(event->valuators.mask, i);
-            if (valuator_get_mode(dev, i) == Absolute)
+            if (!IsTouchEvent((InternalEvent *)event) &&
+                valuator_get_mode(dev, i) == Absolute)
                 SetBit(event->valuators.mode, i);
             event->valuators.data[i] = valuator_mask_get(mask, i);
             event->valuators.data_frac[i] =
@@ -1058,23 +1072,14 @@
 }
 
 static void
-transformAbsolute(DeviceIntPtr dev, ValuatorMask *mask)
+transformAbsolute(DeviceIntPtr dev, ValuatorMask *mask, int *x, int *y)
 {
-    struct pixman_f_vector p;
-
-    /* p' = M * p in homogeneous coordinates */
-    p.v[0] = (valuator_mask_isset(mask, 0) ? valuator_mask_get(mask, 0) :
-              dev->last.valuators[0]);
-    p.v[1] = (valuator_mask_isset(mask, 1) ? valuator_mask_get(mask, 1) :
-              dev->last.valuators[1]);
-    p.v[2] = 1.0;
+    struct pixman_f_vector p = {.v = {*x, *y, 1}};
 
     pixman_f_transform_point(&dev->transform, &p);
 
-    if (lround(p.v[0]) != dev->last.valuators[0])
-        valuator_mask_set(mask, 0, lround(p.v[0]));
-    if (lround(p.v[1]) != dev->last.valuators[1])
-        valuator_mask_set(mask, 1, lround(p.v[1]));
+    *x = lround(p.v[0]);
+    *y = lround(p.v[1]);
 }
 
 /**
@@ -1116,7 +1121,10 @@
     switch (type)
     {
         case MotionNotify:
-            if (!mask_in || valuator_mask_num_valuators(mask_in) <= 0)
+            if (!mask_in || valuator_mask_num_valuators(mask_in) <= 0 ||
+                (pDev->touch && pDev->touch->active_touches > 1 &&
+                 (pDev->touch->mode == XIDependentTouch ||
+                  pDev->touch->mode == XISemiMultitouch)))
                 return 0;
             break;
         case ButtonPress:
@@ -1165,7 +1173,16 @@
             }
         }
 
-        transformAbsolute(pDev, &mask);
+        x = (valuator_mask_isset(&mask, 0) ? valuator_mask_get(&mask, 0) :
+             pDev->last.valuators[0]);
+        y = (valuator_mask_isset(&mask, 1) ? valuator_mask_get(&mask, 1) :
+             pDev->last.valuators[1]);
+        transformAbsolute(pDev, &mask, &x, &y);
+        if (valuator_mask_isset(&mask, 0))
+            valuator_mask_set(&mask, 0, x);
+        if (valuator_mask_isset(&mask, 1))
+            valuator_mask_set(&mask, 1, y);
+
         moveAbsolute(pDev, &x, &y, &mask);
     } else {
         if (flags & POINTER_ACCELERATE) {
@@ -1286,6 +1303,130 @@
     return num_events;
 }
 
+int
+GetTouchOwnershipEvents(EventList *events, DeviceIntPtr pDev,
+                        TouchPointInfoPtr ti, uint8_t reason, XID resource,
+                        uint32_t flags)
+{
+    TouchClassPtr t = pDev->touch;
+    TouchOwnershipEvent *event;
+    CARD32 ms = GetTimeInMillis();
+
+    if (!pDev->enabled || !t || !ti)
+        return 0;
+
+    if (reason != XITouchOwnerAccept && reason != XITouchOwnerRejectEnd)
+        return 0;
+
+    event = (TouchOwnershipEvent *) events->event;
+    init_touch_ownership(pDev, event, ms);
+
+    event->touchid = ti->client_id;
+    event->resource = resource;
+    event->flags = flags;
+
+    return 1;
+}
+
+/**
+ * Get events for a touch. Generates a TouchBegin event if end is not set and
+ * the touch id is not active. Generates a TouchMotion event if end is not set
+ * and the touch id is active. Generates a TouchEnd event if end is set and the
+ * touch id is active.
+ *
+ * events is not NULL-terminated; the return value is the number of events.
+ * The DDX is responsible for allocating the event structure in the first
+ * place via GetMaximumEventsNum(), and for freeing it.
+ */
+int
+GetTouchEvents(EventList *events, DeviceIntPtr pDev, TouchPointInfoPtr ti,
+               uint16_t type, uint32_t flags, const ValuatorMask *mask_in)
+{
+    ScreenPtr scr = pDev->spriteInfo->sprite->hotPhys.pScreen;
+    TouchClassPtr t = pDev->touch;
+    DeviceEvent *event;
+    CARD32 ms = GetTimeInMillis();
+    ValuatorMask mask;
+    int x, y; /* in screen co-ord space */
+    float x_frac = 0.0, y_frac = 0.0; /* as above */
+    int i;
+
+    if (!pDev->enabled || !t || t->x_axis == -1 || t->y_axis == -1)
+        return 0;
+
+    event = (DeviceEvent *) events->event;
+    init_event(pDev, event, ms);
+
+    switch (type) {
+    case XI_TouchBegin:
+        event->type = ET_TouchBegin;
+        /* If we're starting a touch, we must have x & y co-ordinates. */
+        if (!valuator_mask_isset(mask_in, t->x_axis) ||
+            !valuator_mask_isset(mask_in, t->y_axis))
+        {
+            DebugF("%s: Attempted to start touch without x/y (driver bug)\n",
+                   pDev->name);
+            return 0;
+        }
+        break;
+    case XI_TouchUpdate:
+        event->type = ET_TouchMotion;
+        break;
+    case XI_TouchEnd:
+        event->type = ET_TouchEnd;
+        break;
+    default:
+        return 0;
+    }
+
+    event->touchpoint = ti;
+
+    valuator_mask_copy(&mask, mask_in);
+
+    /* Get our screen event co-ordinates (root_x/root_y/event_x/event_y):
+     * these come from the touchpoint in Absolute mode, or the sprite in
+     * Relative. */
+    if (t->mode == XIDirectTouch) {
+        if (valuator_mask_isset(&mask, t->x_axis))
+            x = valuator_mask_get(&mask, t->x_axis);
+        else
+            x = ti->valuators[t->x_axis];
+        x = rescaleValuatorAxis(x, 0.0, &x_frac,
+                                (AxisInfoPtr)(t->axes + t->x_axis),
+                                NULL, scr->width);
+
+        if (valuator_mask_isset(&mask, t->y_axis))
+            y = valuator_mask_get(&mask, t->y_axis);
+        else
+            y = ti->valuators[t->y_axis];
+        y = rescaleValuatorAxis(y, 0.0, &y_frac,
+                                (AxisInfoPtr)(t->axes + t->y_axis),
+                                NULL, scr->height);
+
+        transformAbsolute(pDev, &mask, &x, &y);
+    }
+    else {
+        x = pDev->spriteInfo->sprite->hotPhys.x;
+        y = pDev->spriteInfo->sprite->hotPhys.y;
+    }
+
+    event->root_x = x;
+    event->root_y = y;
+    event->root_x_frac = x_frac;
+    event->root_y_frac = y_frac;
+    event->detail.touch = ti->client_id;
+    event->flags = flags;
+
+    set_valuators(pDev, event, &mask);
+    for (i = 0; i < t->num_axes; i++)
+    {
+        if (valuator_mask_isset(&mask, i))
+            ti->valuators[i] = valuator_mask_get(&mask, i);
+    }
+
+    return 1;
+}
+
 /**
  * Synthesize a single motion event for the core pointer.
  *
Index: b/dix/grabs.c
===================================================================
--- a/dix/grabs.c	2011-02-28 13:56:41.000000000 +1100
+++ b/dix/grabs.c	2011-03-09 13:11:48.103384795 +1100
@@ -60,6 +60,7 @@
 #include "dixgrabs.h"
 #include "xace.h"
 #include "exevents.h"
+#include "mi.h"
 
 #define BITMASK(i) (((Mask)1) << ((i) & 31))
 #define MASKIDX(i) ((i) >> 5)
@@ -243,6 +244,25 @@
 }
 
 /**
+ * Returns the event type to match when comparing grabs.
+ */
+static uint32_t
+GetGrabEventMatch(GrabPtr pGrab)
+{
+    if (pGrab->grabtype != GRABTYPE_XI2)
+        return pGrab->type;
+
+    if (pGrab->type == XI_TouchBegin ||
+        pGrab->type == XI_TouchUpdate ||
+        pGrab->type == XI_TouchUpdateUnowned ||
+        pGrab->type == XI_TouchOwnership ||
+        pGrab->type == XI_TouchEnd)
+        return XI_TouchBegin;
+
+    return pGrab->type;
+}
+
+/**
  * Compares two grabs and returns TRUE if the first grab matches the second
  * grab. 
  * 
@@ -261,6 +281,8 @@
     unsigned int any_modifier = (pFirstGrab->grabtype == GRABTYPE_XI2) ?
                                 (unsigned int)XIAnyModifier :
                                 (unsigned int)AnyModifier;
+    uint32_t first_type = GetGrabEventMatch(pFirstGrab);
+    uint32_t second_type = GetGrabEventMatch(pSecondGrab);
 
     if (pFirstGrab->grabtype != pSecondGrab->grabtype)
         return FALSE;
@@ -288,8 +310,8 @@
              (pFirstGrab->modifierDevice != pSecondGrab->modifierDevice)))
             return FALSE;
 
-    if (pFirstGrab->type != pSecondGrab->type)
-	return FALSE;
+    if (first_type != second_type)
+        return FALSE;
 
     if (GrabSupersedesSecond(pFirstGrab, pSecondGrab) ||
 	GrabSupersedesSecond(pSecondGrab, pFirstGrab))
Index: b/dix/inpututils.c
===================================================================
--- a/dix/inpututils.c	2011-03-09 11:19:13.000000000 +1100
+++ b/dix/inpututils.c	2011-03-09 13:11:48.113385173 +1100
@@ -36,6 +36,7 @@
 #include "xkbsrv.h"
 #include "xkbstr.h"
 #include "inpututils.h"
+#include "eventstr.h"
 
 /* Check if a button map change is okay with the device.
  * Returns -1 for BadValue, as it collides with MappingBusy. */
@@ -556,3 +557,158 @@
 
     return ret;
 }
+
+/**
+ * Given the DDX-facing ID (which is _not_ DeviceEvent::detail.touch), find the
+ * associated TouchPointInfoRec.
+ */
+TouchPointInfoPtr
+FindTouchPointByDDXID(DeviceIntPtr dev, uint32_t ddx_id)
+{
+    TouchClassPtr t = dev->touch;
+    TouchPointInfoPtr ti;
+    int i;
+
+    if (!t)
+        return NULL;
+
+    for (i = 0; i < t->num_touches; i++)
+    {
+        ti = &t->touches[i];
+        if (ti->active && ti->ddx_id == ddx_id && !ti->ddx_pending_finish)
+            return ti;
+    }
+
+    return NULL;
+}
+
+/**
+ * Given a client-facing ID (e.g. DeviceEvent::detail.touch), find the
+ * associated TouchPointInfoRec.
+ */
+TouchPointInfoPtr
+FindTouchPointByClientID(DeviceIntPtr dev, uint32_t client_id)
+{
+    TouchClassPtr t = dev->touch;
+    TouchPointInfoPtr ti;
+    int i;
+
+    if (!t)
+        return NULL;
+
+    for (i = 0; i < t->num_touches; i++)
+    {
+        ti = &t->touches[i];
+        if (ti->active && ti->client_id == client_id)
+            return ti;
+    }
+
+    return NULL;
+}
+
+/**
+ * Given a unique DDX ID for a touchpoint, create a touchpoint record in the
+ * server and return the client-facing ID.
+ *
+ * Returns 0 on failure (i.e. if another touch with that ID is already active,
+ * allocation failure).
+ */
+_X_EXPORT TouchPointInfoPtr
+BeginTouchPoint(DeviceIntPtr dev, uint32_t ddx_id)
+{
+    int i;
+    TouchClassPtr t = dev->touch;
+    TouchPointInfoPtr ti;
+
+    if (!t)
+        return NULL;
+
+    /* Look for another active touchpoint with the same DDX ID.  It's entirely
+     * legitimate for a touchpoint to still exist with the same DDX ID but
+     * be in the pending_finish state as it waits for a client to release its
+     * grab, so allow for that. */
+    if (FindTouchPointByDDXID(dev, ddx_id))
+        return NULL;
+
+    for (i = 0; i < t->num_touches; i++)
+    {
+        ti = &t->touches[i];
+        if (!ti->active) {
+            ti->source = dev;
+            ti->active = TRUE;
+            ti->ddx_id = ddx_id;
+            ti->client_id = t->next_client_id;
+            ti->owner = -1;
+            ti->active_clients = 0;
+            ti->accepted = FALSE;
+            ti->pending_finish = FALSE;
+            t->active_touches++;
+next_touch_id:
+            t->next_client_id++;
+            if (t->next_client_id == 0)
+                t->next_client_id = 1;
+            if (FindTouchPointByClientID(dev, t->next_client_id))
+                goto next_touch_id; /* n'th time's a charm */
+            return ti;
+        }
+    }
+
+    /* If we get here, then we've run out of touches. */
+    LogMessage(X_WARNING, "%s: no more touches available\n", dev->name);
+
+    return NULL;
+}
+
+/**
+ * Releases a touchpoint for use: this must only be called after all events
+ * related to that touchpoint have been sent and finalised.  Called from
+ * ProcessTouchEvent and friends.  Not by you.
+ */
+void
+EndTouchPoint(DeviceIntPtr dev, TouchPointInfoPtr ti)
+{
+    int i;
+    TouchClassPtr t = dev->touch;
+    DeviceIntPtr masterdev = dev->u.master;
+    QdEventPtr qe;
+
+    if (dev->deviceGrab.sync.event &&
+        dev->deviceGrab.sync.event->touchpoint == ti)
+        dev->deviceGrab.sync.event->touchpoint = NULL;
+
+    if (masterdev && masterdev->deviceGrab.sync.event &&
+        masterdev->deviceGrab.sync.event->touchpoint == ti)
+        masterdev->deviceGrab.sync.event->touchpoint = NULL;
+
+    ti->source = NULL;
+    ti->pending_finish = FALSE;
+    ti->sprite.spriteTraceGood = 0;
+    ti->ddx_id = 0;
+    ti->first_history = ti->history;
+    ti->next_history = ti->history;
+    ti->emulate_pointer = FALSE;
+    ti->owner = -1;
+    ti->accepted = FALSE;
+    ti->active_clients = 0;
+    ti->ddx_pending_finish = FALSE;
+    t->active_touches--;
+
+    if (dev->touch->emulate == ti)
+    {
+        dev->touch->emulate = NULL;
+        if (dev->u.master)
+            dev->u.master->emulate_dev = NULL;
+
+        for (qe = syncEvents.pending; qe; qe = qe->next)
+            if ((qe->event->any.type == ET_TouchEnd ||
+                 qe->event->any.type == ET_ButtonRelease) &&
+                qe->event->device_event.touchpoint == ti)
+                qe->event->device_event.touchpoint = NULL;
+    }
+
+    for (i = 0; i < ti->num_valuators; i++)
+        ti->valuators[i] = 0;
+
+    ti->client_id = 0;
+    ti->active = FALSE;
+}
Index: b/dix/window.c
===================================================================
--- a/dix/window.c	2011-02-28 13:56:41.000000000 +1100
+++ b/dix/window.c	2011-03-09 13:11:48.113385173 +1100
@@ -110,6 +110,7 @@
 #include "windowstr.h"
 #include "input.h"
 #include "inputstr.h"
+#include "exevents.h"
 #include "resource.h"
 #include "colormapst.h"
 #include "cursorstr.h"
@@ -2873,8 +2874,10 @@
 	if (!fromConfigure && pScreen->PostValidateTree)
 	    (*pScreen->PostValidateTree)(pLayerWin->parent, pWin, VTUnmap);
     }
-    if (wasRealized && !fromConfigure)
+    if (wasRealized && !fromConfigure) {
 	WindowsRestructured ();
+	WindowGone(pWin);
+    }
     return Success;
 }
 
@@ -2957,8 +2960,10 @@
 	if (anyMarked && pScreen->PostValidateTree)
 	    (*pScreen->PostValidateTree)(pLayerWin->parent, pHead, VTUnmap);
     }
-    if (wasRealized)
+    if (wasRealized) {
 	WindowsRestructured ();
+	WindowGone(pWin);
+    }
 }
 
 
Index: b/hw/xfree86/common/xf86Module.h
===================================================================
--- a/hw/xfree86/common/xf86Module.h	2011-03-09 11:39:57.000000000 +1100
+++ b/hw/xfree86/common/xf86Module.h	2011-03-09 13:13:06.226385017 +1100
@@ -83,7 +83,7 @@
  */
 #define ABI_ANSIC_VERSION	SET_ABI_VERSION(0, 4)
 #define ABI_VIDEODRV_VERSION	SET_ABI_VERSION(10, 0)
-#define ABI_XINPUT_VERSION	SET_ABI_VERSION(12, 2)
+#define ABI_XINPUT_VERSION	SET_ABI_VERSION(12, 3)
 #define ABI_EXTENSION_VERSION	SET_ABI_VERSION(5, 0)
 #define ABI_FONT_VERSION	SET_ABI_VERSION(0, 6)
 
Index: b/hw/xfree86/common/xf86Xinput.c
===================================================================
--- a/hw/xfree86/common/xf86Xinput.c	2011-02-28 16:57:00.000000000 +1100
+++ b/hw/xfree86/common/xf86Xinput.c	2011-03-09 13:11:48.113385173 +1100
@@ -1352,6 +1352,16 @@
 			   max_res, mode);
 }
 
+void
+xf86InitTouchValuatorAxisStruct(DeviceIntPtr dev, int axnum, Atom label,
+                                int minval, int maxval, int resolution)
+{
+    if (!dev || !dev->touch)
+        return;
+
+    InitTouchValuatorAxisStruct(dev, axnum, label, minval, maxval, resolution);
+}
+
 /*
  * Set the valuator values to be in synch with dix/event.c
  * DefineInitialRootWindow().
@@ -1403,4 +1413,50 @@
     EnableDevice(dev, TRUE);
 }
 
+/**
+ * Post a touch event with optional valuators.  If this is the first touch in
+ * the sequence, at least x & y valuators must be provided.  If end is TRUE,
+ * then this is taken to be the last touch in the touch sequence.
+ */
+void
+xf86PostTouchEvent(DeviceIntPtr dev, uint32_t touchid, uint16_t type,
+                   uint32_t flags, const ValuatorMask *mask)
+{
+    int i, nevents;
+    TouchPointInfoPtr ti = FindTouchPointByDDXID(dev, touchid);
+
+    if (ti && type == XI_TouchBegin)
+    {
+        xf86Msg(X_ERROR,
+                "%s: Tried to post touch begin for existing touch %u\n",
+                dev->name, touchid);
+        return;
+    }
+
+    if (!ti)
+    {
+        if (type != XI_TouchBegin)
+        {
+            xf86Msg(X_ERROR,
+                    "%s: Tried to post event for non-existent touch %u\n",
+                    dev->name, touchid);
+            return;
+        }
+
+        ti = BeginTouchPoint(dev, touchid);
+        if (!ti)
+        {
+            xf86Msg(X_ERROR, "%s: Couldn't create touchpoint\n", dev->name);
+            return;
+        }
+    }
+
+    if (type == XI_TouchEnd)
+        ti->ddx_pending_finish = TRUE;
+
+    nevents = GetTouchEvents(xf86Events, dev, ti, type, flags, mask);
+    for (i = 0; i < nevents; i++)
+        mieqEnqueue(dev, (InternalEvent *)((xf86Events + i)->event));
+}
+
 /* end of xf86Xinput.c */
Index: b/hw/xfree86/common/xf86Xinput.h
===================================================================
--- a/hw/xfree86/common/xf86Xinput.h	2011-02-28 13:56:40.000000000 +1100
+++ b/hw/xfree86/common/xf86Xinput.h	2011-03-09 13:11:48.113385173 +1100
@@ -141,6 +141,9 @@
 		       const int *valuators);
 extern _X_EXPORT void xf86PostKeyboardEvent(DeviceIntPtr device, unsigned int key_code,
                            int is_down);
+extern _X_EXPORT void xf86PostTouchEvent(DeviceIntPtr dev, uint32_t touchid,
+                                         uint16_t type, uint32_t flags,
+                                         const ValuatorMask *mask);
 extern _X_EXPORT InputInfoPtr xf86FirstLocalDevice(void);
 extern _X_EXPORT int xf86ScaleAxis(int Cx, int to_max, int to_min, int from_max, int from_min);
 extern _X_EXPORT void xf86XInputSetScreen(InputInfoPtr pInfo, int screen_number, int x, int y);
@@ -148,6 +151,8 @@
 extern _X_EXPORT void xf86InitValuatorAxisStruct(DeviceIntPtr dev, int axnum, Atom label, int minval,
 				int maxval, int resolution, int min_res,
 				int max_res, int mode);
+extern _X_EXPORT void xf86InitTouchValuatorAxisStruct(DeviceIntPtr dev, int axnum, Atom label,
+				int minval, int maxval, int resolution);
 extern _X_EXPORT void xf86InitValuatorDefaults(DeviceIntPtr dev, int axnum);
 extern _X_EXPORT void xf86AddEnabledDevice(InputInfoPtr pInfo);
 extern _X_EXPORT void xf86RemoveEnabledDevice(InputInfoPtr pInfo);
Index: b/include/dix.h
===================================================================
--- a/include/dix.h	2011-03-09 11:19:13.000000000 +1100
+++ b/include/dix.h	2011-03-09 13:11:48.113385173 +1100
@@ -375,7 +375,7 @@
 extern GrabPtr CheckPassiveGrabsOnWindow(
     WindowPtr /* pWin */,
     DeviceIntPtr /* device */,
-    DeviceEvent * /* event */,
+    InternalEvent * /* event */,
     BOOL /* checkCore */,
     BOOL /* activate */);
 
@@ -515,6 +515,11 @@
         DeviceIntPtr /* dev */,
         xEvent* /* events */);
 
+extern void RemoveTouchEventsFromQueue(
+        DeviceIntPtr /* dev */,
+        Bool /*touch*/,
+        Bool /*ignoreOwned*/);
+
 #ifdef PANORAMIX
 extern _X_EXPORT void ReinitializeRootWindow(WindowPtr win, int xoff, int yoff);
 #endif
@@ -526,6 +531,8 @@
 
 extern _X_EXPORT int ffs(int i);
 
+extern void init_event(DeviceIntPtr dev, DeviceEvent* event, Time ms);
+
 
 /*
  *  ServerGrabCallback stuff
@@ -569,6 +576,7 @@
 extern Bool _X_EXPORT IsPointerDevice( DeviceIntPtr dev);
 extern Bool _X_EXPORT IsKeyboardDevice(DeviceIntPtr dev);
 extern Bool IsPointerEvent(InternalEvent *event);
+extern Bool IsTouchEvent(InternalEvent *event);
 extern _X_EXPORT Bool IsMaster(DeviceIntPtr dev);
 
 extern _X_HIDDEN void CopyKeyClass(DeviceIntPtr device, DeviceIntPtr master);
Index: b/include/events.h
===================================================================
--- a/include/events.h	2011-02-28 13:56:40.000000000 +1100
+++ b/include/events.h	2011-03-09 13:11:48.113385173 +1100
@@ -26,6 +26,7 @@
 #define EVENTS_H
 typedef struct _DeviceEvent DeviceEvent;
 typedef struct _DeviceChangedEvent DeviceChangedEvent;
+typedef struct _TouchOwnershipEvent TouchOwnershipEvent;
 #if XFreeXDGA
 typedef struct _DGAEvent DGAEvent;
 #endif
Index: b/include/eventstr.h
===================================================================
--- a/include/eventstr.h	2011-02-28 16:57:00.000000000 +1100
+++ b/include/eventstr.h	2011-03-09 13:11:48.113385173 +1100
@@ -65,6 +65,11 @@
     ET_RawButtonRelease,
     ET_RawMotion,
     ET_XQuartz,
+    ET_TouchBegin,
+    ET_TouchEnd,
+    ET_TouchMotion,
+    ET_TouchMotionUnowned,
+    ET_TouchOwnership,
     ET_Internal = 0xFF /* First byte */
 };
 
@@ -90,6 +95,7 @@
     union {
         uint32_t button;  /**< Button number */
         uint32_t key;     /**< Key code */
+        uint32_t touch;   /**< Touch ID (client_id) */
     } detail;
     int16_t root_x;       /**< Pos relative to root window in integral data */
     float root_x_frac;    /**< Pos relative to root window in frac part */
@@ -117,8 +123,28 @@
     Window      root; /**< Root window of the event */
     int corestate;    /**< Core key/button state BEFORE the event */
     int key_repeat;   /**< Internally-generated key repeat event */
+    uint32_t flags;   /**< Flags to be copied into the generated event */
+    TouchPointInfoPtr touchpoint;
+    Bool check_grab;
 };
 
+/**
+ * Generated internally whenever a touch ownership chain changes - an owner
+ * has accepted or rejected a touch, or a grab/event selection in the delivery
+ * chain has been removed.
+ */
+struct _TouchOwnershipEvent
+{
+    unsigned char header; /**< Always ET_Internal */
+    enum EventType type;  /**< One of EventType */
+    int length;           /**< Length in bytes */
+    Time time;            /**< Time in ms */
+    int deviceid;         /**< Device to post this event for */
+    int sourceid;         /**< The physical source device */
+    uint32_t touchid;     /**< Touch ID (client_id) */
+    uint32_t resource;    /**< Provoking grab or event selection */
+    uint32_t flags;       /**< Flags to be copied into the generated event */
+};
 
 /* Flags used in DeviceChangedEvent to signal if the slave has changed */
 #define DEVCHANGE_SLAVE_SWITCH 0x2
@@ -234,6 +260,7 @@
         } any;
         DeviceEvent device_event;
         DeviceChangedEvent changed_event;
+        TouchOwnershipEvent touch_ownership_event;
 #if XFreeXDGA
         DGAEvent dga_event;
 #endif
Index: b/include/exevents.h
===================================================================
--- a/include/exevents.h	2011-03-04 14:03:20.000000000 +1100
+++ b/include/exevents.h	2011-03-09 13:11:48.113385173 +1100
@@ -51,6 +51,14 @@
 	int                    /* max_res */,
 	int                    /* mode */);
 
+extern _X_EXPORT void InitTouchValuatorAxisStruct(
+	DeviceIntPtr           /* dev */,
+	int                    /* axnum */,
+	Atom                   /* label */,
+	int                    /* minval */,
+	int                    /* maxval */,
+	int                    /* resolution */);
+
 /* Input device properties */
 extern _X_EXPORT void XIDeleteAllDeviceProperties(
         DeviceIntPtr            /* device */
@@ -199,6 +207,14 @@
 	GrabMask*              /* eventMask */);
 
 extern int
+GrabTouch(
+	ClientPtr              /* client */,
+	DeviceIntPtr           /* dev */,
+	DeviceIntPtr           /* mod_dev */,
+	GrabParameters*        /* param */,
+	GrabMask*              /* eventMask */);
+
+extern int
 SelectForWindow(
 	DeviceIntPtr           /* dev */,
 	WindowPtr              /* pWin */,
@@ -222,6 +238,10 @@
 	WindowPtr              /* pWin */,
 	XID                    /* id */);
 
+extern void
+WindowGone(
+	WindowPtr              /* win */);
+
 extern int
 SendEvent (
 	ClientPtr              /* client */,
@@ -309,4 +329,14 @@
 extern int
 XICheckInvalidMaskBits(ClientPtr client, unsigned char *mask, int len);
 
+extern void
+ProcessTouchOwnership(DeviceIntPtr dev, TouchPointInfoPtr ti, uint8_t reason,
+                      Bool touch_grab);
+
+extern int
+DeliverTouchOwnershipEvent(TouchClientPtr client, TouchPointInfoPtr ti);
+
+extern int
+ReleaseButton(DeviceIntPtr device, int button);
+
 #endif /* EXEVENTS_H */
Index: b/include/input.h
===================================================================
--- a/include/input.h	2011-03-09 11:19:13.000000000 +1100
+++ b/include/input.h	2011-03-09 13:11:48.113385173 +1100
@@ -104,6 +104,8 @@
 typedef struct _DeviceIntRec *DeviceIntPtr;
 typedef struct _ClassesRec *ClassesPtr;
 typedef struct _SpriteRec *SpritePtr;
+typedef struct _TouchClassRec *TouchClassPtr;
+typedef struct _TouchPointInfo *TouchPointInfoPtr;
 typedef union _GrabMask GrabMask;
 
 typedef struct _EventList {
@@ -314,6 +316,12 @@
 extern _X_EXPORT Bool InitFocusClassDeviceStruct(
     DeviceIntPtr /*device*/);
 
+extern _X_EXPORT Bool InitTouchClassDeviceStruct(
+    DeviceIntPtr /*device*/,
+    unsigned int /*max_touches*/,
+    unsigned int /*mode*/,
+    unsigned int /*numAxes*/);
+
 typedef void (*BellProcPtr)(
     int /*percent*/,
     DeviceIntPtr /*device*/,
@@ -463,6 +471,22 @@
     int key_code,
     const ValuatorMask *mask);
 
+extern int GetTouchEvents(
+    EventListPtr events,
+    DeviceIntPtr pDev,
+    TouchPointInfoPtr ti,
+    uint16_t type,
+    uint32_t flags,
+    const ValuatorMask *mask);
+
+extern int GetTouchOwnershipEvents(
+    EventListPtr events,
+    DeviceIntPtr pDev,
+    TouchPointInfoPtr ti,
+    uint8_t mode,
+    XID resource,
+    uint32_t flags);
+
 extern int GetProximityEvents(
     EventListPtr events,
     DeviceIntPtr pDev,
@@ -525,6 +549,18 @@
 extern _X_EXPORT InputAttributes *DuplicateInputAttributes(InputAttributes *attrs);
 extern _X_EXPORT void FreeInputAttributes(InputAttributes *attrs);
 
+/* DDX touch API: create with CreateTouchPoint, use its returned ID to lookup
+ * with FindTouchPoint, and eventually end with FinishTouchPoint. */
+extern TouchPointInfoPtr BeginTouchPoint(DeviceIntPtr dev, uint32_t ddx_id);
+extern TouchPointInfoPtr FindTouchPointByDDXID(DeviceIntPtr dev,
+                                               uint32_t ddx_id);
+extern TouchPointInfoPtr FindTouchPointByClientID(DeviceIntPtr dev,
+                                                  uint32_t client_id);
+extern void EndTouchPoint(DeviceIntPtr dev, TouchPointInfoPtr ti);
+/* Internal use only, DDX this is not for you */
+extern Bool InitTouchPoint(TouchClassPtr touch, int index);
+extern void FreeTouchPoint(DeviceIntPtr dev, int index);
+
 /* misc event helpers */
 extern Mask GetEventMask(DeviceIntPtr dev, xEvent* ev, InputClientsPtr clients);
 extern Mask GetEventFilter(DeviceIntPtr dev, xEvent *event);
Index: b/include/inputstr.h
===================================================================
--- a/include/inputstr.h	2011-03-09 11:19:13.000000000 +1100
+++ b/include/inputstr.h	2011-03-09 13:11:48.113385173 +1100
@@ -49,6 +49,8 @@
 #ifndef INPUTSTRUCT_H
 #define INPUTSTRUCT_H
 
+#include <X11/extensions/XI2proto.h>
+
 #include <pixman.h>
 #include "input.h"
 #include "window.h"
@@ -71,7 +73,7 @@
  * events to the protocol, the server will not support these events until
  * this number here is bumped.
  */
-#define XI2LASTEVENT    17 /* XI_RawMotion */
+#define XI2LASTEVENT    XI_TouchUpdateUnowned
 #define XI2MASKSIZE     ((XI2LASTEVENT + 7)/8) /* no of bits for masks */
 
 /**
@@ -244,6 +246,9 @@
 
 } SpriteRec;
 
+#define DeepestSpriteWin(sprite) \
+    ((sprite)->spriteTrace[(sprite)->spriteTraceGood - 1])
+
 typedef struct _KeyClassRec {
     int			sourceid;
     CARD8		down[DOWN_LENGTH];
@@ -254,11 +259,11 @@
 
 typedef struct _AxisInfo {
     int		resolution;
-    int		min_resolution;
-    int		max_resolution;
     int		min_value;
     int		max_value;
     Atom	label;
+    int		min_resolution;
+    int		max_resolution;
     CARD8	mode;
 } AxisInfo, *AxisInfoPtr;
 
@@ -284,6 +289,75 @@
     ValuatorAccelerationRec	accelScheme;
 } ValuatorClassRec, *ValuatorClassPtr;
 
+typedef enum {
+    TOUCH_GRAB,
+    TOUCH_SELECT,
+    TOUCH_SELECT_UNOWNED
+} TouchClientType;
+
+typedef struct _TouchClientRec {
+    ClientPtr       client;
+    WindowPtr       window;
+    TouchClientType type;
+    DeviceIntPtr    device;
+    DeviceIntPtr    source;
+    GrabPtr         grab;
+} TouchClientRec, *TouchClientPtr;
+
+typedef struct _TouchPointInfo {
+    DeviceIntPtr source;
+    Bool        active;             /* whether or not the touch is active */
+    Bool        pending_finish;     /* true if the touch is physically inactive
+                                     * but still owned by a grab */
+    Bool        ddx_pending_finish;
+    uint32_t    client_id;          /* touch ID as seen in client events */
+    uint32_t    ddx_id;             /* touch ID given by the DDX */
+    SpriteRec   sprite;             /* window trace for delivery */
+    TouchClientPtr clients;
+    int         num_clients;
+    int         active_clients;
+    int         owner;
+    Bool        accepted;
+    int         *valuators;         /* last recorded axis values */
+    int         num_valuators;      /* == TouchClassInfo::num_axes */
+#if 0
+    XID         *listeners;         /* grabs/event selection IDs receiving
+                                     * events for this touch */
+    int         num_listeners;
+    int         num_grabs;          /* number of open grabs on this touch
+                                     * which have not accepted or rejected */
+    WindowPtr   select_win;
+    Bool        select_unowned;
+#endif
+    Bool        emulate_pointer;
+    InternalEvent *begin_event;     /* Touch begin event for history */
+    InternalEvent *history;         /* Touch motion and end history events */
+    unsigned int history_size;      /* Size of history ring buffer */
+    InternalEvent *first_history;   /* Pointer to first event in history */
+    InternalEvent *next_history;    /* Pointer to next available event */
+} TouchPointInfoRec;
+
+typedef struct _TouchAxisInfo {
+    int		resolution;
+    int		min_value;
+    int		max_value;
+    Atom	label;
+} TouchAxisInfoRec, *TouchAxisInfoPtr;
+
+typedef struct _TouchClassRec {
+    TouchAxisInfoPtr   axes;
+    unsigned short     num_axes;
+    TouchPointInfoPtr  touches;
+    unsigned short     num_touches;    /* number of allocated touches */
+    unsigned short     max_touches;    /* maximum number of touches, may be 0 */
+    unsigned short     active_touches; /* number of active touches */
+    CARD8              mode;           /* ::XIDirectTouch, XIDependentTouch */
+    uint32_t           next_client_id; /* next client_id to give out */
+    int                x_axis;         /* axis number of x axis */
+    int                y_axis;         /* axis number of y axis */
+    TouchPointInfoPtr  emulate;
+} TouchClassRec;
+
 typedef struct _ButtonClassRec {
     int			sourceid;
     CARD8		numButtons;
@@ -388,6 +462,7 @@
 typedef struct _ClassesRec {
     KeyClassPtr		key;
     ValuatorClassPtr	valuator;
+    TouchClassPtr	touch;
     ButtonClassPtr	button;
     FocusClassPtr	focus;
     ProximityClassPtr	proximity;
@@ -512,6 +587,7 @@
     int			id;
     KeyClassPtr		key;
     ValuatorClassPtr	valuator;
+    TouchClassPtr	touch;
     ButtonClassPtr	button;
     FocusClassPtr	focus;
     ProximityClassPtr	proximity;
@@ -533,6 +609,8 @@
         DeviceIntPtr        master;     /* master device */
         DeviceIntPtr        lastSlave;  /* last slave device used */
     } u;
+    DeviceIntPtr        emulate_dev;
+    Bool                process_touch;
 
     /* last valuator values recorded, not posted to client;
      * for slave devices, valuators is in device coordinates
@@ -592,7 +670,7 @@
  */
 typedef struct _EventSyncInfo {
     QdEventPtr          pending, /**<  list of queued events */
-                        *pendtail; /**< last event in list */
+                        pendtail; /**< last event in list */
     /** The device to replay events for. Only set in AllowEvents(), in which
      * case it is set to the device specified in the request. */
     DeviceIntPtr        replayDev;      /* kludgy rock to put flag for */
Index: b/include/protocol-versions.h
===================================================================
--- a/include/protocol-versions.h	2011-03-09 11:39:57.000000000 +1100
+++ b/include/protocol-versions.h	2011-03-09 13:11:48.113385173 +1100
@@ -131,7 +131,7 @@
 
 /* X Input */
 #define SERVER_XI_MAJOR_VERSION			2
-#define SERVER_XI_MINOR_VERSION			0
+#define SERVER_XI_MINOR_VERSION			1
 
 /* XKB */
 #define SERVER_XKB_MAJOR_VERSION		1
Index: b/mi/mieq.c
===================================================================
--- a/mi/mieq.c	2011-03-09 11:19:13.000000000 +1100
+++ b/mi/mieq.c	2011-03-09 13:11:48.113385173 +1100
@@ -269,8 +269,15 @@
         case ET_ProximityOut:
         case ET_Hierarchy:
         case ET_DeviceChanged:
+        case ET_TouchBegin:
+        case ET_TouchEnd:
+        case ET_TouchMotion:
+        case ET_TouchMotionUnowned:
             event->device_event.deviceid = dev->id;
             break;
+        case ET_TouchOwnership:
+            event->touch_ownership_event.deviceid = dev->id;
+            break;
 #if XFreeXDGA
         case ET_DGAEvent:
             break;
@@ -419,7 +426,7 @@
 
         /* Check for the SD's master in case the device got detached
          * during event processing */
-        if (master && dev->u.master)
+        if (master && dev->u.master && !IsTouchEvent(&mevent))
             master->public.processInputProc(&mevent, master);
     }
 }
Index: b/test/input.c
===================================================================
--- a/test/input.c	2011-03-09 11:39:57.000000000 +1100
+++ b/test/input.c	2011-03-09 13:12:49.355737608 +1100
@@ -278,6 +278,11 @@
     dix_event_to_core_fail(ET_ProximityOut + 1, BadImplementation);
     dix_event_to_core_fail(ET_ProximityIn, BadMatch);
     dix_event_to_core_fail(ET_ProximityOut, BadMatch);
+    dix_event_to_core_fail(ET_TouchBegin, BadMatch);
+    dix_event_to_core_fail(ET_TouchMotion, BadMatch);
+    dix_event_to_core_fail(ET_TouchMotionUnowned, BadMatch);
+    dix_event_to_core_fail(ET_TouchOwnership, BadMatch);
+    dix_event_to_core_fail(ET_TouchEnd, BadMatch);
 
     dix_event_to_core(ET_KeyPress);
     dix_event_to_core(ET_KeyRelease);
@@ -423,6 +428,32 @@
 }
 
 
+static void dix_event_to_xi2_conversion(void)
+{
+    DeviceEvent ev;
+    xXIDeviceEvent *xi2, *xi2_flags;
+    int rc;
+
+    memset(&ev, 0, sizeof(ev));
+
+    ev.header   = 0xFF;
+    ev.length   = sizeof(DeviceEvent);
+    ev.type     = ET_TouchBegin;
+
+    rc          = EventToXI2((InternalEvent*)&ev, (xEvent**)&xi2);
+    g_assert(rc == Success);
+    g_assert(xi2->type == GenericEvent);
+    g_assert(xi2->evtype == XI_TouchBegin);
+    g_assert(xi2->flags == 0);
+
+    rc          = EventToXI2((InternalEvent*)&ev, (xEvent**)&xi2_flags);
+    g_assert(rc == Success);
+    g_assert(xi2_flags->type == GenericEvent);
+    g_assert(xi2_flags->evtype == XI_TouchBegin);
+    xi2_flags->flags = 0;
+    g_assert(memcmp(xi2, xi2_flags, sizeof(*xi2)) == 0);
+}
+
 static void xi2_struct_sizes(void)
 {
 #define compare(req) \
@@ -812,6 +843,38 @@
     g_assert(rc == TRUE);
     rc = GrabMatchesSecond(&b, &a, FALSE);
     g_assert(rc == TRUE);
+
+    /* All touch grabs must match a TouchBegin grab. */
+    a.grabtype = GRABTYPE_XI2;
+    b.grabtype = GRABTYPE_XI2;
+    a.type = XI_TouchBegin;
+    b.type = XI_TouchUpdate;
+    a.detail.exact = 0;
+    b.detail.exact = 0;
+    a.modifiersDetail.exact = 0;
+    b.modifiersDetail.exact = 0;
+    rc = GrabMatchesSecond(&a, &b, FALSE);
+    g_assert(rc == TRUE);
+    rc = GrabMatchesSecond(&b, &a, FALSE);
+    g_assert(rc == TRUE);
+
+    b.type = XI_TouchUpdateUnowned;
+    rc = GrabMatchesSecond(&a, &b, FALSE);
+    g_assert(rc == TRUE);
+    rc = GrabMatchesSecond(&b, &a, FALSE);
+    g_assert(rc == TRUE);
+
+    b.type = XI_TouchOwnership;
+    rc = GrabMatchesSecond(&a, &b, FALSE);
+    g_assert(rc == TRUE);
+    rc = GrabMatchesSecond(&b, &a, FALSE);
+    g_assert(rc == TRUE);
+
+    b.type = XI_TouchEnd;
+    rc = GrabMatchesSecond(&a, &b, FALSE);
+    g_assert(rc == TRUE);
+    rc = GrabMatchesSecond(&b, &a, FALSE);
+    g_assert(rc == TRUE);
 }
 
 static void test_bits_to_byte(int i)
@@ -1199,6 +1262,101 @@
     }
 }
 
+static void touch_create(void)
+{
+    DeviceIntRec dev;
+    TouchClassRec touch;
+    TouchPointInfoRec touches[2];
+    TouchPointInfoPtr ti;
+
+    memset(&dev, 0, sizeof(dev));
+    memset(&touch, 0, sizeof(touch));
+    memset(touches, 0, sizeof(*touches) * 2);
+    touch.touches = touches;
+    touch.num_touches = 2;
+    touch.num_axes = 2;
+    touch.next_client_id = 1;
+    dev.touch = &touch;
+
+    /* Make sure we get a valid touchpoint back. */
+    ti = BeginTouchPoint(&dev, 0xdeadbeef);
+    g_assert(ti);
+    g_assert(ti->active == TRUE);
+    g_assert(ti->ddx_id == 0xdeadbeef);
+    g_assert(ti->client_id != 0);
+    g_assert(ti->pending_finish == 0);
+    g_assert(ti->sprite.spriteTraceGood == 0);
+}
+
+static void touch_find_point(void)
+{
+    DeviceIntRec dev;
+    TouchClassRec touch;
+    TouchPointInfoRec touches[2];
+    TouchPointInfoPtr create_ret, find_ret;
+
+    memset(&dev, 0, sizeof(dev));
+    memset(&touch, 0, sizeof(touch));
+    memset(touches, 0, sizeof(*touches) * 2);
+    touch.touches = touches;
+    touch.num_touches = 2;
+    touch.num_axes = 2;
+    touch.next_client_id = 1;
+    dev.touch = &touch;
+
+    create_ret = BeginTouchPoint(&dev, 0xdeadbeef);
+    g_assert(create_ret);
+
+    /* Make sure we can find the touch by both DDX and client ID. */
+    find_ret = FindTouchPointByDDXID(&dev, 0xdeadbeef);
+    g_assert(create_ret == find_ret);
+    find_ret = FindTouchPointByClientID(&dev, create_ret->client_id);
+    g_assert(find_ret->active == TRUE);
+    g_assert(find_ret->ddx_id == 0xdeadbeef);
+
+    /* Touches which are pending finish must be findable by their client ID,
+     * but not by their DDX ID, as only the DIX can inject ownership change
+     * events. */
+    find_ret->ddx_pending_finish = 1;
+    find_ret = FindTouchPointByClientID(&dev, create_ret->client_id);
+    g_assert(find_ret == create_ret);
+    find_ret = FindTouchPointByDDXID(&dev, 0xdeadbeef);
+    g_assert(!find_ret);
+}
+
+static void touch_finish(void)
+{
+    DeviceIntRec dev;
+    TouchClassRec touch;
+    TouchPointInfoRec touches[2];
+    TouchPointInfoPtr ti;
+    uint32_t client_id;
+
+    memset(&dev, 0, sizeof(dev));
+    memset(&touch, 0, sizeof(touch));
+    memset(touches, 0, sizeof(*touches) * 2);
+    touch.touches = touches;
+    touch.num_touches = 2;
+    touch.num_axes = 2;
+    touch.next_client_id = 1;
+    dev.touch = &touch;
+
+    /* Make sure the touch is in a sane state once we kill it, and that we
+     * can't find it once it's gone. */
+    ti = BeginTouchPoint(&dev, 0xdeadbeef);
+    g_assert(ti);
+    client_id = ti->client_id;
+    EndTouchPoint(&dev, ti);
+    g_assert(ti->active == FALSE);
+    g_assert(ti->pending_finish == 0);
+    g_assert(ti->sprite.spriteTraceGood == 0);
+    g_assert(ti->client_id == 0);
+    g_assert(ti->ddx_id == 0);
+
+    g_assert(FindTouchPointByDDXID(&dev, 0xdeadbeef) == NULL);
+    g_assert(FindTouchPointByClientID(&dev, client_id) == NULL);
+}
+
 int main(int argc, char** argv)
 {
     g_test_init(&argc, &argv,NULL);
@@ -1209,6 +1367,7 @@
     g_test_add_func("/dix/input/init-valuators", dix_init_valuators);
     g_test_add_func("/dix/input/event-core-conversion", dix_event_to_core_conversion);
     g_test_add_func("/dix/input/event-xi1-conversion", dix_event_to_xi1_conversion);
+    g_test_add_func("/dix/input/event-xi2-conversion", dix_event_to_xi2_conversion);
     g_test_add_func("/dix/input/check-grab-values", dix_check_grab_values);
     g_test_add_func("/dix/input/xi2-struct-sizes", xi2_struct_sizes);
     g_test_add_func("/dix/input/grab_matching", dix_grab_matching);
@@ -1397,6 +1397,11 @@
     g_test_add_func("/include/byte_padding_macros", include_byte_padding_macros);
     g_test_add_func("/include/bit_test_macros", include_bit_test_macros);
     g_test_add_func("/Xi/xiproperty/register-unregister", xi_unregister_handlers);
+
+    g_test_add_func("/dix/input/touch-create", touch_create);
+    g_test_add_func("/dix/input/touch-find-point", touch_find_point);
+    g_test_add_func("/dix/input/touch-finish", touch_finish);
+
     g_test_add_func("/dix/input/valuator-alloc", dix_valuator_alloc);
 
     return g_test_run();
Index: b/test/xi2/protocol-eventconvert.c
===================================================================
--- a/test/xi2/protocol-eventconvert.c	2011-02-28 16:57:00.000000000 +1100
+++ b/test/xi2/protocol-eventconvert.c	2011-03-09 13:11:48.123385564 +1100
@@ -149,6 +149,59 @@
     free(swapped);
 }
 
+static void test_values_XITouchOwnershipEvent(TouchOwnershipEvent *in,
+                                              xXITouchOwnershipEvent *out,
+                                              BOOL swap)
+{
+    char n;
+
+    if (swap)
+    {
+        swaps(&out->sequenceNumber, n);
+        swapl(&out->length, n);
+        swaps(&out->evtype, n);
+        swaps(&out->deviceid, n);
+        swapl(&out->time, n);
+        swaps(&out->sourceid, n);
+        swapl(&out->touchid, n);
+        swapl(&out->flags, n);
+    }
+
+    g_assert(out->type == GenericEvent);
+    g_assert(out->extension == 0);
+    g_assert(out->length == bytes_to_int32(sizeof(*out) - sizeof(xEvent)));
+    g_assert(out->evtype == XI_TouchOwnership);
+    g_assert(out->deviceid == in->deviceid);
+    g_assert(out->time == in->time);
+    g_assert(out->sourceid == in->sourceid);
+    g_assert(out->touchid == in->touchid);
+    g_assert(out->flags == in->flags);
+}
+
+static void test_convert_XITouchOwnershipEvent(void)
+{
+    TouchOwnershipEvent in;
+    xXITouchOwnershipEvent *out, swapped;
+    int rc;
+
+    in.header = ET_Internal;
+    in.type = ET_TouchOwnership;
+    in.touchid = 0xdeadbeef;
+    in.time = 234;
+    in.deviceid = 12;
+    in.sourceid = 14;
+    in.resource = 0xcafebabe;
+    in.flags = 0;
+    rc = EventToXI2((InternalEvent *) &in, (xEvent **) &out);
+    g_assert(rc == Success);
+
+    test_values_XITouchOwnershipEvent(&in, out, FALSE);
+    XI2EventSwap((xGenericEvent*)out, (xGenericEvent*)&swapped);
+    test_values_XITouchOwnershipEvent(&in, &swapped, TRUE);
+
+    free(out);
+}
+
 static void test_convert_XIFocusEvent(void)
 {
     xEvent *out;
@@ -272,7 +325,7 @@
     int buttons, valuators;
     int i;
     unsigned char *ptr;
-    uint32_t flagmask = 0;
+    uint32_t flagmask;
     FP3232 *values;
 
     if (swap) {
@@ -311,9 +364,16 @@
     g_assert(out->sourceid == in->sourceid);
 
     switch (in->type) {
+        case ET_ButtonPress:
+        case ET_ButtonRelease:
+        case ET_Motion:
+            flagmask = XIPointerEmulated;
+            break;
         case ET_KeyPress:
             flagmask = XIKeyRepeat;
             break;
+        case ET_TouchMotion:
+        case ET_TouchMotionUnowned:
         default:
             flagmask = 0;
             break;
@@ -636,6 +696,49 @@
     }
 }
 
+static void test_convert_XITouch(void)
+{
+    DeviceEvent in;
+
+    memset(&in, 0, sizeof(in));
+
+    g_test_message("Testing TouchBegin");
+    in.header = ET_Internal;
+    in.type = ET_TouchBegin;
+    in.length = sizeof(DeviceEvent);
+    in.time             = 0;
+    in.deviceid         = 1;
+    in.sourceid         = 2;
+    in.root             = 3;
+    in.root_x           = 4;
+    in.root_x_frac      = 5;
+    in.root_y           = 6;
+    in.root_y_frac      = 7;
+    in.detail.button    = 8;
+    in.mods.base        = 9;
+    in.mods.latched     = 10;
+    in.mods.locked      = 11;
+    in.mods.effective   = 11;
+    in.group.base       = 12;
+    in.group.latched    = 13;
+    in.group.locked     = 14;
+    in.group.effective  = 15;
+    test_XIDeviceEvent(&in);
+
+    in.flags = 0;
+    g_test_message("Testing TouchMotion");
+    in.type = ET_TouchMotion;
+    test_XIDeviceEvent(&in);
+
+    g_test_message("Testing TouchMotionUnowned");
+    in.type = ET_TouchMotionUnowned;
+    test_XIDeviceEvent(&in);
+
+    g_test_message("Testing TouchEnd");
+    in.type = ET_TouchEnd;
+    test_XIDeviceEvent(&in);
+}
+
 static void test_values_XIDeviceChangedEvent(DeviceChangedEvent *in,
                                              xXIDeviceChangedEvent *out,
                                              BOOL swap)
@@ -912,6 +1015,8 @@
     g_test_add_func("/xi2/eventconvert/XIFocusEvent", test_convert_XIFocusEvent);
     g_test_add_func("/xi2/eventconvert/XIDeviceEvent", test_convert_XIDeviceEvent);
     g_test_add_func("/xi2/eventconvert/XIDeviceChangedEvent", test_convert_XIDeviceChangedEvent);
+    g_test_add_func("/xi2/eventconvert/XITouch", test_convert_XITouch);
+    g_test_add_func("/xi2/eventconvert/XITouchOwnership", test_convert_XITouchOwnershipEvent);
 
     return g_test_run();
 }
Index: b/test/xi2/protocol-xiselectevents.c
===================================================================
--- a/test/xi2/protocol-xiselectevents.c	2011-02-28 16:57:00.000000000 +1100
+++ b/test/xi2/protocol-xiselectevents.c	2011-03-09 13:11:48.123385564 +1100
@@ -159,9 +159,33 @@
         memset(bits, 0, mask->mask_len * 4);
         for (j = 0; j <= XI2LASTEVENT; j++)
         {
+            /* Can't select for these events alone */
+            if (j == XI_TouchBegin || j == XI_TouchOwnership ||
+                j == XI_TouchEnd)
+                continue;
+
             SetBit(bits, j);
+
+            /* Must select for TouchBegin + TouchMotion + TouchEnd together,
+             * and optionally also TouchMotionUnowned and TouchOwnerhip. */
+            if (j == XI_TouchUpdate || j == XI_TouchUpdateUnowned) {
+                SetBit(bits, XI_TouchBegin);
+                SetBit(bits, XI_TouchUpdate);
+                SetBit(bits, XI_TouchEnd);
+                if (j == XI_TouchUpdateUnowned)
+                    SetBit(bits, XI_TouchOwnership);
+            }
+
             request_XISelectEvent(req, Success);
             ClearBit(bits, j);
+
+            if (j == XI_TouchUpdate || j == XI_TouchUpdateUnowned) {
+                ClearBit(bits, XI_TouchBegin);
+                ClearBit(bits, XI_TouchUpdate);
+                ClearBit(bits, XI_TouchEnd);
+                if (j == XI_TouchUpdateUnowned)
+                    ClearBit(bits, XI_TouchOwnership);
+            }
         }
 
         /* Test 2:
@@ -175,7 +199,23 @@
 
         for (j = 0; j <= XI2LASTEVENT; j++)
         {
+            /* Can't select for these events alone */
+            if (j == XI_TouchBegin || j == XI_TouchOwnership ||
+                j == XI_TouchEnd)
+                continue;
+
             SetBit(bits, j);
+
+            /* Must select for TouchBegin + TouchMotion + TouchEnd together,
+             * and optionally also TouchMotionUnowned and TouchOwnerhip. */
+            if (j == XI_TouchUpdate || j == XI_TouchUpdateUnowned) {
+                SetBit(bits, XI_TouchBegin);
+                SetBit(bits, XI_TouchUpdate);
+                SetBit(bits, XI_TouchEnd);
+                if (j == XI_TouchUpdateUnowned)
+                    SetBit(bits, XI_TouchOwnership);
+            }
+
             request_XISelectEvent(req, Success);
         }
 
@@ -189,7 +229,23 @@
 
         for (j = XI2LASTEVENT + 1; j < mask->mask_len * 4; j++)
         {
+            /* Can't select for these events alone */
+            if (j == XI_TouchBegin || j == XI_TouchOwnership ||
+                j == XI_TouchEnd)
+                continue;
+
             SetBit(bits, j);
+
+            /* Must select for TouchBegin + TouchMotion + TouchEnd together,
+             * and optionally also TouchMotionUnowned and TouchOwnerhip. */
+            if (j == XI_TouchUpdate || j == XI_TouchUpdateUnowned) {
+                SetBit(bits, XI_TouchBegin);
+                SetBit(bits, XI_TouchUpdate);
+                SetBit(bits, XI_TouchEnd);
+                if (j == XI_TouchUpdateUnowned)
+                    SetBit(bits, XI_TouchOwnership);
+            }
+
             request_XISelectEvent(req, BadValue);
             ClearBit(bits, j);
         }
@@ -202,7 +258,23 @@
         memset(bits, 0, mask->mask_len * 4);
         for (j = 0; j <= XI2LASTEVENT; j++)
         {
+            /* Can't select for these events alone */
+            if (j == XI_TouchBegin || j == XI_TouchOwnership ||
+                j == XI_TouchEnd)
+                continue;
+
             SetBit(bits, j);
+
+            /* Must select for TouchBegin + TouchMotion + TouchEnd together,
+             * and optionally also TouchMotionUnowned and TouchOwnerhip. */
+            if (j == XI_TouchUpdate || j == XI_TouchUpdateUnowned) {
+                SetBit(bits, XI_TouchBegin);
+                SetBit(bits, XI_TouchUpdate);
+                SetBit(bits, XI_TouchEnd);
+                if (j == XI_TouchUpdateUnowned)
+                    SetBit(bits, XI_TouchOwnership);
+            }
+
             request_XISelectEvent(req, Success);
         }