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

#include "config.h"

#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/mman.h>
#include <assert.h>
#include <unistd.h>
#include <values.h>
#include <fcntl.h>
#include <limits.h>
#include <errno.h>

#include "shared/helpers.h"
#include "shared/os-compatibility.h"
#include "shared/timespec-util.h"
#include <libweston/libweston.h>
#include "backend.h"
#include "libweston-internal.h"
#include "relative-pointer-unstable-v1-server-protocol.h"
#include "pointer-constraints-unstable-v1-server-protocol.h"
#include "input-timestamps-unstable-v1-server-protocol.h"

enum pointer_constraint_type {
	POINTER_CONSTRAINT_TYPE_LOCK,
	POINTER_CONSTRAINT_TYPE_CONFINE,
};

enum motion_direction {
	MOTION_DIRECTION_POSITIVE_X = 1 << 0,
	MOTION_DIRECTION_NEGATIVE_X = 1 << 1,
	MOTION_DIRECTION_POSITIVE_Y = 1 << 2,
	MOTION_DIRECTION_NEGATIVE_Y = 1 << 3,
};

struct vec2d {
	double x, y;
};

struct line {
	struct vec2d a;
	struct vec2d b;
};

struct border {
	struct line line;
	enum motion_direction blocking_dir;
};

static void
maybe_warp_confined_pointer(struct weston_pointer_constraint *constraint);

static void
empty_region(pixman_region32_t *region)
{
	pixman_region32_fini(region);
	pixman_region32_init(region);
}

static void
region_init_infinite(pixman_region32_t *region)
{
	pixman_region32_init_rect(region, INT32_MIN, INT32_MIN,
				  UINT32_MAX, UINT32_MAX);
}

static void
send_timestamp(struct wl_resource *resource,
	       const struct timespec *time)
{
	uint32_t tv_sec_hi, tv_sec_lo, tv_nsec;

	timespec_to_proto(time, &tv_sec_hi, &tv_sec_lo, &tv_nsec);
	zwp_input_timestamps_v1_send_timestamp(resource, tv_sec_hi, tv_sec_lo,
					       tv_nsec);
}

static void
send_timestamps_for_input_resource(struct wl_resource *input_resource,
				   struct wl_list *list,
				   const struct timespec *time)
{
	struct wl_resource *resource;

	wl_resource_for_each(resource, list) {
		if (wl_resource_get_user_data(resource) == input_resource)
			send_timestamp(resource, time);
	}
}

static void
remove_input_resource_from_timestamps(struct wl_resource *input_resource,
				      struct wl_list *list)
{
	struct wl_resource *resource;

	wl_resource_for_each(resource, list) {
		if (wl_resource_get_user_data(resource) == input_resource)
			wl_resource_set_user_data(resource, NULL);
	}
}

/** Register a touchscreen input device
 *
 * \param touch The parent weston_touch that identifies the seat.
 * \param syspath Unique device name.
 * \param backend_data Backend private data if necessary.
 * \param ops Calibration operations, or NULL for not able to run calibration.
 * \return New touch device, or NULL on failure.
 */
WL_EXPORT struct weston_touch_device *
weston_touch_create_touch_device(struct weston_touch *touch,
				 const char *syspath,
				 void *backend_data,
				 const struct weston_touch_device_ops *ops)
{
	struct weston_touch_device *device;

	assert(syspath);
	if (ops) {
		assert(ops->get_output);
		assert(ops->get_calibration_head_name);
		assert(ops->get_calibration);
		assert(ops->set_calibration);
	}

	device = zalloc(sizeof *device);
	if (!device)
		return NULL;

	wl_signal_init(&device->destroy_signal);

	device->syspath = strdup(syspath);
	if (!device->syspath) {
		free(device);
		return NULL;
	}

	device->backend_data = backend_data;
	device->ops = ops;

	device->aggregate = touch;
	wl_list_insert(touch->device_list.prev, &device->link);

	return device;
}

/** Destroy the touch device. */
WL_EXPORT void
weston_touch_device_destroy(struct weston_touch_device *device)
{
	wl_list_remove(&device->link);
	wl_signal_emit(&device->destroy_signal, device);
	free(device->syspath);
	free(device);
}

/** Is it possible to run calibration on this touch device? */
WL_EXPORT bool
weston_touch_device_can_calibrate(struct weston_touch_device *device)
{
	return !!device->ops;
}

static enum weston_touch_mode
weston_touch_device_get_mode(struct weston_touch_device *device)
{
	return device->aggregate->seat->compositor->touch_mode;
}

static struct weston_pointer_client *
weston_pointer_client_create(struct wl_client *client)
{
	struct weston_pointer_client *pointer_client;

	pointer_client = zalloc(sizeof *pointer_client);
	if (!pointer_client)
		return NULL;

	pointer_client->client = client;
	wl_list_init(&pointer_client->pointer_resources);
	wl_list_init(&pointer_client->relative_pointer_resources);

	return pointer_client;
}

static void
weston_pointer_client_destroy(struct weston_pointer_client *pointer_client)
{
	struct wl_resource *resource;

	wl_resource_for_each(resource, &pointer_client->pointer_resources) {
		wl_resource_set_user_data(resource, NULL);
	}

	wl_resource_for_each(resource,
			     &pointer_client->relative_pointer_resources) {
		wl_resource_set_user_data(resource, NULL);
	}

	wl_list_remove(&pointer_client->pointer_resources);
	wl_list_remove(&pointer_client->relative_pointer_resources);
	free(pointer_client);
}

static bool
weston_pointer_client_is_empty(struct weston_pointer_client *pointer_client)
{
	return (wl_list_empty(&pointer_client->pointer_resources) &&
		wl_list_empty(&pointer_client->relative_pointer_resources));
}

static struct weston_pointer_client *
weston_pointer_get_pointer_client(struct weston_pointer *pointer,
				  struct wl_client *client)
{
	struct weston_pointer_client *pointer_client;

	wl_list_for_each(pointer_client, &pointer->pointer_clients, link) {
		if (pointer_client->client == client)
			return pointer_client;
	}

	return NULL;
}

static struct weston_pointer_client *
weston_pointer_ensure_pointer_client(struct weston_pointer *pointer,
				     struct wl_client *client)
{
	struct weston_pointer_client *pointer_client;

	pointer_client = weston_pointer_get_pointer_client(pointer, client);
	if (pointer_client)
		return pointer_client;

	pointer_client = weston_pointer_client_create(client);
	wl_list_insert(&pointer->pointer_clients, &pointer_client->link);

	if (pointer->focus &&
	    pointer->focus->surface->resource &&
	    wl_resource_get_client(pointer->focus->surface->resource) == client) {
		pointer->focus_client = pointer_client;
	}

	return pointer_client;
}

static void
weston_pointer_cleanup_pointer_client(struct weston_pointer *pointer,
				      struct weston_pointer_client *pointer_client)
{
	if (weston_pointer_client_is_empty(pointer_client)) {
		if (pointer->focus_client == pointer_client)
			pointer->focus_client = NULL;
		wl_list_remove(&pointer_client->link);
		weston_pointer_client_destroy(pointer_client);
	}
}

static void
unbind_pointer_client_resource(struct wl_resource *resource)
{
	struct weston_pointer *pointer = wl_resource_get_user_data(resource);
	struct wl_client *client = wl_resource_get_client(resource);
	struct weston_pointer_client *pointer_client;

	wl_list_remove(wl_resource_get_link(resource));

	if (pointer) {
		pointer_client = weston_pointer_get_pointer_client(pointer,
								   client);
		assert(pointer_client);
		remove_input_resource_from_timestamps(resource,
						      &pointer->timestamps_list);
		weston_pointer_cleanup_pointer_client(pointer, pointer_client);
	}
}

static void unbind_resource(struct wl_resource *resource)
{
	wl_list_remove(wl_resource_get_link(resource));
}

WL_EXPORT void
weston_pointer_motion_to_abs(struct weston_pointer *pointer,
			     struct weston_pointer_motion_event *event,
			     wl_fixed_t *x, wl_fixed_t *y)
{
	if (event->mask & WESTON_POINTER_MOTION_ABS) {
		*x = wl_fixed_from_double(event->x);
		*y = wl_fixed_from_double(event->y);
	} else if (event->mask & WESTON_POINTER_MOTION_REL) {
		*x = pointer->x + wl_fixed_from_double(event->dx);
		*y = pointer->y + wl_fixed_from_double(event->dy);
	} else {
		assert(!"invalid motion event");
		*x = *y = 0;
	}
}

static bool
weston_pointer_motion_to_rel(struct weston_pointer *pointer,
			     struct weston_pointer_motion_event *event,
			     double *dx, double *dy,
			     double *dx_unaccel, double *dy_unaccel)
{
	if (event->mask & WESTON_POINTER_MOTION_REL &&
	    event->mask & WESTON_POINTER_MOTION_REL_UNACCEL) {
		*dx = event->dx;
		*dy = event->dy;
		*dx_unaccel = event->dx_unaccel;
		*dy_unaccel = event->dy_unaccel;
		return true;
	} else if (event->mask & WESTON_POINTER_MOTION_REL) {
		*dx_unaccel = *dx = event->dx;
		*dy_unaccel = *dy = event->dy;
		return true;
	} else if (event->mask & WESTON_POINTER_MOTION_REL_UNACCEL) {
		*dx_unaccel = *dx = event->dx_unaccel;
		*dy_unaccel = *dy = event->dy_unaccel;
		return true;
	} else {
		return false;
	}
}

WL_EXPORT void
weston_seat_repick(struct weston_seat *seat)
{
	const struct weston_pointer *pointer = weston_seat_get_pointer(seat);

	if (!pointer)
		return;

	pointer->grab->interface->focus(pointer->grab);
}

static void
weston_compositor_idle_inhibit(struct weston_compositor *compositor)
{
	weston_compositor_wake(compositor);
	compositor->idle_inhibit++;
}

static void
weston_compositor_idle_release(struct weston_compositor *compositor)
{
	compositor->idle_inhibit--;
	weston_compositor_wake(compositor);
}

static void
pointer_focus_view_destroyed(struct wl_listener *listener, void *data)
{
	struct weston_pointer *pointer =
		container_of(listener, struct weston_pointer,
			     focus_view_listener);

	weston_pointer_clear_focus(pointer);
}

static void
pointer_focus_resource_destroyed(struct wl_listener *listener, void *data)
{
	struct weston_pointer *pointer =
		container_of(listener, struct weston_pointer,
			     focus_resource_listener);

	weston_pointer_clear_focus(pointer);
}

static void
keyboard_focus_resource_destroyed(struct wl_listener *listener, void *data)
{
	struct weston_keyboard *keyboard =
		container_of(listener, struct weston_keyboard,
			     focus_resource_listener);

	weston_keyboard_set_focus(keyboard, NULL);
}

static void
touch_focus_view_destroyed(struct wl_listener *listener, void *data)
{
	struct weston_touch *touch =
		container_of(listener, struct weston_touch,
			     focus_view_listener);

	weston_touch_set_focus(touch, NULL);
}

static void
touch_focus_resource_destroyed(struct wl_listener *listener, void *data)
{
	struct weston_touch *touch =
		container_of(listener, struct weston_touch,
			     focus_resource_listener);

	weston_touch_set_focus(touch, NULL);
}

static void
move_resources(struct wl_list *destination, struct wl_list *source)
{
	wl_list_insert_list(destination, source);
	wl_list_init(source);
}

static void
move_resources_for_client(struct wl_list *destination,
			  struct wl_list *source,
			  struct wl_client *client)
{
	struct wl_resource *resource, *tmp;
	wl_resource_for_each_safe(resource, tmp, source) {
		if (wl_resource_get_client(resource) == client) {
			wl_list_remove(wl_resource_get_link(resource));
			wl_list_insert(destination,
				       wl_resource_get_link(resource));
		}
	}
}

static void
default_grab_pointer_focus(struct weston_pointer_grab *grab)
{
	struct weston_pointer *pointer = grab->pointer;
	struct weston_view *view;
	wl_fixed_t sx, sy;

	if (pointer->button_count > 0)
		return;

	view = weston_compositor_pick_view(pointer->seat->compositor,
					   pointer->x, pointer->y,
					   &sx, &sy);

	if (pointer->focus != view || pointer->sx != sx || pointer->sy != sy)
		weston_pointer_set_focus(pointer, view, sx, sy);
}

static void
pointer_send_relative_motion(struct weston_pointer *pointer,
			     const struct timespec *time,
			     struct weston_pointer_motion_event *event)
{
	uint64_t time_usec;
	double dx, dy, dx_unaccel, dy_unaccel;
	wl_fixed_t dxf, dyf, dxf_unaccel, dyf_unaccel;
	struct wl_list *resource_list;
	struct wl_resource *resource;

	if (!pointer->focus_client)
		return;

	if (!weston_pointer_motion_to_rel(pointer, event,
					  &dx, &dy,
					  &dx_unaccel, &dy_unaccel))
		return;

	resource_list = &pointer->focus_client->relative_pointer_resources;
	time_usec = timespec_to_usec(&event->time);
	if (time_usec == 0)
		time_usec = timespec_to_usec(time);

	dxf = wl_fixed_from_double(dx);
	dyf = wl_fixed_from_double(dy);
	dxf_unaccel = wl_fixed_from_double(dx_unaccel);
	dyf_unaccel = wl_fixed_from_double(dy_unaccel);

	wl_resource_for_each(resource, resource_list) {
		zwp_relative_pointer_v1_send_relative_motion(
			resource,
			(uint32_t) (time_usec >> 32),
			(uint32_t) time_usec,
			dxf, dyf,
			dxf_unaccel, dyf_unaccel);
	}
}

static void
pointer_send_motion(struct weston_pointer *pointer,
		    const struct timespec *time,
		    wl_fixed_t sx, wl_fixed_t sy)
{
	struct wl_list *resource_list;
	struct wl_resource *resource;
	uint32_t msecs;

	if (!pointer->focus_client)
		return;

	resource_list = &pointer->focus_client->pointer_resources;
	msecs = timespec_to_msec(time);
	wl_resource_for_each(resource, resource_list) {
		send_timestamps_for_input_resource(resource,
                                                   &pointer->timestamps_list,
                                                   time);
		wl_pointer_send_motion(resource, msecs, sx, sy);
	}
}

WL_EXPORT void
weston_pointer_send_motion(struct weston_pointer *pointer,
			   const struct timespec *time,
			   struct weston_pointer_motion_event *event)
{
	wl_fixed_t x, y;
	wl_fixed_t old_sx = pointer->sx;
	wl_fixed_t old_sy = pointer->sy;

	if (pointer->focus) {
		weston_pointer_motion_to_abs(pointer, event, &x, &y);
		weston_view_from_global_fixed(pointer->focus, x, y,
					      &pointer->sx, &pointer->sy);
	}

	weston_pointer_move(pointer, event);

	if (old_sx != pointer->sx || old_sy != pointer->sy) {
		pointer_send_motion(pointer, time,
				    pointer->sx, pointer->sy);
	}

	pointer_send_relative_motion(pointer, time, event);
}

static void
default_grab_pointer_motion(struct weston_pointer_grab *grab,
			    const struct timespec *time,
			    struct weston_pointer_motion_event *event)
{
	weston_pointer_send_motion(grab->pointer, time, event);
}

/** Check if the pointer has focused resources.
 *
 * \param pointer The pointer to check for focused resources.
 * \return Whether or not this pointer has focused resources
 */
WL_EXPORT bool
weston_pointer_has_focus_resource(struct weston_pointer *pointer)
{
	if (!pointer->focus_client)
		return false;

	if (wl_list_empty(&pointer->focus_client->pointer_resources))
		return false;

	return true;
}

/** Send wl_pointer.button events to focused resources.
 *
 * \param pointer The pointer where the button events originates from.
 * \param time The timestamp of the event
 * \param button The button value of the event
 * \param state The state enum value of the event
 *
 * For every resource that is currently in focus, send a wl_pointer.button event
 * with the passed parameters. The focused resources are the wl_pointer
 * resources of the client which currently has the surface with pointer focus.
 */
WL_EXPORT void
weston_pointer_send_button(struct weston_pointer *pointer,
			   const struct timespec *time, uint32_t button,
			   enum wl_pointer_button_state state)
{
	struct wl_display *display = pointer->seat->compositor->wl_display;
	struct wl_list *resource_list;
	struct wl_resource *resource;
	uint32_t serial;
	uint32_t msecs;

	if (!weston_pointer_has_focus_resource(pointer))
		return;

	resource_list = &pointer->focus_client->pointer_resources;
	serial = wl_display_next_serial(display);
	msecs = timespec_to_msec(time);
	wl_resource_for_each(resource, resource_list) {
		send_timestamps_for_input_resource(resource,
                                                   &pointer->timestamps_list,
                                                   time);
		wl_pointer_send_button(resource, serial, msecs, button, state);
	}
}

static void
default_grab_pointer_button(struct weston_pointer_grab *grab,
			    const struct timespec *time, uint32_t button,
			    enum wl_pointer_button_state state)
{
	struct weston_pointer *pointer = grab->pointer;
	struct weston_compositor *compositor = pointer->seat->compositor;
	struct weston_view *view;
	wl_fixed_t sx, sy;

	weston_pointer_send_button(pointer, time, button, state);

	if (pointer->button_count == 0 &&
	    state == WL_POINTER_BUTTON_STATE_RELEASED) {
		view = weston_compositor_pick_view(compositor,
						   pointer->x, pointer->y,
						   &sx, &sy);

		weston_pointer_set_focus(pointer, view, sx, sy);
	}
}

/** Send wl_pointer.axis events to focused resources.
 *
 * \param pointer The pointer where the axis events originates from.
 * \param time The timestamp of the event
 * \param event The axis value of the event
 *
 * For every resource that is currently in focus, send a wl_pointer.axis event
 * with the passed parameters. The focused resources are the wl_pointer
 * resources of the client which currently has the surface with pointer focus.
 */
WL_EXPORT void
weston_pointer_send_axis(struct weston_pointer *pointer,
			 const struct timespec *time,
			 struct weston_pointer_axis_event *event)
{
	struct wl_resource *resource;
	struct wl_list *resource_list;
	uint32_t msecs;

	if (!weston_pointer_has_focus_resource(pointer))
		return;

	resource_list = &pointer->focus_client->pointer_resources;
	msecs = timespec_to_msec(time);
	wl_resource_for_each(resource, resource_list) {
		if (event->has_discrete &&
		    wl_resource_get_version(resource) >=
		    WL_POINTER_AXIS_DISCRETE_SINCE_VERSION)
			wl_pointer_send_axis_discrete(resource, event->axis,
						      event->discrete);

		if (event->value) {
			send_timestamps_for_input_resource(resource,
							   &pointer->timestamps_list,
							   time);
			wl_pointer_send_axis(resource, msecs,
					     event->axis,
					     wl_fixed_from_double(event->value));
		} else if (wl_resource_get_version(resource) >=
			 WL_POINTER_AXIS_STOP_SINCE_VERSION) {
			send_timestamps_for_input_resource(resource,
							   &pointer->timestamps_list,
							   time);
			wl_pointer_send_axis_stop(resource, msecs,
						  event->axis);
		}
	}
}

