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

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "xf86Wacom.h"
#include "Xwacom.h"
#include <xkbsrv.h>

void xf86WcmInitialScreens(LocalDevicePtr local);
void xf86WcmRotateTablet(LocalDevicePtr local, int value);

extern int xf86WcmDevSwitchModeCall(LocalDevicePtr local, int mode);
extern void xf86WcmChangeScreen(LocalDevicePtr local, int value);
extern void xf86WcmInitialCoordinates(LocalDevicePtr local, int axes);
extern void xf86WcmVirtualTabletSize(LocalDevicePtr local);
extern void xf86WcmVirtualTabletPadding(LocalDevicePtr local);
extern void xf86WcmTilt2R(WacomDeviceStatePtr ds);

/*****************************************************************************
 * Static functions
 ****************************************************************************/
 
static void transPressureCurve(WacomDevicePtr pDev, WacomDeviceStatePtr pState);
static void commonDispatchDevice(WacomCommonPtr common, unsigned int channel, 
	const WacomChannelPtr pChannel, int suppress);
static void resetSampleCounter(const WacomChannelPtr pChannel);
static void sendAButton(LocalDevicePtr local, int button, int mask,
		int rx, int ry, int rz, int v3, int v4, int v5);

/*****************************************************************************
 * xf86WcmMappingFactor --
 *   calculate the proper tablet to screen mapping factor according to the 
 *   screen/desktop size and the tablet size 
 ****************************************************************************/

void xf86WcmMappingFactor(LocalDevicePtr local)
{
	WacomDevicePtr priv = (WacomDevicePtr) local->private;
 
	DBG(10, priv->debugLevel, ErrorF("xf86WcmMappingFactor \n"));

	xf86WcmVirtualTabletSize(local);
	
	if (!(priv->flags & ABSOLUTE_FLAG) || !priv->wcmMMonitor)
	{
		/* Get the current screen that the cursor is in */
		if (miPointerGetScreen(local->dev))
			priv->currentScreen = miPointerGetScreen(local->dev)->myNum;
	}
	else
	{
		if (priv->screen_no != -1)
			priv->currentScreen = priv->screen_no;
		else if (priv->currentScreen == -1)
		{
			/* Get the current screen that the cursor is in */
			if (miPointerGetScreen(local->dev))
				priv->currentScreen = miPointerGetScreen(local->dev)->myNum;
		}
	}
	if (priv->currentScreen == -1) /* tool on the tablet */
		priv->currentScreen = 0;

	DBG(10, priv->debugLevel, ErrorF("xf86WcmMappingFactor"
		" Active tablet area x=%d y=%d (virtual tablet area x=%d y=%d) map"
		" to maxWidth =%d maxHeight =%d\n", 
		priv->bottomX, priv->bottomY, priv->sizeX, priv->sizeY, 
		priv->maxWidth, priv->maxHeight));

	priv->factorX = (double)priv->maxWidth / (double)priv->sizeX;
	priv->factorY = (double)priv->maxHeight / (double)priv->sizeY;
	DBG(2, priv->debugLevel, ErrorF("X factor = %.3g, Y factor = %.3g\n",
		priv->factorX, priv->factorY));
}

/*****************************************************************************
 * xf86WcmSetScreen --
 *   set to the proper screen according to the converted (x,y).
 *   this only supports for horizontal setup now.
 *   need to know screen's origin (x,y) to support 
 *   combined horizontal and vertical setups
 ****************************************************************************/

static void xf86WcmSetScreen(LocalDevicePtr local, int v0, int v1)
{
	WacomDevicePtr priv = (WacomDevicePtr) local->private;
	int screenToSet = -1, i, j, x, y, tabletSize = 0;

	DBG(6, priv->debugLevel, ErrorF("xf86WcmSetScreen v0=%d v1=%d "
		"currentScreen=%d\n", v0, v1, priv->currentScreen));

	if (priv->screen_no != -1 && priv->screen_no >= priv->numScreen)
	{
		xf86Msg(X_ERROR, "%s: xf86WcmSetScreen Screen%d is larger than number of available screens (%d)\n",
			local->name, priv->screen_no, priv->numScreen);
		priv->screen_no = -1;
	}

	if (!(local->flags & (XI86_ALWAYS_CORE | XI86_CORE_POINTER))) return;

	if (priv->twinview != TV_NONE && priv->screen_no == -1 && (priv->flags & ABSOLUTE_FLAG))
	{
		if (priv->twinview == TV_LEFT_RIGHT)
		{
			tabletSize = priv->bottomX - priv->tvoffsetX;
			if (v0 > tabletSize && v0 <= priv->bottomX)
				priv->currentScreen = 1;
			if (v0 > priv->topX && v0 <= priv->topX + priv->tvoffsetX)
				priv->currentScreen = 0;
		}
		if (priv->twinview == TV_ABOVE_BELOW)
		{
			tabletSize = priv->bottomY - priv->tvoffsetY;
			if (v0 > tabletSize && v0 <= priv->bottomY)
				priv->currentScreen = 1;
			if (v0 > priv->topY && v0 <= priv->topY + priv->tvoffsetY)
				priv->currentScreen = 0;
		}
		if (priv->twinview == TV_RIGHT_LEFT)
		{
			tabletSize = priv->bottomX - priv->tvoffsetX;
			if (v0 > tabletSize && v0 <= priv->bottomX)
				priv->currentScreen = 0;
			if (v0 > priv->topX && v0 <= priv->topX + priv->tvoffsetX)
				priv->currentScreen = 1;
		}
		if (priv->twinview == TV_BELOW_ABOVE)
		{
			tabletSize = priv->bottomY - priv->tvoffsetY;
			if (v0 > tabletSize && v0 <= priv->bottomY)
				priv->currentScreen = 0;
			if (v0 > priv->topY && v0 <= priv->topY + priv->tvoffsetY)
				priv->currentScreen = 1;
		}
		DBG(10, priv->debugLevel, ErrorF("xf86WcmSetScreen TwinView setup screenToSet=%d\n", 
			priv->currentScreen));
	}

	xf86WcmMappingFactor(local);
	if (!(priv->flags & ABSOLUTE_FLAG) || screenInfo.numScreens == 1 || !priv->wcmMMonitor)
		return;

	v0 = v0 - priv->topX;
	v1 = v1 - priv->topY;

	if (priv->screen_no == -1)
	{
		for (i = 0; i < priv->numScreen; i++)
		{
			if (v0 * priv->factorX >= priv->screenTopX[i] && 
				v0 * priv->factorX < priv->screenBottomX[i] - 0.5)
			{
				
				for (j = 0; j < priv->numScreen; j++)
				{
					if (v1 * priv->factorY >= priv->screenTopY[j] && 
						v1 * priv->factorY <= priv->screenBottomY[j] - 0.5)
					{
						if (j == i)
						{
							screenToSet = i;
							break;
						}
					}
				}
					
				if (screenToSet != -1)
					break;
			}
		}
	}
	else
		screenToSet = priv->screen_no;

	if (screenToSet == -1)
	{
		DBG(3, priv->debugLevel, ErrorF("xf86WcmSetScreen Error: "
			"Can not find valid screen (currentScreen=%d)\n", 
			priv->currentScreen));
		return;
	}

	xf86WcmVirtualTabletPadding(local);
	x = ((double)(v0 + priv->leftPadding) * priv->factorX) - priv->screenTopX[screenToSet] + 0.5;
	y = ((double)(v1 + priv->topPadding) * priv->factorY) - priv->screenTopY[screenToSet] + 0.5;
		
	if (x >= screenInfo.screens[screenToSet]->width)
		x = screenInfo.screens[screenToSet]->width - 1;
	if (y >= screenInfo.screens[screenToSet]->height)
		y = screenInfo.screens[screenToSet]->height - 1;

	xf86XInputSetScreen(local, screenToSet, x, y);
	DBG(10, priv->debugLevel, ErrorF("xf86WcmSetScreen current=%d ToSet=%d\n", 
			priv->currentScreen, screenToSet));
	priv->currentScreen = screenToSet;
}

/*****************************************************************************
 * xf86WcmSendButtons --
 *   Send button events by comparing the current button mask with the
 *   previous one.
 ****************************************************************************/

