File: udev_input.c

package info (click to toggle)
retroarch 1.22.2%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 80,716 kB
  • sloc: ansic: 1,275,794; cpp: 115,470; objc: 9,973; asm: 6,624; python: 4,071; makefile: 2,867; sh: 2,828; xml: 1,408; perl: 393; java: 298; javascript: 196
file content (4259 lines) | stat: -rw-r--r-- 139,430 bytes parent folder | download
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
/*  RetroArch - A frontend for libretro.
 *  Copyright (C) 2010-2015 - Hans-Kristian Arntzen
 *  Copyright (C) 2011-2017 - Daniel De Matteis
 *
 *  RetroArch is free software: you can redistribute it and/or modify it under the terms
 *  of the GNU General Public License as published by the Free Software Found-
 *  ation, either version 3 of the License, or (at your option) any later version.
 *
 *  RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 *  PURPOSE.  See the GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along with RetroArch.
 *  If not, see <http://www.gnu.org/licenses/>.
 */

/* TODO/FIXME - set this once the kqueue codepath is implemented and working properly,
 * also remove libepoll-shim from the Makefile when that happens. */
#if 1
#define HAVE_EPOLL
#else
#ifdef __linux__
#define HAVE_EPOLL 1
#endif

#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined (__NetBSD__)
#define HAVE_KQUEUE 1
#endif
#endif

#include <stdint.h>
#include <string.h>

#include <fcntl.h>
#include <unistd.h>

#include <limits.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

#if defined(HAVE_EPOLL)
#include <sys/epoll.h>
#elif defined(HAVE_KQUEUE)
#include <sys/event.h>
#endif
#include <poll.h>

#include <libudev.h>
#if defined(__linux__)
#include <linux/types.h>
#include <linux/input.h>
#include <linux/kd.h>
#include <linux/version.h>
#elif defined(__FreeBSD__)
#include <dev/evdev/input.h>
#endif

#ifdef HAVE_CONFIG_H
#include "../../config.h"
#endif

#ifdef HAVE_X11
#include <X11/Xlib.h>
#endif

#include <file/file_path.h>
#include <compat/strl.h>
#include <string/stdstring.h>
#include <retro_miscellaneous.h>

#include "../input_keymaps.h"

#include "../common/linux_common.h"

#include "../../configuration.h"
#include "../../retroarch.h"
#include "../../verbosity.h"

#if defined(HAVE_XKBCOMMON) && defined(HAVE_KMS)
#define UDEV_XKB_HANDLING
#endif

/* Force UDEV_XKB_HANDLING for Lakka */
#ifdef HAVE_LAKKA
#ifndef UDEV_XKB_HANDLING
#define UDEV_XKB_HANDLING
#endif
#endif

#define UDEV_MAX_KEYS (KEY_MAX + 7) / 8

#ifdef UDEV_TOUCH_SUPPORT

/* Temporary defines for debugging purposes */

/* Define this to use direct printf debug messages. */
/*#define UDEV_TOUCH_PRINTF_DEBUG*/
/* Define this to add more deep debugging messages - performance will suffer... */
/*#define UDEV_TOUCH_DEEP_DEBUG*/

/* TODO - Temporary debugging using direct printf */
#ifdef UDEV_TOUCH_PRINTF_DEBUG
#define RARCH_ERR(...) do{ \
    printf("[ERR]" __VA_ARGS__); \
} while (0)

#define RARCH_WARN(...) do{ \
    printf("[WARN]" __VA_ARGS__); \
} while (0)

#define RARCH_LOG(...) do{ \
    printf("[LOG]" __VA_ARGS__); \
} while (0)

#define RARCH_DBG(...) do{ \
    printf("[DBG]" __VA_ARGS__); \
} while (0)
#endif
/* UDEV_TOUCH_PRINTF_DEBUG */

#ifdef UDEV_TOUCH_DEEP_DEBUG
#define RARCH_DDBG(...) do{ \
    RARCH_DBG(__VA_ARGS__); \
} while (0)
#else
#define RARCH_DDBG(msg, ...)
#endif
/* UDEV_TOUCH_DEEP_DEBUG */

/* Helper macro for declaring things as unused - use sparingly. */
#define UDEV_INPUT_TOUCH_UNUSED(X) (void)(X)

/* Tracking ID used when not in use */
#define UDEV_INPUT_TOUCH_TRACKING_ID_NONE -1
/* Slot ID used when not in use */
#define UDEV_INPUT_TOUCH_SLOT_ID_NONE -1
/* Upper limit of fingers tracked by this implementation */
#define UDEV_INPUT_TOUCH_FINGER_LIMIT 10
/* Conversion factor from seconds to microseconds */
#define UDEV_INPUT_TOUCH_S_TO_US 1000000
/* Conversion factor from microseconds to nanoseconds */
#define UDEV_INPUT_TOUCH_US_TO_NS 1000
/* Default state of pointer simulation. */
#define UDEV_INPUT_TOUCH_POINTER_EN settings->bools.input_touch_vmouse_pointer
/* Default state of mouse simulation. */
#define UDEV_INPUT_TOUCH_MOUSE_EN settings->bools.input_touch_vmouse_mouse
/* Default state of touchpad simulation. */
#define UDEV_INPUT_TOUCH_TOUCHPAD_EN settings->bools.input_touch_vmouse_touchpad
/* Default state of trackball simulation. */
#define UDEV_INPUT_TOUCH_TRACKBALL_EN settings->bools.input_touch_vmouse_trackball
/* Default state of gesture simulation. */
#define UDEV_INPUT_TOUCH_GEST_EN settings->bools.input_touch_vmouse_gesture
/* Default value of tap time in us. */
#define UDEV_INPUT_TOUCH_MAX_TAP_TIME 250000
/* Default value of tap distance - squared distance in 0x7fff space. */
#define UDEV_INPUT_TOUCH_MAX_TAP_DIST 0x1000
/* Default value of tap time in us. */
#define UDEV_INPUT_TOUCH_GEST_CLICK_TIME 10000
/* Default value of gesture inactivity timeout. */
#define UDEV_INPUT_TOUCH_GEST_TIMEOUT 70000
/* Default sensitivity of the simulated touchpad. */
#define UDEV_INPUT_TOUCH_PAD_SENSITIVITY 0.6f
/* Default value of scroll gesture sensitivity. */
#define UDEV_INPUT_TOUCH_GEST_SCROLL_SENSITIVITY 0xa0
/* Default value of scroll gesture step. */
#define UDEV_INPUT_TOUCH_GEST_SCROLL_STEP 0x10
/* Default value of panel percentage considered corner */
#define UDEV_INPUT_TOUCH_GEST_CORNER 5
/* Default friction of the trackball x-axis rotation, used as a multiplier */
#define UDEV_INPUT_TOUCH_TRACKBALL_FRICT_X 0.9
/* Default friction of the trackball y-axis rotation, used as a multiplier */
#define UDEV_INPUT_TOUCH_TRACKBALL_FRICT_Y 0.9
/* Default sensitivity of the trackball to original movement */
#define UDEV_INPUT_TOUCH_TRACKBALL_SENSITIVITY_X 10
/* Default sensitivity of the trackball to original movement */
#define UDEV_INPUT_TOUCH_TRACKBALL_SENSITIVITY_Y 10
/* Default squared cutoff velocity when trackball ceases all movement */
#define UDEV_INPUT_TOUCH_TRACKBALL_SQ_VEL_CUTOFF 10

typedef enum udev_dragging_type
{
   DRAG_NONE = 0,
   DRAG_TWO_FINGER,
   DRAG_THREE_FINGER
} udev_touch_dragging_type;

typedef enum udev_touch_event_type
{
   FINGERDOWN,
   FINGERUP,
   FINGERMOTION
} udev_touch_event_type;

#endif
/* UDEV_TOUCH_SUPPORT */

struct udev_input;

struct udev_input_device;

enum udev_input_dev_type
{
   UDEV_INPUT_KEYBOARD = 0,
   UDEV_INPUT_MOUSE,
   UDEV_INPUT_TOUCHPAD,
   UDEV_INPUT_TOUCHSCREEN
};

/* NOTE: must be in sync with enum udev_input_dev_type */
static const char *g_dev_type_str[] =
{
   "ID_INPUT_KEY",
   "ID_INPUT_MOUSE",
   "ID_INPUT_TOUCHPAD",
   "ID_INPUT_TOUCHSCREEN"
};

typedef struct
{
   /* If device is "absolute" coords will be in device specific units
      and axis min value will be less than max, otherwise coords will be
      relative to full viewport and min and max values will be zero. */
   int32_t x_abs, y_abs;
   int32_t x_min, y_min;
   int32_t x_max, y_max;
   int32_t x_rel, y_rel;
   int32_t abs;
   bool l, r, m, b4, b5;
   bool wu, wd, whu, whd;
   bool pp;
} udev_input_mouse_t;

#ifdef UDEV_TOUCH_SUPPORT

/**
 * Types of slot changes
 */
typedef enum
{
   /* No change */
   UDEV_TOUCH_CHANGE_NONE = 0,
   /* Touch down, start tracking */
   UDEV_TOUCH_CHANGE_DOWN,
   /* Touch up, end tracking */
   UDEV_TOUCH_CHANGE_UP,
   /* Change in position, size, or pressure */
   UDEV_TOUCH_CHANGE_MOVE
} udev_input_touch_change_type;

/**
 * Types of tap gestures.
 */
typedef enum
{
   /* Gesture selection timeout. */
   UDEV_TOUCH_TGEST_TIMEOUT = 0,
   /* Gesture for one finger tap. */
   UDEV_TOUCH_TGEST_S_TAP,
   /* Gesture for two finger tap. */
   UDEV_TOUCH_TGEST_D_TAP,
   /* Gesture for three finger tap. */
   UDEV_TOUCH_TGEST_T_TAP,
   /* Sentinel and total number of gestures. */
   UDEV_TOUCH_TGEST_LAST
} udev_input_touch_tgest_type;

/**
 * Types of move gestures.
 */
typedef enum
{
   /* No move gesture in process. */
   UDEV_TOUCH_MGEST_NONE = 0,
   /* Gesture for one finger single tap drag. */
   UDEV_TOUCH_MGEST_S_STAP_DRAG,
   /* Gesture for one finger double tap drag. */
   UDEV_TOUCH_MGEST_S_DTAP_DRAG,
   /* Gesture for one finger triple tap drag. */
   UDEV_TOUCH_MGEST_S_TTAP_DRAG,
   /* Gesture for two finger no tap drag. */
   UDEV_TOUCH_MGEST_D_NTAP_DRAG,
   /* Gesture for two finger single tap drag. */
   UDEV_TOUCH_MGEST_D_STAP_DRAG,
   /* Gesture for three finger no tap drag. */
   UDEV_TOUCH_MGEST_T_NTAP_DRAG,
   /* Gesture for three finger single tap drag. */
   UDEV_TOUCH_MGEST_T_STAP_DRAG,
   /* Sentinel and total number of motion gestures. */
   UDEV_TOUCH_MGEST_LAST
} udev_input_touch_mgest_type;

/**
 * Definition of feature limits.
 */
typedef struct
{
   /* Range of values supported by this feature:  */
   int32_t min;
   int32_t max;
   int32_t range;

   /* Optional, but could be useful later:  */
   /* Fuzz value used to filter noise from event stream. */
   int32_t fuzz;
   /* Values within this value will be discarded and reported as 0 */
   int32_t flat;
   /* Resolution for the reported values. */
   int32_t resolution;
   /* Is this feature enabled? */
   bool enabled;
} udev_input_touch_limits_t;

/**
 * Helper structure for representing the time of a touch event.
 */
typedef struct
{
   /* Seconds */
   uint32_t s;
   /* Microseconds */
   uint32_t us;
} udev_touch_ts_t;

/**
 * Abstraction for time-delayed callback.
 */
typedef struct
{
   /* Execute this callback at this or later time. */
   udev_touch_ts_t execute_at;
   /* Callback to execute, providing the custom data. */
   void (*cb)(void *touch, void *data);
   /* Custom data pointer provided to the callback. */
   void *data;
   /* Is this event active? */
   bool active;
} udev_touch_timed_cb_t;

/**
 * Structure representing the state of a single touchscreen slot.
 */
typedef struct
{
   /* Unique tracking ID for this slot. UDEV_TRACKING_ID_NONE -> No touch. */
   int32_t tracking_id;
   /* Current position of the tracked touch. */
   int16_t pos_x;
   int16_t pos_y;
   /* Current major and minor axis. */
   int16_t minor;
   int16_t major;
   /* Current pressure. */
   int16_t pressure;
   /* Type of change which occurred - udev_input_touch_change_type. */
   uint16_t change;
   /* Start timestamp of the current or last touch down. */
   udev_touch_ts_t td_time;
   /* Start position of the current or last touch down. */
   int16_t td_pos_x;
   int16_t td_pos_y;
} udev_slot_state_t;

/* Type used to represent touch slot ID, UDEV_INPUT_TOUCH_SLOT_ID_NONE (-1) is used for none. */
typedef int32_t udev_input_touch_slot_id;

/**
 * Container for touch-related tracking data.
 */
typedef struct
{
   /* Info for number of tracked fingers/touch-points/slots */
   udev_input_touch_limits_t info_slots;
   /* Info for x-axis limits */
   udev_input_touch_limits_t info_x_limits;
   /* Info for y-axis limits */
   udev_input_touch_limits_t info_y_limits;
   /* Info for primary touch axis limits */
   udev_input_touch_limits_t info_major;
   /* Info for secondary touch axis limits */
   udev_input_touch_limits_t info_minor;
   /* Info for pressure limits */
   udev_input_touch_limits_t info_pressure;

   /*
    * Allocated data block compatible with the following structure:
    * struct input_mt_request_layout {
    *     __u32 code;
    *     __s32 values[info_slots->range];
    * };
    * For reference, see linux kernel: include/uapi/linux/input.h#L147
    */
   uint8_t *request_data;
   size_t request_data_size;

   udev_input_touch_slot_id current_slot;
   /* Staging data for the slot states. Sized to [info_slots->range]. */
   udev_slot_state_t *staging;
   uint16_t staging_active;
   /* Current data for the slot states. Sized to [info_slots->range]. */
   udev_slot_state_t *current;
   uint16_t current_active;

   /* Timestamp of when the last touch state update occurred */
   udev_touch_ts_t last_state_update;

   /* Simulated pointer / touchscreen */
   /* Pointer position in the touch panel coordinates. */
   int32_t pointer_pos_x;
   int32_t pointer_pos_y;
   /* Pointer position in the main panel coordinates. */
   int32_t pointer_ma_pos_x;
   int32_t pointer_ma_pos_y;
   /* Pointer position delta in main panel pixels. */
   int16_t pointer_ma_rel_x;
   int16_t pointer_ma_rel_y;
   /* Pointer position mapped onto the primary screen (-0x7fff - 0x7fff). */
   int16_t pointer_scr_pos_x;
   int16_t pointer_scr_pos_y;
   /* Pointer position within the window, -0x7fff - 0x7fff -> inside. */
   int16_t pointer_vp_pos_x;
   int16_t pointer_vp_pos_y;

   /* Simulated mouse */
   /* Mouse position in the original pixel coordinates. */
   int16_t mouse_pos_x;
   int16_t mouse_pos_y;
   /* Mouse position mapped onto the primary screen (-0x7fff - 0x7fff). */
   int16_t mouse_scr_pos_x;
   int16_t mouse_scr_pos_y;
   /* Mouse position within the window, -0x7fff - 0x7fff -> inside. */
   int16_t mouse_vp_pos_x;
   int16_t mouse_vp_pos_y;
   /* Mouse position delta in screen pixels. */
   int16_t mouse_rel_x;
   int16_t mouse_rel_y;
   /* Mouse wheel delta in number of frames to hold that value. */
   int16_t mouse_wheel_x;
   int16_t mouse_wheel_y;

   /* Mouse touchpad simulation */
   /* Sensitivity of the touchpad mouse. */
   float touchpad_sensitivity;
   /* High resolution touchpad pointer position mapped onto the primary screen. */
   float touchpad_pos_x;
   float touchpad_pos_y;

   /* Mouse trackball simulation */
   /* Current high resolution position of the trackball */
   float trackball_pos_x;
   float trackball_pos_y;
   /* Sensitivity of the trackball to movement */
   float trackball_sensitivity_x;
   float trackball_sensitivity_y;
   /* Current velocity of the trackball */
   float trackball_vel_x;
   float trackball_vel_y;
   /* Friction of the trackball */
   float trackball_frict_x;
   float trackball_frict_y;
   /* Squared cutoff velocity of when the trackball ceases all movement */
   int16_t trackball_sq_vel_cutoff;

   /* Gestures and multi-touch tracking */
   /* Primary slot used as the slot index for MT gestures */
   udev_input_touch_slot_id gest_primary_slot;
   /* Secondary slot used as the slot index for MT gestures */
   udev_input_touch_slot_id gest_secondary_slot;
   /* Time of inactivity before gesture is selected. */
   uint32_t gest_timeout;
   /* Maximum contact time in us considered as a "tap". */
   uint32_t gest_tap_time;
   /* Maximum contact distance in normalized screen units considered as a "tap". */
   uint32_t gest_tap_dist;
   /* Time a button should be held down, i.e. a "click". */
   uint32_t gest_click_time;
   /* Number of taps in the current gesture. */
   uint16_t gest_tap_count;
   /* Sensitivity of scrolling for the scroll wheel gesture. */
   uint16_t gest_scroll_sensitivity;
   /* Step of scrolling for the scroll wheel gesture. */
   uint16_t gest_scroll_step;
   /* High resolution scroll. */
   int16_t gest_scroll_x;
   int16_t gest_scroll_y;
   /* Percentage of screen considered as a corner. */
   uint16_t gest_corner;
   /* Time-delayed callbacks used for tap gesture automation. */
   udev_touch_timed_cb_t gest_tcbs[UDEV_TOUCH_TGEST_LAST];
   /* Current move gesture in process. */
   udev_input_touch_mgest_type gest_mgest_type;
   /* Time-delayed callbacks used for move gesture automation. */
   udev_touch_timed_cb_t gest_mcbs[UDEV_TOUCH_MGEST_LAST];

   /* Enable the gestures? */
   bool gest_enabled;
   /* Is it possible for a tap to happen? Set to false once time or distance is over limit. */
   bool gest_tap_possible;
   /* Enable the touchpad mode? Switches between direct (false) and touchpad (true) modes */
   bool touchpad_enabled;
   /* Enable the trackball mode? Switches between immediate stop and trackball-style */
   bool trackball_enabled;
   /* Is the trackball free to rotate under its own inertia? */
   bool trackball_inertial;
   /* Enable mouse simulation? */
   bool mouse_enabled;
   /* Freeze the mouse cursor in place? */
   bool mouse_freeze_cursor;
   /* Mouse buttons. */
   bool mouse_btn_l;
   bool mouse_btn_r;
   bool mouse_btn_m;
   bool mouse_btn_b4;
   bool mouse_btn_b5;
   /* Enable pointer simulation? */
   bool pointer_enabled;
   /* Pointer pressed. */
   bool pointer_btn_pp;
   /* Pointer back - TODO unknown action, RETRO_DEVICE_ID_POINTER_BACK. */
   bool pointer_btn_pb;
   /* Flag used to run the state update. */
   bool run_state_update;
   /* Touch panel properties */
   bool is_touch_device;
} udev_input_touch_t;