/** Send wl_pointer.axis_source events to focused resources.
 *
 * \param pointer The pointer where the axis_source events originates from.
 * \param source The axis_source enum value of the event
 *
 * For every resource that is currently in focus, send a wl_pointer.axis_source
 * event with the passed parameter. The focused resources are the wl_pointer
 * resources of the client which currently has the surface with pointer focus.
 */
WL_EXPORT void
weston_pointer_send_axis_source(struct weston_pointer *pointer,
				enum wl_pointer_axis_source source)
{
	struct wl_resource *resource;
	struct wl_list *resource_list;

	if (!weston_pointer_has_focus_resource(pointer))
		return;

	resource_list = &pointer->focus_client->pointer_resources;
	wl_resource_for_each(resource, resource_list) {
		if (wl_resource_get_version(resource) >=
		    WL_POINTER_AXIS_SOURCE_SINCE_VERSION) {
			wl_pointer_send_axis_source(resource, source);
		}
	}
}

static void
pointer_send_frame(struct wl_resource *resource)
{
	if (wl_resource_get_version(resource) >=
	    WL_POINTER_FRAME_SINCE_VERSION) {
		wl_pointer_send_frame(resource);
	}
}

/** Send wl_pointer.frame events to focused resources.
 *
 * \param pointer The pointer where the frame events originates from.
 *
 * For every resource that is currently in focus, send a wl_pointer.frame event.
 * The focused resources are the wl_pointer resources of the client which
 * currently has the surface with pointer focus.
 */
WL_EXPORT void
weston_pointer_send_frame(struct weston_pointer *pointer)
{
	struct wl_resource *resource;
	struct wl_list *resource_list;

	if (!weston_pointer_has_focus_resource(pointer))
		return;

	resource_list = &pointer->focus_client->pointer_resources;
	wl_resource_for_each(resource, resource_list)
		pointer_send_frame(resource);
}

static void
default_grab_pointer_axis(struct weston_pointer_grab *grab,
			  const struct timespec *time,
			  struct weston_pointer_axis_event *event)
{
	weston_pointer_send_axis(grab->pointer, time, event);
}

static void
default_grab_pointer_axis_source(struct weston_pointer_grab *grab,
				 enum wl_pointer_axis_source source)
{
	weston_pointer_send_axis_source(grab->pointer, source);
}

static void
default_grab_pointer_frame(struct weston_pointer_grab *grab)
{
	weston_pointer_send_frame(grab->pointer);
}

static void
default_grab_pointer_cancel(struct weston_pointer_grab *grab)
{
}

static const struct weston_pointer_grab_interface
				default_pointer_grab_interface = {
	default_grab_pointer_focus,
	default_grab_pointer_motion,
	default_grab_pointer_button,
	default_grab_pointer_axis,
	default_grab_pointer_axis_source,
	default_grab_pointer_frame,
	default_grab_pointer_cancel,
};

/** Check if the touch has focused resources.
 *
 * \param touch The touch to check for focused resources.
 * \return Whether or not this touch has focused resources
 */
WL_EXPORT bool
weston_touch_has_focus_resource(struct weston_touch *touch)
{
	if (!touch->focus)
		return false;

	if (wl_list_empty(&touch->focus_resource_list))
		return false;

	return true;
}

/** Send wl_touch.down events to focused resources.
 *
 * \param touch The touch where the down events originates from.
 * \param time The timestamp of the event
 * \param touch_id The touch_id value of the event
 * \param x The x value of the event
 * \param y The y value of the event
 *
 * For every resource that is currently in focus, send a wl_touch.down event
 * with the passed parameters. The focused resources are the wl_touch
 * resources of the client which currently has the surface with touch focus.
 */
WL_EXPORT void
weston_touch_send_down(struct weston_touch *touch, const struct timespec *time,
		       int touch_id, wl_fixed_t x, wl_fixed_t y)
{
	struct wl_display *display = touch->seat->compositor->wl_display;
	uint32_t serial;
	struct wl_resource *resource;
	struct wl_list *resource_list;
	wl_fixed_t sx, sy;
	uint32_t msecs;

	if (!weston_touch_has_focus_resource(touch))
		return;

	weston_view_from_global_fixed(touch->focus, x, y, &sx, &sy);

	resource_list = &touch->focus_resource_list;
	serial = wl_display_next_serial(display);
	msecs = timespec_to_msec(time);
	wl_resource_for_each(resource, resource_list) {
		send_timestamps_for_input_resource(resource,
						   &touch->timestamps_list,
						   time);
		wl_touch_send_down(resource, serial, msecs,
				   touch->focus->surface->resource,
				   touch_id, sx, sy);
	}
}

static void
default_grab_touch_down(struct weston_touch_grab *grab,
			const struct timespec *time, int touch_id,
			wl_fixed_t x, wl_fixed_t y)
{
	weston_touch_send_down(grab->touch, time, touch_id, x, y);
}

/** Send wl_touch.up events to focused resources.
 *
 * \param touch The touch where the up events originates from.
 * \param time The timestamp of the event
 * \param touch_id The touch_id value of the event
 *
 * For every resource that is currently in focus, send a wl_touch.up event
 * with the passed parameters. The focused resources are the wl_touch
 * resources of the client which currently has the surface with touch focus.
 */
WL_EXPORT void
weston_touch_send_up(struct weston_touch *touch, const struct timespec *time,
		     int touch_id)
{
	struct wl_display *display = touch->seat->compositor->wl_display;
	uint32_t serial;
	struct wl_resource *resource;
	struct wl_list *resource_list;
	uint32_t msecs;

	if (!weston_touch_has_focus_resource(touch))
		return;

	resource_list = &touch->focus_resource_list;
	serial = wl_display_next_serial(display);
	msecs = timespec_to_msec(time);
	wl_resource_for_each(resource, resource_list) {
		send_timestamps_for_input_resource(resource,
						   &touch->timestamps_list,
						   time);
		wl_touch_send_up(resource, serial, msecs, touch_id);
	}
}

static void
default_grab_touch_up(struct weston_touch_grab *grab,
		      const struct timespec *time, int touch_id)
{
	weston_touch_send_up(grab->touch, time, touch_id);
}

/** Send wl_touch.motion events to focused resources.
 *
 * \param touch The touch where the motion events originates from.
 * \param time The timestamp of the event
 * \param touch_id The touch_id value of the event
 * \param x The x value of the event
 * \param y The y value of the event
 *
 * For every resource that is currently in focus, send a wl_touch.motion event
 * with the passed parameters. The focused resources are the wl_touch
 * resources of the client which currently has the surface with touch focus.
 */
WL_EXPORT void
weston_touch_send_motion(struct weston_touch *touch,
			 const struct timespec *time, int touch_id,
			 wl_fixed_t x, wl_fixed_t y)
{
	struct wl_resource *resource;
	struct wl_list *resource_list;
	wl_fixed_t sx, sy;
	uint32_t msecs;

	if (!weston_touch_has_focus_resource(touch))
		return;

	weston_view_from_global_fixed(touch->focus, x, y, &sx, &sy);

	resource_list = &touch->focus_resource_list;
	msecs = timespec_to_msec(time);
	wl_resource_for_each(resource, resource_list) {
		send_timestamps_for_input_resource(resource,
						   &touch->timestamps_list,
						   time);
		wl_touch_send_motion(resource, msecs,
				     touch_id, sx, sy);
	}
}

static void
default_grab_touch_motion(struct weston_touch_grab *grab,
			  const struct timespec *time, int touch_id,
			  wl_fixed_t x, wl_fixed_t y)
{
	weston_touch_send_motion(grab->touch, time, touch_id, x, y);
}


/** Send wl_touch.frame events to focused resources.
 *
 * \param touch The touch where the frame events originates from.
 *
 * For every resource that is currently in focus, send a wl_touch.frame event.
 * The focused resources are the wl_touch resources of the client which
 * currently has the surface with touch focus.
 */
WL_EXPORT void
weston_touch_send_frame(struct weston_touch *touch)
{
	struct wl_resource *resource;

	if (!weston_touch_has_focus_resource(touch))
		return;

	wl_resource_for_each(resource, &touch->focus_resource_list)
		wl_touch_send_frame(resource);
}

static void
default_grab_touch_frame(struct weston_touch_grab *grab)
{
	weston_touch_send_frame(grab->touch);
}

static void
default_grab_touch_cancel(struct weston_touch_grab *grab)
{
}

static const struct weston_touch_grab_interface default_touch_grab_interface = {
	default_grab_touch_down,
	default_grab_touch_up,
	default_grab_touch_motion,
	default_grab_touch_frame,
	default_grab_touch_cancel,
};

/** Check if the keyboard has focused resources.
 *
 * \param keyboard The keyboard to check for focused resources.
 * \return Whether or not this keyboard has focused resources
 */
WL_EXPORT bool
weston_keyboard_has_focus_resource(struct weston_keyboard *keyboard)
{
	if (!keyboard->focus)
		return false;

	if (wl_list_empty(&keyboard->focus_resource_list))
		return false;

	return true;
}

/** Send wl_keyboard.key events to focused resources.
 *
 * \param keyboard The keyboard where the key events originates from.
 * \param time The timestamp of the event
 * \param key The key value of the event
 * \param state The state enum value of the event
 *
 * For every resource that is currently in focus, send a wl_keyboard.key event
 * with the passed parameters. The focused resources are the wl_keyboard
 * resources of the client which currently has the surface with keyboard focus.
 */
WL_EXPORT void
weston_keyboard_send_key(struct weston_keyboard *keyboard,
			 const struct timespec *time, uint32_t key,
			 enum wl_keyboard_key_state state)
{
	struct wl_resource *resource;
	struct wl_display *display = keyboard->seat->compositor->wl_display;
	uint32_t serial;
	struct wl_list *resource_list;
	uint32_t msecs;

	if (!weston_keyboard_has_focus_resource(keyboard))
		return;

	resource_list = &keyboard->focus_resource_list;
	serial = wl_display_next_serial(display);
	msecs = timespec_to_msec(time);
	wl_resource_for_each(resource, resource_list) {
		send_timestamps_for_input_resource(resource,
						   &keyboard->timestamps_list,
						   time);
		wl_keyboard_send_key(resource, serial, msecs, key, state);
	}
};

static void
default_grab_keyboard_key(struct weston_keyboard_grab *grab,
			  const struct timespec *time, uint32_t key,
			  uint32_t state)
{
	weston_keyboard_send_key(grab->keyboard, time, key, state);
}

static void
send_modifiers_to_resource(struct weston_keyboard *keyboard,
			   struct wl_resource *resource,
			   uint32_t serial)
{
	wl_keyboard_send_modifiers(resource,
				   serial,
				   keyboard->modifiers.mods_depressed,
				   keyboard->modifiers.mods_latched,
				   keyboard->modifiers.mods_locked,
				   keyboard->modifiers.group);
}

static void
send_modifiers_to_client_in_list(struct wl_client *client,
				 struct wl_list *list,
				 uint32_t serial,
				 struct weston_keyboard *keyboard)
{
	struct wl_resource *resource;

	wl_resource_for_each(resource, list) {
		if (wl_resource_get_client(resource) == client)
			send_modifiers_to_resource(keyboard,
						   resource,
						   serial);
	}
}

static struct weston_pointer_client *
find_pointer_client_for_surface(struct weston_pointer *pointer,
				struct weston_surface *surface)
{
	struct wl_client *client;

	if (!surface)
		return NULL;

	if (!surface->resource)
		return NULL;

	client = wl_resource_get_client(surface->resource);
	return weston_pointer_get_pointer_client(pointer, client);
}

static struct weston_pointer_client *
find_pointer_client_for_view(struct weston_pointer *pointer, struct weston_view *view)
{
	if (!view)
		return NULL;

	return find_pointer_client_for_surface(pointer, view->surface);
}

static struct wl_resource *
find_resource_for_surface(struct wl_list *list, struct weston_surface *surface)
{
	if (!surface)
		return NULL;

	if (!surface->resource)
		return NULL;

	return wl_resource_find_for_client(list, wl_resource_get_client(surface->resource));
}

/** Send wl_keyboard.modifiers events to focused resources and pointer
 *  focused resources.
 *
 * \param keyboard The keyboard where the modifiers events originates from.
 * \param serial The serial of the event
 * \param mods_depressed The mods_depressed value of the event
 * \param mods_latched The mods_latched value of the event
 * \param mods_locked The mods_locked value of the event
 * \param group The group value of the event
 *
 * For every resource that is currently in focus, send a wl_keyboard.modifiers
 * event with the passed parameters. The focused resources are the wl_keyboard
 * resources of the client which currently has the surface with keyboard focus.
 * This also sends wl_keyboard.modifiers events to the wl_keyboard resources of
 * the client having pointer focus (if different from the keyboard focus client).
 */
WL_EXPORT void
weston_keyboard_send_modifiers(struct weston_keyboard *keyboard,
			       uint32_t serial, uint32_t mods_depressed,
			       uint32_t mods_latched,
			       uint32_t mods_locked, uint32_t group)
{
	struct weston_pointer *pointer =
		weston_seat_get_pointer(keyboard->seat);

	if (weston_keyboard_has_focus_resource(keyboard)) {
		struct wl_list *resource_list;
		struct wl_resource *resource;

		resource_list = &keyboard->focus_resource_list;
		wl_resource_for_each(resource, resource_list) {
			wl_keyboard_send_modifiers(resource, serial,
						   mods_depressed, mods_latched,
						   mods_locked, group);
		}
	}

	if (pointer && pointer->focus && pointer->focus->surface->resource &&
	    pointer->focus->surface != keyboard->focus) {
		struct wl_client *pointer_client =
			wl_resource_get_client(pointer->focus->surface->resource);

		send_modifiers_to_client_in_list(pointer_client,
						 &keyboard->resource_list,
						 serial,
						 keyboard);
	}
}

static void
default_grab_keyboard_modifiers(struct weston_keyboard_grab *grab,
				uint32_t serial, uint32_t mods_depressed,
				uint32_t mods_latched,
				uint32_t mods_locked, uint32_t group)
{
	weston_keyboard_send_modifiers(grab->keyboard, serial, mods_depressed,
				       mods_latched, mods_locked, group);
}

static void
default_grab_keyboard_cancel(struct weston_keyboard_grab *grab)
{
}

static const struct weston_keyboard_grab_interface
				default_keyboard_grab_interface = {
	default_grab_keyboard_key,
	default_grab_keyboard_modifiers,
	default_grab_keyboard_cancel,
};

static void
pointer_unmap_sprite(struct weston_pointer *pointer)
{
	struct weston_surface *surface = pointer->sprite->surface;

	if (weston_surface_is_mapped(surface))
		weston_surface_unmap(surface);

	wl_list_remove(&pointer->sprite_destroy_listener.link);
	surface->committed = NULL;
	surface->committed_private = NULL;
	weston_surface_set_label_func(surface, NULL);
	weston_view_destroy(pointer->sprite);
	pointer->sprite = NULL;
}

static void
pointer_handle_sprite_destroy(struct wl_listener *listener, void *data)
{
	struct weston_pointer *pointer =
		container_of(listener, struct weston_pointer,
			     sprite_destroy_listener);

	pointer->sprite = NULL;
}

static void
weston_pointer_reset_state(struct weston_pointer *pointer)
{
	pointer->button_count = 0;
}

static void
weston_pointer_handle_output_destroy(struct wl_listener *listener, void *data);

static struct weston_pointer *
weston_pointer_create(struct weston_seat *seat)
{
	struct weston_pointer *pointer;

	pointer = zalloc(sizeof *pointer);
	if (pointer == NULL)
		return NULL;

	wl_list_init(&pointer->pointer_clients);
	weston_pointer_set_default_grab(pointer,
					seat->compositor->default_pointer_grab);
	wl_list_init(&pointer->focus_resource_listener.link);
	pointer->focus_resource_listener.notify = pointer_focus_resource_destroyed;
	pointer->default_grab.pointer = pointer;
	pointer->grab = &pointer->default_grab;
	wl_signal_init(&pointer->motion_signal);
	wl_signal_init(&pointer->focus_signal);
	wl_list_init(&pointer->focus_view_listener.link);
	wl_signal_init(&pointer->destroy_signal);
	wl_list_init(&pointer->timestamps_list);

	pointer->sprite_destroy_listener.notify = pointer_handle_sprite_destroy;

	/* FIXME: Pick better co-ords. */
	pointer->x = wl_fixed_from_int(100);
	pointer->y = wl_fixed_from_int(100);

	pointer->output_destroy_listener.notify =
		weston_pointer_handle_output_destroy;
	wl_signal_add(&seat->compositor->output_destroyed_signal,
		      &pointer->output_destroy_listener);

	pointer->sx = wl_fixed_from_int(-1000000);
	pointer->sy = wl_fixed_from_int(-1000000);

	return pointer;
}

static void
weston_pointer_destroy(struct weston_pointer *pointer)
{
	struct weston_pointer_client *pointer_client, *tmp;

	wl_signal_emit(&pointer->destroy_signal, pointer);

	if (pointer->sprite)
		pointer_unmap_sprite(pointer);

	wl_list_for_each_safe(pointer_client, tmp, &pointer->pointer_clients,
			      link) {
		wl_list_remove(&pointer_client->link);
		weston_pointer_client_destroy(pointer_client);
	}

	wl_list_remove(&pointer->focus_resource_listener.link);
	wl_list_remove(&pointer->focus_view_listener.link);
	wl_list_remove(&pointer->output_destroy_listener.link);
	wl_list_remove(&pointer->timestamps_list);
	free(pointer);
}

void
weston_pointer_set_default_grab(struct weston_pointer *pointer,
		const struct weston_pointer_grab_interface *interface)
{
	if (interface)
		pointer->default_grab.interface = interface;
	else
		pointer->default_grab.interface =
			&default_pointer_grab_interface;
}

static struct weston_keyboard *
weston_keyboard_create(void)
{
	struct weston_keyboard *keyboard;

	keyboard = zalloc(sizeof *keyboard);
	if (keyboard == NULL)
	    return NULL;

	wl_list_init(&keyboard->resource_list);
	wl_list_init(&keyboard->focus_resource_list);
	wl_list_init(&keyboard->focus_resource_listener.link);
	keyboard->focus_resource_listener.notify = keyboard_focus_resource_destroyed;
	wl_array_init(&keyboard->keys);
	keyboard->default_grab.interface = &default_keyboard_grab_interface;
	keyboard->default_grab.keyboard = keyboard;
	keyboard->grab = &keyboard->default_grab;
	wl_signal_init(&keyboard->focus_signal);
	wl_list_init(&keyboard->timestamps_list);

	return keyboard;
}

static void
weston_xkb_info_destroy(struct weston_xkb_info *xkb_info);