static void xf86WcmSendButtons(LocalDevicePtr local, int buttons, int rx, int ry, 
		int rz, int v3, int v4, int v5)
{
	int button, mask;
	WacomDevicePtr priv = (WacomDevicePtr) local->private;
	WacomCommonPtr common = priv->common;
	DBG(6, priv->debugLevel, ErrorF("xf86WcmSendButtons "
		"buttons=%d for %s\n", buttons, local->name));

	/* Tablet PC buttons only apply to penabled devices */
	if (common->wcmTPCButton && (priv->flags & STYLUS_ID))
	{
		if ( buttons & 1 )
		{
			if ( !(priv->flags & TPCBUTTONS_FLAG) )
			{
				priv->flags |= TPCBUTTONS_FLAG;

				if (buttons == 1) {
					/* Button 1 pressed */
					sendAButton(local, 0, 1, rx, ry, rz, v3, v4, v5);
				} else {
					/* send all pressed buttons down */
					for (button=2; button<=WCM_MAX_BUTTONS; button++)
					{
						mask = 1 << (button-1);
						if ( buttons & mask )
						{
							/* set to the configured button */
							sendAButton(local, button-1, 1, rx, ry,
									rz, v3, v4, v5);
						}
					}
				}
			}
			else
			{
				for (button=2; button<=WCM_MAX_BUTTONS; button++)
				{
					mask = 1 << (button-1);
					if ((mask & priv->oldButtons) != (mask & buttons))
					{
						/* set to the configured buttons */
						sendAButton(local, button-1, mask & buttons, 
							rx, ry, rz, v3, v4, v5);
					}
				}
			}
		}
		else if ( priv->flags & TPCBUTTONS_FLAG )
		{
			priv->flags &= ~TPCBUTTONS_FLAG;

			/* send all pressed buttons up */
			for (button=1; button<=WCM_MAX_BUTTONS; button++)
			{
				mask = 1 << (button-1);
				if ((mask & priv->oldButtons) != (mask & buttons) || (mask & buttons) )
				{
					/* set to the configured button */
					sendAButton(local, button-1, 0, rx, ry, 
						rz, v3, v4, v5);
				}
			}
		}
	}
	else  /* normal buttons */
	{
		for (button=1; button<=WCM_MAX_BUTTONS; button++)
		{
			mask = 1 << (button-1);
			if ((mask & priv->oldButtons) != (mask & buttons))
			{
				/* set to the configured button */
				sendAButton(local, button-1, mask & buttons, rx, ry, 
					rz, v3, v4, v5);
			}
		}
	}
}

/*****************************************************************************
 * emitKeysym --
 *   Emit a keydown/keyup event
 ****************************************************************************/
static int ODDKEYSYM [][2] = 
{
	{ XK_asciitilde, XK_grave },
	{ XK_exclam, XK_1 },
	{ XK_at, XK_2 },
	{ XK_numbersign, XK_3 },
	{ XK_dollar, XK_4 },
	{ XK_percent, XK_5 },
	{ XK_asciicircum, XK_6 },
	{ XK_ampersand, XK_7 },
	{ XK_asterisk, XK_8 },
	{ XK_parenleft, XK_9 },
	{ XK_parenright, XK_0 },
	{ XK_underscore, XK_minus },
	{ XK_plus, XK_equal },
	{ XK_braceleft, XK_bracketleft },
	{ XK_braceright, XK_bracketright },
	{ XK_colon, XK_semicolon },
	{ XK_quotedbl, XK_quoteright },
	{ XK_less, XK_comma },
	{ XK_greater, XK_period },
	{ XK_question, XK_slash },
	{ XK_bar, XK_backslash },
	{ 0, 0}
};

static void emitKeysym (DeviceIntPtr keydev, int keysym, int state)
{
	int i, j, alt_keysym = 0;

	/* Now that we have the keycode look for key index */
#if GET_ABI_MAJOR(ABI_XINPUT_VERSION) >= 7
	KeySymsRec *ksr = XkbGetCoreMap(keydev);
#else
	KeySymsRec *ksr = &keydev->key->curKeySyms;
#endif

	for (i = ksr->minKeyCode; i <= ksr->maxKeyCode; i++)
		if (ksr->map [(i - ksr->minKeyCode) * ksr->mapWidth] == keysym)
			break;

	if (i > ksr->maxKeyCode)
	{
		if (isupper(keysym))
			alt_keysym = tolower(keysym);
		else
		{
			j = 0;
			while (ODDKEYSYM [j][0])
			{
				if (ODDKEYSYM [j][0] == keysym)
				{
					alt_keysym = ODDKEYSYM [j][1];
					break;
				}
				j++;
			}
		}
		if ( alt_keysym )
		{
			for (j = ksr->minKeyCode; j <= ksr->maxKeyCode; j++)
				if (ksr->map [(j - ksr->minKeyCode) * ksr->mapWidth] == XK_Shift_L)
					break;
			if (state)
				xf86PostKeyboardEvent (keydev, j, 1);
			for (i = ksr->minKeyCode; i <= ksr->maxKeyCode; i++)
				if (ksr->map [(i - ksr->minKeyCode) * ksr->mapWidth] == alt_keysym)
					break;
			xf86PostKeyboardEvent (keydev, i, state);
			if (!state)
				xf86PostKeyboardEvent (keydev, j, 0);
		}
		else
			xf86Msg (X_WARNING, "%s: Couldn't find key with code %08x on keyboard device %s\n",
					keydev->name, keysym, keydev->name);
#if GET_ABI_MAJOR(ABI_XINPUT_VERSION) >= 7
		xfree(ksr);
#endif
		return;
	}
	xf86PostKeyboardEvent (keydev, i, state);
#if GET_ABI_MAJOR(ABI_XINPUT_VERSION) >= 7
	xfree(ksr);
#endif
}

static void toggleDisplay(LocalDevicePtr local)
{
	WacomDevicePtr priv = (WacomDevicePtr) local->private;
	WacomCommonPtr common = priv->common;

	if (priv->numScreen > 1)
	{
		if (IsPad(priv)) /* toggle display for all tools except pad */
		{
			WacomDevicePtr tmppriv;
			for (tmppriv = common->wcmDevices; tmppriv; tmppriv = tmppriv->next)
			{
				if (!IsPad(tmppriv))
				{
					int screen = tmppriv->screen_no;
					if (++screen >= tmppriv->numScreen)
						screen = -1;
					xf86WcmChangeScreen(tmppriv->local, screen);
				}
			}
		}
		else /* toggle display only for the selected tool */
		{
			int screen = priv->screen_no;
			if (++screen >= priv->numScreen)
				screen = -1;
			xf86WcmChangeScreen(local, screen);
		}
	}
}

/*****************************************************************************
 * countPresses
 *   Count the number of key/button presses not released for the given key
 *   array.
 ****************************************************************************/
static int countPresses(int keybtn, unsigned int* keys, int size)
{
	int i, act, count = 0;

	for (i = 0; i < size; i++)
	{
		act = keys[i];
		if ((act & AC_CODE) == keybtn)
			count += (act & AC_KEYBTNPRESS) ? 1 : -1;
	}

	return count;
}

/*****************************************************************************
 * sendAButton --
 *   Send one button event, called by xf86WcmSendButtons
 ****************************************************************************/
static void sendAButton(LocalDevicePtr local, int button, int mask,
		int rx, int ry, int rz, int v3, int v4, int v5)
{
	WacomDevicePtr priv = (WacomDevicePtr) local->private;
#ifdef DEBUG
	WacomCommonPtr common = priv->common;
#endif
	int is_absolute = priv->flags & ABSOLUTE_FLAG;
	int i;

	int naxes = priv->naxes;

	if (!priv->button[button])  /* ignore this button event */
		return;

	DBG(4, priv->debugLevel, ErrorF(
		"sendAButton TPCButton(%s) button=%d state=%d " 
		"code=%08x, for %s coreEvent=%s \n", 
		common->wcmTPCButton ? "on" : "off", 
		button, mask, priv->button[button], 
		local->name, (priv->button[button] & AC_CORE) ? "yes" : "no"));

	if (!priv->keys[button][0])
	{
		/* No button action configured, send button */
		xf86PostButtonEvent(local->dev, is_absolute, priv->button[button], (mask != 0), 0, naxes,
				    rx, ry, rz, v3, v4, v5);
		return;
	}

	/* Actions only trigger on press, not release */
	for (i = 0; mask && i < ARRAY_SIZE(priv->keys[button]); i++)
	{
		unsigned int action = priv->keys[button][i];

		if (!action)
			break;

		switch ((action & AC_TYPE))
		{
			case AC_BUTTON:
				{
					int btn_no = (action & AC_CODE);
					int is_press = (action & AC_KEYBTNPRESS);
					xf86PostButtonEvent(local->dev,
							    is_absolute, btn_no,
							    is_press, 0, naxes,
							    rx, ry, rz, v3, v4, v5);
				}
				break;
			case AC_KEY:
				{
					int key_sym = (action & AC_CODE);
					int is_press = (action & AC_KEYBTNPRESS);
					emitKeysym(local->dev, key_sym, is_press);
				}
				break;
			case AC_MODETOGGLE:
				if (mask)
					xf86WcmDevSwitchModeCall(local,
							(is_absolute) ? Relative : Absolute); /* not a typo! */
				break;
			/* FIXME: this should be implemented as 4 values,
			 * there's no reason to have a DBLCLICK */
			case AC_DBLCLICK:
				xf86PostButtonEvent(local->dev, is_absolute,
						    1,1,0,naxes, rx,ry,rz,v3,v4,v5);
				xf86PostButtonEvent(local->dev, is_absolute,
						    1,0,0,naxes,rx,ry,rz,v3,v4,v5);
				xf86PostButtonEvent(local->dev, is_absolute,
						    1,1,0,naxes, rx,ry,rz,v3,v4,v5);
				xf86PostButtonEvent(local->dev, is_absolute,
						    1,0,0,naxes,rx,ry,rz,v3,v4,v5);
				break;
			case AC_DISPLAYTOGGLE:
				toggleDisplay(local);
				break;
		}
	}

	/* Release all non-released keys for this button. */
	for (i = 0; !mask && i < ARRAY_SIZE(priv->keys[button]); i++)
	{
		unsigned int action = priv->keys[button][i];

		switch ((action & AC_TYPE))
		{
			case AC_BUTTON:
				{
					int btn_no = (action & AC_CODE);

					/* don't care about releases here */
					if (!(action & AC_KEYBTNPRESS))
						break;

					if (countPresses(btn_no, &priv->keys[button][i],
							ARRAY_SIZE(priv->keys[button]) - i))
						xf86PostButtonEvent(local->dev,
								is_absolute, btn_no,
								0, 0, naxes,
								rx, ry, rz, v3, v4, v5);
				}
				break;
			case AC_KEY:
				{
					int key_sym = (action & AC_CODE);

					/* don't care about releases here */
					if (!(action & AC_KEYBTNPRESS))
						break;

					if (countPresses(key_sym, &priv->keys[button][i],
							ARRAY_SIZE(priv->keys[button]) - i))
						emitKeysym(local->dev, key_sym, 0);
				}
		}

	}
}