#endif
/* UDEV_TOUCH_SUPPORT */

typedef struct udev_input_device
{
   void (*handle_cb)(void *data,
         const struct input_event *event,
         struct udev_input_device *dev);
   int fd; /* Device file descriptor */
   dev_t dev; /* Device handle */
   udev_input_mouse_t mouse; /* State tracking for mouse-type devices */
#ifdef UDEV_TOUCH_SUPPORT
   udev_input_touch_t touch; /* State tracking for touch-type devices */
#endif
   enum udev_input_dev_type type; /* Type of this device */
   char devnode[NAME_MAX_LENGTH]; /* Device node path */
   char ident[NAME_MAX_LENGTH]; /* Identifier of the device */
} udev_input_device_t;

typedef void (*device_handle_cb)(void *data,
      const struct input_event *event, udev_input_device_t *dev);

typedef struct udev_input
{
   struct udev *udev;
   struct udev_monitor *monitor;
   udev_input_device_t **devices;

   /* Indices of keyboards in the devices array. Negative values are invalid. */
   int32_t keyboards[MAX_INPUT_DEVICES];
   /* Indices of pointers in the devices array. Negative values are invalid. */
   int32_t pointers[MAX_INPUT_DEVICES];

   int fd;
   /* OS pointer coords (zeros if we don't have X11) */
   int pointer_x;
   int pointer_y;

   unsigned num_devices;

   uint8_t state[UDEV_MAX_KEYS];

#ifdef UDEV_XKB_HANDLING
   bool xkb_handling;
#endif

   linux_illuminance_sensor_t *illuminance_sensor;
} udev_input_t;

#ifdef UDEV_XKB_HANDLING
int init_xkb(int fd, size_t len);
void free_xkb(void);
int handle_xkb(int code, int value);
#endif

static unsigned input_unify_ev_key_code(unsigned code)
{
   /* input_keymaps_translate_keysym_to_rk does not support the case
    * where multiple keysyms translate to the same RETROK_* code,
    * so unify remote control keysyms to keyboard keysyms here.
    *
    * Addendum: The rarch_keysym_lut lookup table also becomes
    * unusable if more than one keysym translates to the same
    * RETROK_* code, so certain keys must be left unmapped in
    * rarch_key_map_linux and instead be handled here */
   switch (code)
   {
      case KEY_OK:
      case KEY_SELECT:
         return KEY_ENTER;
      case KEY_BACK:
         return KEY_BACKSPACE;
      case KEY_EXIT:
         return KEY_CLEAR;
      default:
         break;
   }

   return code;
}

static void udev_handle_keyboard(void *data,
      const struct input_event *event, udev_input_device_t *dev)
{
   unsigned keysym;
   udev_input_t *udev = (udev_input_t*)data;

   switch (event->type)
   {
      case EV_KEY:
         keysym = input_unify_ev_key_code(event->code);
         if (event->value && video_driver_has_focus())
            BIT_SET(udev->state, keysym);
         else
            BIT_CLEAR(udev->state, keysym);

         /* TODO/FIXME: The udev driver is incomplete.
          * When calling input_keyboard_event() the
          * following parameters are omitted:
          * - character: the localised Unicode/UTF-8
          *   value of the pressed key
          * - mod: the current keyboard modifier
          *   bitmask
          * Without these values, input_keyboard_event()
          * does not function correctly (e.g. it is
          * impossible to use text entry in the menu).
          * I cannot find any usable reference for
          * converting a udev-returned key code into a
          * localised Unicode/UTF-8 value, so for the
          * time being we must rely on other sources:
          * - If we are using an X11-based context driver,
          *   input_keyboard_event() is handled correctly
          *   in x11_common:x11_check_window()
          * - If we are using KMS, input_keyboard_event()
          *   is handled correctly in
          *   keyboard_event_xkb:handle_xkb()
          * If neither are available, then just call
          * input_keyboard_event() without character and
          * mod, and hope for the best... */

         if (video_driver_display_type_get() != RARCH_DISPLAY_X11)
         {
#ifdef UDEV_XKB_HANDLING
            if (udev->xkb_handling && handle_xkb(keysym, event->value) == 0)
               return;
#endif
            input_keyboard_event(event->value,
                  input_keymaps_translate_keysym_to_rk(keysym),
                  0, 0, RETRO_DEVICE_KEYBOARD);
         }

         break;

      default:
         break;
   }
}

static void udev_input_kb_free(struct udev_input *udev)
{
   unsigned i;

   for (i = 0; i < UDEV_MAX_KEYS; i++)
      udev->state[i] = 0;

#ifdef UDEV_XKB_HANDLING
   free_xkb();
#endif
}

static udev_input_mouse_t *udev_get_mouse(
      struct udev_input *udev, unsigned port)
{
   unsigned i;
   unsigned mouse_index      = 0;
   int dev_index             = -1;
   settings_t *settings      = config_get_ptr();
   udev_input_mouse_t *mouse = NULL;

   if (port >= MAX_USERS || !video_driver_has_focus())
      return NULL;

   mouse_index = settings->uints.input_mouse_index[port];
   if (mouse_index < MAX_INPUT_DEVICES)
       dev_index = udev->pointers[mouse_index];
   if (dev_index < 0)
       return NULL;
   else
       return &udev->devices[dev_index]->mouse;
}

static void udev_mouse_set_x(udev_input_mouse_t *mouse, int32_t x, bool abs)
{
    video_viewport_t vp;

   if (abs)
   {
      mouse->x_rel += x - mouse->x_abs;
      mouse->x_abs = x;
   }
   else
   {
      mouse->x_rel += x;
      if (video_driver_get_viewport_info(&vp))
      {
         mouse->x_abs += x;

         if (mouse->x_abs < vp.x)
            mouse->x_abs = vp.x;
         else if (mouse->x_abs >= (vp.x + (int)vp.full_width))
            mouse->x_abs = vp.x + vp.full_width - 1;
      }
   }
}

static int16_t udev_mouse_get_x(const udev_input_mouse_t *mouse)
{
   video_viewport_t vp;
   double src_width;
   double x;

   if (!video_driver_get_viewport_info(&vp))
      return 0;

   if (mouse->abs) /* mouse coords are absolute */
      src_width = mouse->x_max - mouse->x_min + 1;
   else
      src_width = vp.full_width;

   x = (double)vp.width / src_width * mouse->x_rel;

   return x + (x < 0 ? -0.5 : 0.5);
}

static void udev_mouse_set_y(udev_input_mouse_t *mouse, int32_t y, bool abs)
{
   video_viewport_t vp;

   if (abs)
   {
      mouse->y_rel += y - mouse->y_abs;
      mouse->y_abs = y;
   }
   else
   {
      mouse->y_rel += y;
      if (video_driver_get_viewport_info(&vp))
      {
         mouse->y_abs += y;

         if (mouse->y_abs < vp.y)
            mouse->y_abs = vp.y;
         else if (mouse->y_abs >= (vp.y + (int)vp.full_height))
            mouse->y_abs = vp.y + vp.full_height - 1;
      }
   }
}

static int16_t udev_mouse_get_y(const udev_input_mouse_t *mouse)
{
   video_viewport_t vp;
   double src_height;
   double y;

   if (!video_driver_get_viewport_info(&vp))
      return 0;

   if (mouse->abs) /* mouse coords are absolute */
      src_height = mouse->y_max - mouse->y_min + 1;
   else
      src_height = vp.full_height;

   y = (double)vp.height / src_height * mouse->y_rel;

   return y + (y < 0 ? -0.5 : 0.5);
}

static bool udev_mouse_get_pointer(const udev_input_mouse_t *mouse,
            bool screen, bool confined, int16_t *ret_x, int16_t *ret_y)
{
   struct video_viewport vp    = {0};
   int16_t scaled_x;
   int16_t scaled_y;
   int16_t res_x               = 0;
   int16_t res_y               = 0;
   int16_t res_screen_x        = 0;
   int16_t res_screen_y        = 0;

   if (!video_driver_get_viewport_info(&vp))
      return false;

   /* mouse coords are absolute? */
   if (mouse->abs)
   {
      /* mouse coordinates are relative to the full screen; convert them
       * to be relative to the viewport */
      scaled_x = vp.full_width  * (mouse->x_abs - mouse->x_min) / (mouse->x_max - mouse->x_min + 1);
      scaled_y = vp.full_height * (mouse->y_abs - mouse->y_min) / (mouse->y_max - mouse->y_min + 1);
   }
   else /* mouse coords are viewport relative */
   {
      scaled_x = mouse->x_abs;
      scaled_y = mouse->y_abs;
   }

   if (confined && video_driver_translate_coord_viewport_confined_wrap(
            &vp, scaled_x, scaled_y,
            &res_x, &res_y, &res_screen_x, &res_screen_y))
   {
   }
   else if (!confined && video_driver_translate_coord_viewport_wrap(
            &vp, scaled_x, scaled_y,
            &res_x, &res_y, &res_screen_x, &res_screen_y))
   {
   }
   else
   {
      return false;
   }

   if (screen)
   {
      *ret_x = res_screen_x;
      *ret_y = res_screen_y;
   }
   else
   {
      *ret_x = res_x;
      *ret_y = res_y;
   }
   return true;
}

static void udev_handle_mouse(void *data,
      const struct input_event *event, udev_input_device_t *dev)
{
   udev_input_mouse_t *mouse = &dev->mouse;

   switch (event->type)
   {
      case EV_KEY:
         switch (event->code)
         {
            case BTN_LEFT:
               mouse->l = event->value;
               break;
            case BTN_RIGHT:
               mouse->r = event->value;
               break;
            case BTN_MIDDLE:
               mouse->m = event->value;
               break;
            case BTN_TOUCH:
               mouse->pp = event->value;
               break;
            case BTN_SIDE:
               mouse->b4 = event->value;
               break;
            case BTN_EXTRA:
               mouse->b5 = event->value;
               break;
            default:
               break;
         }
         break;

      case EV_REL:
         switch (event->code)
         {
            case REL_X:
               udev_mouse_set_x(mouse, event->value, false);
               break;
            case REL_Y:
               udev_mouse_set_y(mouse, event->value, false);
               break;
            case REL_WHEEL:
               if (event->value == 1)
                  mouse->wu = 1;
               else if (event->value == -1)
                  mouse->wd = 1;
               break;
            case REL_HWHEEL:
               if (event->value == 1)
                  mouse->whu = 1;
               else if (event->value == -1)
                  mouse->whd = 1;
               break;
         }
         break;

      case EV_ABS:
         switch (event->code)
         {
            case ABS_X:
               udev_mouse_set_x(mouse, event->value, true);
               break;
            case ABS_Y:
               udev_mouse_set_y(mouse, event->value, true);
               break;
         }
         break;
   }
}

#ifdef UDEV_TOUCH_SUPPORT

/**
 * Copy timestamp from given input event to a timestamp structure.
 *
 * @param event The source input event.
 * @param ts Destination timestamp data.
 */
static void udev_touch_event_ts_copy(const struct input_event *event, udev_touch_ts_t *ts)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,16,0)
  ts->s  = event->input_event_sec;
  ts->us = event->input_event_usec;
#else
  ts->s  = event->time.tv_sec;
  ts->us = event->time.tv_usec;
#endif
}

/**
 * Copy timestamp to timestamp.
 *
 * @param first The source timestamp.
 * @param second Destination timestamp.
 */
static void udev_touch_ts_copy(const udev_touch_ts_t *first, udev_touch_ts_t *second)
{
   second->s  = first->s;
   second->us = first->us;
}

/**
 * Get current time and store it in the given timestamp structure.
 *
 * @param ts Destination timestamp data.
 */
static void udev_touch_ts_now(udev_touch_ts_t *ts)
{
   struct timeval now;
   gettimeofday(&now, NULL);
   ts->s  = now.tv_sec;
   ts->us = now.tv_usec;
}

/**
 * Add time to given base and store resulting timestamp.
 *
 * @param base Base timestamp.
 * @param s Number of seconds to add.
 * @param us Number of microseconds to add.
 * @param dest Destination structure to store the time in.
 */
static void udev_touch_ts_add(const udev_touch_ts_t *base,
        uint32_t s, uint32_t us, udev_touch_ts_t *dest)
{
   dest->s  = base->s  + s + us / UDEV_INPUT_TOUCH_S_TO_US;
   dest->us = base->us + us % UDEV_INPUT_TOUCH_S_TO_US;
}

/**
 * Calculate difference between two timestamps in microseconds.
 * @param first The first timestamp.
 * @param second The second timestamp.
 * @return Returns difference of second - first in microseconds.
 */
static int32_t udev_touch_ts_diff(const udev_touch_ts_t *first, const udev_touch_ts_t *second)
{
   return (second->s - first->s) * UDEV_INPUT_TOUCH_S_TO_US +
          (second->us - first->us);
}

/* Touch point directions between two points. */
enum udev_input_touch_dir
{
   UDEV_INPUT_TOUCH_DIR_TL,
   UDEV_INPUT_TOUCH_DIR_TT,
   UDEV_INPUT_TOUCH_DIR_TR,

   UDEV_INPUT_TOUCH_DIR_ML,
   UDEV_INPUT_TOUCH_DIR_MT,
   UDEV_INPUT_TOUCH_DIR_MR,

   UDEV_INPUT_TOUCH_DIR_BL,
   UDEV_INPUT_TOUCH_DIR_BT,
   UDEV_INPUT_TOUCH_DIR_BR
};

/* Array with touch directions. */
static const enum udev_input_touch_dir g_udev_input_touch_dir_val[] =
{
   UDEV_INPUT_TOUCH_DIR_TL, UDEV_INPUT_TOUCH_DIR_TT, UDEV_INPUT_TOUCH_DIR_TR,
   UDEV_INPUT_TOUCH_DIR_ML, UDEV_INPUT_TOUCH_DIR_MT, UDEV_INPUT_TOUCH_DIR_MR,
   UDEV_INPUT_TOUCH_DIR_BL, UDEV_INPUT_TOUCH_DIR_BT, UDEV_INPUT_TOUCH_DIR_BR,
};

/* Array with touch directions names. */
static const char *g_udev_input_touch_dir_str[] =
{
   "TopLeft", "Top", "TopRight",
   "MidLeft", "Mid", "MidRight",
   "BotLeft", "Bot", "BotRight",
};

/* Convert touch direction enum to a string representation. */
static const char *udev_touch_dir_to_str(enum udev_input_touch_dir dir)
{ return g_udev_input_touch_dir_str[dir]; }

/* Helper functions for determining touch direction. */
static const bool udev_touch_dir_top(enum udev_input_touch_dir dir)
{
   return dir >= UDEV_INPUT_TOUCH_DIR_TL && dir <= UDEV_INPUT_TOUCH_DIR_TR;
}

static const bool udev_touch_dir_left(enum udev_input_touch_dir dir)
{
   return dir == UDEV_INPUT_TOUCH_DIR_TL || dir == UDEV_INPUT_TOUCH_DIR_ML || dir == UDEV_INPUT_TOUCH_DIR_BL;
}

static const bool udev_touch_dir_bot(enum udev_input_touch_dir dir)
{
   return dir >= UDEV_INPUT_TOUCH_DIR_BL && dir <= UDEV_INPUT_TOUCH_DIR_BR;
}

static const bool udev_touch_dir_right(enum udev_input_touch_dir dir)
{
   return dir == UDEV_INPUT_TOUCH_DIR_TR || dir == UDEV_INPUT_TOUCH_DIR_MR || dir == UDEV_INPUT_TOUCH_DIR_BR;
}

/* Get signum for given value. */
static int16_t udev_touch_sign(int16_t val)
{
   return (val > 0) - (val < 0);
}

/* Get max of given values. */
static int16_t udev_touch_max(int16_t first, int16_t second)
{
   return first > second ? first : second;
}

/* Get min of given values. */
static int16_t udev_touch_min(int16_t first, int16_t second)
{
   return first < second ? first : second;
}

/**
 * Calculate distance between given points and a direction.
 * Coordinates and distances are calculated with system
 * origin placed in the top left corner.
 *
 * @param pos1_x X-coordinate of the first position.
 * @param pos1_y Y-coordinate of the first position.
 * @param pos2_x X-coordinate of the second position.
 * @param pos2_y Y-coordinate of the second position.
 * @param dir Estimated direction from pos1 -> pos2.
 *
 * @return Returns squared distance between the two points.
 */
static uint32_t udev_touch_tp_diff(
        int16_t pos1_x, int16_t pos1_y,
        int16_t pos2_x, int16_t pos2_y,
        enum udev_input_touch_dir *dir)
{
   /* Position differences pos1 -> pos2. */
   int16_t diff_x = pos2_x - pos1_x;
   int16_t diff_y = pos2_y - pos1_y;

   /*
    * Directions:
    * TL TT TR
    * ML MM MR
    * BL BB BR
    */
   if (dir)
      *dir = g_udev_input_touch_dir_val[
         /* Index using y-axis sign. */
           (udev_touch_sign(diff_y) + 1) * 3
         /* Index using x-axis sign. */
         + (udev_touch_sign(diff_x) + 1)
      ];
   /* Squared distance */
   return diff_x * diff_x + diff_y * diff_y;
}

/* Print out given timestamp */
static void udev_touch_ts_print(const udev_touch_ts_t *ts)
{
   RARCH_DBG("%u,%u", ts->s, ts->us);
}

/**
 * Get pointer device for given port.
 *
 * @param udev UDev system to search.
 * @param port Target port.
 */
static udev_input_device_t *udev_get_pointer_port_dev(
      struct udev_input *udev, unsigned port)
{
   uint16_t i;
   uint16_t pointer_index    = 0;
   int16_t dev_index         = -1;
   settings_t *settings      = config_get_ptr();
   udev_input_mouse_t *mouse = NULL;

   if (port >= MAX_USERS || !video_driver_has_focus())
      return NULL;

   pointer_index = settings->uints.input_mouse_index[port];
   if (pointer_index < MAX_INPUT_DEVICES)
       dev_index = udev->pointers[pointer_index];
   if (dev_index < 0)
       return NULL;
   return udev->devices[dev_index];
}

/**
 * Dump information about the given absinfo structure.
 *
 * @param label Label to prefix the message with.
 * @param info Info structure to dump.
 */
static void udev_dump_absinfo(const char *label, const struct input_absinfo *info)
{
   RARCH_DBG("[udev] %s: %d %d-%d ~%d |%d r%d\n", label,
           info->value, info->minimum, info->maximum,
           info->fuzz, info->flat, info->resolution);
}

/**
 * Dump information about the given touch limits structure.
 *
 * @param label Label to prefix the message with.
 * @param limits Limits structure to dump.
 */
static void udev_dump_touch_limit(const char *label, const udev_input_touch_limits_t *limits)
{
   if (limits->enabled)
   {
      RARCH_DBG("[udev] %s: %d-%d [%d] ~%d |%d r%d\n", label,
                limits->min, limits->max, limits->range,
                limits->fuzz, limits->flat, limits->resolution);
   }
   else
   {
      RARCH_DBG("[udev] %s: DISABLED\n", label);
   }
}