static void
weston_keyboard_destroy(struct weston_keyboard *keyboard)
{
	struct wl_resource *resource;

	wl_resource_for_each(resource, &keyboard->resource_list) {
		wl_resource_set_user_data(resource, NULL);
	}

	wl_resource_for_each(resource, &keyboard->focus_resource_list) {
		wl_resource_set_user_data(resource, NULL);
	}

	wl_list_remove(&keyboard->resource_list);
	wl_list_remove(&keyboard->focus_resource_list);

	xkb_state_unref(keyboard->xkb_state.state);
	if (keyboard->xkb_info)
		weston_xkb_info_destroy(keyboard->xkb_info);
	xkb_keymap_unref(keyboard->pending_keymap);

	wl_array_release(&keyboard->keys);
	wl_list_remove(&keyboard->focus_resource_listener.link);
	wl_list_remove(&keyboard->timestamps_list);
	free(keyboard);
}

static void
weston_touch_reset_state(struct weston_touch *touch)
{
	touch->num_tp = 0;
}

static struct weston_touch *
weston_touch_create(void)
{
	struct weston_touch *touch;

	touch = zalloc(sizeof *touch);
	if (touch == NULL)
		return NULL;

	wl_list_init(&touch->device_list);
	wl_list_init(&touch->resource_list);
	wl_list_init(&touch->focus_resource_list);
	wl_list_init(&touch->focus_view_listener.link);
	touch->focus_view_listener.notify = touch_focus_view_destroyed;
	wl_list_init(&touch->focus_resource_listener.link);
	touch->focus_resource_listener.notify = touch_focus_resource_destroyed;
	touch->default_grab.interface = &default_touch_grab_interface;
	touch->default_grab.touch = touch;
	touch->grab = &touch->default_grab;
	wl_signal_init(&touch->focus_signal);
	wl_list_init(&touch->timestamps_list);

	return touch;
}

static void
weston_touch_destroy(struct weston_touch *touch)
{
	struct wl_resource *resource;

	assert(wl_list_empty(&touch->device_list));

	wl_resource_for_each(resource, &touch->resource_list) {
		wl_resource_set_user_data(resource, NULL);
	}

	wl_resource_for_each(resource, &touch->focus_resource_list) {
		wl_resource_set_user_data(resource, NULL);
	}

	wl_list_remove(&touch->resource_list);
	wl_list_remove(&touch->focus_resource_list);
	wl_list_remove(&touch->focus_view_listener.link);
	wl_list_remove(&touch->focus_resource_listener.link);
	wl_list_remove(&touch->timestamps_list);
	free(touch);
}

static void
seat_send_updated_caps(struct weston_seat *seat)
{
	enum wl_seat_capability caps = 0;
	struct wl_resource *resource;

	if (seat->pointer_device_count > 0)
		caps |= WL_SEAT_CAPABILITY_POINTER;
	if (seat->keyboard_device_count > 0)
		caps |= WL_SEAT_CAPABILITY_KEYBOARD;
	if (seat->touch_device_count > 0)
		caps |= WL_SEAT_CAPABILITY_TOUCH;

	wl_resource_for_each(resource, &seat->base_resource_list) {
		wl_seat_send_capabilities(resource, caps);
	}
	wl_signal_emit(&seat->updated_caps_signal, seat);
}


/** Clear the pointer focus
 *
 * \param pointer the pointer to clear focus for.
 *
 * This can be used to unset pointer focus and set the co-ordinates to the
 * arbitrary values we use for the no focus case.
 *
 * There's no requirement to use this function.  For example, passing the
 * results of a weston_compositor_pick_view() directly to
 * weston_pointer_set_focus() will do the right thing when no view is found.
 */
WL_EXPORT void
weston_pointer_clear_focus(struct weston_pointer *pointer)
{
	weston_pointer_set_focus(pointer, NULL,
				 wl_fixed_from_int(-1000000),
				 wl_fixed_from_int(-1000000));
}

WL_EXPORT void
weston_pointer_set_focus(struct weston_pointer *pointer,
			 struct weston_view *view,
			 wl_fixed_t sx, wl_fixed_t sy)
{
	struct weston_pointer_client *pointer_client;
	struct weston_keyboard *kbd = weston_seat_get_keyboard(pointer->seat);
	struct wl_resource *resource;
	struct wl_resource *surface_resource;
	struct wl_display *display = pointer->seat->compositor->wl_display;
	uint32_t serial;
	struct wl_list *focus_resource_list;
	int refocus = 0;

	if ((!pointer->focus && view) ||
	    (pointer->focus && !view) ||
	    (pointer->focus && pointer->focus->surface != view->surface) ||
	    pointer->sx != sx || pointer->sy != sy)
		refocus = 1;

	if (pointer->focus_client && refocus) {
		focus_resource_list = &pointer->focus_client->pointer_resources;
		if (!wl_list_empty(focus_resource_list)) {
			serial = wl_display_next_serial(display);
			surface_resource = pointer->focus->surface->resource;
			wl_resource_for_each(resource, focus_resource_list) {
				wl_pointer_send_leave(resource, serial,
						      surface_resource);
				pointer_send_frame(resource);
			}
		}

		pointer->focus_client = NULL;
	}

	pointer_client = find_pointer_client_for_view(pointer, view);
	if (pointer_client && refocus) {
		struct wl_client *surface_client = pointer_client->client;

		serial = wl_display_next_serial(display);

		if (kbd && kbd->focus != view->surface)
			send_modifiers_to_client_in_list(surface_client,
							 &kbd->resource_list,
							 serial,
							 kbd);

		pointer->focus_client = pointer_client;

		focus_resource_list = &pointer->focus_client->pointer_resources;
		wl_resource_for_each(resource, focus_resource_list) {
			wl_pointer_send_enter(resource,
					      serial,
					      view->surface->resource,
					      sx, sy);
			pointer_send_frame(resource);
		}

		pointer->focus_serial = serial;
	}

	wl_list_remove(&pointer->focus_view_listener.link);
	wl_list_init(&pointer->focus_view_listener.link);
	wl_list_remove(&pointer->focus_resource_listener.link);
	wl_list_init(&pointer->focus_resource_listener.link);
	if (view)
		wl_signal_add(&view->destroy_signal, &pointer->focus_view_listener);
	if (view && view->surface->resource)
		wl_resource_add_destroy_listener(view->surface->resource,
						 &pointer->focus_resource_listener);

	pointer->focus = view;
	pointer->focus_view_listener.notify = pointer_focus_view_destroyed;
	pointer->sx = sx;
	pointer->sy = sy;

	assert(view || sx == wl_fixed_from_int(-1000000));
	assert(view || sy == wl_fixed_from_int(-1000000));

	wl_signal_emit(&pointer->focus_signal, pointer);
}

static void
send_enter_to_resource_list(struct wl_list *list,
			    struct weston_keyboard *keyboard,
			    struct weston_surface *surface,
			    uint32_t serial)
{
	struct wl_resource *resource;

	wl_resource_for_each(resource, list) {
		send_modifiers_to_resource(keyboard, resource, serial);
		wl_keyboard_send_enter(resource, serial,
				       surface->resource,
				       &keyboard->keys);
	}
}

WL_EXPORT void
weston_keyboard_set_focus(struct weston_keyboard *keyboard,
			  struct weston_surface *surface)
{
	struct weston_seat *seat = keyboard->seat;
	struct wl_resource *resource;
	struct wl_display *display = keyboard->seat->compositor->wl_display;
	uint32_t serial;
	struct wl_list *focus_resource_list;

	/* Keyboard focus on a surface without a client is equivalent to NULL
	 * focus as nothing would react to the keyboard events anyway.
	 * Just set focus to NULL instead - the destroy listener hangs on the
	 * wl_resource anyway.
	 */
	if (surface && !surface->resource)
		surface = NULL;

	focus_resource_list = &keyboard->focus_resource_list;

	if (!wl_list_empty(focus_resource_list) && keyboard->focus != surface) {
		serial = wl_display_next_serial(display);
		wl_resource_for_each(resource, focus_resource_list) {
			wl_keyboard_send_leave(resource, serial,
					keyboard->focus->resource);
		}
		move_resources(&keyboard->resource_list, focus_resource_list);
	}

	if (find_resource_for_surface(&keyboard->resource_list, surface) &&
	    keyboard->focus != surface) {
		struct wl_client *surface_client =
			wl_resource_get_client(surface->resource);

		serial = wl_display_next_serial(display);

		move_resources_for_client(focus_resource_list,
					  &keyboard->resource_list,
					  surface_client);
		send_enter_to_resource_list(focus_resource_list,
					    keyboard,
					    surface,
					    serial);
		keyboard->focus_serial = serial;
	}

	if (seat->saved_kbd_focus) {
		wl_list_remove(&seat->saved_kbd_focus_listener.link);
		seat->saved_kbd_focus = NULL;
	}

	wl_list_remove(&keyboard->focus_resource_listener.link);
	wl_list_init(&keyboard->focus_resource_listener.link);
	if (surface)
		wl_resource_add_destroy_listener(surface->resource,
						 &keyboard->focus_resource_listener);

	keyboard->focus = surface;
	wl_signal_emit(&keyboard->focus_signal, keyboard);
}

/* Users of this function must manually manage the keyboard focus */
WL_EXPORT void
weston_keyboard_start_grab(struct weston_keyboard *keyboard,
			   struct weston_keyboard_grab *grab)
{
	keyboard->grab = grab;
	grab->keyboard = keyboard;
}

WL_EXPORT void
weston_keyboard_end_grab(struct weston_keyboard *keyboard)
{
	keyboard->grab = &keyboard->default_grab;
}

static void
weston_keyboard_cancel_grab(struct weston_keyboard *keyboard)
{
	keyboard->grab->interface->cancel(keyboard->grab);
}

WL_EXPORT void
weston_pointer_start_grab(struct weston_pointer *pointer,
			  struct weston_pointer_grab *grab)
{
	pointer->grab = grab;
	grab->pointer = pointer;
	pointer->grab->interface->focus(pointer->grab);
}

WL_EXPORT void
weston_pointer_end_grab(struct weston_pointer *pointer)
{
	pointer->grab = &pointer->default_grab;
	pointer->grab->interface->focus(pointer->grab);
}

static void
weston_pointer_cancel_grab(struct weston_pointer *pointer)
{
	pointer->grab->interface->cancel(pointer->grab);
}

WL_EXPORT void
weston_touch_start_grab(struct weston_touch *touch, struct weston_touch_grab *grab)
{
	touch->grab = grab;
	grab->touch = touch;
}

WL_EXPORT void
weston_touch_end_grab(struct weston_touch *touch)
{
	touch->grab = &touch->default_grab;
}

static void
weston_touch_cancel_grab(struct weston_touch *touch)
{
	touch->grab->interface->cancel(touch->grab);
}

static void
weston_pointer_clamp_for_output(struct weston_pointer *pointer,
				struct weston_output *output,
				wl_fixed_t *fx, wl_fixed_t *fy)
{
	int x, y;

	x = wl_fixed_to_int(*fx);
	y = wl_fixed_to_int(*fy);

	if (x < output->x)
		*fx = wl_fixed_from_int(output->x);
	else if (x >= output->x + output->width)
		*fx = wl_fixed_from_int(output->x +
					output->width - 1);
	if (y < output->y)
		*fy = wl_fixed_from_int(output->y);
	else if (y >= output->y + output->height)
		*fy = wl_fixed_from_int(output->y +
					output->height - 1);
}

WL_EXPORT void
weston_pointer_clamp(struct weston_pointer *pointer, wl_fixed_t *fx, wl_fixed_t *fy)
{
	struct weston_compositor *ec = pointer->seat->compositor;
	struct weston_output *output, *prev = NULL;
	int x, y, old_x, old_y, valid = 0;

	x = wl_fixed_to_int(*fx);
	y = wl_fixed_to_int(*fy);
	old_x = wl_fixed_to_int(pointer->x);
	old_y = wl_fixed_to_int(pointer->y);

	wl_list_for_each(output, &ec->output_list, link) {
		if (pointer->seat->output && pointer->seat->output != output)
			continue;
		if (pixman_region32_contains_point(&output->region,
						   x, y, NULL))
			valid = 1;
		if (pixman_region32_contains_point(&output->region,
						   old_x, old_y, NULL))
			prev = output;
	}

	if (!prev)
		prev = pointer->seat->output;

	if (prev && !valid)
		weston_pointer_clamp_for_output(pointer, prev, fx, fy);
}

static void
weston_pointer_move_to(struct weston_pointer *pointer,
		       wl_fixed_t x, wl_fixed_t y)
{
	int32_t ix, iy;

	weston_pointer_clamp (pointer, &x, &y);

	pointer->x = x;
	pointer->y = y;

	ix = wl_fixed_to_int(x);
	iy = wl_fixed_to_int(y);

	if (pointer->sprite) {
		weston_view_set_position(pointer->sprite,
					 ix - pointer->hotspot_x,
					 iy - pointer->hotspot_y);
		weston_view_schedule_repaint(pointer->sprite);
	}

	pointer->grab->interface->focus(pointer->grab);
	wl_signal_emit(&pointer->motion_signal, pointer);
}

WL_EXPORT void
weston_pointer_move(struct weston_pointer *pointer,
		    struct weston_pointer_motion_event *event)
{
	wl_fixed_t x, y;

	weston_pointer_motion_to_abs(pointer, event, &x, &y);
	weston_pointer_move_to(pointer, x, y);
}

/** Verify if the pointer is in a valid position and move it if it isn't.
 */
static void
weston_pointer_handle_output_destroy(struct wl_listener *listener, void *data)
{
	struct weston_pointer *pointer;
	struct weston_compositor *ec;
	struct weston_output *output, *closest = NULL;
	int x, y, distance, min = INT_MAX;
	wl_fixed_t fx, fy;

	pointer = container_of(listener, struct weston_pointer,
			       output_destroy_listener);
	ec = pointer->seat->compositor;

	x = wl_fixed_to_int(pointer->x);
	y = wl_fixed_to_int(pointer->y);

	wl_list_for_each(output, &ec->output_list, link) {
		if (pixman_region32_contains_point(&output->region,
						   x, y, NULL))
			return;

		/* Aproximante the distance from the pointer to the center of
		 * the output. */
		distance = abs(output->x + output->width / 2 - x) +
			   abs(output->y + output->height / 2 - y);
		if (distance < min) {
			min = distance;
			closest = output;
		}
	}

	/* Nothing to do if there's no output left. */
	if (!closest)
		return;

	fx = pointer->x;
	fy = pointer->y;

	weston_pointer_clamp_for_output(pointer, closest, &fx, &fy);
	weston_pointer_move_to(pointer, fx, fy);
}

WL_EXPORT void
notify_motion(struct weston_seat *seat,
	      const struct timespec *time,
	      struct weston_pointer_motion_event *event)
{
	struct weston_compositor *ec = seat->compositor;
	struct weston_pointer *pointer = weston_seat_get_pointer(seat);

	weston_compositor_wake(ec);
	pointer->grab->interface->motion(pointer->grab, time, event);
}

static void
run_modifier_bindings(struct weston_seat *seat, uint32_t old, uint32_t new)
{
	struct weston_compositor *compositor = seat->compositor;
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
	uint32_t diff;
	unsigned int i;
	struct {
		uint32_t xkb;
		enum weston_keyboard_modifier weston;
	} mods[] = {
		{ keyboard->xkb_info->ctrl_mod, MODIFIER_CTRL },
		{ keyboard->xkb_info->alt_mod, MODIFIER_ALT },
		{ keyboard->xkb_info->super_mod, MODIFIER_SUPER },
		{ keyboard->xkb_info->shift_mod, MODIFIER_SHIFT },
	};

	diff = new & ~old;
	for (i = 0; i < ARRAY_LENGTH(mods); i++) {
		if (diff & (1 << mods[i].xkb))
			weston_compositor_run_modifier_binding(compositor,
			                                       keyboard,
			                                       mods[i].weston,
			                                       WL_KEYBOARD_KEY_STATE_PRESSED);
	}

	diff = old & ~new;
	for (i = 0; i < ARRAY_LENGTH(mods); i++) {
		if (diff & (1 << mods[i].xkb))
			weston_compositor_run_modifier_binding(compositor,
			                                       keyboard,
			                                       mods[i].weston,
			                                       WL_KEYBOARD_KEY_STATE_RELEASED);
	}
}

WL_EXPORT void
notify_motion_absolute(struct weston_seat *seat, const struct timespec *time,
		       double x, double y)
{
	struct weston_compositor *ec = seat->compositor;
	struct weston_pointer *pointer = weston_seat_get_pointer(seat);
	struct weston_pointer_motion_event event = { 0 };

	weston_compositor_wake(ec);

	event = (struct weston_pointer_motion_event) {
		.mask = WESTON_POINTER_MOTION_ABS,
		.x = x,
		.y = y,
	};

	pointer->grab->interface->motion(pointer->grab, time, &event);
}

static unsigned int
peek_next_activate_serial(struct weston_compositor *c)
{
	unsigned serial = c->activate_serial + 1;

	return serial == 0 ? 1 : serial;
}

static void
inc_activate_serial(struct weston_compositor *c)
{
	c->activate_serial = peek_next_activate_serial (c);
}

WL_EXPORT void
weston_view_activate(struct weston_view *view,
		     struct weston_seat *seat,
		     uint32_t flags)
{
	struct weston_compositor *compositor = seat->compositor;

	if (flags & WESTON_ACTIVATE_FLAG_CLICKED) {
		view->click_to_activate_serial =
			peek_next_activate_serial(compositor);
	}

	weston_seat_set_keyboard_focus(seat, view->surface);
}

WL_EXPORT void
notify_button(struct weston_seat *seat, const struct timespec *time,
	      int32_t button, enum wl_pointer_button_state state)
{
	struct weston_compositor *compositor = seat->compositor;
	struct weston_pointer *pointer = weston_seat_get_pointer(seat);

	if (state == WL_POINTER_BUTTON_STATE_PRESSED) {
		weston_compositor_idle_inhibit(compositor);
		if (pointer->button_count == 0) {
			pointer->grab_button = button;
			pointer->grab_time = *time;
			pointer->grab_x = pointer->x;
			pointer->grab_y = pointer->y;
		}
		pointer->button_count++;
	} else {
		weston_compositor_idle_release(compositor);
		pointer->button_count--;
	}

	weston_compositor_run_button_binding(compositor, pointer, time, button,
					     state);

	pointer->grab->interface->button(pointer->grab, time, button, state);

	if (pointer->button_count == 1)
		pointer->grab_serial =
			wl_display_get_serial(compositor->wl_display);
}

WL_EXPORT void
notify_axis(struct weston_seat *seat, const struct timespec *time,
	    struct weston_pointer_axis_event *event)
{
	struct weston_compositor *compositor = seat->compositor;
	struct weston_pointer *pointer = weston_seat_get_pointer(seat);

	weston_compositor_wake(compositor);

	if (weston_compositor_run_axis_binding(compositor, pointer,
					       time, event))
		return;

	pointer->grab->interface->axis(pointer->grab, time, event);
}

WL_EXPORT void
notify_axis_source(struct weston_seat *seat, uint32_t source)
{
	struct weston_compositor *compositor = seat->compositor;
	struct weston_pointer *pointer = weston_seat_get_pointer(seat);

	weston_compositor_wake(compositor);

	pointer->grab->interface->axis_source(pointer->grab, source);
}