/*****************************************************************************
 * sendWheelStripEvents --
 *   Send events defined for relative/absolute wheels or strips
 ****************************************************************************/

static void sendWheelStripEvents(LocalDevicePtr local, const WacomDeviceState* ds, 
		int x, int y, int z, int v3, int v4, int v5)
{
	WacomDevicePtr priv = (WacomDevicePtr) local->private;
	int fakeButton = 0, i, value = 0, naxes = priv->naxes;
	unsigned  *keyP = 0;
	int is_absolute = priv->flags & ABSOLUTE_FLAG;

	DBG(10, priv->debugLevel, ErrorF("sendWheelStripEvents for %s \n", local->name));

	/* emulate events for relative wheel */
	if ( ds->relwheel )
	{
		value = ds->relwheel;
		if ( ds->relwheel > 0 )
		{
			fakeButton = priv->relup;
			keyP = priv->rupk;
		}
		else
		{
			fakeButton = priv->reldn;
			keyP = priv->rdnk;
		}
	}

	/* emulate events for absolute wheel when needed */
	if ( ds->abswheel != priv->oldWheel )
	{
		value = priv->oldWheel - ds->abswheel;
		if ( value > 0 )
		{
			fakeButton = priv->wheelup;
			keyP = priv->wupk;
		}
		else
		{
			fakeButton = priv->wheeldn;
			keyP = priv->wdnk;
		}
	}

	/* emulate events for left strip */
	if ( ds->stripx != priv->oldStripX )
	{
		int temp = 0, n;
		for (i=1; i<14; i++)
		{
			n = 1 << (i-1);
			if ( ds->stripx & n )
				temp = i;
			if ( priv->oldStripX & n )
				value = i;
			if ( temp & value) break;
		}

		value -= temp;
		if ( value > 0 )
		{
			fakeButton = priv->striplup;
			keyP = priv->slupk;
		}
		else if ( value < 0 )
		{
			fakeButton = priv->stripldn;
			keyP = priv->sldnk;
		}
	}

	/* emulate events for right strip */
	if ( ds->stripy != priv->oldStripY )
	{
		int temp = 0, n;
		for (i=1; i<14; i++)
		{
			n = 1 << (i-1);
			if ( ds->stripy & n )
				temp = i;
			if ( priv->oldStripY & n )
				value = i;
			if ( temp & value) break;
		}

		value -= temp;
		if ( value > 0 )
		{
			fakeButton = priv->striprup;
			keyP = priv->srupk;
		}
		else if ( value < 0 )
		{
			fakeButton = priv->striprdn;
			keyP = priv->srdnk;
		}
	}

	if (!fakeButton) return;

	DBG(10, priv->debugLevel, ErrorF("sendWheelStripEvents "
		"send fakeButton %x with value = %d \n", 
		fakeButton, value));

	switch (fakeButton & AC_TYPE)
	{
	    case 0: /* no spec. action defined */
	    case AC_BUTTON:
		/* send both button on/off in the same event for pad */	
		xf86PostButtonEvent(local->dev, is_absolute, fakeButton & AC_CODE,
			1,0,naxes,x,y,z,v3,v4,v5);

		xf86PostButtonEvent(local->dev, is_absolute, fakeButton & AC_CODE,
			0,0,naxes,x,y,z,v3,v4,v5);
	    break;

	    case AC_KEY:
		    emitKeysym(local->dev, (fakeButton & AC_CODE), 1);
		    emitKeysym(local->dev, (fakeButton & AC_CODE), 0);
	    break;

	    default:
		xf86Msg(X_WARNING, "%s: unsupported event %x \n", local->name, fakeButton);
	}
}

/*****************************************************************************
 * sendCommonEvents --
 *   Send events common between pad and stylus/cursor/eraser.
 ****************************************************************************/

static void sendCommonEvents(LocalDevicePtr local, const WacomDeviceState* ds, int x, int y, int z, int v3, int v4, int v5)
{
	WacomDevicePtr priv = (WacomDevicePtr) local->private;
	int buttons = ds->buttons;

	/* send button events when state changed or first time in prox and button unpresses */
	if (priv->oldButtons != buttons || (!priv->oldProximity && !buttons))
		xf86WcmSendButtons(local,buttons,x,y,z,v3,v4,v5);

	/* emulate wheel/strip events when defined */
	if ( ds->relwheel || ds->abswheel || 
		( (ds->stripx - priv->oldStripX) && ds->stripx && priv->oldStripX) || 
			((ds->stripy - priv->oldStripY) && ds->stripy && priv->oldStripY) )
		sendWheelStripEvents(local, ds, x, y, z, v3, v4, v5);
}

/*****************************************************************************
 * xf86WcmSendEvents --
 *   Send events according to the device state.
 ****************************************************************************/