/* Convert given udev ABS_MT_* code to string representation. */
static const char *udev_mt_code_to_str(uint32_t code)
{
   switch (code)
   {
      case ABS_MT_SLOT:
         return "ABS_MT_SLOT";
      case ABS_MT_TOUCH_MAJOR:
         return "ABS_MT_TOUCH_MAJOR";
      case ABS_MT_TOUCH_MINOR:
         return "ABS_MT_TOUCH_MINOR";
      case ABS_MT_WIDTH_MAJOR:
         return "ABS_MT_WIDTH_MAJOR";
      case ABS_MT_WIDTH_MINOR:
         return "ABS_MT_WIDTH_MINOR";
      case ABS_MT_ORIENTATION:
         return "ABS_MT_ORIENTATION";
      case ABS_MT_POSITION_X:
         return "ABS_MT_POSITION_X";
      case ABS_MT_POSITION_Y:
         return "ABS_MT_POSITION_Y";
      case ABS_MT_TOOL_TYPE:
         return "ABS_MT_TOOL_TYPE";
      case ABS_MT_BLOB_ID:
         return "ABS_MT_BLOB_ID";
      case ABS_MT_TRACKING_ID:
         return "ABS_MT_TRACKING_ID";
      case ABS_MT_PRESSURE:
         return "ABS_MT_PRESSURE";
      case ABS_MT_DISTANCE:
         return "ABS_MT_DISTANCE";
      case ABS_MT_TOOL_X:
         return "ABS_MT_TOOL_X";
      case ABS_MT_TOOL_Y:
         return "ABS_MT_TOOL_Y";
      default:
         break;
   }
   return "UNKNOWN";
}

/**
 * Dump information contained within given request_data with structure:
 * struct input_mt_request_layout {
 *     __u32 code;
 *     __s32 values[count];
 * };
 * For reference, see linux kernel: include/uapi/linux/input.h#L147
 *
 * @param label Label to prefix the message with.
 * @param request_data Input data structure to dump.
 * @param len Number of elements in the values array.
 */
static void udev_dump_mt_request_data(const char *label, const uint8_t *request_data, size_t len)
{
   uint32_t *mt_req_code = (uint32_t*) request_data;
   int32_t *mt_req_values = ((int32_t*) request_data) + 1;
   RARCH_DBG("[udev] %s: Req { %s, [ ", label, udev_mt_code_to_str(*mt_req_code));
   for (; mt_req_values < (((int32_t*) mt_req_code) + len + 1); ++mt_req_values)
   {
      RARCH_DBG("%d, ", *mt_req_values);
   }
   RARCH_DBG("]\n");
}

/* Convert given UDEV_TOUCH_CHANGE_* code to string representation */
static const char *udev_touch_change_to_str(uint16_t change)
{
   switch (change)
   {
      case UDEV_TOUCH_CHANGE_NONE:
         return "NONE";
      case UDEV_TOUCH_CHANGE_DOWN:
         return "DOWN";
      case UDEV_TOUCH_CHANGE_UP:
         return "UP";
      case UDEV_TOUCH_CHANGE_MOVE:
         return "MOVE";
      default:
         break;
   }
   return "UNKNOWN";
}

/**
 * Dump information about given touchscreen slot.
 *
 * @param label Label prefix for the printed line.
 * @param slot_state Input slot state to print.
 */
static void udev_dump_touch_slot(const char *label, const udev_slot_state_t *slot_state)
{
   RARCH_DBG("[udev] %s\t(%u,%u) %d:%hdx%hd (@%hdx%hd) %hd <%hdx%hd> %s\n", label,
             slot_state->td_time.s, slot_state->td_time.us,
             slot_state->tracking_id,
             slot_state->pos_x, slot_state->pos_y,
             slot_state->td_pos_x, slot_state->td_pos_y,
             slot_state->pressure,
             slot_state->minor, slot_state->major,
             udev_touch_change_to_str(slot_state->change));
}

/**
 * Dump information about tracked slots in given touchscreen device.
 *
 * @param indent Indentation prefix for each printed line.
 * @param touch Input touchscreen device to dump.
 */
static void udev_dump_touch_device_slots(const char *indent, const udev_input_touch_t *touch)
{
   int iii;

   RARCH_DBG("[udev] %sStagingSlots: {\n", indent);
   if (touch->staging != NULL)
   {
      for (iii = 0; iii < touch->info_slots.range; ++iii)
         udev_dump_touch_slot(indent, &touch->staging[iii]);
   }
   else
   {
      RARCH_DBG("[udev] %s\tNOT ALLOCATED\n", indent);
   }
   RARCH_DBG("[udev] %s}\n", indent);

   RARCH_DBG("[udev] %sCurrentSlots: {\n", indent);
   if (touch->staging != NULL)
   {
      for (iii = 0; iii < touch->info_slots.range; ++iii)
         udev_dump_touch_slot(indent, &touch->current[iii]);
   }
   else
   {
      RARCH_DBG("[udev] %s\tNOT ALLOCATED\n", indent);
   }
   RARCH_DBG("[udev] %s}\n", indent);
}

/**
 * Set touch limits from given absinfo structure.
 *
 * @param info Input info structure.
 * @param limits Target limits structure.
 */
static void udev_touch_set_limits_from(struct input_absinfo *info,
        udev_input_touch_limits_t *limits)
{
   limits->enabled    = true;
   limits->min        = info->minimum;
   limits->max        = info->maximum;
   limits->range      = limits->max - limits->min + 1;
   limits->fuzz       = info->fuzz;
   limits->flat       = info->flat;
   limits->resolution = info->resolution;
}

/**
 * Dump information about the provided device. Works even
 * for non-touch devices.
 *
 * @param dev Input device to dump information for.
 */
static void udev_dump_touch_dev(udev_input_device_t *dev)
{
   udev_input_mouse_t *mouse = &dev->mouse;
   udev_input_touch_t *touch = &dev->touch;

   RARCH_DBG("[udev] === UDEV_INPUT_DEVICE INFO DUMP ===\n");

   RARCH_DBG("[udev] \tident = %s\n", dev->ident);
   RARCH_DBG("[udev] \tdevnode = %s\n", dev->devnode);
   RARCH_DBG("[udev] \ttype = %s\n", g_dev_type_str[dev->type]);
   RARCH_DBG("[udev] \thandle_cb = %p\n", dev->handle_cb);
   RARCH_DBG("[udev] \tfd = %d\n", dev->fd);
   RARCH_DBG("[udev] \tdev = %lu\n", dev->dev);

   RARCH_DBG("[udev] \tmouse = {\n");
   RARCH_DBG("[udev] \t\tabs = %d\n", mouse->abs);
   RARCH_DBG("[udev] \t\tx -> %d~%d (%d-%d)\n",
             mouse->x_abs, mouse->x_rel,
             mouse->x_min, mouse->x_max);
   RARCH_DBG("[udev] \t\ty -> %d~%d (%d-%d)\n",
             mouse->y_abs, mouse->y_rel,
             mouse->y_min, mouse->y_max);
   RARCH_DBG("[udev] \t\tL = %c | R = %c | M = %c | 4 = %c | 5 = %c\n",
             mouse->l ? 'X' : 'O', mouse->r ? 'X' : 'O',
             mouse->m ? 'X' : 'O',
             mouse->b4 ? 'X' : 'O', mouse->b5 ? 'X' : 'O');
   RARCH_DBG("[udev] \t\tWU = %c | WD = %c | WHU = %c | WHD = %c\n",
             mouse->wu ? 'X' : 'O', mouse->wd ? 'X' : 'O',
             mouse->whu ? 'X' : 'O', mouse->whd ? 'X' : 'O');
   RARCH_DBG("[udev] \t\tPP = %c\n", mouse->pp ? 'X' : 'O');
   RARCH_DBG("[udev] \t}\n");

   RARCH_DBG("[udev] \ttouch = {\n");
   udev_dump_touch_limit("\t\tSlots", &touch->info_slots);
   udev_dump_touch_limit("\t\tX-Axis", &touch->info_x_limits);
   udev_dump_touch_limit("\t\tY-Axis", &touch->info_y_limits);
   udev_dump_touch_limit("\t\tMajor", &touch->info_major);
   udev_dump_touch_limit("\t\tMinor", &touch->info_minor);
   udev_dump_touch_limit("\t\tPressure", &touch->info_pressure);
   udev_dump_mt_request_data("\t\tRequestData", touch->request_data, touch->info_slots.range);
   udev_dump_touch_device_slots("\t\t", touch);

   RARCH_DBG("[udev] \t}\n");

   RARCH_DBG("[udev] === END OF INFO DUMP ===\n");
}

/**
 * Cleanup and destroy given touch device.
 *
 * @param dev Device to cleanup and destroy.
 */
static void udev_destroy_touch_dev(udev_input_device_t *dev)
{
   udev_input_touch_t *touch = &dev->touch;

   RARCH_DBG("[udev] Destroying touch device \"%s\"\n", dev->ident);

   if (touch->request_data)
   {
       free(touch->request_data);
       touch->request_data      = NULL;
       touch->request_data_size = 0;
   }

   if (touch->staging)
   {
       free(touch->staging);
       touch->staging = NULL;
   }

   if (touch->current)
   {
       free(touch->current);
       touch->current = NULL;
   }

   touch->current_slot = UDEV_INPUT_TOUCH_SLOT_ID_NONE;
}

/**
 * Update options from settings if they changed.
 *
 * @param dev Input touch device to update.
 * @param force Force setting of the values.
 */
static void udev_update_touch_dev_options(udev_input_device_t *dev, bool force)
{
   static bool pointer_en;
   static bool mouse_en;
   static bool touchpad_en;
   static bool trackball_en;
   static bool gest_en;

   bool mouse_en_new;
   bool touchpad_en_new;
   bool trackball_en_new;
   bool gest_en_new;
   settings_t *settings = config_get_ptr();
   bool pointer_en_new  = UDEV_INPUT_TOUCH_POINTER_EN;
   if (force || pointer_en_new != pointer_en)
   {
       pointer_en                 = pointer_en_new;
       dev->touch.pointer_enabled = pointer_en_new;
   }

   mouse_en_new = UDEV_INPUT_TOUCH_MOUSE_EN;
   if (force || mouse_en_new != mouse_en)
   {
       mouse_en                 = mouse_en_new;
       dev->touch.mouse_enabled = mouse_en_new;
   }

   touchpad_en_new = UDEV_INPUT_TOUCH_TOUCHPAD_EN;
   if (force || touchpad_en_new != touchpad_en)
   {
       touchpad_en                 = touchpad_en_new;
       dev->touch.touchpad_enabled = touchpad_en_new;
   }

   trackball_en_new = UDEV_INPUT_TOUCH_TRACKBALL_EN;
   if (force || trackball_en_new != trackball_en)
   {
       trackball_en                 = trackball_en_new;
       dev->touch.trackball_enabled = trackball_en_new;
   }

   gest_en_new = UDEV_INPUT_TOUCH_GEST_EN;
   if (force || gest_en_new != gest_en)
   {
       gest_en                 = gest_en_new;
       dev->touch.gest_enabled = gest_en_new;
   }
}

/**
 * Initialize given touch device.
 *
 * @param dev Input touch device to initialize.
 */
static void udev_init_touch_dev(udev_input_device_t *dev)
{
   int iii, ret;
   struct input_absinfo abs_info;
   unsigned long xreq, yreq;
   udev_input_touch_t *touch = &dev->touch;
   settings_t *settings      = config_get_ptr();

   RARCH_DBG("[udev] Initializing touch device \"%s\"\n", dev->ident);

   /* TODO - Unused for now. */
   UDEV_INPUT_TOUCH_UNUSED(udev_touch_dir_to_str);
   UDEV_INPUT_TOUCH_UNUSED(udev_touch_dir_top);
   UDEV_INPUT_TOUCH_UNUSED(udev_touch_dir_left);
   UDEV_INPUT_TOUCH_UNUSED(udev_touch_dir_bot);
   UDEV_INPUT_TOUCH_UNUSED(udev_touch_dir_right);
   UDEV_INPUT_TOUCH_UNUSED(udev_touch_min);
   UDEV_INPUT_TOUCH_UNUSED(udev_touch_max);
   UDEV_INPUT_TOUCH_UNUSED(udev_dump_absinfo);
   UDEV_INPUT_TOUCH_UNUSED(udev_touch_ts_print);

   /* Get slot limits - number of touch points */
   ret = ioctl(dev->fd, EVIOCGABS(ABS_MT_SLOT), &abs_info);
   if (ret < 0)
   {
      RARCH_WARN("[udev] Failed to get touchscreen limits.\n");

      touch->info_slots.enabled = false;
   }
   else
      udev_touch_set_limits_from(&abs_info, &touch->info_slots);

   /* Single-touch devices use ABS_X/Y, Multi-touch use ABS_MT_POSITION_X/Y */
   if (abs_info.maximum == 0)
   {
      /* TODO - Test for single-touch devices. */
      RARCH_WARN("[udev] Single-touch devices are currently untested.\n");

      xreq = EVIOCGABS(ABS_X);
      yreq = EVIOCGABS(ABS_Y);
   }
   else
   {
      xreq = EVIOCGABS(ABS_MT_POSITION_X);
      yreq = EVIOCGABS(ABS_MT_POSITION_Y);
   }

   /* Get x-axis limits */
   ret = ioctl(dev->fd, xreq, &abs_info);
   if (ret < 0)
   {
      RARCH_DBG("[udev] Failed to get touchscreen x-limits\n");

      touch->info_x_limits.enabled = false;
   }
   else
      udev_touch_set_limits_from(&abs_info, &touch->info_x_limits);

   /* Get y-axis limits */
   ret = ioctl(dev->fd, yreq, &abs_info);
   if (ret < 0)
   {
      RARCH_DBG("[udev] Failed to get touchscreen y-limits\n");

      touch->info_y_limits.enabled = false;
   }
   else
      udev_touch_set_limits_from(&abs_info, &touch->info_y_limits);

   /* Get major axis limits - i.e. primary radius of the touch */
   ret = ioctl(dev->fd, EVIOCGABS(ABS_MT_TOUCH_MAJOR), &abs_info);
   if (ret < 0)
   {
      RARCH_DBG("[udev] Failed to get touchscreen major limits\n");

      touch->info_major.enabled = false;
   }
   else
      udev_touch_set_limits_from(&abs_info, &touch->info_major);

   /* Get minor axis limits - i.e. secondary radius of the touch */
   ret = ioctl(dev->fd, EVIOCGABS(ABS_MT_TOUCH_MINOR), &abs_info);
   if (ret < 0)
   {
      RARCH_DBG("[udev] Failed to get touchscreen minor limits\n");

      touch->info_minor.enabled = false;
   }
   else
      udev_touch_set_limits_from(&abs_info, &touch->info_minor);

   /* Get pressure limits */
   ret = ioctl(dev->fd, EVIOCGABS(ABS_MT_PRESSURE), &abs_info);
   if (ret < 0)
   {
      RARCH_DBG("[udev] Failed to get touchscreen pres-limits\n");

      touch->info_pressure.enabled = false;
   }
   else
      udev_touch_set_limits_from(&abs_info, &touch->info_pressure);

   /* Allocate the data blocks required for state tracking */
   /* __u32 + __s32[num_slots] */
   touch->request_data_size = sizeof(int32_t) + sizeof(uint32_t) * touch->info_slots.range;
   touch->request_data      = calloc(1, touch->request_data_size);
   if (!touch->request_data)
   {
      RARCH_ERR("[udev] Failed to allocate request_data for touch state tracking.\n");
      udev_destroy_touch_dev(dev);
      return;
   }

   touch->staging        = calloc(1, sizeof(*touch->staging) * touch->info_slots.range);
   touch->staging_active = 0;
   if (!touch->staging)
   {
      RARCH_ERR("[udev] Failed to allocate staging for touch state tracking.\n");
      udev_destroy_touch_dev(dev);
      return;
   }
   touch->current        = calloc(1, sizeof(*touch->current) * touch->info_slots.range);
   touch->current_active = 0;
   if (!touch->current)
   {
      RARCH_ERR("[udev] Failed to allocate current for touch state tracking.\n");
      udev_destroy_touch_dev(dev);
      return;
   }

   /* Initialize touch device */
   touch->current_slot      = UDEV_INPUT_TOUCH_SLOT_ID_NONE;
   touch->is_touch_device   = true;
   touch->run_state_update  = false;
   udev_touch_ts_now(&touch->last_state_update);

   /* Initialize pointer simulation */
   touch->pointer_enabled   = UDEV_INPUT_TOUCH_POINTER_EN;
   touch->pointer_btn_pp    = false;
   touch->pointer_btn_pb    = false;
   touch->pointer_pos_x     = 0;
   touch->pointer_pos_y     = 0;
   touch->pointer_ma_pos_x  = 0;
   touch->pointer_ma_pos_y  = 0;
   touch->pointer_ma_rel_x  = 0;
   touch->pointer_ma_rel_y  = 0;
   touch->pointer_scr_pos_x = 0;
   touch->pointer_scr_pos_y = 0;
   touch->pointer_vp_pos_x  = 0;
   touch->pointer_vp_pos_y  = 0;

   /* Initialize mouse simulation */
   touch->mouse_enabled = UDEV_INPUT_TOUCH_MOUSE_EN;
   touch->mouse_freeze_cursor = false;
   touch->mouse_scr_pos_x = 0;
   touch->mouse_scr_pos_y = 0;
   touch->mouse_vp_pos_x = 0;
   touch->mouse_vp_pos_y = 0;
   touch->mouse_rel_x = 0;
   touch->mouse_rel_y = 0;
   touch->mouse_wheel_x = 0;
   touch->mouse_wheel_y = 0;
   touch->mouse_btn_l = false;
   touch->mouse_btn_r = false;
   touch->mouse_btn_m = false;
   touch->mouse_btn_b4 = false;
   touch->mouse_btn_b5 = false;

   /* Initialize touchpad simulation */
   touch->touchpad_enabled     = UDEV_INPUT_TOUCH_TOUCHPAD_EN;
   touch->touchpad_sensitivity = UDEV_INPUT_TOUCH_PAD_SENSITIVITY;
   touch->touchpad_pos_x       = 0.0f;
   touch->touchpad_pos_y       = 0.0f;

   /* Initialize trackball simulation */
   touch->trackball_enabled = UDEV_INPUT_TOUCH_TRACKBALL_EN;
   touch->trackball_inertial = false;
   touch->trackball_pos_x = 0.0f;
   touch->trackball_pos_y = 0.0f;
   touch->trackball_sensitivity_x = UDEV_INPUT_TOUCH_TRACKBALL_SENSITIVITY_X;
   touch->trackball_sensitivity_y = UDEV_INPUT_TOUCH_TRACKBALL_SENSITIVITY_Y;
   touch->trackball_vel_x = 0.0f;
   touch->trackball_vel_y = 0.0f;
   touch->trackball_frict_x = UDEV_INPUT_TOUCH_TRACKBALL_FRICT_X;
   touch->trackball_frict_y = UDEV_INPUT_TOUCH_TRACKBALL_FRICT_Y;
   touch->trackball_sq_vel_cutoff = UDEV_INPUT_TOUCH_TRACKBALL_SQ_VEL_CUTOFF;

   /* Initialize gestures */
   touch->gest_enabled = UDEV_INPUT_TOUCH_GEST_EN;
   touch->gest_primary_slot = UDEV_INPUT_TOUCH_SLOT_ID_NONE;
   touch->gest_secondary_slot = UDEV_INPUT_TOUCH_SLOT_ID_NONE;
   touch->gest_timeout = UDEV_INPUT_TOUCH_GEST_TIMEOUT;
   touch->gest_tap_time = UDEV_INPUT_TOUCH_MAX_TAP_TIME;
   touch->gest_tap_dist = UDEV_INPUT_TOUCH_MAX_TAP_DIST;
   touch->gest_click_time = UDEV_INPUT_TOUCH_GEST_CLICK_TIME;
   touch->gest_tap_count = 0;
   touch->gest_tap_possible = false;
   touch->gest_scroll_sensitivity = UDEV_INPUT_TOUCH_GEST_SCROLL_SENSITIVITY;
   touch->gest_scroll_step = UDEV_INPUT_TOUCH_GEST_SCROLL_STEP;
   touch->gest_scroll_x = 0;
   touch->gest_scroll_y = 0;
   touch->gest_corner = UDEV_INPUT_TOUCH_GEST_CORNER;

   for (iii = 0; iii < UDEV_TOUCH_TGEST_LAST; ++iii)
   {
      touch->gest_tcbs[iii].active        = false;
      touch->gest_tcbs[iii].execute_at.s  = 0;
      touch->gest_tcbs[iii].execute_at.us = 0;
      touch->gest_tcbs[iii].cb            = NULL;
      touch->gest_tcbs[iii].data          = NULL;
   }

   touch->gest_mgest_type = UDEV_TOUCH_MGEST_NONE;
   for (iii = 0; iii < UDEV_TOUCH_MGEST_LAST; ++iii)
   {
      touch->gest_mcbs[iii].active        = false;
      touch->gest_mcbs[iii].execute_at.s  = 0;
      touch->gest_mcbs[iii].execute_at.us = 0;
      touch->gest_mcbs[iii].cb            = NULL;
      touch->gest_mcbs[iii].data          = NULL;
   }

   /* Force load the options from settings */
   udev_update_touch_dev_options(dev, true);

   /* Print debug information */
   udev_dump_touch_dev(dev);
}