WL_EXPORT void
notify_pointer_frame(struct weston_seat *seat)
{
	struct weston_compositor *compositor = seat->compositor;
	struct weston_pointer *pointer = weston_seat_get_pointer(seat);

	weston_compositor_wake(compositor);

	pointer->grab->interface->frame(pointer->grab);
}

WL_EXPORT int
weston_keyboard_set_locks(struct weston_keyboard *keyboard,
			  uint32_t mask, uint32_t value)
{
	uint32_t serial;
	xkb_mod_mask_t mods_depressed, mods_latched, mods_locked, group;
	xkb_mod_mask_t num, caps;

	/* We don't want the leds to go out of sync with the actual state
	 * so if the backend has no way to change the leds don't try to
	 * change the state */
	if (!keyboard->seat->led_update)
		return -1;

	mods_depressed = xkb_state_serialize_mods(keyboard->xkb_state.state,
						XKB_STATE_DEPRESSED);
	mods_latched = xkb_state_serialize_mods(keyboard->xkb_state.state,
						XKB_STATE_LATCHED);
	mods_locked = xkb_state_serialize_mods(keyboard->xkb_state.state,
						XKB_STATE_LOCKED);
	group = xkb_state_serialize_group(keyboard->xkb_state.state,
                                      XKB_STATE_EFFECTIVE);

	num = (1 << keyboard->xkb_info->mod2_mod);
	caps = (1 << keyboard->xkb_info->caps_mod);
	if (mask & WESTON_NUM_LOCK) {
		if (value & WESTON_NUM_LOCK)
			mods_locked |= num;
		else
			mods_locked &= ~num;
	}
	if (mask & WESTON_CAPS_LOCK) {
		if (value & WESTON_CAPS_LOCK)
			mods_locked |= caps;
		else
			mods_locked &= ~caps;
	}

	xkb_state_update_mask(keyboard->xkb_state.state, mods_depressed,
			      mods_latched, mods_locked, 0, 0, group);

	serial = wl_display_next_serial(
				keyboard->seat->compositor->wl_display);
	notify_modifiers(keyboard->seat, serial);

	return 0;
}

WL_EXPORT void
notify_modifiers(struct weston_seat *seat, uint32_t serial)
{
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
	struct weston_keyboard_grab *grab = keyboard->grab;
	uint32_t mods_depressed, mods_latched, mods_locked, group;
	uint32_t mods_lookup;
	enum weston_led leds = 0;
	int changed = 0;

	/* Serialize and update our internal state, checking to see if it's
	 * different to the previous state. */
	mods_depressed = xkb_state_serialize_mods(keyboard->xkb_state.state,
						  XKB_STATE_MODS_DEPRESSED);
	mods_latched = xkb_state_serialize_mods(keyboard->xkb_state.state,
						XKB_STATE_MODS_LATCHED);
	mods_locked = xkb_state_serialize_mods(keyboard->xkb_state.state,
					       XKB_STATE_MODS_LOCKED);
	group = xkb_state_serialize_layout(keyboard->xkb_state.state,
					   XKB_STATE_LAYOUT_EFFECTIVE);

	if (mods_depressed != keyboard->modifiers.mods_depressed ||
	    mods_latched != keyboard->modifiers.mods_latched ||
	    mods_locked != keyboard->modifiers.mods_locked ||
	    group != keyboard->modifiers.group)
		changed = 1;

	run_modifier_bindings(seat, keyboard->modifiers.mods_depressed,
	                      mods_depressed);

	keyboard->modifiers.mods_depressed = mods_depressed;
	keyboard->modifiers.mods_latched = mods_latched;
	keyboard->modifiers.mods_locked = mods_locked;
	keyboard->modifiers.group = group;

	/* And update the modifier_state for bindings. */
	mods_lookup = mods_depressed | mods_latched;
	seat->modifier_state = 0;
	if (mods_lookup & (1 << keyboard->xkb_info->ctrl_mod))
		seat->modifier_state |= MODIFIER_CTRL;
	if (mods_lookup & (1 << keyboard->xkb_info->alt_mod))
		seat->modifier_state |= MODIFIER_ALT;
	if (mods_lookup & (1 << keyboard->xkb_info->super_mod))
		seat->modifier_state |= MODIFIER_SUPER;
	if (mods_lookup & (1 << keyboard->xkb_info->shift_mod))
		seat->modifier_state |= MODIFIER_SHIFT;

	/* Finally, notify the compositor that LEDs have changed. */
	if (xkb_state_led_index_is_active(keyboard->xkb_state.state,
					  keyboard->xkb_info->num_led))
		leds |= LED_NUM_LOCK;
	if (xkb_state_led_index_is_active(keyboard->xkb_state.state,
					  keyboard->xkb_info->caps_led))
		leds |= LED_CAPS_LOCK;
	if (xkb_state_led_index_is_active(keyboard->xkb_state.state,
					  keyboard->xkb_info->scroll_led))
		leds |= LED_SCROLL_LOCK;
	if (leds != keyboard->xkb_state.leds && seat->led_update)
		seat->led_update(seat, leds);
	keyboard->xkb_state.leds = leds;

	if (changed) {
		grab->interface->modifiers(grab,
					   serial,
					   keyboard->modifiers.mods_depressed,
					   keyboard->modifiers.mods_latched,
					   keyboard->modifiers.mods_locked,
					   keyboard->modifiers.group);
	}
}

static void
update_modifier_state(struct weston_seat *seat, uint32_t serial, uint32_t key,
		      enum wl_keyboard_key_state state)
{
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
	enum xkb_key_direction direction;

	if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
		direction = XKB_KEY_DOWN;
	else
		direction = XKB_KEY_UP;

	/* Offset the keycode by 8, as the evdev XKB rules reflect X's
	 * broken keycode system, which starts at 8. */
	xkb_state_update_key(keyboard->xkb_state.state, key + 8, direction);

	notify_modifiers(seat, serial);
}

WL_EXPORT void
weston_keyboard_send_keymap(struct weston_keyboard *kbd, struct wl_resource *resource)
{
	struct weston_xkb_info *xkb_info = kbd->xkb_info;
	int fd;
	size_t size;
	enum ro_anonymous_file_mapmode mapmode;

	if (wl_resource_get_version(resource) < 7)
		mapmode = RO_ANONYMOUS_FILE_MAPMODE_SHARED;
	else
		mapmode = RO_ANONYMOUS_FILE_MAPMODE_PRIVATE;

	fd = os_ro_anonymous_file_get_fd(xkb_info->keymap_rofile, mapmode);
	size = os_ro_anonymous_file_size(xkb_info->keymap_rofile);

	if (fd == -1) {
		weston_log("creating a keymap file failed: %s\n",
			   strerror(errno));
		return;
	}

	wl_keyboard_send_keymap(resource,
				WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1,
				fd,
				size);

	os_ro_anonymous_file_put_fd(fd);
}

static void
send_modifiers(struct wl_resource *resource, uint32_t serial, struct weston_keyboard *keyboard)
{
	wl_keyboard_send_modifiers(resource, serial,
				   keyboard->modifiers.mods_depressed,
				   keyboard->modifiers.mods_latched,
				   keyboard->modifiers.mods_locked,
				   keyboard->modifiers.group);
}

static struct weston_xkb_info *
weston_xkb_info_create(struct xkb_keymap *keymap);

static void
update_keymap(struct weston_seat *seat)
{
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
	struct wl_resource *resource;
	struct weston_xkb_info *xkb_info;
	struct xkb_state *state;
	xkb_mod_mask_t latched_mods;
	xkb_mod_mask_t locked_mods;

	xkb_info = weston_xkb_info_create(keyboard->pending_keymap);

	xkb_keymap_unref(keyboard->pending_keymap);
	keyboard->pending_keymap = NULL;

	if (!xkb_info) {
		weston_log("failed to create XKB info\n");
		return;
	}

	state = xkb_state_new(xkb_info->keymap);
	if (!state) {
		weston_log("failed to initialise XKB state\n");
		weston_xkb_info_destroy(xkb_info);
		return;
	}

	latched_mods = xkb_state_serialize_mods(keyboard->xkb_state.state,
						XKB_STATE_MODS_LATCHED);
	locked_mods = xkb_state_serialize_mods(keyboard->xkb_state.state,
					       XKB_STATE_MODS_LOCKED);
	xkb_state_update_mask(state,
			      0, /* depressed */
			      latched_mods,
			      locked_mods,
			      0, 0, 0);

	weston_xkb_info_destroy(keyboard->xkb_info);
	keyboard->xkb_info = xkb_info;

	xkb_state_unref(keyboard->xkb_state.state);
	keyboard->xkb_state.state = state;

	wl_resource_for_each(resource, &keyboard->resource_list)
		weston_keyboard_send_keymap(keyboard, resource);
	wl_resource_for_each(resource, &keyboard->focus_resource_list)
		weston_keyboard_send_keymap(keyboard, resource);

	notify_modifiers(seat, wl_display_next_serial(seat->compositor->wl_display));

	if (!latched_mods && !locked_mods)
		return;

	wl_resource_for_each(resource, &keyboard->resource_list)
		send_modifiers(resource, wl_display_get_serial(seat->compositor->wl_display), keyboard);
	wl_resource_for_each(resource, &keyboard->focus_resource_list)
		send_modifiers(resource, wl_display_get_serial(seat->compositor->wl_display), keyboard);
}

WL_EXPORT void
notify_key(struct weston_seat *seat, const struct timespec *time, uint32_t key,
	   enum wl_keyboard_key_state state,
	   enum weston_key_state_update update_state)
{
	struct weston_compositor *compositor = seat->compositor;
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
	struct weston_keyboard_grab *grab = keyboard->grab;
	uint32_t *k, *end;

	if (state == WL_KEYBOARD_KEY_STATE_PRESSED) {
		weston_compositor_idle_inhibit(compositor);
	} else {
		weston_compositor_idle_release(compositor);
	}

	end = keyboard->keys.data + keyboard->keys.size;
	for (k = keyboard->keys.data; k < end; k++) {
		if (*k == key) {
			/* Ignore server-generated repeats. */
			if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
				return;
			*k = *--end;
		}
	}
	keyboard->keys.size = (void *) end - keyboard->keys.data;
	if (state == WL_KEYBOARD_KEY_STATE_PRESSED) {
		k = wl_array_add(&keyboard->keys, sizeof *k);
		*k = key;
	}

	if (grab == &keyboard->default_grab ||
	    grab == &keyboard->input_method_grab) {
		weston_compositor_run_key_binding(compositor, keyboard, time,
						  key, state);
		grab = keyboard->grab;
	}

	grab->interface->key(grab, time, key, state);

	if (keyboard->pending_keymap &&
	    keyboard->keys.size == 0)
		update_keymap(seat);

	if (update_state == STATE_UPDATE_AUTOMATIC) {
		update_modifier_state(seat,
				      wl_display_get_serial(compositor->wl_display),
				      key,
				      state);
	}

	keyboard->grab_serial = wl_display_get_serial(compositor->wl_display);
	if (state == WL_KEYBOARD_KEY_STATE_PRESSED) {
		keyboard->grab_time = *time;
		keyboard->grab_key = key;
	}
}

WL_EXPORT void
notify_pointer_focus(struct weston_seat *seat, struct weston_output *output,
		     double x, double y)
{
	struct weston_pointer *pointer = weston_seat_get_pointer(seat);

	if (output) {
		weston_pointer_move_to(pointer,
				       wl_fixed_from_double(x),
				       wl_fixed_from_double(y));
	} else {
		/* FIXME: We should call weston_pointer_set_focus(seat,
		 * NULL) here, but somehow that breaks re-entry... */
	}
}

static void
destroy_device_saved_kbd_focus(struct wl_listener *listener, void *data)
{
	struct weston_seat *ws;

	ws = container_of(listener, struct weston_seat,
			  saved_kbd_focus_listener);

	ws->saved_kbd_focus = NULL;
}

WL_EXPORT void
notify_keyboard_focus_in(struct weston_seat *seat, struct wl_array *keys,
			 enum weston_key_state_update update_state)
{
	struct weston_compositor *compositor = seat->compositor;
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
	struct weston_surface *surface;
	uint32_t *k, serial;

	serial = wl_display_next_serial(compositor->wl_display);
	wl_array_copy(&keyboard->keys, keys);
	wl_array_for_each(k, &keyboard->keys) {
		weston_compositor_idle_inhibit(compositor);
		if (update_state == STATE_UPDATE_AUTOMATIC)
			update_modifier_state(seat, serial, *k,
					      WL_KEYBOARD_KEY_STATE_PRESSED);
	}

	surface = seat->saved_kbd_focus;
	if (surface) {
		weston_keyboard_set_focus(keyboard, surface);
	}
}

WL_EXPORT void
notify_keyboard_focus_out(struct weston_seat *seat)
{
	struct weston_compositor *compositor = seat->compositor;
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
	struct weston_pointer *pointer = weston_seat_get_pointer(seat);
	struct weston_surface *focus = keyboard->focus;
	uint32_t *k, serial;

	serial = wl_display_next_serial(compositor->wl_display);
	wl_array_for_each(k, &keyboard->keys) {
		weston_compositor_idle_release(compositor);
		update_modifier_state(seat, serial, *k,
				      WL_KEYBOARD_KEY_STATE_RELEASED);
	}

	seat->modifier_state = 0;

	weston_keyboard_set_focus(keyboard, NULL);
	weston_keyboard_cancel_grab(keyboard);
	if (pointer)
		weston_pointer_cancel_grab(pointer);

	if (focus) {
		seat->saved_kbd_focus = focus;
		seat->saved_kbd_focus_listener.notify =
			destroy_device_saved_kbd_focus;
		wl_signal_add(&focus->destroy_signal,
			      &seat->saved_kbd_focus_listener);
	}
}

WL_EXPORT void
weston_touch_set_focus(struct weston_touch *touch, struct weston_view *view)
{
	struct wl_list *focus_resource_list;

	focus_resource_list = &touch->focus_resource_list;

	if (view && touch->focus &&
	    touch->focus->surface == view->surface) {
		touch->focus = view;
		return;
	}

	wl_list_remove(&touch->focus_resource_listener.link);
	wl_list_init(&touch->focus_resource_listener.link);
	wl_list_remove(&touch->focus_view_listener.link);
	wl_list_init(&touch->focus_view_listener.link);

	if (!wl_list_empty(focus_resource_list)) {
		move_resources(&touch->resource_list,
			       focus_resource_list);
	}

	if (view) {
		struct wl_client *surface_client;

		if (!view->surface->resource) {
			touch->focus = NULL;
			return;
		}

		surface_client = wl_resource_get_client(view->surface->resource);
		move_resources_for_client(focus_resource_list,
					  &touch->resource_list,
					  surface_client);
		wl_resource_add_destroy_listener(view->surface->resource,
						 &touch->focus_resource_listener);
		wl_signal_add(&view->destroy_signal, &touch->focus_view_listener);
	}
	touch->focus = view;
}

static void
process_touch_normal(struct weston_touch_device *device,
		     const struct timespec *time, int touch_id,
		     double double_x, double double_y, int touch_type)
{
	struct weston_touch *touch = device->aggregate;
	struct weston_touch_grab *grab = device->aggregate->grab;
	struct weston_compositor *ec = device->aggregate->seat->compositor;
	struct weston_view *ev;
	wl_fixed_t sx, sy;
	wl_fixed_t x = wl_fixed_from_double(double_x);
	wl_fixed_t y = wl_fixed_from_double(double_y);

	/* Update grab's global coordinates. */
	if (touch_id == touch->grab_touch_id && touch_type != WL_TOUCH_UP) {
		touch->grab_x = x;
		touch->grab_y = y;
	}

	switch (touch_type) {
	case WL_TOUCH_DOWN:
		/* the first finger down picks the view, and all further go
		 * to that view for the remainder of the touch session i.e.
		 * until all touch points are up again. */
		if (touch->num_tp == 1) {
			ev = weston_compositor_pick_view(ec, x, y, &sx, &sy);
			weston_touch_set_focus(touch, ev);
		} else if (!touch->focus) {
			/* Unexpected condition: We have non-initial touch but
			 * there is no focused surface.
			 */
			weston_log("touch event received with %d points down "
				   "but no surface focused\n", touch->num_tp);
			return;
		}

		weston_compositor_run_touch_binding(ec, touch,
						    time, touch_type);

		grab->interface->down(grab, time, touch_id, x, y);
		if (touch->num_tp == 1) {
			touch->grab_serial =
				wl_display_get_serial(ec->wl_display);
			touch->grab_touch_id = touch_id;
			touch->grab_time = *time;
			touch->grab_x = x;
			touch->grab_y = y;
		}

		break;
	case WL_TOUCH_MOTION:
		ev = touch->focus;
		if (!ev)
			break;

		grab->interface->motion(grab, time, touch_id, x, y);
		break;
	case WL_TOUCH_UP:
		grab->interface->up(grab, time, touch_id);
		if (touch->num_tp == 0)
			weston_touch_set_focus(touch, NULL);
		break;
	}
}

static enum weston_touch_mode
get_next_touch_mode(enum weston_touch_mode from)
{
	switch (from) {
	case WESTON_TOUCH_MODE_PREP_NORMAL:
		return WESTON_TOUCH_MODE_NORMAL;

	case WESTON_TOUCH_MODE_PREP_CALIB:
		return WESTON_TOUCH_MODE_CALIB;

	case WESTON_TOUCH_MODE_NORMAL:
	case WESTON_TOUCH_MODE_CALIB:
		return from;
	}

	return WESTON_TOUCH_MODE_NORMAL;
}

/** Global touch mode update
 *
 * If no seat has a touch down and the compositor is in a PREP touch mode,
 * set the compositor to the goal touch mode.
 *
 * Calls calibrator if touch mode changed.
 */
static void
weston_compositor_update_touch_mode(struct weston_compositor *compositor)
{
	struct weston_seat *seat;
	struct weston_touch *touch;
	enum weston_touch_mode goal;

	wl_list_for_each(seat, &compositor->seat_list, link) {
		touch = weston_seat_get_touch(seat);
		if (!touch)
			continue;

		if (touch->num_tp > 0)
			return;
	}

	goal = get_next_touch_mode(compositor->touch_mode);
	if (compositor->touch_mode != goal) {
		compositor->touch_mode = goal;
		touch_calibrator_mode_changed(compositor);
	}
}

/** Start transition to normal touch event handling
 *
 * The touch event mode changes when all touches on all touch devices have
 * been lifted. If no touches are currently down, the transition is immediate.
 *
 * \sa weston_touch_mode
 */
void
weston_compositor_set_touch_mode_normal(struct weston_compositor *compositor)
{
	switch (compositor->touch_mode) {
	case WESTON_TOUCH_MODE_PREP_NORMAL:
	case WESTON_TOUCH_MODE_NORMAL:
		return;
	case WESTON_TOUCH_MODE_PREP_CALIB:
		compositor->touch_mode = WESTON_TOUCH_MODE_NORMAL;
		touch_calibrator_mode_changed(compositor);
		return;
	case WESTON_TOUCH_MODE_CALIB:
		compositor->touch_mode = WESTON_TOUCH_MODE_PREP_NORMAL;
	}

	weston_compositor_update_touch_mode(compositor);
}