void xf86WcmSendEvents(LocalDevicePtr local, const WacomDeviceState* ds)
{
#ifdef DEBUG
	int is_button = !!(ds->buttons);
#endif
	int type = ds->device_type;
	int id = ds->device_id;
	int serial = (int)ds->serial_num;
	int is_proximity = ds->proximity;
	int x = ds->x;
	int y = ds->y;
	int z = ds->pressure;
	int buttons = ds->buttons;
	int tx = ds->tiltx;
	int ty = ds->tilty;
	int rot = ds->rotation;
	int throttle = ds->throttle;
	int wheel = ds->abswheel;
	int tmp_coord;
	WacomDevicePtr priv = (WacomDevicePtr) local->private;
	WacomCommonPtr common = priv->common;
	int naxes = priv->naxes;
	int is_absolute = priv->flags & ABSOLUTE_FLAG;
	int v3, v4, v5;

	if (priv->serial && serial != priv->serial)
	{
		DBG(10, priv->debugLevel, ErrorF("[%s] serial number"
			" is %u but your system configured %u", 
			local->name, serial, (int)priv->serial));
		return;
	}

	/* don't move the cursor when going out-prox */
	if (!ds->proximity)
	{
		x = priv->oldX;
		y = priv->oldY;
	}

	/* use tx and ty to report stripx and stripy */
	if (type == PAD_ID)
	{
		tx = ds->stripx;
		ty = ds->stripy;
	}

	DBG(7, priv->debugLevel, ErrorF("[%s] o_prox=%s x=%d y=%d z=%d "
		"b=%s b=%d tx=%d ty=%d wl=%d rot=%d th=%d\n",
		(type == STYLUS_ID) ? "stylus" :
			(type == CURSOR_ID) ? "cursor" : 
			(type == ERASER_ID) ? "eraser" :
			(type == TOUCH_ID) ? "touch" : "pad",
		priv->oldProximity ? "true" : "false",
		x, y, z, is_button ? "true" : "false", buttons,
		tx, ty, wheel, rot, throttle));

	/* rotation mixes x and y up a bit */
	if (common->wcmRotate == ROTATE_CW)
	{
		tmp_coord = x;
		x = y;
		if (!IsTouch(priv))
			y = common->wcmMaxY - tmp_coord;
		else
			y = common->wcmMaxTouchY - tmp_coord;
	}
	else if (common->wcmRotate == ROTATE_CCW)
	{
		tmp_coord = y;
		y = x;
		if (!IsTouch(priv))
			x = common->wcmMaxX - tmp_coord;
		else
			y = common->wcmMaxTouchX - tmp_coord;
	}
	else if (common->wcmRotate == ROTATE_HALF)
	{
		if (!IsTouch(priv))
		{
			x = common->wcmMaxX - x;
			y = common->wcmMaxY - y;
		}
		else
		{
			x = common->wcmMaxTouchX - x;
			y = common->wcmMaxTouchY - y;
		}
	}

	if (IsCursor(priv)) 
	{
		v3 = rot;
		v4 = throttle;
	}
	else  /* Intuos styli have tilt */
	{
		v3 = tx;
		v4 = ty;
	}
	v5 = wheel;

	DBG(6, priv->debugLevel, ErrorF("[%s] %s prox=%d\tx=%d"
		"\ty=%d\tz=%d\tv3=%d\tv4=%d\tv5=%d\tid=%d"
		"\tserial=%u\tbutton=%s\tbuttons=%d\n",
		local->name,
		is_absolute ? "abs" : "rel",
		is_proximity,
		x, y, z, v3, v4, v5, id, serial,
		is_button ? "true" : "false", buttons));

	priv->currentX = x;
	priv->currentY = y;

	/* update the old records */
	if(!priv->oldProximity)
	{
		priv->oldWheel = wheel;
		priv->oldX = priv->currentX;
		priv->oldY = priv->currentY;
		priv->oldZ = z;
		priv->oldTiltX = tx;
		priv->oldTiltY = ty;
		priv->oldCapacity = ds->capacity;
		priv->oldStripX = ds->stripx;
		priv->oldStripY = ds->stripy;
		priv->oldRot = rot;
		priv->oldThrottle = throttle;
		priv->oldButtons = 0;
	}
	if (!is_absolute)
	{
		x -= priv->oldX;
		y -= priv->oldY;
	}

	if (type != PAD_ID)
	{
		/* coordinates are ready we can send events */
		if (is_proximity)
		{
			/* for multiple monitor support, we need to set the proper 
			 * screen and modify the axes before posting events */
			if(!(priv->flags & BUTTONS_ONLY_FLAG))
			{
				xf86WcmSetScreen(local, x, y);
			}

			/* unify acceleration in both directions 
			 * for relative mode to draw a circle 
			 */
			if (!is_absolute)
				x *= priv->factorY / priv->factorX;
 			else
			{
				/* Padding virtual values */
				xf86WcmVirtualTabletPadding(local);
				x += priv->leftPadding;
				y += priv->topPadding;
			}

			if (common->wcmScaling)
			{
				/* In the case that xf86WcmDevConvert doesn't get called.
				 * The +-0.4 is to increase the sensitivity in relative mode.
				 * Must be sensitive to which way the tool is moved or one way
				 * will get a severe penalty for small movements.
				 */
 				if(is_absolute) {
					x -= priv->topX;
					y -= priv->topY;
					if (priv->currentScreen == 1 && priv->twinview != TV_NONE)
					{
						x -= priv->tvoffsetX;
						y -= priv->tvoffsetY;
					}
				}
				x = (int)((double)x * priv->factorX + (x>=0?0.4:-0.4));
				y = (int)((double)y * priv->factorY + (y>=0?0.4:-0.4));

				if ((priv->flags & ABSOLUTE_FLAG) && (priv->twinview == TV_NONE))
				{
					x -= priv->screenTopX[priv->currentScreen];
					y -= priv->screenTopY[priv->currentScreen];
				}

				if (priv->screen_no != -1)
				{
					if (x > priv->screenBottomX[priv->currentScreen] - priv->screenTopX[priv->currentScreen])
						x = priv->screenBottomX[priv->currentScreen];
					if (x < 0) x = 0;
					if (y > priv->screenBottomY[priv->currentScreen] - priv->screenTopY[priv->currentScreen])
						y = priv->screenBottomY[priv->currentScreen];
					if (y < 0) y = 0;
	
				}
				priv->currentSX = x;
				priv->currentSY = y;
			}

			/* don't emit proximity events if device does not support proximity */
			if ((local->dev->proximity && !priv->oldProximity))
				xf86PostProximityEvent(local->dev, 1, 0, naxes, x, y, z, v3, v4, v5);

			/* Move the cursor to where it should be before sending button events */
			if(!(priv->flags & BUTTONS_ONLY_FLAG))
				xf86PostMotionEvent(local->dev, is_absolute,
					0, naxes, x, y, z, v3, v4, v5);

			sendCommonEvents(local, ds, x, y, z, v3, v4, v5);
		}

		/* not in proximity */
		else
		{
			buttons = 0;

			if (common->wcmScaling)
			{
				/* In the case that xf86WcmDevConvert doesn't called */
				x = priv->currentSX;
				y = priv->currentSY;
			}

			/* reports button up when the device has been
			 * down and becomes out of proximity */
			if (priv->oldButtons)
				xf86WcmSendButtons(local,0,x,y,z,v3,v4,v5);

			if (priv->oldProximity && local->dev->proximity)
				xf86PostProximityEvent(local->dev,0,0,naxes,x,y,z,v3,v4,v5);
		} /* not in proximity */
	}
	else
	{
		if (v3 || v4 || v5 || buttons || ds->relwheel)
		{
			x = 0;
			y = 0;
			if ( v3 || v4 || v5 )
				xf86WcmSetScreen(local, x, y);

			/* don't emit proximity events if device does not support proximity */
			if ((local->dev->proximity && !priv->oldProximity))
			xf86PostProximityEvent(local->dev, 1, 0, naxes, x, y, z, v3, v4, v5);

			sendCommonEvents(local, ds, x, y, z, v3, v4, v5);
			is_proximity = 1;
			/* xf86PostMotionEvent is only needed to post the valuators
			 * It should NOT move the cursor.
			 */
			if ( v3 || v4 || v5 )
			{
	 			xf86PostMotionEvent(local->dev, is_absolute,
					0, naxes, x, y, z, v3, v4, v5);
			}
		}
		else
		{
			if (priv->oldButtons)
				xf86WcmSendButtons(local, buttons, 
					x, y, z, v3, v4, v5);
			if (priv->oldProximity && local->dev->proximity)
 				xf86PostProximityEvent(local->dev, 0, 0, naxes, 
				x, y, z, v3, v4, v5);
			is_proximity = 0;
		}
	}
	priv->oldProximity = is_proximity;
	priv->old_device_id = id;
	priv->old_serial = serial;
	if (is_proximity)
	{
		priv->oldButtons = buttons;
		priv->oldWheel = wheel;
		priv->oldX = priv->currentX;
		priv->oldY = priv->currentY;
		priv->oldZ = z;
		priv->oldCapacity = ds->capacity;
		priv->oldTiltX = tx;
		priv->oldTiltY = ty;
		priv->oldStripX = ds->stripx;
		priv->oldStripY = ds->stripy;
		priv->oldRot = rot;
		priv->oldThrottle = throttle;
	}
	else
	{
		priv->oldButtons = 0;
		priv->oldWheel = 0;
		priv->oldX = 0;
		priv->oldY = 0;
		priv->oldZ = 0;
		priv->oldCapacity = ds->capacity;
		priv->oldTiltX = 0;
		priv->oldTiltY = 0;
		priv->oldStripX = 0;
		priv->oldStripY = 0;
		priv->oldRot = 0;
		priv->oldThrottle = 0;
		priv->devReverseCount = 0;
	}
}

/*****************************************************************************
 * xf86WcmSuppress --
 *  Determine whether device state has changed enough - return 0
 *  if not.
 ****************************************************************************/