/**
 * Fully synchronize the statue of given touch device.
 * This is inefficient compared to the event-driven
 * approach, but results in fully synchronized state.
 *
 * @param dev Input touch device to synchronize.
 */
static void udev_sync_touch(udev_input_device_t *dev)
{
   int iii, ret;
   struct input_absinfo abs_info;
   uint32_t *mt_req_code;
   int32_t *mt_req_values;
   uint8_t *mt_request_data;
   size_t mt_request_data_size;
   size_t slot_count;
   udev_touch_ts_t now;
   udev_input_touch_t *touch = &dev->touch;
   udev_slot_state_t *staging = dev->touch.staging;

   RARCH_DDBG("[udev] Synchronizing touch data...\n");

   /* Get time for timestamp purposes */
   /*ktime_get_ts64(&ts); */
   /*u64_t Vkk */

   /*
    * Data block compatible with the following structure:
    * struct input_mt_request_layout {
    *     __u32 code;
    *     __s32 values[slot_count];
    * };
    */
   mt_request_data      = touch->request_data;
   mt_request_data_size = touch->request_data_size;
   slot_count           = touch->info_slots.range;

   /* Get current time for initialization */
   udev_touch_ts_now(&now);

   if (mt_request_data == NULL)
      return;

   mt_req_code   = (uint32_t*)mt_request_data;
   mt_req_values = ((int32_t*)mt_request_data) + 1;

   /* Request tracking IDs for each slot */
   *mt_req_code  = ABS_MT_TRACKING_ID;
   ret = ioctl(dev->fd, EVIOCGMTSLOTS(mt_request_data_size), mt_request_data);
   if (ret < 0)
      return;
   RARCH_DDBG("[udev] \tTracking IDs:\n");
   for (iii = 0; iii < slot_count; ++iii)
   {
      RARCH_DDBG("[udev] \t\t%d: %d -> %d\n", iii, staging[iii].tracking_id, mt_req_values[iii]);
      staging[iii].tracking_id = mt_req_values[iii];
      udev_touch_ts_copy(&now, &staging[iii].td_time);
   }

   /* Request MT position on the x-axis for each slot */
   *mt_req_code = ABS_MT_POSITION_X;
   ret          = ioctl(dev->fd, EVIOCGMTSLOTS(mt_request_data_size), mt_request_data);
   if (ret < 0)
      return;
   RARCH_DDBG("[udev] \tMT X-Positions:\n");
   for (iii = 0; iii < slot_count; ++iii)
   {
      RARCH_DDBG("[udev] \t\t%d: %d -> %d\n", iii, staging[iii].pos_x, mt_req_values[iii]);
      staging[iii].pos_x = mt_req_values[iii];
      staging[iii].td_pos_x = mt_req_values[iii];
   }

   /* Request MT position on the y-axis for each slot */
   *mt_req_code = ABS_MT_POSITION_Y;
   ret          = ioctl(dev->fd, EVIOCGMTSLOTS(mt_request_data_size), mt_request_data);
   if (ret < 0)
      return;
   RARCH_DDBG("[udev] \tMT Y-Positions:\n");
   for (iii = 0; iii < slot_count; ++iii)
   {
      RARCH_DDBG("[udev] \t\t%d: %d -> %d\n", iii, staging[iii].pos_y, mt_req_values[iii]);
      staging[iii].pos_y    = mt_req_values[iii];
      staging[iii].td_pos_y = mt_req_values[iii];
   }

   /* Request minor axis for each slot */
   *mt_req_code = ABS_MT_TOUCH_MINOR;
   ret          = ioctl(dev->fd, EVIOCGMTSLOTS(mt_request_data_size), mt_request_data);
   if (ret < 0)
      return;
   RARCH_DDBG("[udev] \tMinor:\n");
   for (iii = 0; iii < slot_count; ++iii)
   {
      RARCH_DDBG("[udev] \t\t%d: %d -> %d\n", iii, staging[iii].minor, mt_req_values[iii]);
      staging[iii].minor = mt_req_values[iii];
   }

   /* Request major axis for each slot */
   *mt_req_code = ABS_MT_TOUCH_MAJOR;
   ret          = ioctl(dev->fd, EVIOCGMTSLOTS(mt_request_data_size), mt_request_data);
   if (ret < 0)
      return;
   RARCH_DDBG("[udev] \tMajor:\n");
   for (iii = 0; iii < slot_count; ++iii)
   {
      RARCH_DDBG("[udev] \t\t%d: %d -> %d\n", iii, staging[iii].major, mt_req_values[iii]);
      staging[iii].major = mt_req_values[iii];
   }

   /* Request major axis for each slot */
   *mt_req_code = ABS_MT_PRESSURE;
   ret          = ioctl(dev->fd, EVIOCGMTSLOTS(mt_request_data_size), mt_request_data);
   if (ret < 0)
      return;
   RARCH_DDBG("[udev] \tPressure:\n");
   for (iii = 0; iii < slot_count; ++iii)
   {
      RARCH_DDBG("[udev] \t\t%d: %d -> %d\n", iii, staging[iii].pressure, mt_req_values[iii]);
      staging[iii].pressure = mt_req_values[iii];
   }

   /* Get the current slot */
   ret = ioctl(dev->fd, EVIOCGABS(ABS_MT_SLOT), &abs_info);
   if (ret < 0)
       return;
   RARCH_DDBG("[udev] \tCurrent slot: %d -> %d\n", touch->current_slot, abs_info.value);
   touch->current_slot = abs_info.value;
}

/**
 * Translate touch panel position into other coordinate systems.
 *
 * @param src_touch Information concerning the source touch panel.
 * @param target_vp Information about the target panel. Pre-filled
 *   with the video_driver_get_viewport_info function.
 * @param pointer_pos_x Input x-coordinate on the touch panel.
 * @param pointer_pos_y Input y-coordinate on the touch panel.
 * @param pointer_ma_pos_x Output x-coordinate on the target panel.
 * @param pointer_ma_pos_y Output y-coordinate on the target panel.
 * @param pointer_ma_rel_x Output x-coordinate change on the target panel.
 *   The resulting delta is added to this output!
 * @param pointer_ma_rel_y Output y-coordinate change on the target panel.
 *   The resulting delta is added to this output!
 * @param pointer_scr_pos_x Output x-coordinate on the target screen.
 *   Uses the scaled coordinates -0x7fff - 0x7fff.
 * @param pointer_vp_pos_x Output x-coordinate on the target window.
 *   Uses the scaled coordinates -0x7fff - 0x7fff and -0x8000 when OOB.
 * @return Returns true on success.
 */
static bool udev_translate_touch_pos(
        const udev_input_touch_t *src_touch,
        video_viewport_t *target_vp,
        int32_t pointer_pos_x, int32_t pointer_pos_y,
        int32_t *pointer_ma_pos_x, int32_t *pointer_ma_pos_y,
        int16_t *pointer_ma_rel_x, int16_t *pointer_ma_rel_y,
        int16_t *pointer_scr_pos_x, int16_t *pointer_scr_pos_y,
        int16_t *pointer_vp_pos_x, int16_t *pointer_vp_pos_y)
{
   /* Touch panel -> Main panel */
   /*
    * TODO - This keeps the precision, but might result in +-1 pixel difference
    *   One way to fix this is to add or remove 0.5, but this needs floating
    *   point operations which might not be desirable.
    */
   int32_t ma_pos_x   = (((((pointer_pos_x + src_touch->info_x_limits.min) * 0x7fff) / src_touch->info_x_limits.range) * target_vp->full_width) / 0x7fff);
   int32_t ma_pos_y   = (((((pointer_pos_y + src_touch->info_y_limits.min) * 0x7fff) / src_touch->info_y_limits.range) * target_vp->full_height) / 0x7fff);

   /* Calculate relative offsets. */
   *pointer_ma_rel_x += ma_pos_x - *pointer_ma_pos_x;
   *pointer_ma_rel_y += ma_pos_y - *pointer_ma_pos_y;

   /* Set the new main panel positions. */
   *pointer_ma_pos_x  = ma_pos_x;
   *pointer_ma_pos_y  = ma_pos_y;

   /* Main panel -> Screen and Viewport */
   return video_driver_translate_coord_viewport_wrap(
      target_vp,
      *pointer_ma_pos_x,
      *pointer_ma_pos_y,
      pointer_vp_pos_x,
      pointer_vp_pos_y,
      pointer_scr_pos_x,
      pointer_scr_pos_y
   );
}

/**
 * Setup a delayed callback. Automatically activates it.
 *
 * @param timed_cb Target structure to fill.
 * @param now Current time.
 * @param delay_us Delay in microseconds.
 * @param cb Callback function to execute.
 * @param data Data passed to the callback.
 */
static void udev_input_touch_gest_set_cb(
        udev_touch_timed_cb_t *timed_cb,
        const udev_touch_ts_t *now,
        uint32_t delay_us,
        void (*cb) (void*, void*), void *data)
{
   timed_cb->active = true;
   udev_touch_ts_add(now, 0, delay_us, &timed_cb->execute_at);
   timed_cb->cb     = cb;
   timed_cb->data   = data;
}

/**
 * Execute given callback and set it as inactive.
 *
 * @param timed_cb Callback to execute.
 * @param touch Touch structure to pass to the callback.
 */
static void udev_input_touch_gest_exec_cb(
        udev_touch_timed_cb_t *timed_cb,
        udev_input_touch_t *touch)
{
   timed_cb->active = false;
   timed_cb->cb(touch, timed_cb->data);
}

/**
 * Disable given callback, rendering it inactive.
 *
 * @param timed_cb Callback to execute.
 */
static void udev_input_touch_gest_disable_cb(
        udev_touch_timed_cb_t *timed_cb)
{
   timed_cb->active = false;
}

/* Callback used for resetting boolean variable to false. */
static void udev_input_touch_gest_reset_bool(void *touch, void *tgt)
{
   *((bool*)tgt) = false;
}

/* Callback used for resetting mouse_wheel_x/y variables to 0. */
static void udev_input_touch_gest_reset_scroll(void *touch, void *none)
{
   ((udev_input_touch_t*)touch)->gest_scroll_x = 0;
   ((udev_input_touch_t*)touch)->gest_scroll_y = 0;
}

/**
 * Runner for special functions. Currently, the following
 * functions are implemented:
 * * Top Left corner -> Enable/Disable mouse.
 * * Top Right corner -> Enable/Disable touchpad.
 * * Bottom Left corner -> Enable/Disable pointer.
 * * Bottom Right corner -> Enable/Disable trackball.
 */
static bool udev_input_touch_tgest_special(udev_input_touch_t *touch,
        const udev_touch_ts_t *now, int32_t pos_x, int32_t pos_y)
{
   /* Did we act for the input position? */
   bool serviced = false;
   /* Convert pos_x/y into percentage of touch panel. */
   int32_t ptg_x = ((pos_x + touch->info_x_limits.min) * 100) / touch->info_x_limits.range;
   int32_t ptg_y = ((pos_y + touch->info_y_limits.min) * 100) / touch->info_y_limits.range;

   /* Negative (left, bottom) and positive (right, up) corner percentages */
   uint16_t ptg_corner_neg = touch->gest_corner;
   uint16_t ptg_corner_pos = 100 - ptg_corner_neg;

   /* TODO - Currently unused. */
   UDEV_INPUT_TOUCH_UNUSED(now);

   /* Top Left corner */
   if (ptg_y < ptg_corner_neg && ptg_x < ptg_corner_neg)
   {
      touch->mouse_enabled = !touch->mouse_enabled;
      RARCH_DBG("[udev] TGesture: SF/TT -> Top Left: Mouse %s\n",
              touch->mouse_enabled ? "enabled" : "disabled");
      serviced = true;
   }
   else if (ptg_y < ptg_corner_neg && ptg_x > ptg_corner_pos)
   { /* Top Right corner */
      touch->touchpad_enabled = !touch->touchpad_enabled;
      RARCH_DBG("[udev] TGesture: SF/TT -> Top Right: Touchpad %s\n",
              touch->touchpad_enabled ? "enabled" : "disabled");
      serviced = true;
   }
   else if (ptg_y > ptg_corner_pos && ptg_x < ptg_corner_neg)
   { /* Bottom Left corner */
      touch->pointer_enabled = !touch->pointer_enabled;
      RARCH_DBG("[udev] TGesture: SF/TT -> Bottom Left: Pointer %s\n",
              touch->pointer_enabled ? "enabled" : "disabled");
      serviced = true;
   }
   else if (ptg_y > ptg_corner_pos && ptg_x > ptg_corner_pos)
   { /* Bottom Right corner */
      touch->trackball_enabled = !touch->trackball_enabled;
      RARCH_DBG("[udev] TGesture: SF/TT -> Bottom Right: Trackball %s\n",
              touch->gest_enabled ? "enabled" : "disabled");
      serviced = true;
   }

   return serviced;
}

/**
 * Callback performing tap gesture selection, usually triggered
 * upon reaching gesture timeout.
 *
 * @param touch_ptr Pointer to the touch structure.
 * @param data Additional data. TODO - Currently unused (NULL).
 */
static void udev_input_touch_tgest_select(void *touch_ptr, void *data)
{
   udev_touch_ts_t now;
   /* Based on the gesture, change current touch state */
   udev_input_touch_t *touch = (udev_input_touch_t*) touch_ptr;

   /* Get current time for measurements */
   udev_touch_ts_now(&now);

   /* No hold with single finger tap */
   if (touch->staging_active == 0)
   {
      switch (touch->gest_tap_count)
      {
         case 1:
            /* One tap -> Left mouse button */
            touch->mouse_btn_l = true;
            /* Setup callback to reset the button state. */
            udev_input_touch_gest_set_cb(
               &touch->gest_tcbs[UDEV_TOUCH_TGEST_S_TAP],
               &now, touch->gest_click_time,
               udev_input_touch_gest_reset_bool, &touch->mouse_btn_l);
            RARCH_DDBG("[udev] TGesture: SF/ST -> Left Mouse Button\n");
            break;
         case 2:
            /* Two taps -> Right mouse button */
            touch->mouse_btn_r = true;
            /* Setup callback to reset the button state. */
            udev_input_touch_gest_set_cb(
               &touch->gest_tcbs[UDEV_TOUCH_TGEST_D_TAP],
               &now, touch->gest_click_time,
               udev_input_touch_gest_reset_bool, &touch->mouse_btn_r);
            RARCH_DDBG("[udev] TGesture: SF/DT -> Right Mouse Button\n");
            break;
         case 3:
            /* Three taps -> Middle mouse button & Specials */
            if (!udev_input_touch_tgest_special(touch, &now,
                        touch->pointer_pos_x, touch->pointer_pos_y))
            {
               touch->mouse_btn_m = true;
               /* Setup callback to reset the button state. */
               udev_input_touch_gest_set_cb(
                  &touch->gest_tcbs[UDEV_TOUCH_TGEST_T_TAP],
                  &now, touch->gest_click_time,
                  udev_input_touch_gest_reset_bool, &touch->mouse_btn_r);
               RARCH_DDBG("[udev] TGesture: SF/TT -> Middle Mouse Button\n");
            }
            break;
         default:
            /* More taps -> No action */
            break;
      }
   }
   else if (touch->staging_active == 1)
   { /* Single hold with second finger tap */
      touch->mouse_btn_r = true;
      /* Setup callback to reset the button state. */
      udev_input_touch_gest_set_cb(
         &touch->gest_tcbs[UDEV_TOUCH_TGEST_D_TAP],
         &now, touch->gest_click_time,
         udev_input_touch_gest_reset_bool, &touch->mouse_btn_r);
      RARCH_DDBG("[udev] TGesture: DF/ST -> Right Mouse Button\n");
   }
   else if (touch->staging_active == 2)
   { /* Two hold with third finger tap */
      touch->mouse_btn_m = true;
      /* Setup callback to reset the button state. */
      udev_input_touch_gest_set_cb(
         &touch->gest_tcbs[UDEV_TOUCH_TGEST_T_TAP],
         &now, touch->gest_click_time,
         udev_input_touch_gest_reset_bool, &touch->mouse_btn_m);
      RARCH_DDBG("[udev] TGesture: TF/ST -> Middle Mouse Button\n");
   }

   /* Reset the tap count for the next gesture. */
   touch->gest_tap_count = 0;
}

/**
 * Reset the move-based gestures.
 *
 * @param touch Pointer to the touch structure.
 */
static void udev_input_touch_mgest_reset(udev_input_touch_t *touch,
        udev_input_touch_slot_id current_slot_id,
        const udev_touch_ts_t *now)
{
   switch (touch->gest_mgest_type)
   {
      case UDEV_TOUCH_MGEST_S_STAP_DRAG:
         /* Gesture for one finger single tap drag. */
         touch->mouse_btn_l = false;
         break;
      case UDEV_TOUCH_MGEST_S_DTAP_DRAG:
         /* Gesture for one finger double tap drag. */
         touch->mouse_btn_r = false;
         break;
      case UDEV_TOUCH_MGEST_S_TTAP_DRAG:
         /* Gesture for one finger triple tap drag. */
         touch->mouse_btn_m = false;
         break;
      case UDEV_TOUCH_MGEST_D_NTAP_DRAG:
         /* Gesture for two finger no tap drag. */
         /* Completely reset the scroll after timeout. */
         udev_input_touch_gest_set_cb(
            &touch->gest_mcbs[UDEV_TOUCH_MGEST_D_NTAP_DRAG],
            now, touch->gest_timeout,
            udev_input_touch_gest_reset_scroll, NULL);
         break;
      case UDEV_TOUCH_MGEST_D_STAP_DRAG:
         /* Gesture for two finger single tap drag. */
         break;
      case UDEV_TOUCH_MGEST_T_NTAP_DRAG:
         /* Gesture for three finger no tap drag. */
         break;
      case UDEV_TOUCH_MGEST_T_STAP_DRAG:
         /* Gesture for three finger single tap drag. */
         break;
      default:
         /* No action */
         break;
   }

   /* Reset the current move-gesture */
   touch->gest_mgest_type = UDEV_TOUCH_MGEST_NONE;
}