/** Start transition to calibrator touch event handling
 *
 * The touch event mode changes when all touches on all touch devices have
 * been lifted. If no touches are currently down, the transition is immediate.
 *
 * \sa weston_touch_mode
 */
void
weston_compositor_set_touch_mode_calib(struct weston_compositor *compositor)
{
	switch (compositor->touch_mode) {
	case WESTON_TOUCH_MODE_PREP_CALIB:
	case WESTON_TOUCH_MODE_CALIB:
		assert(0);
		return;
	case WESTON_TOUCH_MODE_PREP_NORMAL:
		compositor->touch_mode = WESTON_TOUCH_MODE_CALIB;
		touch_calibrator_mode_changed(compositor);
		return;
	case WESTON_TOUCH_MODE_NORMAL:
		compositor->touch_mode = WESTON_TOUCH_MODE_PREP_CALIB;
	}

	weston_compositor_update_touch_mode(compositor);
}

/** Feed in touch down, motion, and up events, calibratable device.
 *
 * It assumes always the correct cycle sequence until it gets here: touch_down
 * → touch_update → ... → touch_update → touch_end. The driver is responsible
 * for sending along such order.
 *
 * \param device The physical device that generated the event.
 * \param time The event timestamp.
 * \param touch_id ID for the touch point of this event (multi-touch).
 * \param x X coordinate in compositor global space.
 * \param y Y coordinate in compositor global space.
 * \param norm Normalized device X, Y coordinates in calibration space, or NULL.
 * \param touch_type Either WL_TOUCH_DOWN, WL_TOUCH_UP, or WL_TOUCH_MOTION.
 *
 * Coordinates double_x and double_y are used for normal operation.
 *
 * Coordinates norm are only used for touch device calibration. If and only if
 * the weston_touch_device does not support calibrating, norm must be NULL.
 *
 * The calibration space is the normalized coordinate space
 * [0.0, 1.0]×[0.0, 1.0] of the weston_touch_device. This is assumed to
 * map to the similar normalized coordinate space of the associated
 * weston_output.
 */
WL_EXPORT void
notify_touch_normalized(struct weston_touch_device *device,
			const struct timespec *time,
			int touch_id,
			double x, double y,
			const struct weston_point2d_device_normalized *norm,
			int touch_type)
{
	struct weston_seat *seat = device->aggregate->seat;
	struct weston_touch *touch = device->aggregate;

	if (touch_type != WL_TOUCH_UP) {
		if (weston_touch_device_can_calibrate(device))
			assert(norm != NULL);
		else
			assert(norm == NULL);
	}

	/* Update touchpoints count regardless of the current mode. */
	switch (touch_type) {
	case WL_TOUCH_DOWN:
		weston_compositor_idle_inhibit(seat->compositor);

		touch->num_tp++;
		break;
	case WL_TOUCH_UP:
		if (touch->num_tp == 0) {
			/* This can happen if we start out with one or
			 * more fingers on the touch screen, in which
			 * case we didn't get the corresponding down
			 * event. */
			weston_log("Unmatched touch up event on seat %s, device %s\n",
				   seat->seat_name, device->syspath);
			return;
		}
		weston_compositor_idle_release(seat->compositor);

		touch->num_tp--;
		break;
	default:
		break;
	}

	/* Properly forward the touch event */
	switch (weston_touch_device_get_mode(device)) {
	case WESTON_TOUCH_MODE_NORMAL:
	case WESTON_TOUCH_MODE_PREP_CALIB:
		process_touch_normal(device, time, touch_id, x, y, touch_type);
		break;
	case WESTON_TOUCH_MODE_CALIB:
	case WESTON_TOUCH_MODE_PREP_NORMAL:
		notify_touch_calibrator(device, time, touch_id,
					norm, touch_type);
		break;
	}
}

WL_EXPORT void
notify_touch_frame(struct weston_touch_device *device)
{
	struct weston_touch_grab *grab;

	switch (weston_touch_device_get_mode(device)) {
	case WESTON_TOUCH_MODE_NORMAL:
	case WESTON_TOUCH_MODE_PREP_CALIB:
		grab = device->aggregate->grab;
		grab->interface->frame(grab);
		break;
	case WESTON_TOUCH_MODE_CALIB:
	case WESTON_TOUCH_MODE_PREP_NORMAL:
		notify_touch_calibrator_frame(device);
		break;
	}

	weston_compositor_update_touch_mode(device->aggregate->seat->compositor);
}

WL_EXPORT void
notify_touch_cancel(struct weston_touch_device *device)
{
	struct weston_touch_grab *grab;

	switch (weston_touch_device_get_mode(device)) {
	case WESTON_TOUCH_MODE_NORMAL:
	case WESTON_TOUCH_MODE_PREP_CALIB:
		grab = device->aggregate->grab;
		grab->interface->cancel(grab);
		break;
	case WESTON_TOUCH_MODE_CALIB:
	case WESTON_TOUCH_MODE_PREP_NORMAL:
		notify_touch_calibrator_cancel(device);
		break;
	}

	weston_compositor_update_touch_mode(device->aggregate->seat->compositor);
}

static int
pointer_cursor_surface_get_label(struct weston_surface *surface,
				 char *buf, size_t len)
{
	return snprintf(buf, len, "cursor");
}

static void
pointer_cursor_surface_committed(struct weston_surface *es,
				 int32_t dx, int32_t dy)
{
	struct weston_pointer *pointer = es->committed_private;
	int x, y;

	if (es->width == 0)
		return;

	assert(es == pointer->sprite->surface);

	pointer->hotspot_x -= dx;
	pointer->hotspot_y -= dy;

	x = wl_fixed_to_int(pointer->x) - pointer->hotspot_x;
	y = wl_fixed_to_int(pointer->y) - pointer->hotspot_y;

	weston_view_set_position(pointer->sprite, x, y);

	empty_region(&es->pending.input);
	empty_region(&es->input);

	if (!weston_surface_is_mapped(es)) {
		weston_layer_entry_insert(&es->compositor->cursor_layer.view_list,
					  &pointer->sprite->layer_link);
		weston_view_update_transform(pointer->sprite);
		es->is_mapped = true;
		pointer->sprite->is_mapped = true;
	}
}

static void
pointer_set_cursor(struct wl_client *client, struct wl_resource *resource,
		   uint32_t serial, struct wl_resource *surface_resource,
		   int32_t x, int32_t y)
{
	struct weston_pointer *pointer = wl_resource_get_user_data(resource);
	struct weston_surface *surface = NULL;

	if (!pointer)
		return;

	if (surface_resource)
		surface = wl_resource_get_user_data(surface_resource);

	if (pointer->focus == NULL)
		return;
	/* pointer->focus->surface->resource can be NULL. Surfaces like the
	black_surface used in shell.c for fullscreen don't have
	a resource, but can still have focus */
	if (pointer->focus->surface->resource == NULL)
		return;
	if (wl_resource_get_client(pointer->focus->surface->resource) != client)
		return;
	if (pointer->focus_serial - serial > UINT32_MAX / 2)
		return;

	if (!surface) {
		if (pointer->sprite)
			pointer_unmap_sprite(pointer);
		return;
	}

	if (pointer->sprite && pointer->sprite->surface == surface &&
	    pointer->hotspot_x == x && pointer->hotspot_y == y)
		return;

	if (!pointer->sprite || pointer->sprite->surface != surface) {
		if (weston_surface_set_role(surface, "wl_pointer-cursor",
					    resource,
					    WL_POINTER_ERROR_ROLE) < 0)
			return;

		if (pointer->sprite)
			pointer_unmap_sprite(pointer);

		wl_signal_add(&surface->destroy_signal,
			      &pointer->sprite_destroy_listener);

		surface->committed = pointer_cursor_surface_committed;
		surface->committed_private = pointer;
		weston_surface_set_label_func(surface,
					    pointer_cursor_surface_get_label);
		pointer->sprite = weston_view_create(surface);
	}

	pointer->hotspot_x = x;
	pointer->hotspot_y = y;

	if (surface->buffer_ref.buffer) {
		pointer_cursor_surface_committed(surface, 0, 0);
		weston_view_schedule_repaint(pointer->sprite);
	}
}

static void
pointer_release(struct wl_client *client, struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static const struct wl_pointer_interface pointer_interface = {
	pointer_set_cursor,
	pointer_release
};

static void
seat_get_pointer(struct wl_client *client, struct wl_resource *resource,
		 uint32_t id)
{
	struct weston_seat *seat = wl_resource_get_user_data(resource);
	/* We use the pointer_state directly, which means we'll
	 * give a wl_pointer if the seat has ever had one - even though
	 * the spec explicitly states that this request only takes effect
	 * if the seat has the pointer capability.
	 *
	 * This prevents a race between the compositor sending new
	 * capabilities and the client trying to use the old ones.
	 */
	struct weston_pointer *pointer = seat ? seat->pointer_state : NULL;
	struct wl_resource *cr;
	struct weston_pointer_client *pointer_client;

        cr = wl_resource_create(client, &wl_pointer_interface,
				wl_resource_get_version(resource), id);
	if (cr == NULL) {
		wl_client_post_no_memory(client);
		return;
	}

	wl_list_init(wl_resource_get_link(cr));
	wl_resource_set_implementation(cr, &pointer_interface, pointer,
				       unbind_pointer_client_resource);

	/* If we don't have a pointer_state, the resource is inert, so there
	 * is nothing more to set up */
	if (!pointer)
		return;

	pointer_client = weston_pointer_ensure_pointer_client(pointer, client);
	if (!pointer_client) {
		wl_client_post_no_memory(client);
		return;
	}

	wl_list_insert(&pointer_client->pointer_resources,
		       wl_resource_get_link(cr));

	if (pointer->focus && pointer->focus->surface->resource &&
	    wl_resource_get_client(pointer->focus->surface->resource) == client) {
		wl_fixed_t sx, sy;

		weston_view_from_global_fixed(pointer->focus,
					      pointer->x,
					      pointer->y,
					      &sx, &sy);

		wl_pointer_send_enter(cr,
				      pointer->focus_serial,
				      pointer->focus->surface->resource,
				      sx, sy);
		pointer_send_frame(cr);
	}
}

static void
destroy_keyboard_resource(struct wl_resource *resource)
{
	struct weston_keyboard *keyboard = wl_resource_get_user_data(resource);

	wl_list_remove(wl_resource_get_link(resource));

	if (keyboard) {
		remove_input_resource_from_timestamps(resource,
						      &keyboard->timestamps_list);
	}
}

static void
keyboard_release(struct wl_client *client, struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static const struct wl_keyboard_interface keyboard_interface = {
	keyboard_release
};

static bool
should_send_modifiers_to_client(struct weston_seat *seat,
				struct wl_client *client)
{
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
	struct weston_pointer *pointer = weston_seat_get_pointer(seat);

	if (keyboard &&
	    keyboard->focus &&
	    keyboard->focus->resource &&
	    wl_resource_get_client(keyboard->focus->resource) == client)
		return true;

	if (pointer &&
	    pointer->focus &&
	    pointer->focus->surface->resource &&
	    wl_resource_get_client(pointer->focus->surface->resource) == client)
		return true;

	return false;
}

static void
seat_get_keyboard(struct wl_client *client, struct wl_resource *resource,
		  uint32_t id)
{
	struct weston_seat *seat = wl_resource_get_user_data(resource);
	/* We use the keyboard_state directly, which means we'll
	 * give a wl_keyboard if the seat has ever had one - even though
	 * the spec explicitly states that this request only takes effect
	 * if the seat has the keyboard capability.
	 *
	 * This prevents a race between the compositor sending new
	 * capabilities and the client trying to use the old ones.
	 */
	struct weston_keyboard *keyboard = seat ? seat->keyboard_state : NULL;
	struct wl_resource *cr;

        cr = wl_resource_create(client, &wl_keyboard_interface,
				wl_resource_get_version(resource), id);
	if (cr == NULL) {
		wl_client_post_no_memory(client);
		return;
	}

	wl_list_init(wl_resource_get_link(cr));
	wl_resource_set_implementation(cr, &keyboard_interface,
				       keyboard, destroy_keyboard_resource);

	/* If we don't have a keyboard_state, the resource is inert, so there
	 * is nothing more to set up */
	if (!keyboard)
		return;

	/* May be moved to focused list later by either
	 * weston_keyboard_set_focus or directly if this client is already
	 * focused */
	wl_list_insert(&keyboard->resource_list, wl_resource_get_link(cr));

	if (wl_resource_get_version(cr) >= WL_KEYBOARD_REPEAT_INFO_SINCE_VERSION) {
		wl_keyboard_send_repeat_info(cr,
					     seat->compositor->kb_repeat_rate,
					     seat->compositor->kb_repeat_delay);
	}

	weston_keyboard_send_keymap(keyboard, cr);

	if (should_send_modifiers_to_client(seat, client)) {
		send_modifiers_to_resource(keyboard,
					   cr,
					   keyboard->focus_serial);
	}

	if (keyboard->focus && keyboard->focus->resource &&
	    wl_resource_get_client(keyboard->focus->resource) == client) {
		struct weston_surface *surface =
			(struct weston_surface *)keyboard->focus;

		wl_list_remove(wl_resource_get_link(cr));
		wl_list_insert(&keyboard->focus_resource_list,
			       wl_resource_get_link(cr));
		wl_keyboard_send_enter(cr,
				       keyboard->focus_serial,
				       surface->resource,
				       &keyboard->keys);

		/* If this is the first keyboard resource for this
		 * client... */
		if (keyboard->focus_resource_list.prev ==
		    wl_resource_get_link(cr))
			wl_data_device_set_keyboard_focus(seat);
	}
}

static void
destroy_touch_resource(struct wl_resource *resource)
{
	struct weston_touch *touch = wl_resource_get_user_data(resource);

	wl_list_remove(wl_resource_get_link(resource));

	if (touch) {
		remove_input_resource_from_timestamps(resource,
						      &touch->timestamps_list);
	}
}

static void
touch_release(struct wl_client *client, struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static const struct wl_touch_interface touch_interface = {
	touch_release
};

static void
seat_get_touch(struct wl_client *client, struct wl_resource *resource,
	       uint32_t id)
{
	struct weston_seat *seat = wl_resource_get_user_data(resource);
	/* We use the touch_state directly, which means we'll
	 * give a wl_touch if the seat has ever had one - even though
	 * the spec explicitly states that this request only takes effect
	 * if the seat has the touch capability.
	 *
	 * This prevents a race between the compositor sending new
	 * capabilities and the client trying to use the old ones.
	 */
	struct weston_touch *touch = seat ? seat->touch_state : NULL;
	struct wl_resource *cr;

        cr = wl_resource_create(client, &wl_touch_interface,
				wl_resource_get_version(resource), id);
	if (cr == NULL) {
		wl_client_post_no_memory(client);
		return;
	}

	wl_list_init(wl_resource_get_link(cr));
	wl_resource_set_implementation(cr, &touch_interface,
				       touch, destroy_touch_resource);

	/* If we don't have a touch_state, the resource is inert, so there
	 * is nothing more to set up */
	if (!touch)
		return;

	if (touch->focus &&
	    wl_resource_get_client(touch->focus->surface->resource) == client) {
		wl_list_insert(&touch->focus_resource_list,
			       wl_resource_get_link(cr));
	} else {
		wl_list_insert(&touch->resource_list,
			       wl_resource_get_link(cr));
	}
}

static void
seat_release(struct wl_client *client, struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static const struct wl_seat_interface seat_interface = {
	seat_get_pointer,
	seat_get_keyboard,
	seat_get_touch,
	seat_release,
};

static void
bind_seat(struct wl_client *client, void *data, uint32_t version, uint32_t id)
{
	struct weston_seat *seat = data;
	struct wl_resource *resource;
	enum wl_seat_capability caps = 0;

	resource = wl_resource_create(client,
				      &wl_seat_interface, version, id);
	wl_list_insert(&seat->base_resource_list, wl_resource_get_link(resource));
	wl_resource_set_implementation(resource, &seat_interface, data,
				       unbind_resource);

	if (weston_seat_get_pointer(seat))
		caps |= WL_SEAT_CAPABILITY_POINTER;
	if (weston_seat_get_keyboard(seat))
		caps |= WL_SEAT_CAPABILITY_KEYBOARD;
	if (weston_seat_get_touch(seat))
		caps |= WL_SEAT_CAPABILITY_TOUCH;

	wl_seat_send_capabilities(resource, caps);
	if (version >= WL_SEAT_NAME_SINCE_VERSION)
		wl_seat_send_name(resource, seat->seat_name);
}

static void
relative_pointer_destroy(struct wl_client *client,
			 struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static const struct zwp_relative_pointer_v1_interface relative_pointer_interface = {
	relative_pointer_destroy
};

static void
relative_pointer_manager_destroy(struct wl_client *client,
				 struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static void
relative_pointer_manager_get_relative_pointer(struct wl_client *client,
					      struct wl_resource *resource,
					      uint32_t id,
					      struct wl_resource *pointer_resource)
{
	struct weston_pointer *pointer =
		wl_resource_get_user_data(pointer_resource);
	struct weston_pointer_client *pointer_client;
	struct wl_resource *cr;

	cr = wl_resource_create(client, &zwp_relative_pointer_v1_interface,
				wl_resource_get_version(resource), id);
	if (cr == NULL) {
		wl_client_post_no_memory(client);
		return;
	}

	pointer_client = weston_pointer_ensure_pointer_client(pointer, client);
	if (!pointer_client) {
		wl_client_post_no_memory(client);
		return;
	}

	wl_list_insert(&pointer_client->relative_pointer_resources,
		       wl_resource_get_link(cr));
	wl_resource_set_implementation(cr, &relative_pointer_interface,
				       pointer,
				       unbind_pointer_client_resource);
}

static const struct zwp_relative_pointer_manager_v1_interface relative_pointer_manager = {
	relative_pointer_manager_destroy,
	relative_pointer_manager_get_relative_pointer,
};

static void
bind_relative_pointer_manager(struct wl_client *client, void *data,
			      uint32_t version, uint32_t id)
{
	struct weston_compositor *compositor = data;
	struct wl_resource *resource;

	resource = wl_resource_create(client,
				      &zwp_relative_pointer_manager_v1_interface,
				      1, id);

	wl_resource_set_implementation(resource, &relative_pointer_manager,
				       compositor,
				       NULL);
}

WL_EXPORT int
weston_compositor_set_xkb_rule_names(struct weston_compositor *ec,
				     struct xkb_rule_names *names)
{
	if (ec->xkb_context == NULL) {
		ec->xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
		if (ec->xkb_context == NULL) {
			weston_log("failed to create XKB context\n");
			return -1;
		}
	}

	if (names)
		ec->xkb_names = *names;
	if (!ec->xkb_names.rules)
		ec->xkb_names.rules = strdup("evdev");
	if (!ec->xkb_names.model)
		ec->xkb_names.model = strdup("pc105");
	if (!ec->xkb_names.layout)
		ec->xkb_names.layout = strdup("us");

	return 0;
}

static void
weston_xkb_info_destroy(struct weston_xkb_info *xkb_info)
{
	if (--xkb_info->ref_count > 0)
		return;

	xkb_keymap_unref(xkb_info->keymap);

	os_ro_anonymous_file_destroy(xkb_info->keymap_rofile);
	free(xkb_info);
}

void
weston_compositor_xkb_destroy(struct weston_compositor *ec)
{
	free((char *) ec->xkb_names.rules);
	free((char *) ec->xkb_names.model);
	free((char *) ec->xkb_names.layout);
	free((char *) ec->xkb_names.variant);
	free((char *) ec->xkb_names.options);

	if (ec->xkb_info)
		weston_xkb_info_destroy(ec->xkb_info);
	xkb_context_unref(ec->xkb_context);
}

static struct weston_xkb_info *
weston_xkb_info_create(struct xkb_keymap *keymap)
{
	char *keymap_string;
	size_t keymap_size;
	struct weston_xkb_info *xkb_info = zalloc(sizeof *xkb_info);
	if (xkb_info == NULL)
		return NULL;

	xkb_info->keymap = xkb_keymap_ref(keymap);
	xkb_info->ref_count = 1;

	xkb_info->shift_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
						       XKB_MOD_NAME_SHIFT);
	xkb_info->caps_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
						      XKB_MOD_NAME_CAPS);
	xkb_info->ctrl_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
						      XKB_MOD_NAME_CTRL);
	xkb_info->alt_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
						     XKB_MOD_NAME_ALT);
	xkb_info->mod2_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
						      "Mod2");
	xkb_info->mod3_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
						      "Mod3");
	xkb_info->super_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
						       XKB_MOD_NAME_LOGO);
	xkb_info->mod5_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
						      "Mod5");

	xkb_info->num_led = xkb_keymap_led_get_index(xkb_info->keymap,
						     XKB_LED_NAME_NUM);
	xkb_info->caps_led = xkb_keymap_led_get_index(xkb_info->keymap,
						      XKB_LED_NAME_CAPS);
	xkb_info->scroll_led = xkb_keymap_led_get_index(xkb_info->keymap,
							XKB_LED_NAME_SCROLL);

	keymap_string = xkb_keymap_get_as_string(xkb_info->keymap,
							   XKB_KEYMAP_FORMAT_TEXT_V1);
	if (keymap_string == NULL) {
		weston_log("failed to get string version of keymap\n");
		goto err_keymap;
	}
	keymap_size = strlen(keymap_string) + 1;

	xkb_info->keymap_rofile = os_ro_anonymous_file_create(keymap_size,
							      keymap_string);
	free(keymap_string);

	if (!xkb_info->keymap_rofile) {
		weston_log("failed to create anonymous file for keymap\n");
		goto err_keymap;
	}

	return xkb_info;