static int xf86WcmSuppress(WacomCommonPtr common, const WacomDeviceState* dsOrig, 
	WacomDeviceState* dsNew)
{
	int suppress = common->wcmSuppress;
	/* NOTE: Suppression value of zero disables suppression. */
	int returnV = 0;

	if (dsOrig->buttons != dsNew->buttons) returnV = 1;
	if (dsOrig->proximity != dsNew->proximity) returnV = 1;
	if (dsOrig->stripx != dsNew->stripx) returnV = 1;
	if (dsOrig->stripy != dsNew->stripy) returnV = 1;
	if (ABS(dsOrig->tiltx - dsNew->tiltx) > suppress) returnV = 1;
	if (ABS(dsOrig->tilty - dsNew->tilty) > suppress) returnV = 1;
	if (ABS(dsOrig->pressure - dsNew->pressure) > suppress) returnV = 1;
	if (ABS(dsOrig->capacity - dsNew->capacity) > suppress) returnV = 1;
	if (ABS(dsOrig->throttle - dsNew->throttle) > suppress) returnV = 1;
	if (ABS(dsOrig->rotation - dsNew->rotation) > suppress &&
		(1800 - ABS(dsOrig->rotation - dsNew->rotation)) >  suppress) returnV = 1;

	/* look for change in absolute wheel position 
	 * or any relative wheel movement
	 */
	if ((ABS(dsOrig->abswheel - dsNew->abswheel) > suppress) 
		|| (dsNew->relwheel != 0)) returnV = 1;

	/* cursor moves or not? */
	if ((ABS(dsOrig->x - dsNew->x) > suppress) || 
			(ABS(dsOrig->y - dsNew->y) > suppress)) 
	{
		if (!returnV) /* need to check if cursor moves or not */
			returnV = 2;
	}
	else /* don't move cursor */
	{
		dsNew->x = dsOrig->x;
		dsNew->y = dsOrig->y;
	}

	DBG(10, common->debugLevel, ErrorF("xf86WcmSuppress at level = %d"
		" return value = %d\n", suppress, returnV));
	return returnV;
}

/* reset raw data counters for filters */
static void resetSampleCounter(const WacomChannelPtr pChannel)
{
	/* if out of proximity, reset hardware filter */
	if (!pChannel->valid.state.proximity)
	{
		pChannel->nSamples = 0;
		pChannel->rawFilter.npoints = 0;
		pChannel->rawFilter.statex = 0;
		pChannel->rawFilter.statey = 0;
	}
}

/*****************************************************************************
 * xf86WcmEvent -
 *   Handles suppression, transformation, filtering, and event dispatch.
 ****************************************************************************/

void xf86WcmEvent(WacomCommonPtr common, unsigned int channel,
	const WacomDeviceState* pState)
{
	WacomDeviceState* pLast;
	WacomDeviceState ds;
	WacomChannelPtr pChannel;
	WacomFilterState* fs;
	int i, suppress = 0;

	pChannel = common->wcmChannel + channel;
	pLast = &pChannel->valid.state;

	DBG(10, common->debugLevel, ErrorF("xf86WcmEvent at channel = %d\n", channel));

	/* sanity check the channel */
	if (channel >= MAX_CHANNELS)
		return;
	
	/* we must copy the state because certain types of filtering
	 * will need to change the values (ie. for error correction) */
	ds = *pState;

	/* timestamp the state for velocity and acceleration analysis */
	ds.sample = (int)GetTimeInMillis();
	DBG(10, common->debugLevel, ErrorF("xf86WcmEvent: "
		"c=%d i=%d t=%d s=%u x=%d y=%d b=%d "
		"p=%d rz=%d tx=%d ty=%d aw=%d rw=%d "
		"t=%d df=%d px=%d st=%d cs=%d \n",
		channel,
		ds.device_id,
		ds.device_type,
		ds.serial_num,
		ds.x, ds.y, ds.buttons,
		ds.pressure, ds.rotation, ds.tiltx,
		ds.tilty, ds.abswheel, ds.relwheel, ds.throttle,
		ds.discard_first, ds.proximity, ds.sample,
		pChannel->nSamples));

	/* Discard the first 2 USB packages due to events delay */
	if ( (pChannel->nSamples < 2) && (common->wcmDevCls == &gWacomUSBDevice) && 
		ds.device_type != PAD_ID && (ds.device_type != TOUCH_ID) )
	{
		DBG(11, common->debugLevel, 
			ErrorF("discarded %dth USB data.\n", 
			pChannel->nSamples));
		++pChannel->nSamples;
		return; /* discard */
	}

	if (strstr(common->wcmModel->name, "Intuos4"))
	{
		/* convert Intuos4 mouse tilt to rotation */
		xf86WcmTilt2R(&ds);
	}

	fs = &pChannel->rawFilter;
	if (!fs->npoints && ds.proximity)
	{
		DBG(11, common->debugLevel, ErrorF("initialize Channel data.\n"));
		/* store channel device state for later use */
		for (i=common->wcmRawSample - 1; i>=0; i--)
		{
			fs->x[i]= ds.x;
			fs->y[i]= ds.y;
			fs->tiltx[i] = ds.tiltx;
			fs->tilty[i] = ds.tilty;
		}
		++fs->npoints;
	} else  {
		/* Filter raw data, fix hardware defects, perform error correction */
		for (i=common->wcmRawSample - 1; i>0; i--)
		{
			fs->x[i]= fs->x[i-1];
			fs->y[i]= fs->y[i-1];
		}
		fs->x[0] = ds.x;
		fs->y[0] = ds.y;
		if (HANDLE_TILT(common) && (ds.device_type == STYLUS_ID || ds.device_type == ERASER_ID))
		{
			for (i=common->wcmRawSample - 1; i>0; i--)
			{
				fs->tiltx[i]= fs->tiltx[i-1];
				fs->tilty[i]= fs->tilty[i-1];
			}
			fs->tiltx[0] = ds.tiltx;
			fs->tilty[0] = ds.tilty;
		}
		if (RAW_FILTERING(common) && common->wcmModel->FilterRaw && ds.device_type != PAD_ID)
		{
			if (common->wcmModel->FilterRaw(common,pChannel,&ds))
			{
				DBG(10, common->debugLevel, ErrorF(
					"Raw filtering discarded data.\n"));
				resetSampleCounter(pChannel);
				return; /* discard */
			}
		}

		/* Discard unwanted data */
		suppress = xf86WcmSuppress(common, pLast, &ds);
		if (!suppress)
		{
			resetSampleCounter(pChannel);
			return;
		}
	}

	/* JEJ - Do not move this code without discussing it with me.
	 * The device state is invariant of any filtering performed below.
	 * Changing the device state after this point can and will cause
	 * a feedback loop resulting in oscillations, error amplification,
	 * unnecessary quantization, and other annoying effects. */

	/* save channel device state and device to which last event went */
	memmove(pChannel->valid.states + 1,
		pChannel->valid.states,
		sizeof(WacomDeviceState) * (common->wcmRawSample - 1));
	pChannel->valid.state = ds; /*save last raw sample */
	if (pChannel->nSamples < common->wcmRawSample) ++pChannel->nSamples;

	commonDispatchDevice(common,channel,pChannel, suppress);
	resetSampleCounter(pChannel);
}

static int idtotype(int id)
{
	int type = CURSOR_ID;

	/* tools with id, such as Intuos series and Cintiq 21UX */
	switch (id)
	{
		case 0x812: /* Inking pen */
		case 0x801: /* Intuos3 Inking pen */
		case 0x012: 
		case 0x822: /* Pen */
		case 0x842:
		case 0x852:
		case 0x823: /* Intuos3 Grip Pen */
		case 0x813: /* Intuos3 Classic Pen */
		case 0x885: /* Intuos3 Marker Pen */
		case 0x022: 
		case 0x832: /* Stroke pen */
		case 0x032: 
		case 0xd12: /* Airbrush */
		case 0x912:
		case 0x112: 
		case 0x913: /* Intuos3 Airbrush */
			type = STYLUS_ID;
			break;
		case 0x82a: /* Eraser */
		case 0x85a:
		case 0x91a:
		case 0xd1a:
		case 0x0fa: 
		case 0x82b: /* Intuos3 Grip Pen Eraser */
		case 0x81b: /* Intuos3 Classic Pen Eraser */
		case 0x91b: /* Intuos3 Airbrush Eraser */
			type = ERASER_ID;
			break;
	}
	return type;
}