/**
 * Perform move-based gesture selection, usually triggered upon
 * movement after tap is impossible.
 *
 * @param touch Pointer to the touch structure.
 * @param current_slot_id ID of the currently serviced slot. Can be
 *   used to compare against gest_primary/secondary_slot.
 * @param now Current time.
 */
static void udev_input_touch_mgest_select(udev_input_touch_t *touch,
        udev_input_touch_slot_id current_slot_id,
        const udev_touch_ts_t *now)
{
   /* Perform actions only for the primary slot */
   if (current_slot_id != touch->gest_primary_slot)
      return;

   /* Determine type of move-gesture */
   if (touch->gest_mgest_type == UDEV_TOUCH_MGEST_NONE)
   {
      /* Single finger hold with single tap */
      if (touch->staging_active == 1)
      {
         switch (touch->gest_tap_count)
         {
            case 1:
               /* One tap hold -> Left mouse button drag */
               touch->mouse_btn_l = true;
               touch->gest_mgest_type = UDEV_TOUCH_MGEST_S_STAP_DRAG;
               RARCH_DDBG("[udev] MGesture: SF/STD -> Left Mouse Button Drag\n");
               break;
            case 2:
               /* Two taps -> Right mouse button drag */
               touch->mouse_btn_r = true;
               touch->gest_mgest_type = UDEV_TOUCH_MGEST_S_DTAP_DRAG;
               RARCH_DDBG("[udev] MGesture: SF/DTD -> Right Mouse Button\n");
               break;
            case 3:
               /* Three taps -> Middle mouse button drag */
               touch->mouse_btn_m = true;
               touch->gest_mgest_type = UDEV_TOUCH_MGEST_S_TTAP_DRAG;
               RARCH_DDBG("[udev] MGesture: SF/TTD -> Middle Mouse Button\n");
               break;
            default:
               /* More taps drag -> No action */
               break;
         }
      }
      /* Two finger hold with single tap */
      else if (touch->staging_active == 2)
      {
         switch (touch->gest_tap_count)
         {
            case 0:
               /* No tap hold -> 3D wheel scrolling */
               touch->gest_mgest_type = UDEV_TOUCH_MGEST_D_NTAP_DRAG;
               RARCH_DDBG("[udev] MGesture: DF/NTD -> 3D Wheel\n");
               break;
            case 1:
               /* Single tap hold -> TODO - Some interesting action? */
               touch->gest_mgest_type = UDEV_TOUCH_MGEST_D_STAP_DRAG;
               RARCH_DDBG("[udev] MGesture: DF/STD -> TODO\n");
               break;
            default:
               /* More taps drag -> No action */
               break;
         }
      }
      /* Three finger hold with single tap */
      else if (touch->staging_active == 3)
      {
         switch (touch->gest_tap_count)
         {
            case 0:
               /* No tap hold -> TODO - Some interesting action? */
               touch->gest_mgest_type = UDEV_TOUCH_MGEST_T_NTAP_DRAG;
               RARCH_DDBG("[udev] MGesture: DF/NTD -> TODO\n");
               break;
            case 1:
               /* Single tap hold -> TODO - Some interesting action? */
               touch->gest_mgest_type = UDEV_TOUCH_MGEST_T_STAP_DRAG;
               RARCH_DDBG("[udev] MGesture: DF/STD -> TODO\n");
               break;
            default:
               /* More taps drag -> No action */
               break;
         }
      }

      /* Reset the tap count for the next gesture. */
      touch->gest_tap_count = 0;
   }

   /* Update the current state of move-gesture */
   switch (touch->gest_mgest_type)
   {
      case UDEV_TOUCH_MGEST_S_STAP_DRAG:
         /* Gesture for one finger single tap drag. */
         break;
      case UDEV_TOUCH_MGEST_S_DTAP_DRAG:
         /* Gesture for one finger double tap drag. */
         break;
      case UDEV_TOUCH_MGEST_S_TTAP_DRAG:
         /* Gesture for one finger triple tap drag. */
         break;
      case UDEV_TOUCH_MGEST_D_NTAP_DRAG:
         /* Gesture for two finger no tap drag. */
         touch->gest_scroll_x +=
            (
               touch->pointer_ma_rel_x *
               touch->gest_scroll_sensitivity
            ) / touch->info_x_limits.range;
         touch->gest_scroll_y +=
            (
               touch->pointer_ma_rel_y *
               touch->gest_scroll_sensitivity
            ) / touch->info_y_limits.range;
         RARCH_DDBG("[udev] MGesture: DF/NTD -> 3D Wheel: %hd x %hd | %hd\n", touch->gest_scroll_x, touch->gest_scroll_y, touch->gest_scroll_step);
         break;
      case UDEV_TOUCH_MGEST_D_STAP_DRAG:
         /* Gesture for two finger single tap drag. */
         break;
      case UDEV_TOUCH_MGEST_T_NTAP_DRAG:
         /* Gesture for three finger no tap drag. */
         break;
      case UDEV_TOUCH_MGEST_T_STAP_DRAG:
         /* Gesture for three finger single tap drag. */
         break;
      default:
         /* No action */
         break;
   }
}

/**
 * Synchronize touch events to other endpoints and
 * reset for the next event packet.
 *
 * @param udev Input udev system.
 * @param dev Input touch device to report for.
 */
static void udev_report_touch(udev_input_t *udev, udev_input_device_t *dev)
{
   /* Touch state being modified. */
   udev_input_touch_t *touch = &dev->touch;

   /* Helper variables. */
   int iii;
   int32_t ts_diff;
   uint32_t tp_diff;
   int32_t last_mouse_pos_x;
   int32_t last_mouse_pos_y;
   enum udev_input_touch_dir tp_diff_dir;
   video_viewport_t vp;
   udev_touch_ts_t now;
   udev_slot_state_t *slot_curr;
   udev_slot_state_t *slot_prev;

   /* Get main panel information for coordinate translation */
   video_driver_get_viewport_info(&vp);
   /* Get current time for measurements */
   udev_touch_ts_now(&now);

   /*udev_dump_touch_dev(dev); */

   for (iii = 0; iii < touch->info_slots.range; ++iii)
   {
      slot_curr = &touch->staging[iii];
      slot_prev = &touch->current[iii];

      /* TODO - Unused for now */
      UDEV_INPUT_TOUCH_UNUSED(slot_prev);

      switch (slot_curr->change)
      {
         case UDEV_TOUCH_CHANGE_NONE:
            /* No operation */
            break;
         case UDEV_TOUCH_CHANGE_DOWN:
            /* Tracking started -> touchdown */
            touch->staging_active++;

            /* First touchpoint is our primary gesture point */
            if (touch->staging_active == 1)
            { touch->gest_primary_slot = iii; }
            /* Second touchpoint is our secondary gesture point */
            if (touch->staging_active == 2)
            { touch->gest_secondary_slot = iii; }
            RARCH_DDBG("[udev] Active: %d\n", touch->staging_active);

            /* Touchscreen update */
            if (iii == touch->gest_primary_slot)
            {
               /* Use position of the primary touch point */
               touch->pointer_pos_x = slot_curr->pos_x;
               touch->pointer_pos_y = slot_curr->pos_y;
               udev_translate_touch_pos(
                  touch, &vp,
                  touch->pointer_pos_x, touch->pointer_pos_y,
                  &touch->pointer_ma_pos_x, &touch->pointer_ma_pos_y,
                  &touch->pointer_ma_rel_x, &touch->pointer_ma_rel_y,
                  &touch->pointer_scr_pos_x, &touch->pointer_scr_pos_y,
                  &touch->pointer_vp_pos_x, &touch->pointer_vp_pos_y
               );

               /* Reset deltas after, since first touchdown has no delta. */
               touch->pointer_ma_rel_x = 0;
               touch->pointer_ma_rel_y = 0;
            }

            /* Pointer section */
            /* Simulated pointer */
            if (touch->pointer_enabled)
               touch->pointer_btn_pp = true;

            /* Mouse section */
            if (touch->mouse_enabled)
            { /* Simulated mouse */
               if (touch->touchpad_enabled)
               {  /* Touchpad mode -> Touchpad virtual mouse. */
                  /* Initialize touchpad position to the current mouse position */
                  touch->touchpad_pos_x = (float) touch->mouse_pos_x;
                  touch->touchpad_pos_y = (float) touch->mouse_pos_y;
               }
               else
               {  /* Direct mode -> Direct virtual mouse. */
                  /* Initialize mouse position to the current pointer position */
                  touch->mouse_pos_x = touch->pointer_ma_pos_x;
                  touch->mouse_pos_y = touch->pointer_ma_pos_y;
               }

               /* Trackball mode */
               if (touch->trackball_enabled)
                  touch->trackball_inertial = false; /* The trackball is anchored */
            }

            /* Gesture section */
            if (touch->gest_enabled)
            {
               /* Pause the tap-gesture detection timeout. */
               udev_input_touch_gest_disable_cb(
                  &touch->gest_tcbs[UDEV_TOUCH_TGEST_TIMEOUT]
               );
               /* Expect the possibility of a tap. */
               touch->gest_tap_possible = true;

               /* Freeze the mouse cursor upon getting second contact */
               if (touch->staging_active > 1)
                  touch->mouse_freeze_cursor = true;
            }

            break;
         case UDEV_TOUCH_CHANGE_UP:
            /* Ending tracking, touch up */
            if (touch->staging_active > 0)
               touch->staging_active--;
            else
            {
               RARCH_ERR("[udev] Cannot report touch up since there are no active points.\n");
            }

            /* Letting go of the primary gesture point -> Wait for full release */
            if (iii == touch->gest_primary_slot)
               touch->gest_primary_slot = UDEV_INPUT_TOUCH_TRACKING_ID_NONE;
            /* Letting go of the secondary gesture point -> Wait for full release */
            if (iii == touch->gest_secondary_slot)
               touch->gest_secondary_slot = UDEV_INPUT_TOUCH_TRACKING_ID_NONE;

            /* Touchscreen update */
#if 0
            if (iii == touch->gest_primary_slot) { }
#endif

            /* Pointer section */
            /* Simulated pointer */
            /* Release the pointer only after all contacts are released */
            if (touch->pointer_enabled)
               touch->pointer_btn_pp = (touch->staging_active == 0);

            /* Mouse section */
            if (touch->mouse_enabled)
            {
#if 0
               /* Simulated mouse */
               if (touch->touchpad_enabled)
               {
                  /* Touchpad mode -> Touchpad virtual mouse. */
                  /* Mouse buttons are governed by gestures. */
               }
               else
               {
                  /* Direct mode -> Direct virtual mouse. */
                  /* Mouse buttons are governed by gestures. */
               }
#endif

               /* Trackball mode */
               if (touch->trackball_enabled)
               {
                  /* Update trackball position */
                  touch->trackball_pos_x    = (float) touch->mouse_pos_x;
                  touch->trackball_pos_y    = (float) touch->mouse_pos_y;
                  /* The trackball is free to move */
                  touch->trackball_inertial = true;
               }
            }

            /* Gesture section */
            if (touch->gest_enabled)
            {
               if (touch->gest_tap_possible)
               {
                  /* Time of contact */
                  ts_diff = udev_touch_ts_diff(&slot_curr->td_time, &now);
                  /* Distance and direction of start -> end touch point */
                  tp_diff = udev_touch_tp_diff(
                     slot_curr->td_pos_x, slot_curr->td_pos_y,
                     slot_curr->pos_x, slot_curr->pos_y,
                     &tp_diff_dir
                  );
                  /* Tap is possible only if neither time nor distance is over limit. */
                  touch->gest_tap_possible =
                         ts_diff < touch->gest_tap_time
                      && tp_diff < touch->gest_tap_dist;
               }

               /* Tap detected */
               if (touch->gest_tap_possible)
               {
                  /* Only single tap should be possible. */
                  touch->gest_tap_possible = false;
                  /* Add additional tap. */
                  touch->gest_tap_count++;
                  /* Setup gesture timeout after which gesture is detected. */
                  udev_input_touch_gest_set_cb(
                     &touch->gest_tcbs[UDEV_TOUCH_TGEST_TIMEOUT],
                     &now, touch->gest_timeout,
                     /* TODO - Use the additional data? */
                     udev_input_touch_tgest_select, NULL);
               }

               /* Reset the move-based gestures. */
               udev_input_touch_mgest_reset(touch, iii, &now);

               /* Unfreeze the mouse cursor when releasing all contacts */
               if (touch->staging_active == 0)
                  touch->mouse_freeze_cursor = false;
            }

            break;
         case UDEV_TOUCH_CHANGE_MOVE:
            /* Change of position, size, or pressure */

            /* Touchscreen update */
            if (iii == touch->gest_primary_slot)
            {
               /* Use position of the primary touch point */
               touch->pointer_pos_x    = slot_curr->pos_x;
               touch->pointer_pos_y    = slot_curr->pos_y;

               /* Reset deltas first, so we can get new change. */
               touch->pointer_ma_rel_x = 0;
               touch->pointer_ma_rel_y = 0;

               udev_translate_touch_pos(
                  touch, &vp,
                  touch->pointer_pos_x, touch->pointer_pos_y,
                  &touch->pointer_ma_pos_x, &touch->pointer_ma_pos_y,
                  &touch->pointer_ma_rel_x, &touch->pointer_ma_rel_y,
                  &touch->pointer_scr_pos_x, &touch->pointer_scr_pos_y,
                  &touch->pointer_vp_pos_x, &touch->pointer_vp_pos_y
               );
            }

#if 0
            /* Pointer section */
            if (touch->pointer_enabled)
            {
               /* Simulated pointer */
            }
#endif

            /* Mouse section */
            if (touch->mouse_enabled && !touch->mouse_freeze_cursor)
            {
               /* Simulated mouse */
               if (touch->touchpad_enabled)
               {
                  /* Touchpad mode -> Touchpad virtual mouse. */
                  /* Calculate high resolution positions and clip them. */
                  touch->touchpad_pos_x   += touch->pointer_ma_rel_x * touch->touchpad_sensitivity;
                  if (touch->touchpad_pos_x < 0.0f)
                     touch->touchpad_pos_x = 0.0f;
                  else if (touch->touchpad_pos_x > vp.full_width)
                     touch->touchpad_pos_x = vp.full_width;
                  touch->touchpad_pos_y += touch->pointer_ma_rel_y * touch->touchpad_sensitivity;
                  if (touch->touchpad_pos_y < 0.0f)
                     touch->touchpad_pos_y = 0.0f;
                  else if (touch->touchpad_pos_y > vp.full_height)
                     touch->touchpad_pos_y = vp.full_height;

                  /* Backup last values for delta. */
                  last_mouse_pos_x   = touch->mouse_pos_x;
                  last_mouse_pos_y   = touch->mouse_pos_y;

                  /* Convert high resolution (sub-pixels) -> low resolution (pixels) */
                  touch->mouse_pos_x = (int32_t) touch->touchpad_pos_x;
                  touch->mouse_pos_y = (int32_t) touch->touchpad_pos_y;

                  /* Translate the panel coordinates into normalized coordinates. */
                  video_driver_translate_coord_viewport_wrap(
                     &vp, touch->mouse_pos_x, touch->mouse_pos_y,
                     &touch->mouse_vp_pos_x, &touch->mouse_vp_pos_y,
                     &touch->mouse_scr_pos_x, &touch->mouse_scr_pos_y
                  );

                  /* Calculate cursor delta in screen space. */
                  touch->mouse_rel_x += touch->mouse_pos_x - last_mouse_pos_x;
                  touch->mouse_rel_y += touch->mouse_pos_y - last_mouse_pos_y;
               }
               else
               {
                  /* Direct mode -> Direct virtual mouse. */
                  /* Set mouse cursor position directly from the pointer. */
                  last_mouse_pos_x       = touch->mouse_pos_x;
                  last_mouse_pos_y       = touch->mouse_pos_y;
                  touch->mouse_rel_x    += touch->pointer_ma_pos_x - touch->mouse_pos_x;
                  touch->mouse_rel_y    += touch->pointer_ma_pos_y - touch->mouse_pos_y;
                  touch->mouse_pos_x     = touch->pointer_ma_pos_x;
                  touch->mouse_pos_y     = touch->pointer_ma_pos_y;
                  touch->mouse_scr_pos_x = touch->pointer_scr_pos_x;
                  touch->mouse_scr_pos_y = touch->pointer_scr_pos_y;
                  touch->mouse_vp_pos_x  = touch->pointer_vp_pos_x;
                  touch->mouse_vp_pos_y  = touch->pointer_vp_pos_y;
               }

               /* Trackball mode */
               if (touch->trackball_enabled)
               {
                  /* Update trackball position */
                  touch->trackball_pos_x = (float)touch->mouse_pos_x;
                  touch->trackball_pos_y = (float)touch->mouse_pos_y;
                  /* Accumulate trackball velocity */
                  touch->trackball_vel_x = \
                     touch->trackball_frict_x * touch->trackball_vel_x + \
                     touch->trackball_sensitivity_x * \
                     (touch->mouse_pos_x - last_mouse_pos_x);
                  touch->trackball_vel_y = \
                     touch->trackball_frict_y * touch->trackball_vel_y + \
                     touch->trackball_sensitivity_y * \
                     (touch->mouse_pos_y - last_mouse_pos_y);
               }
            }

            /* Gesture section */
            if (touch->gest_enabled)
            { /* Move-based gestures - swiping, pinching, etc. */
               if (touch->gest_tap_possible)
               {
                  /* Time of contact */
                  ts_diff = udev_touch_ts_diff(&slot_curr->td_time, &now);
                  /* Distance and direction of start -> end touch point */
                  tp_diff = udev_touch_tp_diff(
                     slot_curr->td_pos_x, slot_curr->td_pos_y,
                     slot_curr->pos_x, slot_curr->pos_y,
                     &tp_diff_dir
                  );
                  /* Tap is possible only if neither time nor distance is over limit. */
                  touch->gest_tap_possible =
                         ts_diff < touch->gest_tap_time
                      && tp_diff < touch->gest_tap_dist;
               }

               /* Once tap is impossible, we can detect move-based gestures. */
               /*
                * At this moment, tap gestures are no longer possible,
                * since gest_tap_possible == false
                */
               if (!touch->gest_tap_possible)
                  udev_input_touch_mgest_select(touch, iii, &now);
            }
            break;
         default:
            RARCH_ERR("[udev] Unknown slot change %d.\n", touch->staging[iii].change);
            break;
      }

   }

   /* Copy staging to current slots and prepare for next round */
   memcpy(touch->current, touch->staging, sizeof(udev_slot_state_t) * touch->info_slots.range);
   touch->current_active = touch->staging_active;

   /* Reset the change flag to prepare for next round */
   for (iii = 0; iii < touch->info_slots.range; ++iii)
      touch->staging[iii].change = UDEV_TOUCH_CHANGE_NONE;
}