err_keymap:
	xkb_keymap_unref(xkb_info->keymap);
	free(xkb_info);
	return NULL;
}

static int
weston_compositor_build_global_keymap(struct weston_compositor *ec)
{
	struct xkb_keymap *keymap;

	if (ec->xkb_info != NULL)
		return 0;

	keymap = xkb_keymap_new_from_names(ec->xkb_context,
					   &ec->xkb_names,
					   0);
	if (keymap == NULL) {
		weston_log("failed to compile global XKB keymap\n");
		weston_log("  tried rules %s, model %s, layout %s, variant %s, "
			"options %s\n",
			ec->xkb_names.rules, ec->xkb_names.model,
			ec->xkb_names.layout, ec->xkb_names.variant,
			ec->xkb_names.options);
		return -1;
	}

	ec->xkb_info = weston_xkb_info_create(keymap);
	xkb_keymap_unref(keymap);
	if (ec->xkb_info == NULL)
		return -1;

	return 0;
}

WL_EXPORT void
weston_seat_update_keymap(struct weston_seat *seat, struct xkb_keymap *keymap)
{
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);

	if (!keyboard || !keymap)
		return;

	xkb_keymap_unref(keyboard->pending_keymap);
	keyboard->pending_keymap = xkb_keymap_ref(keymap);

	if (keyboard->keys.size == 0)
		update_keymap(seat);
}

WL_EXPORT int
weston_seat_init_keyboard(struct weston_seat *seat, struct xkb_keymap *keymap)
{
	struct weston_keyboard *keyboard;

	if (seat->keyboard_state) {
		seat->keyboard_device_count += 1;
		if (seat->keyboard_device_count == 1)
			seat_send_updated_caps(seat);
		return 0;
	}

	keyboard = weston_keyboard_create();
	if (keyboard == NULL) {
		weston_log("failed to allocate weston keyboard struct\n");
		return -1;
	}

	if (keymap != NULL) {
		keyboard->xkb_info = weston_xkb_info_create(keymap);
		if (keyboard->xkb_info == NULL)
			goto err;
	} else {
		if (weston_compositor_build_global_keymap(seat->compositor) < 0)
			goto err;
		keyboard->xkb_info = seat->compositor->xkb_info;
		keyboard->xkb_info->ref_count++;
	}

	keyboard->xkb_state.state = xkb_state_new(keyboard->xkb_info->keymap);
	if (keyboard->xkb_state.state == NULL) {
		weston_log("failed to initialise XKB state\n");
		goto err;
	}

	keyboard->xkb_state.leds = 0;

	seat->keyboard_state = keyboard;
	seat->keyboard_device_count = 1;
	keyboard->seat = seat;

	seat_send_updated_caps(seat);

	return 0;

err:
	if (keyboard->xkb_info)
		weston_xkb_info_destroy(keyboard->xkb_info);
	free(keyboard);

	return -1;
}

static void
weston_keyboard_reset_state(struct weston_keyboard *keyboard)
{
	struct weston_seat *seat = keyboard->seat;
	struct xkb_state *state;

	state = xkb_state_new(keyboard->xkb_info->keymap);
	if (!state) {
		weston_log("failed to reset XKB state\n");
		return;
	}
	xkb_state_unref(keyboard->xkb_state.state);
	keyboard->xkb_state.state = state;

	keyboard->xkb_state.leds = 0;

	seat->modifier_state = 0;
}

WL_EXPORT void
weston_seat_release_keyboard(struct weston_seat *seat)
{
	seat->keyboard_device_count--;
	assert(seat->keyboard_device_count >= 0);
	if (seat->keyboard_device_count == 0) {
		weston_keyboard_set_focus(seat->keyboard_state, NULL);
		weston_keyboard_cancel_grab(seat->keyboard_state);
		weston_keyboard_reset_state(seat->keyboard_state);
		seat_send_updated_caps(seat);
	}
}

WL_EXPORT void
weston_seat_init_pointer(struct weston_seat *seat)
{
	struct weston_pointer *pointer;

	if (seat->pointer_state) {
		seat->pointer_device_count += 1;
		if (seat->pointer_device_count == 1)
			seat_send_updated_caps(seat);
		return;
	}

	pointer = weston_pointer_create(seat);
	if (pointer == NULL)
		return;

	seat->pointer_state = pointer;
	seat->pointer_device_count = 1;
	pointer->seat = seat;

	seat_send_updated_caps(seat);
}

WL_EXPORT void
weston_seat_release_pointer(struct weston_seat *seat)
{
	struct weston_pointer *pointer = seat->pointer_state;

	seat->pointer_device_count--;
	if (seat->pointer_device_count == 0) {
		weston_pointer_clear_focus(pointer);
		weston_pointer_cancel_grab(pointer);

		if (pointer->sprite)
			pointer_unmap_sprite(pointer);

		weston_pointer_reset_state(pointer);
		seat_send_updated_caps(seat);

		/* seat->pointer is intentionally not destroyed so that
		 * a newly attached pointer on this seat will retain
		 * the previous cursor co-ordinates.
		 */
	}
}

WL_EXPORT void
weston_seat_init_touch(struct weston_seat *seat)
{
	struct weston_touch *touch;

	if (seat->touch_state) {
		seat->touch_device_count += 1;
		if (seat->touch_device_count == 1)
			seat_send_updated_caps(seat);
		return;
	}

	touch = weston_touch_create();
	if (touch == NULL)
		return;

	seat->touch_state = touch;
	seat->touch_device_count = 1;
	touch->seat = seat;

	seat_send_updated_caps(seat);
}

WL_EXPORT void
weston_seat_release_touch(struct weston_seat *seat)
{
	seat->touch_device_count--;
	if (seat->touch_device_count == 0) {
		weston_touch_set_focus(seat->touch_state, NULL);
		weston_touch_cancel_grab(seat->touch_state);
		weston_touch_reset_state(seat->touch_state);
		seat_send_updated_caps(seat);
	}
}

WL_EXPORT void
weston_seat_init(struct weston_seat *seat, struct weston_compositor *ec,
		 const char *seat_name)
{
	memset(seat, 0, sizeof *seat);

	seat->selection_data_source = NULL;
	wl_list_init(&seat->base_resource_list);
	wl_signal_init(&seat->selection_signal);
	wl_list_init(&seat->drag_resource_list);
	wl_signal_init(&seat->destroy_signal);
	wl_signal_init(&seat->updated_caps_signal);

	seat->global = wl_global_create(ec->wl_display, &wl_seat_interface,
					MIN(wl_seat_interface.version, 7),
					seat, bind_seat);

	seat->compositor = ec;
	seat->modifier_state = 0;
	seat->seat_name = strdup(seat_name);

	wl_list_insert(ec->seat_list.prev, &seat->link);

	clipboard_create(seat);

	wl_signal_emit(&ec->seat_created_signal, seat);
}

WL_EXPORT void
weston_seat_release(struct weston_seat *seat)
{
	struct wl_resource *resource;

	wl_resource_for_each(resource, &seat->base_resource_list) {
		wl_resource_set_user_data(resource, NULL);
	}

	wl_resource_for_each(resource, &seat->drag_resource_list) {
		wl_resource_set_user_data(resource, NULL);
	}

	wl_list_remove(&seat->base_resource_list);
	wl_list_remove(&seat->drag_resource_list);

	wl_list_remove(&seat->link);

	if (seat->saved_kbd_focus)
		wl_list_remove(&seat->saved_kbd_focus_listener.link);

	if (seat->pointer_state)
		weston_pointer_destroy(seat->pointer_state);
	if (seat->keyboard_state)
		weston_keyboard_destroy(seat->keyboard_state);
	if (seat->touch_state)
		weston_touch_destroy(seat->touch_state);

	free (seat->seat_name);

	wl_global_destroy(seat->global);

	wl_signal_emit(&seat->destroy_signal, seat);
}

/** Get a seat's keyboard pointer
 *
 * \param seat The seat to query
 * \return The seat's keyboard pointer, or NULL if no keyboard is present
 *
 * The keyboard pointer for a seat isn't freed when all keyboards are removed,
 * so it should only be used when the seat's keyboard_device_count is greater
 * than zero.  This function does that test and only returns a pointer
 * when a keyboard is present.
 */
WL_EXPORT struct weston_keyboard *
weston_seat_get_keyboard(struct weston_seat *seat)
{
	if (!seat)
		return NULL;

	if (seat->keyboard_device_count)
		return seat->keyboard_state;

	return NULL;
}

/** Get a seat's pointer pointer
 *
 * \param seat The seat to query
 * \return The seat's pointer pointer, or NULL if no pointer device is present
 *
 * The pointer pointer for a seat isn't freed when all mice are removed,
 * so it should only be used when the seat's pointer_device_count is greater
 * than zero.  This function does that test and only returns a pointer
 * when a pointing device is present.
 */
WL_EXPORT struct weston_pointer *
weston_seat_get_pointer(struct weston_seat *seat)
{
	if (!seat)
		return NULL;

	if (seat->pointer_device_count)
		return seat->pointer_state;

	return NULL;
}

static const struct zwp_locked_pointer_v1_interface locked_pointer_interface;
static const struct zwp_confined_pointer_v1_interface confined_pointer_interface;

static enum pointer_constraint_type
pointer_constraint_get_type(struct weston_pointer_constraint *constraint)
{
	if (wl_resource_instance_of(constraint->resource,
				    &zwp_locked_pointer_v1_interface,
				    &locked_pointer_interface)) {
		return POINTER_CONSTRAINT_TYPE_LOCK;
	} else if (wl_resource_instance_of(constraint->resource,
					   &zwp_confined_pointer_v1_interface,
					   &confined_pointer_interface)) {
		return POINTER_CONSTRAINT_TYPE_CONFINE;
	}

	abort();
	return 0;
}

static void
pointer_constraint_notify_activated(struct weston_pointer_constraint *constraint)
{
	struct wl_resource *resource = constraint->resource;

	switch (pointer_constraint_get_type(constraint)) {
	case POINTER_CONSTRAINT_TYPE_LOCK:
		zwp_locked_pointer_v1_send_locked(resource);
		break;
	case POINTER_CONSTRAINT_TYPE_CONFINE:
		zwp_confined_pointer_v1_send_confined(resource);
		break;
	}
}

static void
pointer_constraint_notify_deactivated(struct weston_pointer_constraint *constraint)
{
	struct wl_resource *resource = constraint->resource;

	switch (pointer_constraint_get_type(constraint)) {
	case POINTER_CONSTRAINT_TYPE_LOCK:
		zwp_locked_pointer_v1_send_unlocked(resource);
		break;
	case POINTER_CONSTRAINT_TYPE_CONFINE:
		zwp_confined_pointer_v1_send_unconfined(resource);
		break;
	}
}

static struct weston_pointer_constraint *
get_pointer_constraint_for_pointer(struct weston_surface *surface,
				   struct weston_pointer *pointer)
{
	struct weston_pointer_constraint *constraint;

	wl_list_for_each(constraint, &surface->pointer_constraints, link) {
		if (constraint->pointer == pointer)
			return constraint;
	}

	return NULL;
}

/** Get a seat's touch pointer
 *
 * \param seat The seat to query
 * \return The seat's touch pointer, or NULL if no touch device is present
 *
 * The touch pointer for a seat isn't freed when all touch devices are removed,
 * so it should only be used when the seat's touch_device_count is greater
 * than zero.  This function does that test and only returns a pointer
 * when a touch device is present.
 */
WL_EXPORT struct weston_touch *
weston_seat_get_touch(struct weston_seat *seat)
{
	if (!seat)
		return NULL;

	if (seat->touch_device_count)
		return seat->touch_state;

	return NULL;
}

/** Sets the keyboard focus to the given surface
 *
 * \param surface the surface to focus on
 * \param seat The seat to query
 */
WL_EXPORT void
weston_seat_set_keyboard_focus(struct weston_seat *seat,
			       struct weston_surface *surface)
{
	struct weston_compositor *compositor = seat->compositor;
	struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
	struct weston_surface_activation_data activation_data;

	if (keyboard && keyboard->focus != surface) {
		weston_keyboard_set_focus(keyboard, surface);
		wl_data_device_set_keyboard_focus(seat);
	}

	inc_activate_serial(compositor);

	activation_data = (struct weston_surface_activation_data) {
		.surface = surface,
		.seat = seat,
	};
	wl_signal_emit(&compositor->activate_signal, &activation_data);
}

static void
enable_pointer_constraint(struct weston_pointer_constraint *constraint,
			  struct weston_view *view)
{
	assert(constraint->view == NULL);
	constraint->view = view;
	pointer_constraint_notify_activated(constraint);
	weston_pointer_start_grab(constraint->pointer, &constraint->grab);
	wl_list_remove(&constraint->surface_destroy_listener.link);
	wl_list_init(&constraint->surface_destroy_listener.link);
}

static bool
is_pointer_constraint_enabled(struct weston_pointer_constraint *constraint)
{
	return constraint->view != NULL;
}

static void
weston_pointer_constraint_disable(struct weston_pointer_constraint *constraint)
{
	constraint->view = NULL;
	pointer_constraint_notify_deactivated(constraint);
	weston_pointer_end_grab(constraint->grab.pointer);
}

void
weston_pointer_constraint_destroy(struct weston_pointer_constraint *constraint)
{
	if (is_pointer_constraint_enabled(constraint))
		weston_pointer_constraint_disable(constraint);

	wl_list_remove(&constraint->pointer_destroy_listener.link);
	wl_list_remove(&constraint->surface_destroy_listener.link);
	wl_list_remove(&constraint->surface_commit_listener.link);
	wl_list_remove(&constraint->surface_activate_listener.link);

	wl_resource_set_user_data(constraint->resource, NULL);
	pixman_region32_fini(&constraint->region);
	wl_list_remove(&constraint->link);
	free(constraint);
}

static void
disable_pointer_constraint(struct weston_pointer_constraint *constraint)
{
	switch (constraint->lifetime) {
	case ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ONESHOT:
		weston_pointer_constraint_destroy(constraint);
		break;
	case ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT:
		weston_pointer_constraint_disable(constraint);
		break;
	}
}

static bool
is_within_constraint_region(struct weston_pointer_constraint *constraint,
			    wl_fixed_t sx, wl_fixed_t sy)
{
	struct weston_surface *surface = constraint->surface;
	pixman_region32_t constraint_region;
	bool result;

	pixman_region32_init(&constraint_region);
	pixman_region32_intersect(&constraint_region,
				  &surface->input,
				  &constraint->region);
	result = pixman_region32_contains_point(&constraint_region,
						wl_fixed_to_int(sx),
						wl_fixed_to_int(sy),
						NULL);
	pixman_region32_fini(&constraint_region);

	return result;
}

static void
maybe_enable_pointer_constraint(struct weston_pointer_constraint *constraint)
{
	struct weston_surface *surface = constraint->surface;
	struct weston_view *vit;
	struct weston_view *view = NULL;
	struct weston_pointer *pointer = constraint->pointer;
	struct weston_keyboard *keyboard;
	struct weston_seat *seat = pointer->seat;
	int32_t x, y;

	/* Postpone if no view of the surface was most recently clicked. */
	wl_list_for_each(vit, &surface->views, surface_link) {
		if (vit->click_to_activate_serial ==
		    surface->compositor->activate_serial) {
			view = vit;
		}
	}
	if (view == NULL)
		return;

	/* Postpone if surface doesn't have keyboard focus. */
	keyboard = weston_seat_get_keyboard(seat);
	if (!keyboard || keyboard->focus != surface)
		return;

	/* Postpone constraint if the pointer is not within the
	 * constraint region.
	 */
	weston_view_from_global(view,
				wl_fixed_to_int(pointer->x),
				wl_fixed_to_int(pointer->y),
				&x, &y);
	if (!is_within_constraint_region(constraint,
					 wl_fixed_from_int(x),
					 wl_fixed_from_int(y)))
		return;

	enable_pointer_constraint(constraint, view);
}

static void
locked_pointer_grab_pointer_focus(struct weston_pointer_grab *grab)
{
}

static void
locked_pointer_grab_pointer_motion(struct weston_pointer_grab *grab,
				   const struct timespec *time,
				   struct weston_pointer_motion_event *event)
{
	pointer_send_relative_motion(grab->pointer, time, event);
}

static void
locked_pointer_grab_pointer_button(struct weston_pointer_grab *grab,
				   const struct timespec *time,
				   uint32_t button,
				   uint32_t state_w)
{
	weston_pointer_send_button(grab->pointer, time, button, state_w);
}