static void commonDispatchDevice(WacomCommonPtr common, unsigned int channel,
	const WacomChannelPtr pChannel, int suppress)
{
	LocalDevicePtr pDev = NULL;
	WacomToolPtr tool = NULL;
	WacomToolPtr tooldef = NULL;
	WacomDeviceState* ds = &pChannel->valid.states[0];
	WacomDevicePtr priv = NULL;

	if (!ds->device_type && ds->proximity)
	{
		/* Tool may be on the tablet when X starts. 
		 * Figure out device type by device id
		 */
		switch (ds->device_id)
		{
			case STYLUS_DEVICE_ID:
				ds->device_type = STYLUS_ID;
				break;
			case ERASER_DEVICE_ID:
				ds->device_type = ERASER_ID;
				break;
			case CURSOR_DEVICE_ID:
				ds->device_type = CURSOR_ID;
				break;
			case TOUCH_DEVICE_ID:
				ds->device_type = TOUCH_ID;
				break;
			default:
				ds->device_type = idtotype(ds->device_id);
		}
		if (ds->serial_num)
			for (tool = common->wcmTool; tool; tool = tool->next)
				if (ds->serial_num == tool->serial)
				{
					ds->device_type = tool->typeid;
					break;
				}
	}

	DBG(10, common->debugLevel, ErrorF("commonDispatchDevice device type = %d\n", ds->device_type));
	/* Find the device the current events are meant for */
	/* 1: Find the tool (the one with correct serial or in second
	 * hand, the one with serial set to 0 if no match with the
	 * specified serial exists) that is used for this event */
	for (tool = common->wcmTool; tool; tool = tool->next)
	{
		if (tool->typeid == ds->device_type)
		{
			if (tool->serial == ds->serial_num)
				break;
			else if (!tool->serial)
				tooldef = tool;
		}
	}

	/* Use default tool (serial == 0) if no specific was found */
	if (!tool)
		tool = tooldef;

	/* 2: Find the associated area, and its InputDevice */
	if (tool)
	{
		/* if the current area is not in-prox anymore, we
		 * might want to use another area. So move the
		 * current-pointer away for a moment while we have a
		 * look if there's a better area defined.
		 * Skip this if only one area is defined 
		 */
		WacomToolAreaPtr outprox = NULL;
		if (tool->current && tool->arealist->next && 
			!WcmPointInArea(tool->current, ds->x, ds->y))
		{
			outprox = tool->current;
			tool->current = NULL;
		}

		/* If only one area is defined for the tool, always
		 * use this area even if we're not inside it
		 */
		if (!tool->current && !tool->arealist->next)
			tool->current = tool->arealist;

		/* If no current area in-prox, find a matching area */
		if(!tool->current)
		{
			WacomToolAreaPtr area = tool->arealist;
			for(; area; area = area->next)
				if (WcmPointInArea(area, ds->x, ds->y))
					break;
			tool->current = area;
		}

		/* If a better area was found, send a soft prox-out
		 * for the current in-prox area, else use the old one. */
		if (outprox)
		{
			if (tool->current)
			{
				/* Send soft prox-out for the old area */
				LocalDevicePtr oDev = outprox->device;
				WacomDeviceState out = { 0 };
				out.device_type = DEVICE_ID(((WacomDevicePtr)(oDev->private))->flags);
				DBG(2, common->debugLevel, ErrorF("Soft prox-out for %s\n",
					outprox->device->name));
				xf86WcmSendEvents(oDev, &out);
			}
			else
				tool->current = outprox;
		}

		/* If there was one already in use or we found one */
		if(tool->current)
		{
			pDev = tool->current->device;
			DBG(11, common->debugLevel, ErrorF("tool id=%d for %s\n",
				       ds->device_type, pDev->name));
		}
	}
	/* X: InputDevice selection done! */

	/* Tool on the tablet when driver starts. This sometime causes
	 * access errors to the device */
	if (pDev && !miPointerGetScreen(pDev->dev))
	{
		xf86Msg(X_ERROR, "xf86WcmEvent: Wacom driver can not get Current Screen ID\n");
		xf86Msg(X_ERROR, "Please remove Wacom tool from the tablet and bring it back again.\n");
		return;
	}

	/* if a device matched criteria, handle filtering per device
	 * settings, and send event to XInput */
	if (pDev)
	{
		WacomDeviceState filtered = pChannel->valid.state;

		/* Device transformations come first */
		/* button 1 Threshold test */
		int button = 1;
		priv = pDev->private;

		if (common->wcmDevCls == &gWacomUSBDevice && IsTouch(priv) && !ds->proximity)
		{
			priv->hardProx = 0;
		}		

		if (common->wcmDevCls == &gWacomUSBDevice && (IsStylus(priv) || IsEraser(priv)))
		{
			priv->hardProx = 1;
		}
		
		/* send a touch out for USB Tablet PCs */
		if (common->wcmDevCls == &gWacomUSBDevice && !IsTouch(priv) 
			&& common->wcmTouchDefault && !priv->oldProximity)
		{ 
			LocalDevicePtr localDevices = xf86FirstLocalDevice();
			WacomCommonPtr tempcommon = NULL;
			WacomDevicePtr temppriv = NULL;

			/* Lookup to see if associated touch was enabled */
			for (; localDevices != NULL; localDevices = localDevices->next)
			{
				if (strstr(localDevices->drv->driverName, "wacom"))
				{
					temppriv = (WacomDevicePtr) localDevices->private;
					tempcommon = temppriv->common;

					if ((tempcommon->tablet_id == common->tablet_id) && 
						IsTouch(temppriv) && temppriv->oldProximity)
					{
						/* Send soft prox-out for touch first */
						WacomDeviceState out = { 0 };
						out.device_type = DEVICE_ID(temppriv->flags);
						DBG(2, common->debugLevel, ErrorF(
							"Send soft prox-out for %s first\n",
							localDevices->name));
						xf86WcmSendEvents(localDevices, &out);
					}
				}
			}
		}

		if (IsStylus(priv) || IsEraser(priv))
		{
			/* set button1 (left click) on/off */
			if (filtered.pressure >= common->wcmThreshold)
				filtered.buttons |= button;
			else
			{
				/* threshold tolerance */
				int tol = common->wcmMaxZ / 250;
				if (strstr(common->wcmModel->name, "Intuos4"))
					tol = common->wcmMaxZ / 125;
				if (filtered.pressure < common->wcmThreshold - tol)
					filtered.buttons &= ~button;
			}
			/* transform pressure */
			transPressureCurve(priv,&filtered);
		}

		/* touch capacity is supported */
		if (IsTouch(priv) && (common->wcmCapacityDefault >= 0) && !priv->hardProx)
		{
			if (((double)(filtered.capacity * 5) / 
					(double)common->wcmMaxZ) > 
					(5 - common->wcmCapacity))
				filtered.buttons |= button;
		}
		else if (IsCursor(priv) && !priv->hardProx)
		{
			/* initial current max distance */
			if (strstr(common->wcmModel->name, "Intuos"))
				common->wcmMaxCursorDist = 256;
			else
				common->wcmMaxCursorDist = 0;
		}

		/* Store current hard prox for next use */
		if (!IsTouch(priv))
			priv->hardProx = ds->proximity;		

		/* User-requested filtering comes next */

		/* User-requested transformations come last */

		if ((!(priv->flags & ABSOLUTE_FLAG)) && (!IsPad(priv)))
		{
			/* To improve the accuracy of relative x/y,
			 * don't send motion event when there is no movement.
			 */
			double deltx = filtered.x - priv->oldX;
			double delty = filtered.y - priv->oldY;
			deltx *= priv->factorX;
			delty *= priv->factorY;
	
			if (ABS(deltx)<1 && ABS(delty)<1) 
			{
				/* don't move the cursor */
				if (suppress == 1) 
				{
					/* send other events, such as button/wheel */
					filtered.x = priv->oldX;
					filtered.y = priv->oldY;
				}
				else /* no other events to send */
				{
					DBG(10, common->debugLevel, ErrorF(
						"Ignore non-movement relative data \n"));
					return;
				}
			}
			else
			{
				int temp = deltx;
				deltx = (double)temp/(priv->factorX);
				temp = delty;
				delty = (double)temp/(priv->factorY);
				filtered.x = deltx + priv->oldX;
				filtered.y = delty + priv->oldY;
			}
		}

		/* force out-prox when distance is outside wcmCursorProxoutDist for pucks */
		if (IsCursor(priv))
		{
			/* force out-prox when distance is outside wcmCursorProxoutDist. */
			if (common->wcmProtocolLevel == 5)
			{
				if (common->wcmMaxCursorDist > filtered.distance)
					common->wcmMaxCursorDist = filtered.distance;
			}
			else
			{
				if (common->wcmMaxCursorDist < filtered.distance)
					common->wcmMaxCursorDist = filtered.distance;
			}
			DBG(10, common->debugLevel, ErrorF("Distance over"
				" the tablet: %d, ProxoutDist: %d current"
				" min/max %d hard prox: %d\n",
				filtered.distance, 
				common->wcmCursorProxoutDist, 
				common->wcmMaxCursorDist, 
				ds->proximity));

			if (priv->oldProximity)
			{
				if (abs(filtered.distance - common->wcmMaxCursorDist) 
						> common->wcmCursorProxoutDist)
					filtered.proximity = 0;
			}
			/* once it is out. Don't let it in until a hard in */
			/* or it gets inside wcmCursorProxoutDist */
			else
			{
				if (abs(filtered.distance - common->wcmMaxCursorDist) > 
						common->wcmCursorProxoutDist && ds->proximity)
					return;
				if (!ds->proximity)
					return;	
			}
		}
		xf86WcmSendEvents(pDev, &filtered);
		/* If out-prox, reset the current area pointer */
		if (!filtered.proximity)
			tool->current = NULL;
	}

	/* otherwise, if no device matched... */
	else
	{
		DBG(11, common->debugLevel, ErrorF("no device matches with"
				" id=%d, serial=%u\n",
				ds->device_type, ds->serial_num));
	}
}