/**
 * Function handling incoming udev events pertaining to a touch device.
 *
 * @param data Data passed by the callback -> udev_input_t*
 * @param event Incoming event.
 * @param dev The source device.
 */
static void udev_handle_touch(void *data,
      const struct input_event *event, udev_input_device_t *dev)
{
   udev_input_t *udev        = (udev_input_t*)data;
   udev_input_mouse_t *mouse = &dev->mouse;
   udev_input_touch_t *touch = &dev->touch;

   /* struct input_event */
   /* { */
   /*   (pseudo) input_event_sec; */
   /*   (pseudo) input_event_usec; */
   /*   __u16 type; */
   /*   __u16 code; */
   /*   __s32 value; */
   /* } */
   /* Timestamp for the event in event->time */
   /* type: code -> value */
   /* EV_ABS: ABS_MT_TRACKING_ID -> Unique ID for each touch */
   /* EV_ABS: ABS_MT_POSITION_X/Y -> Absolute position of the multitouch */
   /* EV_ABS: ABS_MT_TOUCH_MAJOR -> Major axis (size) of the touch */
   /* EV_KEY: BTN_TOUCH -> Signal for any touch - 1 down and 0 up */
   /* EV_ABS: ABS_X/Y -> Absolute position of the touch */
   /* SYN_REPORT -> End of packet */

   switch (event->type)
   {
      case EV_ABS:
         switch (event->code)
         {
            case ABS_MT_SLOT:
               /* Move to a specific slot */
               if (event->value >= 0 && event->value < touch->info_slots.range)
                  touch->current_slot = event->value;
               else
               {
                  RARCH_WARN("[udev] handle_touch: Invalid touch slot id [%d]\n", event->value);
               }
               break;
            case ABS_MT_TRACKING_ID:
               touch->staging[touch->current_slot].tracking_id = event->value;

               if (event->value >= 0)
               {
                  /* Starting a new tracking */
                  RARCH_DDBG("[udev] handle_touch: Tracking slot [%d]\n", touch->current_slot);
                  touch->staging[touch->current_slot].change = UDEV_TOUCH_CHANGE_DOWN;
                  udev_touch_event_ts_copy(event, &touch->staging[touch->current_slot].td_time);
               }
               else
               {
                  /* End tracking */
                  RARCH_DDBG("[udev] handle_touch: End tracking slot [%d]\n", touch->current_slot);
                  touch->staging[touch->current_slot].change = UDEV_TOUCH_CHANGE_UP;
                  /* TODO - Just to be sure, event->value should be negative? */
                  touch->staging[touch->current_slot].tracking_id = UDEV_INPUT_TOUCH_TRACKING_ID_NONE;
               }
               break;
            case ABS_X:
               /* TODO - Currently using single-touch events as touch with id 0 */
               RARCH_DDBG("[udev] handle_touch: [0] ST_X to %d\n", event->value);
               touch->staging[0].pos_x = event->value;

               /* Low priority event, mark the change. */
               if (touch->staging[0].change == UDEV_TOUCH_CHANGE_NONE)
                  touch->staging[0].change = UDEV_TOUCH_CHANGE_MOVE;
               /* Starting tracing, remember touchdown position. */
               else if (touch->staging[0].change == UDEV_TOUCH_CHANGE_DOWN)
                  touch->staging[0].td_pos_x = event->value;
               break;
            case ABS_MT_POSITION_X:
               RARCH_DDBG("[udev] handle_touch: [%d] MT_X to %d\n", touch->current_slot, event->value);
               touch->staging[touch->current_slot].pos_x = event->value;
               /* Low priority event, mark the change. */
               if (touch->staging[touch->current_slot].change == UDEV_TOUCH_CHANGE_NONE)
                  touch->staging[touch->current_slot].change = UDEV_TOUCH_CHANGE_MOVE;
               /* Starting tracing, remember touchdown position. */
               else if (touch->staging[touch->current_slot].change == UDEV_TOUCH_CHANGE_DOWN)
                  touch->staging[touch->current_slot].td_pos_x = event->value;
               break;
            case ABS_Y:
               /* TODO - Currently using single-touch events as touch with id 0 */
               RARCH_DDBG("[udev] handle_touch: [0] ST_Y to %d\n", event->value);
               touch->staging[0].pos_y = event->value;
               /* Low priority event, mark the change. */
               if (touch->staging[0].change == UDEV_TOUCH_CHANGE_NONE)
                  touch->staging[0].change = UDEV_TOUCH_CHANGE_MOVE;
               /* Starting tracing, remember touchdown position. */
               else if (touch->staging[0].change == UDEV_TOUCH_CHANGE_DOWN)
                  touch->staging[0].td_pos_y = event->value;
               break;
            case ABS_MT_POSITION_Y:
               RARCH_DDBG("[udev] handle_touch: [%d] MT_Y to %d\n", touch->current_slot, event->value);
               touch->staging[touch->current_slot].pos_y = event->value;
               /* Low priority event, mark the change. */
               if (touch->staging[touch->current_slot].change == UDEV_TOUCH_CHANGE_NONE)
                  touch->staging[touch->current_slot].change = UDEV_TOUCH_CHANGE_MOVE;
               /* Starting tracing, remember touchdown position. */
               else if (touch->staging[touch->current_slot].change == UDEV_TOUCH_CHANGE_DOWN)
                  touch->staging[touch->current_slot].td_pos_y = event->value;
               break;
            case ABS_MT_TOUCH_MINOR:
               RARCH_DDBG("[udev] handle_touch: [%d] MINOR to %d\n", touch->current_slot, event->value);
               touch->staging[touch->current_slot].minor = event->value;
               /* Low priority event, mark the change. */
               if (touch->staging[touch->current_slot].change == UDEV_TOUCH_CHANGE_NONE)
                  touch->staging[touch->current_slot].change = UDEV_TOUCH_CHANGE_MOVE;
               break;
            case ABS_MT_TOUCH_MAJOR:
               RARCH_DDBG("[udev] handle_touch: [%d] MAJOR to %d\n", touch->current_slot, event->value);
               touch->staging[touch->current_slot].major = event->value;
               /* Low priority event, mark the change. */
               if (touch->staging[touch->current_slot].change == UDEV_TOUCH_CHANGE_NONE)
                  touch->staging[touch->current_slot].change = UDEV_TOUCH_CHANGE_MOVE;
               break;
            case ABS_MT_PRESSURE:
               RARCH_DDBG("[udev] handle_touch: [%d] PRES to %d\n", touch->current_slot, event->value);
               touch->staging[touch->current_slot].pressure = event->value;
               /* Low priority event, mark the change. */
               if (touch->staging[touch->current_slot].change == UDEV_TOUCH_CHANGE_NONE)
                  touch->staging[touch->current_slot].change = UDEV_TOUCH_CHANGE_MOVE;
               break;
            default:
               RARCH_WARN("[udev] handle_touch: EV_ABS (code %d) is not handled\n", event->code);
               break;
         }
         break;
      case EV_KEY:
         if (event->code == BTN_TOUCH)
         {
            RARCH_DDBG("[udev] handle_touch: [%d] TOUCH %d\n", touch->current_slot, event->value);
            if (event->value > 0)
               touch->staging[touch->current_slot].change = UDEV_TOUCH_CHANGE_DOWN;
            else
               touch->staging[touch->current_slot].change = UDEV_TOUCH_CHANGE_UP;
            break;
         }
         else
         {
            RARCH_WARN("[udev] handle_touch: EV_KEY (code %d) is not handled\n", event->code);
         }
         break;
      case EV_REL:
         RARCH_WARN("[udev] handle_touch: EV_REL (code %d) is not handled\n", event->code);
         break;
      case EV_SYN:
         switch (event->code)
         {
            case SYN_DROPPED:
               RARCH_DDBG("[udev] handle_touch: SYN_DROP -> !sync!\n");
               udev_sync_touch(dev);
               break;
            case SYN_MT_REPORT:
               /* TODO - Unused, add to support type-A devices [multi-touch-protocol.txt]*/
               break;
            case SYN_REPORT:
               RARCH_DDBG("[udev] handle_touch: SYN_REPORT\n");
               udev_report_touch(udev, dev);
               break;
            default:
               RARCH_WARN("[udev] handle_touch: EV_SYN (code %d) is not handled\n", event->code);
               break;
         }
         break;
      default:
         RARCH_WARN("[udev] handle_touch: Event type %d is not handled\n", event->type);
         break;
   }
}

/**
 * Periodic update of trackball state.
 *
 * @param touch Target touch state.
 * @param now Current time.
 */
static void udev_input_touch_state_trackball(
        udev_input_touch_t *touch,
        const udev_touch_ts_t *now)
{
   video_viewport_t vp;
   float delta_x;
   float delta_y;
   float delta_t;

   /* Let's perform these only once per state polling loop */
   if (!touch->run_state_update)
      return;

   /* Update trackball mouse position */
   if (touch->trackball_enabled)
   { /* Trackball is moving */
      if (touch->trackball_inertial)
      {
         /* Calculate time delta */
         delta_t = (float) udev_touch_ts_diff(&touch->last_state_update, now) / \
            UDEV_INPUT_TOUCH_S_TO_US;
         /* Calculate position delta */
         delta_x = touch->trackball_vel_x * delta_t;
         delta_y = touch->trackball_vel_y * delta_t;
         /* Update the high-resolution mouse position */
         touch->trackball_pos_x += delta_x;
         touch->trackball_pos_y += delta_y;
         /* Update the real mouse position */
         touch->mouse_pos_x = (int16_t) touch->trackball_pos_x;
         touch->mouse_pos_y = (int16_t) touch->trackball_pos_y;

         /* Get current viewport information */
         video_driver_get_viewport_info(&vp);
         /* Translate the raw coordinates into normalized coordinates. */
         video_driver_translate_coord_viewport_wrap(
            &vp, touch->mouse_pos_x, touch->mouse_pos_y,
            &touch->mouse_vp_pos_x, &touch->mouse_vp_pos_y,
            &touch->mouse_scr_pos_x, &touch->mouse_scr_pos_y
         );

         /* Add the movement to mouse delta */
         touch->mouse_rel_x += delta_x;
         touch->mouse_rel_y += delta_y;
      }

      /* Attenuate the velocity */
      touch->trackball_vel_x *= touch->trackball_frict_x;
      touch->trackball_vel_y *= touch->trackball_frict_y;
      /* Automatically cut off the inertia when the velocity is low enough */
      if (   (touch->trackball_vel_x * touch->trackball_vel_x)
          +  (touch->trackball_vel_y * touch->trackball_vel_y)
          <=  touch->trackball_sq_vel_cutoff)
      {
          touch->trackball_vel_x    = 0.0f;
          touch->trackball_vel_y    = 0.0f;
          touch->trackball_inertial = false;
      }
   }
}

/**
 * Gesture time-dependant processing.
 * TODO - Current implementation may result in cancelling a button
 * state before it gets reported at least once. However, this is
 * a better approach compared to waiting, since _state call may
 * never occur.
 *
 * @param touch Target touch state.
 * @param now Current time.
 */
static void udev_input_touch_state_gest(
        udev_input_touch_t *touch,
        const udev_touch_ts_t *now)
{
   int iii;

   /* Tap-based gesture processing */
   for (iii = 0; iii < UDEV_TOUCH_TGEST_LAST; ++iii)
   { /* Process time-delayed callbacks. */
      if (touch->gest_tcbs[iii].active)
      { /* Callback is active. */
         /* Execution time passed. */
         if (udev_touch_ts_diff(now, &touch->gest_tcbs[iii].execute_at) <= 0)
            udev_input_touch_gest_exec_cb(&touch->gest_tcbs[iii], touch);
      }
   }

   /* Move-based gesture processing */
   for (iii = 0; iii < UDEV_TOUCH_MGEST_LAST; ++iii)
   { /* Process time-delayed callbacks. */
      if (touch->gest_mcbs[iii].active)
      { /* Callback is active. */
         /* Execution time passed. */
         if (udev_touch_ts_diff(now, &touch->gest_mcbs[iii].execute_at) <= 0)
            udev_input_touch_gest_exec_cb(&touch->gest_mcbs[iii], touch);
      }
   }

   /* Let's perform these only once per state polling loop */
   if (!touch->run_state_update)
      return;

   /* Tap-based gesture processing */
   /* TODO - Currently none */

   /* Move-based gesture processing */
   switch (touch->gest_mgest_type)
   {
      case UDEV_TOUCH_MGEST_S_STAP_DRAG:
         /* Gesture for one finger single tap drag. */
         break;
      case UDEV_TOUCH_MGEST_S_DTAP_DRAG:
         /* Gesture for one finger double tap drag. */
         break;
      case UDEV_TOUCH_MGEST_S_TTAP_DRAG:
         /* Gesture for one finger triple tap drag. */
         break;
      case UDEV_TOUCH_MGEST_D_NTAP_DRAG:
         /* Gesture for two finger no tap drag. */
         /* Convert accumulated scrolls to mouse_wheel_x/y */
         if (   touch->gest_scroll_x >  touch->gest_scroll_step
             || touch->gest_scroll_x < -touch->gest_scroll_step)
         { /* Add one scroll step. TODO - Add multiple? */
            /* Add if oriented the same or simply set to one. */
            if (touch->gest_scroll_x * touch->mouse_wheel_x > 0)
               touch->mouse_wheel_x += 1 * udev_touch_sign(touch->gest_scroll_x);
            else
               touch->mouse_wheel_x  = 1 * udev_touch_sign(touch->gest_scroll_x);
            /* Reset the scroll for the next delta */
            touch->gest_scroll_x -= touch->gest_scroll_step *
               udev_touch_sign(touch->gest_scroll_x);
         }
         if (   touch->gest_scroll_y > touch->gest_scroll_step
             || touch->gest_scroll_y < -touch->gest_scroll_step)
         {
            /* Add one scroll step. TODO - Add multiple? */
            /* TODO - Note the -sign, the vertical scroll seems inverted. */
            /* Add if oriented the same or simply set to one. */
            if (touch->gest_scroll_y * touch->mouse_wheel_x > 0)
               touch->mouse_wheel_y += 1 * -udev_touch_sign(touch->gest_scroll_y);
            else
               touch->mouse_wheel_y = 1 * -udev_touch_sign(touch->gest_scroll_y);
            /* Reset the scroll for the next delta */
            touch->gest_scroll_y -= touch->gest_scroll_step *
               udev_touch_sign(touch->gest_scroll_y);
         }
         break;
      case UDEV_TOUCH_MGEST_D_STAP_DRAG:
         /* Gesture for two finger single tap drag. */
         break;
      case UDEV_TOUCH_MGEST_T_NTAP_DRAG:
         /* Gesture for three finger no tap drag. */
         break;
      case UDEV_TOUCH_MGEST_T_STAP_DRAG:
         /* Gesture for three finger single tap drag. */
         break;
      default:
         /* No action */
         break;
   }
}

/**
 * State function handling touch devices.
 *
 * @param udev Source UDev system.
 * @param dev The touch device being polled.
 * @param binds Bindings structure.
 * @param keyboard_mapping_blocked Block keyboard mapped inputs.
 * @param port Port (player) of the device being polled.
 * @param device Type of device RETRO_DEVICE_* being polled.
 * @param idx Index of the device being polled.
 * @param id Identifier of the axis / button being polled -
 *   e.g. RETRO_DEVICE_ID_*.
 */
static int16_t udev_input_touch_state(
      udev_input_t *udev,
      udev_input_device_t *dev,
      const retro_keybind_set *binds,
      bool keyboard_mapping_blocked,
      unsigned port,
      unsigned device,
      unsigned idx,
      unsigned id)
{
   int16_t ret = 0;
   bool screen = false;
   udev_input_touch_t *touch = &dev->touch;
   udev_touch_ts_t now;

   /* Get current time for measurements */
   udev_touch_ts_now(&now);

   /* TODO - Process timed gestures before or after getting state? */
   /* Process timed gestures. */
   udev_input_touch_state_gest(touch, &now);
   /* Process trackball. */
   udev_input_touch_state_trackball(touch, &now);

   /* Perform state update only once */
   if (touch->run_state_update)
   {
      touch->run_state_update = false;
      /* Update last update timestamp */
      udev_touch_ts_copy(&now, &touch->last_state_update);
      /* Force load the options from settings */
      udev_update_touch_dev_options(dev, false);
   }

   switch (device)
   {
      case RETRO_DEVICE_MOUSE:
      case RARCH_DEVICE_MOUSE_SCREEN:
         screen = (device == RARCH_DEVICE_MOUSE_SCREEN);
         switch (id)
         {
            case RETRO_DEVICE_ID_MOUSE_X:
               if (screen)
                  ret = touch->mouse_pos_x;
               else
               {
                  ret = touch->mouse_rel_x;
                  touch->mouse_rel_x = 0;
               }
               break;
            case RETRO_DEVICE_ID_MOUSE_Y:
               if (screen)
                  ret = touch->mouse_pos_y;
               else
               {
                  ret = touch->mouse_rel_y;
                  touch->mouse_rel_y = 0;
               }
               break;
            case RETRO_DEVICE_ID_MOUSE_LEFT:
               ret = touch->mouse_btn_l;
               break;
            case RETRO_DEVICE_ID_MOUSE_RIGHT:
               ret = touch->mouse_btn_r;
               break;
            case RETRO_DEVICE_ID_MOUSE_MIDDLE:
               ret = touch->mouse_btn_m;
               break;
            case RETRO_DEVICE_ID_MOUSE_BUTTON_4:
               ret = touch->mouse_btn_b4;
               break;
            case RETRO_DEVICE_ID_MOUSE_BUTTON_5:
               ret = touch->mouse_btn_b5;
               break;
            case RETRO_DEVICE_ID_MOUSE_WHEELUP:
               ret = touch->mouse_wheel_y > 0;
               if (ret)
                  touch->mouse_wheel_y--;
               break;
            case RETRO_DEVICE_ID_MOUSE_WHEELDOWN:
               ret = touch->mouse_wheel_y < 0;
               if (ret)
                  touch->mouse_wheel_y++;
               break;
            case RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELUP:
               ret = touch->mouse_wheel_x > 0;
               if (ret)
                  touch->mouse_wheel_x--;
               break;
            case RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELDOWN:
               ret = touch->mouse_wheel_x < 0;
               if (ret)
                  touch->mouse_wheel_x++;
               break;
            default:
               break;
         }
         break;

      case RETRO_DEVICE_POINTER:
      case RARCH_DEVICE_POINTER_SCREEN:
         screen = (device == RARCH_DEVICE_MOUSE_SCREEN);
         break;
         switch (id)
         {
            case RETRO_DEVICE_ID_POINTER_X:
               if (screen)
                  ret = touch->pointer_scr_pos_x;
               else
                  ret = touch->pointer_vp_pos_x;
               break;
            case RETRO_DEVICE_ID_POINTER_Y:
               if (screen)
                  ret = touch->pointer_scr_pos_y;
               else
                  ret = touch->pointer_vp_pos_y;
               break;
            case RETRO_DEVICE_ID_POINTER_PRESSED:
               ret = touch->pointer_btn_pp;
               break;
            case RARCH_DEVICE_ID_POINTER_BACK:
               /* TODO - Remove this function? */
               ret = touch->pointer_btn_pb;
               break;
            default:
               break;
         }
         break;

      case RETRO_DEVICE_LIGHTGUN:
         switch (id)
         {
            /* TODO - Add simulated lightgun? */
            case RETRO_DEVICE_ID_LIGHTGUN_SCREEN_X:
            case RETRO_DEVICE_ID_LIGHTGUN_SCREEN_Y:
            case RETRO_DEVICE_ID_LIGHTGUN_IS_OFFSCREEN:
            case RETRO_DEVICE_ID_LIGHTGUN_TRIGGER:
            case RETRO_DEVICE_ID_LIGHTGUN_RELOAD:
            case RETRO_DEVICE_ID_LIGHTGUN_AUX_A:
            case RETRO_DEVICE_ID_LIGHTGUN_AUX_B:
            case RETRO_DEVICE_ID_LIGHTGUN_AUX_C:
            case RETRO_DEVICE_ID_LIGHTGUN_START:
            case RETRO_DEVICE_ID_LIGHTGUN_SELECT:
            case RETRO_DEVICE_ID_LIGHTGUN_DPAD_UP:
            case RETRO_DEVICE_ID_LIGHTGUN_DPAD_DOWN:
            case RETRO_DEVICE_ID_LIGHTGUN_DPAD_LEFT:
            case RETRO_DEVICE_ID_LIGHTGUN_DPAD_RIGHT:
            case RETRO_DEVICE_ID_LIGHTGUN_PAUSE:
            case RETRO_DEVICE_ID_LIGHTGUN_X:
            case RETRO_DEVICE_ID_LIGHTGUN_Y:
               break;
         }
         break;
   }

   return ret;
}