static void
locked_pointer_grab_pointer_axis(struct weston_pointer_grab *grab,
				 const struct timespec *time,
				 struct weston_pointer_axis_event *event)
{
	weston_pointer_send_axis(grab->pointer, time, event);
}

static void
locked_pointer_grab_pointer_axis_source(struct weston_pointer_grab *grab,
					uint32_t source)
{
	weston_pointer_send_axis_source(grab->pointer, source);
}

static void
locked_pointer_grab_pointer_frame(struct weston_pointer_grab *grab)
{
	weston_pointer_send_frame(grab->pointer);
}

static void
locked_pointer_grab_pointer_cancel(struct weston_pointer_grab *grab)
{
	struct weston_pointer_constraint *constraint =
		container_of(grab, struct weston_pointer_constraint, grab);

	disable_pointer_constraint(constraint);
}

static const struct weston_pointer_grab_interface
				locked_pointer_grab_interface = {
	locked_pointer_grab_pointer_focus,
	locked_pointer_grab_pointer_motion,
	locked_pointer_grab_pointer_button,
	locked_pointer_grab_pointer_axis,
	locked_pointer_grab_pointer_axis_source,
	locked_pointer_grab_pointer_frame,
	locked_pointer_grab_pointer_cancel,
};

static void
pointer_constraint_constrain_resource_destroyed(struct wl_resource *resource)
{
	struct weston_pointer_constraint *constraint =
		wl_resource_get_user_data(resource);

	if (!constraint)
		return;

	weston_pointer_constraint_destroy(constraint);
}

static void
pointer_constraint_surface_activate(struct wl_listener *listener, void *data)
{
	struct weston_surface_activation_data *activation = data;
	struct weston_pointer *pointer;
	struct weston_surface *focus = activation->surface;
	struct weston_pointer_constraint *constraint =
		container_of(listener, struct weston_pointer_constraint,
			     surface_activate_listener);
	bool is_constraint_surface;

	pointer = weston_seat_get_pointer(activation->seat);
	if (!pointer)
		return;

	is_constraint_surface =
		get_pointer_constraint_for_pointer(focus, pointer) == constraint;

	if (is_constraint_surface &&
	    !is_pointer_constraint_enabled(constraint))
		maybe_enable_pointer_constraint(constraint);
	else if (!is_constraint_surface &&
		 is_pointer_constraint_enabled(constraint))
		disable_pointer_constraint(constraint);
}

static void
pointer_constraint_pointer_destroyed(struct wl_listener *listener, void *data)
{
	struct weston_pointer_constraint *constraint =
		container_of(listener, struct weston_pointer_constraint,
			     pointer_destroy_listener);

	weston_pointer_constraint_destroy(constraint);
}

static void
pointer_constraint_surface_destroyed(struct wl_listener *listener, void *data)
{
	struct weston_pointer_constraint *constraint =
		container_of(listener, struct weston_pointer_constraint,
			     surface_destroy_listener);

	weston_pointer_constraint_destroy(constraint);
}

static void
pointer_constraint_surface_committed(struct wl_listener *listener, void *data)
{
	struct weston_pointer_constraint *constraint =
		container_of(listener, struct weston_pointer_constraint,
			     surface_commit_listener);

	if (constraint->region_is_pending) {
		constraint->region_is_pending = false;
		pixman_region32_copy(&constraint->region,
				     &constraint->region_pending);
		pixman_region32_fini(&constraint->region_pending);
		pixman_region32_init(&constraint->region_pending);
	}

	if (constraint->hint_is_pending) {
		constraint->hint_is_pending = false;

		constraint->hint_is_pending = true;
		constraint->hint_x = constraint->hint_x_pending;
		constraint->hint_y = constraint->hint_y_pending;
	}

	if (pointer_constraint_get_type(constraint) ==
	    POINTER_CONSTRAINT_TYPE_CONFINE &&
	    is_pointer_constraint_enabled(constraint))
		maybe_warp_confined_pointer(constraint);
}

static struct weston_pointer_constraint *
weston_pointer_constraint_create(struct weston_surface *surface,
				 struct weston_pointer *pointer,
				 struct weston_region *region,
				 enum zwp_pointer_constraints_v1_lifetime lifetime,
				 struct wl_resource *cr,
				 const struct weston_pointer_grab_interface *grab_interface)
{
	struct weston_pointer_constraint *constraint;

	constraint = zalloc(sizeof *constraint);
	if (!constraint)
		return NULL;

	constraint->lifetime = lifetime;
	pixman_region32_init(&constraint->region);
	pixman_region32_init(&constraint->region_pending);
	wl_list_insert(&surface->pointer_constraints, &constraint->link);
	constraint->surface = surface;
	constraint->pointer = pointer;
	constraint->resource = cr;
	constraint->grab.interface = grab_interface;
	if (region) {
		pixman_region32_copy(&constraint->region,
				     &region->region);
	} else {
		pixman_region32_fini(&constraint->region);
		region_init_infinite(&constraint->region);
	}

	constraint->surface_activate_listener.notify =
		pointer_constraint_surface_activate;
	constraint->surface_destroy_listener.notify =
		pointer_constraint_surface_destroyed;
	constraint->surface_commit_listener.notify =
		pointer_constraint_surface_committed;
	constraint->pointer_destroy_listener.notify =
		pointer_constraint_pointer_destroyed;

	wl_signal_add(&surface->compositor->activate_signal,
		      &constraint->surface_activate_listener);
	wl_signal_add(&pointer->destroy_signal,
		      &constraint->pointer_destroy_listener);
	wl_signal_add(&surface->destroy_signal,
		      &constraint->surface_destroy_listener);
	wl_signal_add(&surface->commit_signal,
		      &constraint->surface_commit_listener);

	return constraint;
}

static void
init_pointer_constraint(struct wl_resource *pointer_constraints_resource,
			uint32_t id,
			struct weston_surface *surface,
			struct weston_pointer *pointer,
			struct weston_region *region,
			enum zwp_pointer_constraints_v1_lifetime lifetime,
			const struct wl_interface *interface,
			const void *implementation,
			const struct weston_pointer_grab_interface *grab_interface)
{
	struct wl_client *client =
		wl_resource_get_client(pointer_constraints_resource);
	struct wl_resource *cr;
	struct weston_pointer_constraint *constraint;

	if (pointer && get_pointer_constraint_for_pointer(surface, pointer)) {
		wl_resource_post_error(pointer_constraints_resource,
				       ZWP_POINTER_CONSTRAINTS_V1_ERROR_ALREADY_CONSTRAINED,
				       "the pointer has a lock/confine request on this surface");
		return;
	}

	cr = wl_resource_create(client, interface,
				wl_resource_get_version(pointer_constraints_resource),
				id);
	if (cr == NULL) {
		wl_client_post_no_memory(client);
		return;
	}

	if (pointer) {
		constraint = weston_pointer_constraint_create(surface, pointer,
							      region, lifetime,
							      cr, grab_interface);
		if (constraint == NULL) {
			wl_client_post_no_memory(client);
			return;
		}
	} else {
		constraint = NULL;
	}

	wl_resource_set_implementation(cr, implementation, constraint,
				       pointer_constraint_constrain_resource_destroyed);

	if (constraint)
		maybe_enable_pointer_constraint(constraint);
}