/*****************************************************************************
 * xf86WcmInitTablet -- common initialization for all tablets
 ****************************************************************************/

int xf86WcmInitTablet(LocalDevicePtr local, const char* id, float version)
{
	WacomDevicePtr priv = (WacomDevicePtr)local->private;
	WacomCommonPtr common = priv->common;
	WacomModelPtr model = common->wcmModel;

	/* Initialize the tablet */
	model->Initialize(common,id,version);

	/* Get tablet resolution */
	if (model->GetResolution)
		model->GetResolution(local);

	/* Get tablet range */
	if (model->GetRanges && (model->GetRanges(local) != Success))
		return !Success;
	
	/* Default threshold value if not set */
	if (common->wcmThreshold <= 0)
	{
		/* Threshold for counting pressure as a button */
		if (strstr(common->wcmModel->name, "Intuos4"))
			common->wcmThreshold = common->wcmMaxZ * 3 / 25;
		else
			common->wcmThreshold = common->wcmMaxZ * 3 / 50;
		xf86Msg(X_PROBED, "%s: using pressure threshold of %d for button 1\n",
			local->name, common->wcmThreshold);
	}

	/* Reset tablet to known state */
	if (model->Reset && (model->Reset(local) != Success))
	{
		xf86Msg(X_ERROR, "Wacom xf86WcmWrite error : %s\n", strerror(errno));
		return !Success;
	}

	/* Enable tilt mode, if requested and available */
	if ((common->wcmFlags & TILT_REQUEST_FLAG) && model->EnableTilt)
	{
		if (model->EnableTilt(local) != Success)
			return !Success;
	}

	/* Enable hardware suppress, if requested and available */
	if (model->EnableSuppress)
	{
		if (model->EnableSuppress(local) != Success)
			return !Success;
	}

	/* output tablet state as probed */
	xf86Msg(X_PROBED, "%s: Wacom %s tablet speed=%d maxX=%d maxY=%d maxZ=%d "
			"resX=%d resY=%d  tilt=%s\n",
			local->name,
			model->name, common->wcmISDV4Speed, 
			common->wcmMaxX, common->wcmMaxY, common->wcmMaxZ,
			common->wcmResolX, common->wcmResolY,
			HANDLE_TILT(common) ? "enabled" : "disabled");
  
	/* start the tablet data */
	if (model->Start && (model->Start(local) != Success))
		return !Success;

	return Success;
}

/*****************************************************************************
** Transformations
*****************************************************************************/

static void transPressureCurve(WacomDevicePtr pDev, WacomDeviceStatePtr pState)
{
	if (pDev->pPressCurve)
	{
		int p = pState->pressure;

		/* clip */
		p = (p < 0) ? 0 : (p > pDev->common->wcmMaxZ) ?
			pDev->common->wcmMaxZ : p;

		/* rescale pressure to FILTER_PRESSURE_RES */
		p = (p * FILTER_PRESSURE_RES) / pDev->common->wcmMaxZ;

		/* apply pressure curve function */
		p = pDev->pPressCurve[p];

		/* scale back to wcmMaxZ */
		pState->pressure = (p * pDev->common->wcmMaxZ) /
			FILTER_PRESSURE_RES;
	}
}

/*****************************************************************************
 * xf86WcmInitialTVScreens
 ****************************************************************************/

static void xf86WcmInitialTVScreens(LocalDevicePtr local)
{
	WacomDevicePtr priv = (WacomDevicePtr)local->private;

	if (priv->twinview == TV_NONE)
		return;

	priv->numScreen = 2;

	if ((priv->twinview == TV_LEFT_RIGHT) || (priv->twinview == TV_RIGHT_LEFT))
	{
		/* it does not need the offset if always map to a specific screen */
		if (priv->screen_no == -1)
		{
			priv->tvoffsetX = 60;
			priv->tvoffsetY = 0;
		}

		/* default resolution */
		if(!priv->tvResolution[0])
		{
			priv->tvResolution[0] = screenInfo.screens[0]->width/2;
			priv->tvResolution[1] = screenInfo.screens[0]->height;
			priv->tvResolution[2] = priv->tvResolution[0];
			priv->tvResolution[3] = priv->tvResolution[1];
		}
	}
	else if ((priv->twinview == TV_ABOVE_BELOW) || (priv->twinview == TV_BELOW_ABOVE))
	{
		/* it does not need the offset if always map to a specific screen */
		if (priv->screen_no == -1)
		{
			priv->tvoffsetX = 0;
			priv->tvoffsetY = 60;
		}

		/* default resolution */
		if(!priv->tvResolution[0])
		{
			priv->tvResolution[0] = screenInfo.screens[0]->width;
			priv->tvResolution[1] = screenInfo.screens[0]->height/2;
			priv->tvResolution[2] = priv->tvResolution[0];
			priv->tvResolution[3] = priv->tvResolution[1];
		}
	}

	/* initial screen info */
	if (priv->twinview == TV_ABOVE_BELOW)
	{
		priv->screenTopX[0] = 0;
		priv->screenTopY[0] = 0;
		priv->screenBottomX[0] = priv->tvResolution[0];
		priv->screenBottomY[0] = priv->tvResolution[1];
		priv->screenTopX[1] = 0;
		priv->screenTopY[1] = priv->tvResolution[1];
		priv->screenBottomX[1] = priv->tvResolution[2];
		priv->screenBottomY[1] = priv->tvResolution[1] + priv->tvResolution[3];
	}
	if (priv->twinview == TV_LEFT_RIGHT)
	{
		priv->screenTopX[0] = 0;
		priv->screenTopY[0] = 0;
		priv->screenBottomX[0] = priv->tvResolution[0];
		priv->screenBottomY[0] = priv->tvResolution[1];
		priv->screenTopX[1] = priv->tvResolution[0];
		priv->screenTopY[1] = 0;
		priv->screenBottomX[1] = priv->tvResolution[0] + priv->tvResolution[2];
		priv->screenBottomY[1] = priv->tvResolution[3];
	}
	if (priv->twinview == TV_BELOW_ABOVE)
	{
		priv->screenTopX[0] = 0;
		priv->screenTopY[0] = priv->tvResolution[1];
		priv->screenBottomX[0] = priv->tvResolution[2];
		priv->screenBottomY[0] = priv->tvResolution[1] + priv->tvResolution[3];
		priv->screenTopX[1] = 0;
		priv->screenTopY[1] = 0;
		priv->screenBottomX[1] = priv->tvResolution[0];
		priv->screenBottomY[1] = priv->tvResolution[1];
	}
	if (priv->twinview == TV_RIGHT_LEFT)
	{
		priv->screenTopX[0] = priv->tvResolution[0];
		priv->screenTopY[0] = 0;
		priv->screenBottomX[0] = priv->tvResolution[0] + priv->tvResolution[2];
		priv->screenBottomY[0] = priv->tvResolution[3];
		priv->screenTopX[1] = 0;
		priv->screenTopY[1] = 0;
		priv->screenBottomX[1] = priv->tvResolution[0];
		priv->screenBottomY[1] = priv->tvResolution[1];
	}

	DBG(10, priv->debugLevel, ErrorF("xf86WcmInitialTVScreens for \"%s\" "
		"topX0=%d topY0=%d bottomX0=%d bottomY0=%d "
		"topX1=%d topY1=%d bottomX1=%d bottomY1=%d \n",
		local->name, priv->screenTopX[0], priv->screenTopY[0],
		priv->screenBottomX[0], priv->screenBottomY[0],
		priv->screenTopX[1], priv->screenTopY[1],
		priv->screenBottomX[1], priv->screenBottomY[1]));
}

/*****************************************************************************
 * xf86WcmInitialScreens
 ****************************************************************************/

void xf86WcmInitialScreens(LocalDevicePtr local)
{
	WacomDevicePtr priv = (WacomDevicePtr)local->private;
	int i;

	DBG(2, priv->debugLevel, ErrorF("xf86WcmInitialScreens for \"%s\" "
		"number of screen=%d \n", local->name, screenInfo.numScreens));
	priv->tvoffsetX = 0;
	priv->tvoffsetY = 0;
	if (priv->twinview != TV_NONE)
	{
		xf86WcmInitialTVScreens(local);
		return;
	}

	/* initial screen info */
	priv->numScreen = screenInfo.numScreens;
	priv->screenTopX[0] = 0;
	priv->screenTopY[0] = 0;
	priv->screenBottomX[0] = 0;
	priv->screenBottomY[0] = 0;
	for (i=0; i<screenInfo.numScreens; i++)
	{
		if (screenInfo.numScreens > 1)
		{
			priv->screenTopX[i] = dixScreenOrigins[i].x;
			priv->screenTopY[i] = dixScreenOrigins[i].y;
			priv->screenBottomX[i] = dixScreenOrigins[i].x;
			priv->screenBottomY[i] = dixScreenOrigins[i].y;

			DBG(10, priv->debugLevel, ErrorF("xf86WcmInitialScreens from dix for \"%s\" "
				"ScreenOrigins[%d].x=%d ScreenOrigins[%d].y=%d \n",
				local->name, i, priv->screenTopX[i], i, priv->screenTopY[i]));
		}

		priv->screenBottomX[i] += screenInfo.screens[i]->width;
		priv->screenBottomY[i] += screenInfo.screens[i]->height;

		DBG(10, priv->debugLevel, ErrorF("xf86WcmInitialScreens for \"%s\" "
			"topX[%d]=%d topY[%d]=%d bottomX[%d]=%d bottomY[%d]=%d \n",
			local->name, i, priv->screenTopX[i], i, priv->screenTopY[i],
			i, priv->screenBottomX[i], i, priv->screenBottomY[i]));
	}
}