#endif
/* UDEV_TOUCH_SUPPORT */

#define test_bit(array, bit)    (array[bit/8] & (1<<(bit%8)))

static int udev_input_add_device(udev_input_t *udev,
      enum udev_input_dev_type type, const char *devnode, device_handle_cb cb)
{
   unsigned char keycaps[(KEY_MAX / 8) + 1] = {'\0'};
   unsigned char abscaps[(ABS_MAX / 8) + 1] = {'\0'};
   unsigned char relcaps[(REL_MAX / 8) + 1] = {'\0'};
   udev_input_device_t **tmp                = NULL;
   udev_input_device_t *device              = NULL;
   struct input_absinfo absinfo;
   int fd                                   = -1;
   int ret                                  = 0;
   struct stat st;
#if defined(HAVE_EPOLL)
   struct epoll_event event;
#elif defined(HAVE_KQUEUE)
   struct kevent event;
#endif

   st.st_dev = 0;

   if (stat(devnode, &st) < 0)
      goto end;

   fd = open(devnode, O_RDONLY | O_NONBLOCK);
   if (fd < 0)
      goto end;

   device = (udev_input_device_t*)calloc(1, sizeof(*device));
   if (!device)
      goto end;

   device->fd        = fd;
   device->dev       = st.st_dev;
   device->handle_cb = cb;
   device->type      = type;

   strlcpy(device->devnode, devnode, sizeof(device->devnode));

   if (ioctl(fd, EVIOCGNAME(sizeof(device->ident)), device->ident) < 0)
      device->ident[0] = '\0';

   /* UDEV_INPUT_MOUSE may report in absolute coords too */
   if (type == UDEV_INPUT_MOUSE || type == UDEV_INPUT_TOUCHPAD || type == UDEV_INPUT_TOUCHSCREEN )
   {
      bool mouse = 0;
      bool touch = 0;
      /* gotta have some buttons!  return -1 to skip error logging for this:)  */
      if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof (keycaps)), keycaps) == -1)
      {
         ret = -1;
         goto end;
      }

      if (ioctl(fd, EVIOCGBIT(EV_REL, sizeof (relcaps)), relcaps) != -1)
      {
         if ( (test_bit(relcaps, REL_X)) && (test_bit(relcaps, REL_Y)) )
         {
            mouse = 1;

            if (!test_bit(keycaps, BTN_MOUSE))
               RARCH_DBG("[udev] Warning REL pointer device (%s) has no mouse button.\n",device->ident);
         }
      }

      if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof (abscaps)), abscaps) != -1)
      {
         if ( (test_bit(abscaps, ABS_X)) && (test_bit(abscaps, ABS_Y)) )
         {
            mouse = 1;

            /* check for abs touch devices... */
            if (test_bit(keycaps, BTN_TOUCH))
            {
               touch             = 1;
               device->mouse.abs = 1;
            }
            /* check for light gun or any other device that might not have a touch button */
            else
               device->mouse.abs = 2;

            if ( !test_bit(keycaps, BTN_TOUCH) && !test_bit(keycaps, BTN_MOUSE) )
               RARCH_DBG("[udev] Warning ABS pointer device (%s) has no touch or mouse button.\n",device->ident);
         }
      }

      device->mouse.x_min = 0;
      device->mouse.y_min = 0;
      device->mouse.x_max = 0;
      device->mouse.y_max = 0;

      if (device->mouse.abs)
      {
         if (ioctl(fd, EVIOCGABS(ABS_X), &absinfo) == -1)
         {
            RARCH_DBG("[udev] ABS pointer device (%s) Failed to get ABS_X parameters.\n",device->ident);
            goto end;
         }

         device->mouse.x_min = absinfo.minimum;
         device->mouse.x_max = absinfo.maximum;

         if (ioctl(fd, EVIOCGABS(ABS_Y), &absinfo) == -1)
         {
            RARCH_DBG("[udev] ABS pointer device (%s) Failed to get ABS_Y parameters.\n",device->ident);
            goto end;
         }
         device->mouse.y_min = absinfo.minimum;
         device->mouse.y_max = absinfo.maximum;
      }

      if (touch)
      {
#ifdef UDEV_TOUCH_SUPPORT
          udev_init_touch_dev(device);
          udev_sync_touch(device);
#endif
      }

      if (!mouse)
         goto end;
   }

   tmp = (udev_input_device_t**)realloc(udev->devices,
         (udev->num_devices + 1) * sizeof(*udev->devices));

   if (!tmp)
      goto end;

   tmp[udev->num_devices++] = device;
   udev->devices            = tmp;

#if defined(HAVE_EPOLL)
   event.events             = EPOLLIN;
   event.data.ptr           = device;

   /* Shouldn't happen, but just check it. */
   if (epoll_ctl(udev->fd, EPOLL_CTL_ADD, fd, &event) < 0)
   {
      RARCH_ERR("[udev] Failed to add FD (%d) to epoll list (%s).\n",
            fd, strerror(errno));
   }
#elif defined(HAVE_KQUEUE)
   EV_SET(&event, fd, EVFILT_READ, EV_ADD, 0, 0, LISTENSOCKET);
   if (kevent(udev->fd, &event, 1, NULL, 0, NULL) == -1)
   {
      RARCH_ERR("[udev] Failed to add FD (%d) to kqueue list (%s).\n",
            fd, strerror(errno));
   }
#endif
   ret = 1;

end:
   /* Free resources in the event of
    * an error */
   if (ret != 1)
   {
      if (fd >= 0)
         close(fd);
      if (device)
         free(device);
   }

   return ret;
}

static void udev_input_remove_device(udev_input_t *udev, const char *devnode)
{
   unsigned i;

   for (i = 0; i < udev->num_devices; i++)
   {
      if (!string_is_equal(devnode, udev->devices[i]->devnode))
         continue;

      close(udev->devices[i]->fd);
      free(udev->devices[i]);
      memmove(udev->devices + i, udev->devices + i + 1,
            (udev->num_devices - (i + 1)) * sizeof(*udev->devices));
      udev->num_devices--;
   }
}

static void udev_input_handle_hotplug(udev_input_t *udev)
{
   device_handle_cb cb;
   enum udev_input_dev_type dev_type = UDEV_INPUT_KEYBOARD;
   const char *val_key               = NULL;
   const char *val_mouse             = NULL;
   const char *val_touchpad          = NULL;
   const char *val_touchscreen       = NULL;
   const char *action                = NULL;
   const char *devnode               = NULL;
   int mouse                         = 0;
   int keyboard                      = 0;
   int check                         = 0;
   int i                             = 0;
   struct udev_device *dev           = udev_monitor_receive_device(
         udev->monitor);

   if (!dev)
      return;

   val_key         = udev_device_get_property_value(dev, "ID_INPUT_KEY");
   val_mouse       = udev_device_get_property_value(dev, "ID_INPUT_MOUSE");
   val_touchpad    = udev_device_get_property_value(dev, "ID_INPUT_TOUCHPAD");
   val_touchscreen = udev_device_get_property_value(dev, "ID_INPUT_TOUCHSCREEN");
   action          = udev_device_get_action(dev);
   devnode         = udev_device_get_devnode(dev);

   if (val_key && string_is_equal(val_key, "1") && devnode)
   {
      /* EV_KEY device, can be a keyboard or a remote control device.  */
      dev_type   = UDEV_INPUT_KEYBOARD;
      cb         = udev_handle_keyboard;
   }
   else if (val_mouse && string_is_equal(val_mouse, "1") && devnode)
   {
      dev_type   = UDEV_INPUT_MOUSE;
      cb         = udev_handle_mouse;
   }
   else if (val_touchpad && string_is_equal(val_touchpad, "1") && devnode)
   {
      dev_type   = UDEV_INPUT_TOUCHPAD;
      cb         = udev_handle_mouse;
   }
   else if (val_touchscreen && string_is_equal(val_touchscreen, "1") && devnode)
   {
#ifdef UDEV_TOUCH_SUPPORT
      dev_type   = UDEV_INPUT_TOUCHSCREEN;
      cb         = udev_handle_touch;
#else
      dev_type   = UDEV_INPUT_TOUCHPAD;
      cb         = udev_handle_mouse;
#endif
   }
   else
      goto end;

   /* Hotplug add */
   if (string_is_equal(action, "add"))
      udev_input_add_device(udev, dev_type, devnode, cb);
   /* Hotplug remove */
   else if (string_is_equal(action, "remove"))
      udev_input_remove_device(udev, devnode);

   /* we need to re index the mouse and keyboard indirection
    * structures when a device is hotplugged
    */
   /* first clear all */
   for (i = 0; i < MAX_USERS; i++)
   {
      input_config_set_mouse_display_name(i, "N/A");
      udev->pointers[i]  = -1;
      udev->keyboards[i] = -1;
   }

   /* Add what devices we have now */
   for (i = 0; i < (int)udev->num_devices; i++)
   {
      if (udev->devices[i]->type != UDEV_INPUT_KEYBOARD)
      {
         /* Pointers */
         input_config_set_mouse_display_name(mouse, udev->devices[i]->ident);
         udev->pointers[mouse]     = i;
         mouse++;
      }
      else
      {
         /* Keyboard */
         udev->keyboards[keyboard] = i;
         keyboard++;
      }
   }

end:
   udev_device_unref(dev);
}

#ifdef HAVE_X11
static void udev_input_get_pointer_position(int *x, int *y)
{
   if (video_driver_display_type_get() == RARCH_DISPLAY_X11)
   {
      Window w;
      int p;
      unsigned m;
      Display *display = (Display*)video_driver_display_get();
      Window window    = (Window)video_driver_window_get();

      XQueryPointer(display, window, &w, &w, &p, &p, x, y, &m);
   }
}

static void udev_input_adopt_rel_pointer_position_from_mouse(
      int *x, int *y, udev_input_mouse_t *mouse)
{
   static int noX11DispX = 0;
   static int noX11DispY = 0;

   struct video_viewport view;
   bool r = video_driver_get_viewport_info(&view);
   int dx = udev_mouse_get_x(mouse);
   int dy = udev_mouse_get_y(mouse);
   if (      r
         && (dx || dy)
         && video_driver_display_type_get() != RARCH_DISPLAY_X11)
   {
      int minX      = view.x;
      int maxX      = view.x + view.width;
      int minY      = view.y;
      int maxY      = view.y + view.height;
      /* Not running in a window. */
      noX11DispX    = noX11DispX + dx;
      if (noX11DispX < minX)
         noX11DispX = minX;
      if (noX11DispX > maxX)
         noX11DispX = maxX;
      noX11DispY    = noX11DispY + dy;
      if (noX11DispY < minY)
         noX11DispY = minY;
      if (noX11DispY > maxY)
         noX11DispY = maxY;
      *x            = noX11DispX;
      *y            = noX11DispY;
   }
   mouse->x_rel     = 0;
   mouse->y_rel     = 0;
}
#endif

static bool udev_input_poll_hotplug_available(struct udev_monitor *dev)
{
   struct pollfd fds;

   fds.fd      = udev_monitor_get_fd(dev);
   fds.events  = POLLIN;
   fds.revents = 0;

   return (poll(&fds, 1, 0) == 1) && (fds.revents & POLLIN);
}

static void udev_input_poll(void *data)
{
   int i, ret;
#if defined(HAVE_EPOLL)
   struct epoll_event events[32];
#elif defined(HAVE_KQUEUE)
   struct kevent events[32];
#endif
   udev_input_mouse_t *mouse = NULL;
   udev_input_t *udev        = (udev_input_t*)data;

#ifdef HAVE_X11
   udev_input_get_pointer_position(&udev->pointer_x, &udev->pointer_y);
#endif

   for (i = 0; i < (int)udev->num_devices; i++)
   {
      if (udev->devices[i]->type == UDEV_INPUT_KEYBOARD)
         continue;

      mouse = &udev->devices[i]->mouse;
#ifdef HAVE_X11
      udev_input_adopt_rel_pointer_position_from_mouse(
            &udev->pointer_x, &udev->pointer_y, mouse);
#else
      mouse->x_rel = 0;
      mouse->y_rel = 0;
#endif
      mouse->wu    = false;
      mouse->wd    = false;
      mouse->whu   = false;
      mouse->whd   = false;

#ifdef UDEV_TOUCH_SUPPORT
      /* Schedule touch state update. */
      udev->devices[i]->touch.run_state_update = true;
#endif
   }

   while (udev->monitor && udev_input_poll_hotplug_available(udev->monitor))
      udev_input_handle_hotplug(udev);

#if defined(HAVE_EPOLL)
   ret = epoll_wait(udev->fd, events, ARRAY_SIZE(events), 0);
#elif defined(HAVE_KQUEUE)
   {
      struct timespec timeoutspec;
      timeoutspec.tv_sec  = timeout;
      timeoutspec.tv_nsec = 0;
      ret                 = kevent(udev->fd, NULL, 0, events,
            ARRAY_SIZE(events), &timeoutspec);
   }
#endif

   for (i = 0; i < ret; i++)
   {
      /* TODO/FIXME - add HAVE_EPOLL/HAVE_KQUEUE codepaths here */
      if (events[i].events & EPOLLIN)
      {
         int j, len;
         struct input_event input_events[32];
#if defined(HAVE_EPOLL)
         udev_input_device_t *device = (udev_input_device_t*)events[i].data.ptr;
#elif defined(HAVE_KQUEUE)
         udev_input_device_t *device = (udev_input_device_t*)events[i].udata;
#endif

         while ((len = read(device->fd,
                     input_events, sizeof(input_events))) > 0)
         {
            len /= sizeof(*input_events);
            for (j = 0; j < len; j++)
               device->handle_cb(udev, &input_events[j], device);
         }
      }
   }
}

static bool udev_pointer_is_off_window(const udev_input_t *udev)
{
#ifdef HAVE_X11
   struct video_viewport view;
   bool r = video_driver_get_viewport_info(&view);
   if (r)
      return (udev->pointer_x < 0
           || udev->pointer_x >= (int)view.full_width
           || udev->pointer_y < 0
           || udev->pointer_y >= (int)view.full_height);
#endif
   return false;
}

static int16_t udev_lightgun_aiming_state(
      udev_input_t *udev, unsigned port, unsigned id )
{

   udev_input_mouse_t *mouse   = udev_get_mouse(udev, port);
   int16_t res_x;
   int16_t res_y;

   if (mouse && udev_mouse_get_pointer(mouse, false, false, &res_x, &res_y))
   {
      switch ( id )
      {
         case RETRO_DEVICE_ID_LIGHTGUN_SCREEN_X:
            return res_x;
         case RETRO_DEVICE_ID_LIGHTGUN_SCREEN_Y:
            return res_y;
         case RETRO_DEVICE_ID_LIGHTGUN_IS_OFFSCREEN:
            return input_driver_pointer_is_offscreen(res_x, res_y);
         default:
            break;
      }
   }

   return 0;
}

static int16_t udev_mouse_state(udev_input_t *udev,
      unsigned port, unsigned id, bool screen)
{
   udev_input_mouse_t *mouse = udev_get_mouse(udev, port);

   if (mouse)
   {
      if (     id != RETRO_DEVICE_ID_MOUSE_X
            && id != RETRO_DEVICE_ID_MOUSE_Y
            && udev_pointer_is_off_window(udev))
         return 0;

      switch (id)
      {
         case RETRO_DEVICE_ID_MOUSE_X:
            return screen ? udev->pointer_x : udev_mouse_get_x(mouse);
         case RETRO_DEVICE_ID_MOUSE_Y:
            return screen ? udev->pointer_y : udev_mouse_get_y(mouse);
         case RETRO_DEVICE_ID_MOUSE_LEFT:
            return mouse->l;
         case RETRO_DEVICE_ID_MOUSE_RIGHT:
            return mouse->r;
         case RETRO_DEVICE_ID_MOUSE_MIDDLE:
            return mouse->m;
         case RETRO_DEVICE_ID_MOUSE_BUTTON_4:
            return mouse->b4;
         case RETRO_DEVICE_ID_MOUSE_BUTTON_5:
            return mouse->b5;
         case RETRO_DEVICE_ID_MOUSE_WHEELUP:
            return mouse->wu;
         case RETRO_DEVICE_ID_MOUSE_WHEELDOWN:
            return mouse->wd;
         case RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELUP:
            return mouse->whu;
         case RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELDOWN:
            return mouse->whd;
      }
   }

   return 0;
}

static bool udev_keyboard_pressed(udev_input_t *udev, unsigned key)
{
   int bit = rarch_keysym_lut[key];
   return (key) ? BIT_GET(udev->state, bit) : false;
}

static bool udev_mouse_button_pressed(
      udev_input_t *udev, unsigned port, unsigned key)
{
   udev_input_mouse_t *mouse = udev_get_mouse(udev, port);

   if (mouse)
   {
      /* TODO/FIXME - add multi touch button check pointer devices */
      switch ( key )
      {
         case RETRO_DEVICE_ID_MOUSE_LEFT:
            return mouse->l;
         case RETRO_DEVICE_ID_MOUSE_RIGHT:
            return mouse->r;
         case RETRO_DEVICE_ID_MOUSE_MIDDLE:
            return mouse->m;
         case RETRO_DEVICE_ID_MOUSE_BUTTON_4:
            return mouse->b4;
         case RETRO_DEVICE_ID_MOUSE_BUTTON_5:
            return mouse->b5;
         case RETRO_DEVICE_ID_MOUSE_WHEELUP:
            return mouse->wu;
         case RETRO_DEVICE_ID_MOUSE_WHEELDOWN:
            return mouse->wd;
         case RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELUP:
            return mouse->whu;
         case RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELDOWN:
            return mouse->whd;
      }
   }

   return false;
}