static void
pointer_constraints_destroy(struct wl_client *client,
			    struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static void
locked_pointer_destroy(struct wl_client *client,
		       struct wl_resource *resource)
{
	struct weston_pointer_constraint *constraint =
		wl_resource_get_user_data(resource);
	wl_fixed_t x, y;

	if (constraint && constraint->view && constraint->hint_is_pending &&
	    is_within_constraint_region(constraint,
					constraint->hint_x,
					constraint->hint_y)) {
		weston_view_to_global_fixed(constraint->view,
					    constraint->hint_x,
					    constraint->hint_y,
					    &x, &y);
		weston_pointer_move_to(constraint->pointer, x, y);
	}
	wl_resource_destroy(resource);
}

static void
locked_pointer_set_cursor_position_hint(struct wl_client *client,
					struct wl_resource *resource,
					wl_fixed_t surface_x,
					wl_fixed_t surface_y)
{
	struct weston_pointer_constraint *constraint =
		wl_resource_get_user_data(resource);

	/* Ignore a set cursor hint that was sent after the lock was cancelled.
	 */
	if (!constraint ||
	    !constraint->resource ||
	    constraint->resource != resource)
		return;

	constraint->hint_is_pending = true;
	constraint->hint_x_pending = surface_x;
	constraint->hint_y_pending = surface_y;
}

static void
locked_pointer_set_region(struct wl_client *client,
			  struct wl_resource *resource,
			  struct wl_resource *region_resource)
{
	struct weston_pointer_constraint *constraint =
		wl_resource_get_user_data(resource);
	struct weston_region *region = region_resource ?
		wl_resource_get_user_data(region_resource) : NULL;

	if (!constraint)
		return;

	if (region) {
		pixman_region32_copy(&constraint->region_pending,
				     &region->region);
	} else {
		pixman_region32_fini(&constraint->region_pending);
		region_init_infinite(&constraint->region_pending);
	}
	constraint->region_is_pending = true;
}


static const struct zwp_locked_pointer_v1_interface locked_pointer_interface = {
	locked_pointer_destroy,
	locked_pointer_set_cursor_position_hint,
	locked_pointer_set_region,
};

static void
pointer_constraints_lock_pointer(struct wl_client *client,
				 struct wl_resource *resource,
				 uint32_t id,
				 struct wl_resource *surface_resource,
				 struct wl_resource *pointer_resource,
				 struct wl_resource *region_resource,
				 uint32_t lifetime)
{
	struct weston_surface *surface =
		wl_resource_get_user_data(surface_resource);
	struct weston_pointer *pointer = wl_resource_get_user_data(pointer_resource);
	struct weston_region *region = region_resource ?
		wl_resource_get_user_data(region_resource) : NULL;

	init_pointer_constraint(resource, id, surface, pointer, region, lifetime,
				&zwp_locked_pointer_v1_interface,
				&locked_pointer_interface,
				&locked_pointer_grab_interface);
}

static void
confined_pointer_grab_pointer_focus(struct weston_pointer_grab *grab)
{
}

static double
vec2d_cross_product(struct vec2d a, struct vec2d b)
{
	return a.x * b.y - a.y * b.x;
}

static struct vec2d
vec2d_add(struct vec2d a, struct vec2d b)
{
	return (struct vec2d) {
		.x = a.x + b.x,
		.y = a.y + b.y,
	};
}

static struct vec2d
vec2d_subtract(struct vec2d a, struct vec2d b)
{
	return (struct vec2d) {
		.x = a.x - b.x,
		.y = a.y - b.y,
	};
}

static struct vec2d
vec2d_multiply_constant(double c, struct vec2d a)
{
	return (struct vec2d) {
		.x = c * a.x,
		.y = c * a.y,
	};
}

static bool
lines_intersect(struct line *line1, struct line *line2,
		struct vec2d *intersection)
{
	struct vec2d p = line1->a;
	struct vec2d r = vec2d_subtract(line1->b, line1->a);
	struct vec2d q = line2->a;
	struct vec2d s = vec2d_subtract(line2->b, line2->a);
	double rxs;
	double sxr;
	double t;
	double u;

	/*
	 * The line (p, r) and (q, s) intersects where
	 *
	 *   p + t r = q + u s
	 *
	 * Calculate t:
	 *
	 *   (p + t r) × s = (q + u s) × s
	 *   p × s + t (r × s) = q × s + u (s × s)
	 *   p × s + t (r × s) = q × s
	 *   t (r × s) = q × s - p × s
	 *   t (r × s) = (q - p) × s
	 *   t = ((q - p) × s) / (r × s)
	 *
	 * Using the same method, for u we get:
	 *
	 *   u = ((p - q) × r) / (s × r)
	 */

	rxs = vec2d_cross_product(r, s);
	sxr = vec2d_cross_product(s, r);

	/* If r × s = 0 then the lines are either parallel or collinear. */
	if (fabs(rxs) < DBL_MIN)
		return false;

	t = vec2d_cross_product(vec2d_subtract(q, p), s) / rxs;
	u = vec2d_cross_product(vec2d_subtract(p, q), r) / sxr;

	/* The lines only intersect if 0 ≤ t ≤ 1 and 0 ≤ u ≤ 1. */
	if (t < 0.0 || t > 1.0 || u < 0.0 || u > 1.0)
		return false;

	*intersection = vec2d_add(p, vec2d_multiply_constant(t, r));
	return true;
}

static struct border *
add_border(struct wl_array *array,
	   double x1, double y1,
	   double x2, double y2,
	   enum motion_direction blocking_dir)
{
	struct border *border = wl_array_add(array, sizeof *border);

	*border = (struct border) {
		.line = (struct line) {
			.a = (struct vec2d) {
				.x = x1,
				.y = y1,
			},
			.b = (struct vec2d) {
				.x = x2,
				.y = y2,
			},
		},
		.blocking_dir = blocking_dir,
	};

	return border;
}

static int
compare_lines_x(const void *a, const void *b)
{
	const struct border *border_a = a;
	const struct border *border_b = b;


	if (border_a->line.a.x == border_b->line.a.x)
		return border_a->line.b.x < border_b->line.b.x;
	else
		return border_a->line.a.x > border_b->line.a.x;
}

static void
add_non_overlapping_edges(pixman_box32_t *boxes,
			  int band_above_start,
			  int band_below_start,
			  int band_below_end,
			  struct wl_array *borders)
{
	int i;
	struct wl_array band_merge;
	struct border *border;
	struct border *prev_border;
	struct border *new_border;

	wl_array_init(&band_merge);

	/* Add bottom band of previous row, and top band of current row, and
	 * sort them so lower left x coordinate comes first. If there are two
	 * borders with the same left x coordinate, the wider one comes first.
	 */
	for (i = band_above_start; i < band_below_start; i++) {
		pixman_box32_t *box = &boxes[i];
		add_border(&band_merge, box->x1, box->y2, box->x2, box->y2,
			   MOTION_DIRECTION_POSITIVE_Y);
	}
	for (i = band_below_start; i < band_below_end; i++) {
		pixman_box32_t *box= &boxes[i];
		add_border(&band_merge, box->x1, box->y1, box->x2, box->y1,
			   MOTION_DIRECTION_NEGATIVE_Y);
	}
	qsort(band_merge.data,
	      band_merge.size / sizeof *border,
	      sizeof *border,
	      compare_lines_x);

	/* Combine the two combined bands so that any overlapping border is
	 * eliminated. */
	prev_border = NULL;
	wl_array_for_each(border, &band_merge) {
		assert(border->line.a.y == border->line.b.y);
		assert(!prev_border ||
		       prev_border->line.a.y == border->line.a.y);
		assert(!prev_border ||
		       (prev_border->line.a.x != border->line.a.x ||
			prev_border->line.b.x != border->line.b.x));
		assert(!prev_border ||
		       prev_border->line.a.x <= border->line.a.x);

		if (prev_border &&
		    prev_border->line.a.x == border->line.a.x) {
			/*
			 * ------------ +
			 * -------      =
			 * [     ]-----
			 */
			prev_border->line.a.x = border->line.b.x;
		} else if (prev_border &&
			   prev_border->line.b.x == border->line.b.x) {
			/*
			 * ------------ +
			 *       ------ =
			 * ------[    ]
			 */
			prev_border->line.b.x = border->line.a.x;
		} else if (prev_border &&
			   prev_border->line.b.x == border->line.a.x) {
			/*
			 * --------        +
			 *         ------  =
			 * --------------
			 */
			prev_border->line.b.x = border->line.b.x;
		} else if (prev_border &&
			   prev_border->line.b.x >= border->line.a.x) {
			/*
			 * --------------- +
			 *      ------     =
			 * -----[    ]----
			 */
			new_border = add_border(borders,
						border->line.b.x,
						border->line.b.y,
						prev_border->line.b.x,
						prev_border->line.b.y,
						prev_border->blocking_dir);
			prev_border->line.b.x = border->line.a.x;
			prev_border = new_border;
		} else {
			assert(!prev_border ||
			       prev_border->line.b.x < border->line.a.x);
			/*
			 * First border or non-overlapping.
			 *
			 * -----           +
			 *        -----    =
			 * -----  -----
			 */
			new_border = wl_array_add(borders, sizeof *border);
			*new_border = *border;
			prev_border = new_border;
		}
	}

	wl_array_release(&band_merge);
}

static void
add_band_bottom_edges(pixman_box32_t *boxes,
		      int band_start,
		      int band_end,
		      struct wl_array *borders)
{
	int i;

	for (i = band_start; i < band_end; i++) {
		add_border(borders,
			   boxes[i].x1, boxes[i].y2,
			   boxes[i].x2, boxes[i].y2,
			   MOTION_DIRECTION_POSITIVE_Y);
	}
}

static void
region_to_outline(pixman_region32_t *region, struct wl_array *borders)
{
	pixman_box32_t *boxes;
	int num_boxes;
	int i;
	int top_most, bottom_most;
	int current_roof;
	int prev_top;
	int band_start, prev_band_start;

	/*
	 * Remove any overlapping lines from the set of rectangles. Note that
	 * pixman regions are grouped as rows of rectangles, where rectangles
	 * in one row never touch or overlap and are all of the same height.
	 *
	 *             -------- ---                   -------- ---
	 *             |      | | |                   |      | | |
	 *   ----------====---- ---         -----------  ----- ---
	 *   |            |            =>   |            |
	 *   ----==========---------        -----        ----------
	 *       |                 |	        |                 |
	 *       -------------------            -------------------
	 *
	 */

	boxes = pixman_region32_rectangles(region, &num_boxes);
	prev_top = 0;
	top_most = boxes[0].y1;
	current_roof = top_most;
	bottom_most = boxes[num_boxes - 1].y2;
	band_start = 0;
	prev_band_start = 0;
	for (i = 0; i < num_boxes; i++) {
		/* Detect if there is a vertical empty space, and add the lower
		 * level of the previous band if so was the case. */
		if (i > 0 &&
		    boxes[i].y1 != prev_top &&
		    boxes[i].y1 != boxes[i - 1].y2) {
			current_roof = boxes[i].y1;
			add_band_bottom_edges(boxes,
					      band_start,
					      i,
					      borders);
		}

		/* Special case adding the last band, since it won't be handled
		 * by the band change detection below. */
		if (boxes[i].y1 != current_roof && i == num_boxes - 1) {
			if (boxes[i].y1 != prev_top) {
				/* The last band is a single box, so we don't
				 * have a prev_band_start to tell us when the
				 * previous band started. */
				add_non_overlapping_edges(boxes,
							  band_start,
							  i,
							  i + 1,
							  borders);
			} else {
				add_non_overlapping_edges(boxes,
							  prev_band_start,
							  band_start,
							  i + 1,
							  borders);
			}
		}

		/* Detect when passing a band and combine the top border of the
		 * just passed band with the bottom band of the previous band.
		 */
		if (boxes[i].y1 != top_most && boxes[i].y1 != prev_top) {
			/* Combine the two passed bands. */
			if (prev_top != current_roof) {
				add_non_overlapping_edges(boxes,
							  prev_band_start,
							  band_start,
							  i,
							  borders);
			}

			prev_band_start = band_start;
			band_start = i;
		}

		/* Add the top border if the box is part of the current roof. */
		if (boxes[i].y1 == current_roof) {
			add_border(borders,
				   boxes[i].x1, boxes[i].y1,
				   boxes[i].x2, boxes[i].y1,
				   MOTION_DIRECTION_NEGATIVE_Y);
		}

		/* Add the bottom border of the last band. */
		if (boxes[i].y2 == bottom_most) {
			add_border(borders,
				   boxes[i].x1, boxes[i].y2,
				   boxes[i].x2, boxes[i].y2,
				   MOTION_DIRECTION_POSITIVE_Y);
		}

		/* Always add the left border. */
		add_border(borders,
			   boxes[i].x1, boxes[i].y1,
			   boxes[i].x1, boxes[i].y2,
			   MOTION_DIRECTION_NEGATIVE_X);

		/* Always add the right border. */
		add_border(borders,
			   boxes[i].x2, boxes[i].y1,
			   boxes[i].x2, boxes[i].y2,
			   MOTION_DIRECTION_POSITIVE_X);

		prev_top = boxes[i].y1;
	}
}

static bool
is_border_horizontal (struct border *border)
{
	return border->line.a.y == border->line.b.y;
}

static bool
is_border_blocking_directions(struct border *border,
			      uint32_t directions)
{
	/* Don't block parallel motions. */
	if (is_border_horizontal(border)) {
		if ((directions & (MOTION_DIRECTION_POSITIVE_Y |
				   MOTION_DIRECTION_NEGATIVE_Y)) == 0)
			return false;
	} else {
		if ((directions & (MOTION_DIRECTION_POSITIVE_X |
				   MOTION_DIRECTION_NEGATIVE_X)) == 0)
			return false;
	}

	return (~border->blocking_dir & directions) != directions;
}

static struct border *
get_closest_border(struct wl_array *borders,
		   struct line *motion,
		   uint32_t directions)
{
	struct border *border;
	struct vec2d intersection;
	struct vec2d delta;
	double distance_2;
	struct border *closest_border = NULL;
	double closest_distance_2 = DBL_MAX;

	wl_array_for_each(border, borders) {
		if (!is_border_blocking_directions(border, directions))
			continue;

		if (!lines_intersect(&border->line, motion, &intersection))
			continue;

		delta = vec2d_subtract(intersection, motion->a);
		distance_2 = delta.x*delta.x + delta.y*delta.y;
		if (distance_2 < closest_distance_2) {
			closest_border = border;
			closest_distance_2 = distance_2;
		}
	}

	return closest_border;
}

static void
clamp_to_border(struct border *border,
		struct line *motion,
		uint32_t *motion_dir)
{
	/*
	 * When clamping either rightward or downward motions, the motion needs
	 * to be clamped so that the destination coordinate does not end up on
	 * the border (see weston_pointer_clamp_event_to_region). Do this by
	 * clamping such motions to the border minus the smallest possible
	 * wl_fixed_t value.
	 */
	if (is_border_horizontal(border)) {
		if (*motion_dir & MOTION_DIRECTION_POSITIVE_Y)
			motion->b.y = border->line.a.y - wl_fixed_to_double(1);
		else
			motion->b.y = border->line.a.y;
		*motion_dir &= ~(MOTION_DIRECTION_POSITIVE_Y |
				 MOTION_DIRECTION_NEGATIVE_Y);
	} else {
		if (*motion_dir & MOTION_DIRECTION_POSITIVE_X)
			motion->b.x = border->line.a.x - wl_fixed_to_double(1);
		else
			motion->b.x = border->line.a.x;
		*motion_dir &= ~(MOTION_DIRECTION_POSITIVE_X |
				 MOTION_DIRECTION_NEGATIVE_X);
	}
}

static uint32_t
get_motion_directions(struct line *motion)
{
	uint32_t directions = 0;

	if (motion->a.x < motion->b.x)
		directions |= MOTION_DIRECTION_POSITIVE_X;
	else if (motion->a.x > motion->b.x)
		directions |= MOTION_DIRECTION_NEGATIVE_X;
	if (motion->a.y < motion->b.y)
		directions |= MOTION_DIRECTION_POSITIVE_Y;
	else if (motion->a.y > motion->b.y)
		directions |= MOTION_DIRECTION_NEGATIVE_Y;

	return directions;
}

static void
weston_pointer_clamp_event_to_region(struct weston_pointer *pointer,
				     struct weston_pointer_motion_event *event,
				     pixman_region32_t *region,
				     wl_fixed_t *clamped_x,
				     wl_fixed_t *clamped_y)
{
	wl_fixed_t x, y;
	wl_fixed_t sx, sy;
	wl_fixed_t old_sx = pointer->sx;
	wl_fixed_t old_sy = pointer->sy;
	struct wl_array borders;
	struct line motion;
	struct border *closest_border;
	float new_x_f, new_y_f;
	uint32_t directions;

	weston_pointer_motion_to_abs(pointer, event, &x, &y);
	weston_view_from_global_fixed(pointer->focus, x, y, &sx, &sy);

	wl_array_init(&borders);

	/*
	 * Generate borders given the confine region we are to use. The borders
	 * are defined to be the outer region of the allowed area. This means
	 * top/left borders are "within" the allowed area, while bottom/right
	 * borders are outside. This needs to be considered when clamping
	 * confined motion vectors.
	 */
	region_to_outline(region, &borders);

	motion = (struct line) {
		.a = (struct vec2d) {
			.x = wl_fixed_to_double(old_sx),
			.y = wl_fixed_to_double(old_sy),
		},
		.b = (struct vec2d) {
			.x = wl_fixed_to_double(sx),
			.y = wl_fixed_to_double(sy),
		},
	};
	directions = get_motion_directions(&motion);

	while (directions) {
		closest_border = get_closest_border(&borders,
						    &motion,
						    directions);
		if (closest_border)
			clamp_to_border(closest_border, &motion, &directions);
		else
			break;
	}

	weston_view_to_global_float(pointer->focus,
				    (float) motion.b.x, (float) motion.b.y,
				    &new_x_f, &new_y_f);
	*clamped_x = wl_fixed_from_double(new_x_f);
	*clamped_y = wl_fixed_from_double(new_y_f);

	wl_array_release(&borders);
}

static double
point_to_border_distance_2(struct border *border, double x, double y)
{
	double orig_x, orig_y;
	double dx, dy;

	if (is_border_horizontal(border)) {
		if (x < border->line.a.x)
			orig_x = border->line.a.x;
		else if (x > border->line.b.x)
			orig_x = border->line.b.x;
		else
			orig_x = x;
		orig_y = border->line.a.y;
	} else {
		if (y < border->line.a.y)
			orig_y = border->line.a.y;
		else if (y > border->line.b.y)
			orig_y = border->line.b.y;
		else
			orig_y = y;
		orig_x = border->line.a.x;
	}


	dx = fabs(orig_x - x);
	dy = fabs(orig_y - y);
	return dx*dx + dy*dy;
}

static void
warp_to_behind_border(struct border *border, wl_fixed_t *sx, wl_fixed_t *sy)
{
	switch (border->blocking_dir) {
	case MOTION_DIRECTION_POSITIVE_X:
	case MOTION_DIRECTION_NEGATIVE_X:
		if (border->blocking_dir == MOTION_DIRECTION_POSITIVE_X)
			*sx = wl_fixed_from_double(border->line.a.x) - 1;
		else
			*sx = wl_fixed_from_double(border->line.a.x) + 1;
		if (*sy < wl_fixed_from_double(border->line.a.y))
			*sy = wl_fixed_from_double(border->line.a.y) + 1;
		else if (*sy > wl_fixed_from_double(border->line.b.y))
			*sy = wl_fixed_from_double(border->line.b.y) - 1;
		break;
	case MOTION_DIRECTION_POSITIVE_Y:
	case MOTION_DIRECTION_NEGATIVE_Y:
		if (border->blocking_dir == MOTION_DIRECTION_POSITIVE_Y)
			*sy = wl_fixed_from_double(border->line.a.y) - 1;
		else
			*sy = wl_fixed_from_double(border->line.a.y) + 1;
		if (*sx < wl_fixed_from_double(border->line.a.x))
			*sx = wl_fixed_from_double(border->line.a.x) + 1;
		else if (*sx > wl_fixed_from_double(border->line.b.x))
			*sx = wl_fixed_from_double(border->line.b.x) - 1;
		break;
	}
}

static void
maybe_warp_confined_pointer(struct weston_pointer_constraint *constraint)
{
	wl_fixed_t x;
	wl_fixed_t y;
	wl_fixed_t sx;
	wl_fixed_t sy;

	weston_view_from_global_fixed(constraint->view,
				      constraint->pointer->x,
				      constraint->pointer->y,
				      &sx,
				      &sy);

	if (!is_within_constraint_region(constraint, sx, sy)) {
		double xf = wl_fixed_to_double(sx);
		double yf = wl_fixed_to_double(sy);
		pixman_region32_t confine_region;
		struct wl_array borders;
		struct border *border;
		double closest_distance_2 = DBL_MAX;
		struct border *closest_border = NULL;

		wl_array_init(&borders);

		pixman_region32_init(&confine_region);
		pixman_region32_intersect(&confine_region,
					  &constraint->view->surface->input,
					  &constraint->region);
		region_to_outline(&confine_region, &borders);
		pixman_region32_fini(&confine_region);

		wl_array_for_each(border, &borders) {
			double distance_2;

			distance_2 = point_to_border_distance_2(border, xf, yf);
			if (distance_2 < closest_distance_2) {
				closest_border = border;
				closest_distance_2 = distance_2;
			}
		}
		assert(closest_border);

		warp_to_behind_border(closest_border, &sx, &sy);

		wl_array_release(&borders);

		weston_view_to_global_fixed(constraint->view, sx, sy, &x, &y);
		weston_pointer_move_to(constraint->pointer, x, y);
	}
}

static void
confined_pointer_grab_pointer_motion(struct weston_pointer_grab *grab,
				     const struct timespec *time,
				     struct weston_pointer_motion_event *event)
{
	struct weston_pointer_constraint *constraint =
		container_of(grab, struct weston_pointer_constraint, grab);
	struct weston_pointer *pointer = grab->pointer;
	struct weston_surface *surface;
	wl_fixed_t x, y;
	wl_fixed_t old_sx = pointer->sx;
	wl_fixed_t old_sy = pointer->sy;
	pixman_region32_t confine_region;

	assert(pointer->focus);
	assert(pointer->focus->surface == constraint->surface);

	surface = pointer->focus->surface;

	pixman_region32_init(&confine_region);
	pixman_region32_intersect(&confine_region,
				  &surface->input,
				  &constraint->region);
	weston_pointer_clamp_event_to_region(pointer, event,
					     &confine_region, &x, &y);
	weston_pointer_move_to(pointer, x, y);
	pixman_region32_fini(&confine_region);

	weston_view_from_global_fixed(pointer->focus, x, y,
				      &pointer->sx, &pointer->sy);

	if (old_sx != pointer->sx || old_sy != pointer->sy) {
		pointer_send_motion(pointer, time,
				    pointer->sx, pointer->sy);
	}

	pointer_send_relative_motion(pointer, time, event);
}

static void
confined_pointer_grab_pointer_button(struct weston_pointer_grab *grab,
				     const struct timespec *time,
				     uint32_t button,
				     uint32_t state_w)
{
	weston_pointer_send_button(grab->pointer, time, button, state_w);
}

static void
confined_pointer_grab_pointer_axis(struct weston_pointer_grab *grab,
				   const struct timespec *time,
				   struct weston_pointer_axis_event *event)
{
	weston_pointer_send_axis(grab->pointer, time, event);
}

static void
confined_pointer_grab_pointer_axis_source(struct weston_pointer_grab *grab,
					  uint32_t source)
{
	weston_pointer_send_axis_source(grab->pointer, source);
}

static void
confined_pointer_grab_pointer_frame(struct weston_pointer_grab *grab)
{
	weston_pointer_send_frame(grab->pointer);
}

static void
confined_pointer_grab_pointer_cancel(struct weston_pointer_grab *grab)
{
	struct weston_pointer_constraint *constraint =
		container_of(grab, struct weston_pointer_constraint, grab);

	disable_pointer_constraint(constraint);
}

static const struct weston_pointer_grab_interface
				confined_pointer_grab_interface = {
	confined_pointer_grab_pointer_focus,
	confined_pointer_grab_pointer_motion,
	confined_pointer_grab_pointer_button,
	confined_pointer_grab_pointer_axis,
	confined_pointer_grab_pointer_axis_source,
	confined_pointer_grab_pointer_frame,
	confined_pointer_grab_pointer_cancel,
};

static void
confined_pointer_destroy(struct wl_client *client,
			 struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static void
confined_pointer_set_region(struct wl_client *client,
			    struct wl_resource *resource,
			    struct wl_resource *region_resource)
{
	struct weston_pointer_constraint *constraint =
		wl_resource_get_user_data(resource);
	struct weston_region *region = region_resource ?
		wl_resource_get_user_data(region_resource) : NULL;

	if (!constraint)
		return;

	if (region) {
		pixman_region32_copy(&constraint->region_pending,
				     &region->region);
	} else {
		pixman_region32_fini(&constraint->region_pending);
		region_init_infinite(&constraint->region_pending);
	}
	constraint->region_is_pending = true;
}

static const struct zwp_confined_pointer_v1_interface confined_pointer_interface = {
	confined_pointer_destroy,
	confined_pointer_set_region,
};

static void
pointer_constraints_confine_pointer(struct wl_client *client,
				    struct wl_resource *resource,
				    uint32_t id,
				    struct wl_resource *surface_resource,
				    struct wl_resource *pointer_resource,
				    struct wl_resource *region_resource,
				    uint32_t lifetime)
{
	struct weston_surface *surface =
		wl_resource_get_user_data(surface_resource);
	struct weston_pointer *pointer = wl_resource_get_user_data(pointer_resource);
	struct weston_region *region = region_resource ?
		wl_resource_get_user_data(region_resource) : NULL;

	init_pointer_constraint(resource, id, surface, pointer, region, lifetime,
				&zwp_confined_pointer_v1_interface,
				&confined_pointer_interface,
				&confined_pointer_grab_interface);
}

static const struct zwp_pointer_constraints_v1_interface pointer_constraints_interface = {
	pointer_constraints_destroy,
	pointer_constraints_lock_pointer,
	pointer_constraints_confine_pointer,
};

static void
bind_pointer_constraints(struct wl_client *client, void *data,
			 uint32_t version, uint32_t id)
{
	struct wl_resource *resource;

	resource = wl_resource_create(client,
				      &zwp_pointer_constraints_v1_interface,
				      1, id);

	wl_resource_set_implementation(resource, &pointer_constraints_interface,
				       NULL, NULL);
}

static void
input_timestamps_destroy(struct wl_client *client,
			 struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static const struct zwp_input_timestamps_v1_interface
				input_timestamps_interface = {
	input_timestamps_destroy,
};

static void
input_timestamps_manager_destroy(struct wl_client *client,
				 struct wl_resource *resource)
{
	wl_resource_destroy(resource);
}

static void
input_timestamps_manager_get_keyboard_timestamps(struct wl_client *client,
						 struct wl_resource *resource,
						 uint32_t id,
						 struct wl_resource *keyboard_resource)
{
	struct weston_keyboard *keyboard =
		wl_resource_get_user_data(keyboard_resource);
	struct wl_resource *input_ts;

	input_ts = wl_resource_create(client,
				      &zwp_input_timestamps_v1_interface,
				      1, id);
	if (!input_ts) {
		wl_client_post_no_memory(client);
		return;
	}

	if (keyboard) {
		wl_list_insert(&keyboard->timestamps_list,
			       wl_resource_get_link(input_ts));
	} else {
		wl_list_init(wl_resource_get_link(input_ts));
	}

	wl_resource_set_implementation(input_ts,
				       &input_timestamps_interface,
				       keyboard_resource,
				       unbind_resource);
}

static void
input_timestamps_manager_get_pointer_timestamps(struct wl_client *client,
						struct wl_resource *resource,
						uint32_t id,
						struct wl_resource *pointer_resource)
{
	struct weston_pointer *pointer =
		wl_resource_get_user_data(pointer_resource);
	struct wl_resource *input_ts;

	input_ts = wl_resource_create(client,
				      &zwp_input_timestamps_v1_interface,
				      1, id);
	if (!input_ts) {
		wl_client_post_no_memory(client);
		return;
	}

	if (pointer) {
		wl_list_insert(&pointer->timestamps_list,
			       wl_resource_get_link(input_ts));
	} else {
		wl_list_init(wl_resource_get_link(input_ts));
	}

	wl_resource_set_implementation(input_ts,
				       &input_timestamps_interface,
				       pointer_resource,
				       unbind_resource);
}

static void
input_timestamps_manager_get_touch_timestamps(struct wl_client *client,
					      struct wl_resource *resource,
					      uint32_t id,
					      struct wl_resource *touch_resource)
{
	struct weston_touch *touch = wl_resource_get_user_data(touch_resource);
	struct wl_resource *input_ts;

	input_ts = wl_resource_create(client,
				      &zwp_input_timestamps_v1_interface,
				      1, id);
	if (!input_ts) {
		wl_client_post_no_memory(client);
		return;
	}

	if (touch) {
		wl_list_insert(&touch->timestamps_list,
			       wl_resource_get_link(input_ts));
	} else {
		wl_list_init(wl_resource_get_link(input_ts));
	}

	wl_resource_set_implementation(input_ts,
				       &input_timestamps_interface,
				       touch_resource,
				       unbind_resource);
}

static const struct zwp_input_timestamps_manager_v1_interface
				input_timestamps_manager_interface = {
	input_timestamps_manager_destroy,
	input_timestamps_manager_get_keyboard_timestamps,
	input_timestamps_manager_get_pointer_timestamps,
	input_timestamps_manager_get_touch_timestamps,
};

static void
bind_input_timestamps_manager(struct wl_client *client, void *data,
			      uint32_t version, uint32_t id)
{
	struct wl_resource *resource =
		wl_resource_create(client,
				   &zwp_input_timestamps_manager_v1_interface,
				   1, id);

	if (resource == NULL) {
		wl_client_post_no_memory(client);
		return;
	}

	wl_resource_set_implementation(resource,
				       &input_timestamps_manager_interface,
				       NULL, NULL);
}

int
weston_input_init(struct weston_compositor *compositor)
{
	if (!wl_global_create(compositor->wl_display,
			      &zwp_relative_pointer_manager_v1_interface, 1,
			      compositor, bind_relative_pointer_manager))
		return -1;

	if (!wl_global_create(compositor->wl_display,
			      &zwp_pointer_constraints_v1_interface, 1,
			      NULL, bind_pointer_constraints))
		return -1;

	if (!wl_global_create(compositor->wl_display,
			      &zwp_input_timestamps_manager_v1_interface, 1,
			      NULL, bind_input_timestamps_manager))
		return -1;

	return 0;
}