/*****************************************************************************
 * rotateOneTool
 ****************************************************************************/

static void rotateOneTool(WacomDevicePtr priv)
{
	WacomCommonPtr common = priv->common;
	WacomToolAreaPtr area = priv->toolarea;
	int tmpTopX, tmpTopY, tmpBottomX, tmpBottomY, oldMaxX, oldMaxY;

	DBG(10, priv->debugLevel, ErrorF("rotateOneTool for \"%s\" \n", priv->local->name));

	if (!IsTouch(priv))
	{
		oldMaxX = common->wcmMaxX;
		oldMaxY = common->wcmMaxY;
	}
	else
	{
		oldMaxX = common->wcmMaxTouchX;
		oldMaxY = common->wcmMaxTouchY;
	}

	tmpTopX = priv->topX;
	tmpBottomX = priv->bottomX;
	tmpTopY = priv->topY;
	tmpBottomY = priv->bottomY;

	if (common->wcmRotate == ROTATE_CW || common->wcmRotate == ROTATE_CCW)
	{
		if (!IsTouch(priv))
		{
		    common->wcmMaxX = oldMaxY;
		    common->wcmMaxY = oldMaxX;
		}
		else
		{
		    common->wcmMaxTouchX = oldMaxY;
		    common->wcmMaxTouchY = oldMaxX;
		}
	}

	switch (common->wcmRotate) {
	      case ROTATE_CW:
		area->topX = priv->topX = tmpTopY;
		area->bottomX = priv->bottomX = tmpBottomY;
		area->topY = priv->topY = oldMaxX - tmpBottomX;
		area->bottomY = priv->bottomY =oldMaxX - tmpTopX;
		break;
	      case ROTATE_CCW:
		area->topX = priv->topX = oldMaxY - tmpBottomY;
		area->bottomX = priv->bottomX = oldMaxY - tmpTopY;
		area->topY = priv->topY = tmpTopX;
		area->bottomY = priv->bottomY = tmpBottomX;
		break;
	      case ROTATE_HALF:
		area->topX = priv->topX = oldMaxX - tmpBottomX;
		area->bottomX = priv->bottomX = oldMaxX - tmpTopX;
		area->topY = priv->topY= oldMaxY - tmpBottomY;
		area->bottomY = priv->bottomY = oldMaxY - tmpTopY;
		break;
	}
	xf86WcmMappingFactor(priv->local);
	xf86WcmInitialCoordinates(priv->local, 0);
	xf86WcmInitialCoordinates(priv->local, 1);

	if (tmpTopX != priv->topX)
		xf86ReplaceIntOption(priv->local->options, "TopX", priv->topX);
	if (tmpTopY != priv->topY)
		xf86ReplaceIntOption(priv->local->options, "TopY", priv->topY);
	if (tmpBottomX != priv->bottomX)
		xf86ReplaceIntOption(priv->local->options, "BottomX", priv->bottomX);
	if (tmpBottomY != priv->bottomY)
		xf86ReplaceIntOption(priv->local->options, "BottomY", priv->bottomY);
}

/*****************************************************************************
 * xf86WcmRotateTablet
 ****************************************************************************/

void xf86WcmRotateTablet(LocalDevicePtr local, int value)
{
	WacomDevicePtr priv = (WacomDevicePtr)local->private;
	WacomCommonPtr common = priv->common;
	WacomDevicePtr tmppriv;
	int oldRotation;
	int tmpTopX, tmpTopY, tmpBottomX, tmpBottomY, oldMaxX, oldMaxY;

	DBG(10, priv->debugLevel, ErrorF("xf86WcmRotateTablet for \"%s\" \n", local->name));

	if (common->wcmRotate == value) /* initialization */
	{
		rotateOneTool(priv);
	}
	else
	{
		oldRotation = common->wcmRotate;
		common->wcmRotate = value;

		/* rotate all devices at once! else they get misaligned */
		for (tmppriv = common->wcmDevices; tmppriv; tmppriv = tmppriv->next)
		{
		    if (!IsTouch(priv))
		    {
			oldMaxX = common->wcmMaxX;
			oldMaxY = common->wcmMaxY;
		    }
		    else
		    {
			oldMaxX = common->wcmMaxTouchX;
			oldMaxY = common->wcmMaxTouchY;
		    }

		    if (oldRotation == ROTATE_CW || oldRotation == ROTATE_CCW) 
		    {
			if (!IsTouch(priv))
			{
				common->wcmMaxX = oldMaxY;
				common->wcmMaxY = oldMaxX;
			}
			else
			{
				common->wcmMaxTouchX = oldMaxY;
				common->wcmMaxTouchY = oldMaxX;
			}
		    }

		    tmpTopX = tmppriv->topX;
		    tmpBottomX = tmppriv->bottomX;
		    tmpTopY = tmppriv->topY;
		    tmpBottomY = tmppriv->bottomY;

		    /* recover to the unrotated xy-rectangles */
		    switch (oldRotation) {
		      case ROTATE_CW:
			tmppriv->topX = oldMaxY - tmpBottomY;
			tmppriv->bottomX = oldMaxY - tmpTopY;
			tmppriv->topY = tmpTopX;
			tmppriv->bottomY = tmpBottomX;
			break;
		      case ROTATE_CCW:
			tmppriv->topX = tmpTopY;
			tmppriv->bottomX = tmpBottomY;
			tmppriv->topY = oldMaxX - tmpBottomX;
			tmppriv->bottomY = oldMaxX - tmpTopX;
			break;
		      case ROTATE_HALF:
			tmppriv->topX = oldMaxX - tmpBottomX;
			tmppriv->bottomX = oldMaxX - tmpTopX;
			tmppriv->topY = oldMaxY - tmpBottomY;
			tmppriv->bottomY = oldMaxY - tmpTopY;
			break;
		    }

		    /* and rotate them to the new value */
		    rotateOneTool(tmppriv);

		    switch(value) {
			case ROTATE_NONE:
			    xf86ReplaceStrOption(local->options, "Rotate", "NONE");
			break;
			case ROTATE_CW:
			    xf86ReplaceStrOption(local->options, "Rotate", "CW");
			break;
			case ROTATE_CCW:
			    xf86ReplaceStrOption(local->options, "Rotate", "CCW");
			break;
			case ROTATE_HALF:
			    xf86ReplaceStrOption(local->options, "Rotate", "HALF");
			break;
		    }
		}
	}
}

/* WcmPointInArea - check whether the point is within the area */

Bool WcmPointInArea(WacomToolAreaPtr area, int x, int y)
{
	if (area->topX <= x && x <= area->bottomX &&
	    area->topY <= y && y <= area->bottomY)
		return 1;
	return 0;
}

/* WcmAreasOverlap - check if two areas are overlapping */

static Bool WcmAreasOverlap(WacomToolAreaPtr area1, WacomToolAreaPtr area2)
{
	if (WcmPointInArea(area1, area2->topX, area2->topY) ||
	    WcmPointInArea(area1, area2->topX, area2->bottomY) ||
	    WcmPointInArea(area1, area2->bottomX, area2->topY) ||
	    WcmPointInArea(area1, area2->bottomX, area2->bottomY))
		return 1;
	if (WcmPointInArea(area2, area1->topX, area1->topY) ||
	    WcmPointInArea(area2, area1->topX, area1->bottomY) ||
	    WcmPointInArea(area2, area1->bottomX, area1->topY) ||
	    WcmPointInArea(area2, area1->bottomX, area1->bottomY))
	        return 1;
	return 0;
}

/* WcmAreaListOverlaps - check if the area overlaps any area in the list */
Bool WcmAreaListOverlap(WacomToolAreaPtr area, WacomToolAreaPtr list)
{
	for (; list; list=list->next)
		if (area != list && WcmAreasOverlap(list, area))
			return 1;
	return 0;
}


/* vim: set noexpandtab shiftwidth=8: */