static int16_t udev_pointer_state(udev_input_t *udev,
      unsigned port, unsigned idx, unsigned id, bool screen)
{
   udev_input_mouse_t *mouse = udev_get_mouse(udev, port);
   int16_t res_x;
   int16_t res_y;

   if (mouse && udev_mouse_get_pointer(mouse, screen, true, &res_x, &res_y))
   {
      switch (id)
      {
         case RETRO_DEVICE_ID_POINTER_X:
            return res_x;
         case RETRO_DEVICE_ID_POINTER_Y:
            return res_y;
         case RETRO_DEVICE_ID_POINTER_PRESSED:
            if (mouse->abs == 1)
            {
               if (idx == 0)
                  return mouse->pp;
               else
                  return 0;
            }
            /* Simulate max. 3 touches with mouse buttons*/
            else if (idx == 0)
               return (mouse->l | mouse->r | mouse->m);
            else if (idx == 1)
               return (mouse->r | mouse->m);
            else if (idx == 2)
               return mouse->m;
         case RETRO_DEVICE_ID_POINTER_IS_OFFSCREEN:
            return input_driver_pointer_is_offscreen(res_x, res_y);
      }
   }

   return 0;
}

static int16_t udev_input_state(
      void *data,
      const input_device_driver_t *joypad,
      const input_device_driver_t *sec_joypad,
      rarch_joypad_info_t *joypad_info,
      const retro_keybind_set *binds,
      bool keyboard_mapping_blocked,
      unsigned port,
      unsigned device,
      unsigned idx,
      unsigned id)
{
   udev_input_t *udev               = (udev_input_t*)data;
#ifdef UDEV_TOUCH_SUPPORT
   udev_input_device_t *pointer_dev = udev_get_pointer_port_dev(udev, port);
#endif

   switch (device)
   {
      case RETRO_DEVICE_JOYPAD:
         if (id == RETRO_DEVICE_ID_JOYPAD_MASK)
         {
            unsigned i;
            int16_t ret = 0;

            for (i = 0; i < RARCH_FIRST_CUSTOM_BIND; i++)
            {
               if (binds[port][i].valid)
               {
                  if (udev_mouse_button_pressed(udev, port, binds[port][i].mbutton))
                     ret |= (1 << i);
               }
            }

            if (!keyboard_mapping_blocked)
            {
               for (i = 0; i < RARCH_FIRST_CUSTOM_BIND; i++)
               {
                  if (binds[port][i].valid)
                  {
                     if (     (binds[port][i].key && binds[port][i].key < RETROK_LAST)
                           && udev_keyboard_pressed(udev, binds[port][i].key))
                        ret |= (1 << i);
                  }
               }
            }

            return ret;
         }

         if (id < RARCH_BIND_LIST_END)
         {
            if (binds[port][id].valid)
            {
               if (     (binds[port][id].key && binds[port][id].key < RETROK_LAST)
                     && udev_keyboard_pressed(udev, binds[port][id].key)
                     && (id == RARCH_GAME_FOCUS_TOGGLE || !keyboard_mapping_blocked)
                  )
                  return 1;
               else if (udev_mouse_button_pressed(udev, port, binds[port][id].mbutton))
                  return 1;
            }
         }
         break;
      case RETRO_DEVICE_ANALOG:
         if (binds)
         {
            int id_minus_key      = 0;
            int id_plus_key       = 0;
            unsigned id_minus     = 0;
            unsigned id_plus      = 0;
            int16_t ret           = 0;
            bool id_plus_valid    = false;
            bool id_minus_valid   = false;

            input_conv_analog_id_to_bind_id(idx, id, id_minus, id_plus);

            id_minus_valid        = binds[port][id_minus].valid;
            id_plus_valid         = binds[port][id_plus].valid;
            id_minus_key          = binds[port][id_minus].key;
            id_plus_key           = binds[port][id_plus].key;

            if (id_plus_valid && id_plus_key && id_plus_key < RETROK_LAST)
            {
               unsigned sym = rarch_keysym_lut[(enum retro_key)id_plus_key];
               if BIT_GET(udev->state, sym)
                  ret = 0x7fff;
            }
            if (id_minus_valid && id_minus_key && id_minus_key < RETROK_LAST)
            {
               unsigned sym = rarch_keysym_lut[(enum retro_key)id_minus_key];
               if (BIT_GET(udev->state, sym))
                  ret += -0x7fff;
            }

            return ret;
         }
         break;
      case RETRO_DEVICE_KEYBOARD:
         return (id && id < RETROK_LAST) && udev_keyboard_pressed(udev, id);
      case RETRO_DEVICE_MOUSE:
      case RARCH_DEVICE_MOUSE_SCREEN:
#ifdef UDEV_TOUCH_SUPPORT
         if (pointer_dev && pointer_dev->touch.is_touch_device)
             return udev_input_touch_state(udev, pointer_dev, binds,
                     keyboard_mapping_blocked, port, device, idx, id);
#endif
         return udev_mouse_state(udev, port, id,
               device == RARCH_DEVICE_MOUSE_SCREEN);

      case RETRO_DEVICE_POINTER:
      case RARCH_DEVICE_POINTER_SCREEN:
#ifdef UDEV_TOUCH_SUPPORT
         if (pointer_dev && pointer_dev->touch.is_touch_device)
             return udev_input_touch_state(udev, pointer_dev, binds,
                     keyboard_mapping_blocked, port, device, idx, id);
#endif
         if (idx < 3)
            return udev_pointer_state(udev, port, idx, id,
                  device == RARCH_DEVICE_POINTER_SCREEN);
         break;

      case RETRO_DEVICE_LIGHTGUN:
#ifdef UDEV_TOUCH_SUPPORT
         if (pointer_dev && pointer_dev->touch.is_touch_device)
             return udev_input_touch_state(udev, pointer_dev, binds,
                     keyboard_mapping_blocked, port, device, idx, id);
#endif
         switch ( id )
         {
            /*aiming*/
            case RETRO_DEVICE_ID_LIGHTGUN_SCREEN_X:
            case RETRO_DEVICE_ID_LIGHTGUN_SCREEN_Y:
            case RETRO_DEVICE_ID_LIGHTGUN_IS_OFFSCREEN:
               return udev_lightgun_aiming_state( udev, port, id );

               /*buttons*/
            case RETRO_DEVICE_ID_LIGHTGUN_TRIGGER:
            case RETRO_DEVICE_ID_LIGHTGUN_RELOAD:
            case RETRO_DEVICE_ID_LIGHTGUN_AUX_A:
            case RETRO_DEVICE_ID_LIGHTGUN_AUX_B:
            case RETRO_DEVICE_ID_LIGHTGUN_AUX_C:
            case RETRO_DEVICE_ID_LIGHTGUN_START:
            case RETRO_DEVICE_ID_LIGHTGUN_SELECT:
            case RETRO_DEVICE_ID_LIGHTGUN_DPAD_UP:
            case RETRO_DEVICE_ID_LIGHTGUN_DPAD_DOWN:
            case RETRO_DEVICE_ID_LIGHTGUN_DPAD_LEFT:
            case RETRO_DEVICE_ID_LIGHTGUN_DPAD_RIGHT:
            case RETRO_DEVICE_ID_LIGHTGUN_PAUSE: /* deprecated */
               {
                  unsigned new_id                = input_driver_lightgun_id_convert(id);
                  const uint64_t bind_joykey     = input_config_binds[port][new_id].joykey;
                  const uint64_t bind_joyaxis    = input_config_binds[port][new_id].joyaxis;
                  const uint64_t autobind_joykey = input_autoconf_binds[port][new_id].joykey;
                  const uint64_t autobind_joyaxis= input_autoconf_binds[port][new_id].joyaxis;
                  uint16_t joyport               = joypad_info->joy_idx;
                  float axis_threshold           = joypad_info->axis_threshold;
                  const uint64_t joykey          = (bind_joykey != NO_BTN)
                     ? bind_joykey  : autobind_joykey;
                  const uint32_t joyaxis         = (bind_joyaxis != AXIS_NONE)
                     ? bind_joyaxis : autobind_joyaxis;

                  if (binds[port][new_id].valid)
                  {
                     if ((uint16_t)joykey != NO_BTN && joypad->button(
                              joyport, (uint16_t)joykey))
                        return 1;
                     if (joyaxis != AXIS_NONE &&
                           ((float)abs(joypad->axis(joyport, joyaxis))
                            / 0x8000) > axis_threshold)
                        return 1;
                     else if ((binds[port][new_id].key && binds[port][new_id].key < RETROK_LAST)
                           && !keyboard_mapping_blocked
                           && udev_keyboard_pressed(udev, binds[port][new_id].key)
                        )
                        return 1;
                     else if (udev_mouse_button_pressed(udev, port, binds[port][new_id].mbutton))
                        return 1;
                  }
               }
               break;
               /*deprecated*/
            case RETRO_DEVICE_ID_LIGHTGUN_X:
               {
                  udev_input_mouse_t *mouse = udev_get_mouse(udev, port);
                  if (mouse)
                     return udev_mouse_get_x(mouse);
               }
               break;
            case RETRO_DEVICE_ID_LIGHTGUN_Y:
               {
                  udev_input_mouse_t *mouse = udev_get_mouse(udev, port);
                  if (mouse)
                     return udev_mouse_get_y(mouse);
               }
               break;
         }
         break;
   }

   return 0;
}

static void udev_input_free(void *data)
{
   unsigned i;
   udev_input_t *udev = (udev_input_t*)data;

   if (!data || !udev)
      return;

#ifdef __linux__
   linux_terminal_restore_input();
#endif

   if (udev->fd >= 0)
      close(udev->fd);

   udev->fd = -1;

   for (i = 0; i < udev->num_devices; i++)
   {
      close(udev->devices[i]->fd);
      free(udev->devices[i]);
   }
   free(udev->devices);

   if (udev->monitor)
      udev_monitor_unref(udev->monitor);
   if (udev->udev)
      udev_unref(udev->udev);

   udev_input_kb_free(udev);

   linux_close_illuminance_sensor(udev->illuminance_sensor);

   free(udev);
}

static bool udev_set_sensor_state(void *data, unsigned port, enum retro_sensor_action action, unsigned rate)
{
   udev_input_t *udev = (udev_input_t*)data;

   if (!udev)
      return false;

   switch (action)
   {
      case RETRO_SENSOR_ILLUMINANCE_DISABLE:
         /* If already disabled, then do nothing */
         linux_close_illuminance_sensor(udev->illuminance_sensor); /* noop if NULL */
         udev->illuminance_sensor = NULL;
      case RETRO_SENSOR_GYROSCOPE_DISABLE:
      case RETRO_SENSOR_ACCELEROMETER_DISABLE:
         /** Unimplemented sensor actions that probably shouldn't fail */
         return true;

      case RETRO_SENSOR_ILLUMINANCE_ENABLE:
         if (udev->illuminance_sensor)
            /* If we already have a sensor, just set the rate */
            linux_set_illuminance_sensor_rate(udev->illuminance_sensor, rate);
         else
            udev->illuminance_sensor = linux_open_illuminance_sensor(rate);

         return udev->illuminance_sensor != NULL;
      default:
         break;
   }

   return false;
}

static float udev_get_sensor_input(void *data, unsigned port, unsigned id)
{
   udev_input_t *udev = (udev_input_t*)data;

   if (!udev)
      return 0.0f;

   switch (id)
   {
      case RETRO_SENSOR_ILLUMINANCE:
         if (udev->illuminance_sensor)
            return linux_get_illuminance_reading(udev->illuminance_sensor);
      default:
         break;
   }

   return 0.0f;
}

static bool open_devices(udev_input_t *udev,
      enum udev_input_dev_type type, device_handle_cb cb)
{
   struct udev_device *dev;
   const char             *type_str = g_dev_type_str[type];
   struct udev_list_entry     *devs = NULL;
   struct udev_list_entry     *item = NULL;
   struct udev_enumerate *enumerate = udev_enumerate_new(udev->udev);

   RARCH_DBG("[udev] Adding devices of type %u -> \"%s\".\n", type, type_str);
   if (!enumerate)
      return false;

   udev_enumerate_add_match_property(enumerate, type_str, "1");
   udev_enumerate_add_match_subsystem(enumerate, "input");
   udev_enumerate_scan_devices(enumerate);
   devs = udev_enumerate_get_list_entry(enumerate);

   for (item = devs; item; item = udev_list_entry_get_next(item))
   {
      const char *devnode;
      const char *name = udev_list_entry_get_name(item);

      RARCH_DBG("[udev] Adding device (t%u) \"%s\".\n", type, name);

      /* Get the filename of the /sys entry for the device
       * and create a udev_device object (dev) representing it. */
      dev     = udev_device_new_from_syspath(udev->udev, name);
      devnode = udev_device_get_devnode(dev);

      if (devnode)
      {
         int fd = open(devnode, O_RDONLY | O_NONBLOCK);

         if (fd != -1)
         {
            if (udev_input_add_device(udev, type, devnode, cb) == 0)
               RARCH_DBG("[udev] udev_input_add_device error: %s (%s).\n",
                     devnode, strerror(errno));

            close(fd);
         }
      }
      udev_device_unref(dev);
   }

   udev_enumerate_unref(enumerate);

   return true;
}

static void *udev_input_init(const char *joypad_driver)
{
   int mouse = 0;
   int keyboard=0;
   int fd;
   int i;
#ifdef UDEV_XKB_HANDLING
   gfx_ctx_ident_t ctx_ident;
#endif
   udev_input_t *udev   = (udev_input_t*)calloc(1, sizeof(*udev));

   if (!udev)
      return NULL;

   udev->udev = udev_new();
   if (!udev->udev)
      goto error;

   if ((udev->monitor = udev_monitor_new_from_netlink(udev->udev, "udev")))
   {
      udev_monitor_filter_add_match_subsystem_devtype(udev->monitor, "input", NULL);
      udev_monitor_enable_receiving(udev->monitor);
   }

#ifdef UDEV_XKB_HANDLING
   if (init_xkb(-1, 0) == -1)
      goto error;

   video_context_driver_get_ident(&ctx_ident);
#ifdef HAVE_LAKKA
   /* Force xkb_handling on Lakka */
   udev->xkb_handling = true;
#else
   udev->xkb_handling = string_is_equal(ctx_ident.ident, "kms");
#endif /* HAVE_LAKKA */
#endif

#if defined(HAVE_EPOLL)
   fd = epoll_create(32);
   if (fd < 0)
      goto error;
#elif defined(HAVE_KQUEUE)
   fd = kqueue();
   if (fd == -1)
      goto error;
#endif

   udev->fd  = fd;

   if (!open_devices(udev, UDEV_INPUT_KEYBOARD, udev_handle_keyboard))
      goto error;

   if (!open_devices(udev, UDEV_INPUT_MOUSE, udev_handle_mouse))
      goto error;

   if (!open_devices(udev, UDEV_INPUT_TOUCHPAD, udev_handle_mouse))
      goto error;

#ifdef UDEV_TOUCH_SUPPORT
   if (!open_devices(udev, UDEV_INPUT_TOUCHSCREEN, udev_handle_touch))
      goto error;
#endif

   /* If using KMS and we forgot this,
    * we could lock ourselves out completely. */
   if (!udev->num_devices)
   {
      settings_t *settings = config_get_ptr();
      RARCH_WARN("[udev] Couldn't open any keyboard, mouse or touchpad. Are permissions set correctly for /dev/input/event* and /run/udev/?\n");
      /* Start screen is not used nowadays, but it still gets true value only
       * on first startup without config file, so it should be good to catch
       * initial boots without udev devices available. */
#if defined(__linux__) && !defined(ANDROID)
      if (settings->bools.menu_show_start_screen)
      {
         /* Force fallback to linuxraw. Driver reselection would happen even
          * without overwriting input_driver setting, but that would not be saved
          * as input driver auto-changes are not stored (due to interlock with
          * video context driver), and on next boot user would be stuck with a
          * possibly nonworking configuration.
          */
         strlcpy(settings->arrays.input_driver, "linuxraw",
                 sizeof(settings->arrays.input_driver));
         RARCH_WARN("[udev] First boot and without input devices, forcing fallback to linuxraw.\n");
         goto error;
      }
#endif
   }

   input_keymaps_init_keyboard_lut(rarch_key_map_linux);

#ifdef __linux__
   linux_terminal_disable_input();
#endif

#ifndef HAVE_X11
   /* TODO/FIXME - this can't be hidden behind a compile-time ifdef */
   RARCH_WARN("[udev] Fullscreen pointer won't be available.\n");
#endif

   /* Reset the indirection array */
   for (i = 0; i < MAX_USERS; i++)
   {
      udev->pointers[i] = -1;
      udev->keyboards[i] = -1;
   }

   for (i = 0; i < (int)udev->num_devices; ++i)
   {
      if (udev->devices[i]->type != UDEV_INPUT_KEYBOARD)
      {
          RARCH_LOG("[udev] Mouse/Touch #%u: \"%s\" (%s) %s.\n",
             mouse,
             udev->devices[i]->ident,
             udev->devices[i]->mouse.abs ? "ABS" : "REL",
             udev->devices[i]->devnode);

          input_config_set_mouse_display_name(mouse, udev->devices[i]->ident);
          udev->pointers[mouse] = i;
          mouse++;
       }
       else
       {
          RARCH_LOG("[udev] Keyboard #%u: \"%s\" (%s).\n",
             keyboard,
             udev->devices[i]->ident,
             udev->devices[i]->devnode);
          udev->keyboards[keyboard] = i;
          keyboard++;
       }
   }

   return udev;

error:
   udev_input_free(udev);
   return NULL;
}

static uint64_t udev_input_get_capabilities(void *data)
{
   return
        (1 << RETRO_DEVICE_JOYPAD)
      | (1 << RETRO_DEVICE_ANALOG)
      | (1 << RETRO_DEVICE_KEYBOARD)
      | (1 << RETRO_DEVICE_MOUSE)
      | (1 << RETRO_DEVICE_POINTER)
      | (1 << RETRO_DEVICE_LIGHTGUN);
}

static void udev_input_grab_mouse(void *data, bool state)
{
#ifdef HAVE_X11
   Window window;
   Display *display = NULL;

   if (video_driver_display_type_get() != RARCH_DISPLAY_X11)
   {
      RARCH_WARN("[udev] Mouse grab/ungrab feature unavailable.\n");
      return;
   }

   display = (Display*)video_driver_display_get();
   window  = (Window)video_driver_window_get();

   if (state)
      XGrabPointer(display, window, False,
            ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
            GrabModeAsync, GrabModeAsync, window, None, CurrentTime);
   else
      XUngrabPointer(display, CurrentTime);
#else
   RARCH_WARN("[udev] Mouse grab/ungrab feature unavailable.\n");
#endif
}

input_driver_t input_udev = {
   udev_input_init,
   udev_input_poll,
   udev_input_state,
   udev_input_free,
   udev_set_sensor_state,
   udev_get_sensor_input,
   udev_input_get_capabilities,
   "udev",
   udev_input_grab_mouse,
#ifdef __linux__
   linux_terminal_grab_stdin,
#else
   NULL,
#endif
   NULL
};