summaryrefslogtreecommitdiff
path: root/src/evtouch2.c
blob: a345c88901c8d2b80da92082221367cdf9d37868 (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
/*
 * Copyright 2004 by Kenan Esau <kenan.esau@conan.de>, Baltmannsweiler, Germany.
 * Copyright © 2005-2009 by SuperSonic Imagine, SA
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the names of copyright holders not be
 * used in advertising or publicity pertaining to distribution of the
 * software without specific, written prior permission.  The copyright holders
 * make no representations about the suitability of this
 * software for any purpose.  It is provided "as is" without express or
 * implied warranty.
 *
 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
 * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Authors: 
 *          Kenan Esau <kenan.esau@conan.de>
 *          Nicolas Bruguier <nicolas.bruguier@supersonicimagine.fr>
 */

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

#include <string.h>
#include <errno.h>
#include <X11/extensions/XIproto.h>
#include <xf86.h>
#include <xf86_OSlib.h>
#include <xf86Xinput.h>

#define DBG(lvl, f) {if ((lvl) <= debug_level) f;}
#define MAX(a, b) (a > b ? a : b)
#define MIN(a, b) (a < b ? a : b)

/*****************************************************************************
 *        Local Headers
 ****************************************************************************/
#include <linux/input.h>
#include <exevents.h>
#include <xisb.h>
#include <randrstr.h>

#include "libconfig.h"
#include "libtouch.h"
#include "evtouch2.h"

#ifdef HAVE_PROPERTIES
#include <X11/Xatom.h>
#include <evtouch2-properties.h>
#include <xserver-properties.h>
#endif

/*****************************************************************************
 *        Defines
 ****************************************************************************/
#define EVTOUCH2_DEFAULT_DEBUG_LEVEL        0
#define EVTOUCH2_DEFAULT_TOUCH_BUTTON       0
#define EVTOUCH2_DEFAULT_EMULATE3           FALSE
#define EVTOUCH2_DEFAULT_EMULATE3_TIMEOUT   50
#define EVTOUCH2_DEFAULT_SWAP_X             FALSE
#define EVTOUCH2_DEFAULT_SWAP_Y             FALSE
#define EVTOUCH2_DEFAULT_SWAP_AXES          FALSE
#define EVTOUCH2_DEFAULT_ROTATION           EVTOUCH2_ROTATE_NONE
#define EVTOUCH2_DEFAULT_MINX               130
#define EVTOUCH2_DEFAULT_MAXX               3945
#define EVTOUCH2_DEFAULT_MINY               197
#define EVTOUCH2_DEFAULT_MAXY               3894

/*****************************************************************************
 *        Local Variables
 ****************************************************************************/
static InputInfoPtr
EVTouch2PreInit(InputDriverPtr drv, IDevPtr dev, int flags);
static void
EVTouch2PtrCtrl(DeviceIntPtr device, PtrCtrl *ctrl);
static Bool
EVTouch2ConvertProc ( LocalDevicePtr local,
                     int first,
                     int num,
                     int v0,
                     int v1,
                     int v2,
                     int v3,
                     int v4,
                     int v5,
                     int *x,
                     int *y );

#ifdef HAVE_PROPERTIES
static void EVTouch2InitProperty(DeviceIntPtr dev);
static int EVTouch2SetProperty(DeviceIntPtr dev, Atom atom,
                               XIPropertyValuePtr val, BOOL checkonly);
static Atom prop_screen_num = 0;
static Atom prop_debug_level = 0;
static Atom prop_touch_button = 0;
static Atom prop_emulate3 = 0;
static Atom prop_emulate3_timeout = 0;
static Atom prop_invert_axes = 0;
static Atom prop_swap_axes = 0;
static Atom prop_rotation = 0;
static Atom prop_pan_viewport = 0;
static Atom prop_calibration = 0;
static Atom prop_calibration_axes = 0;
static Atom prop_calibration_axes_diff = 0;
#endif

static int debug_level = 0;

InputDriverRec EVTOUCH2 = {
        1,
        "evtouch2",
        NULL,
        EVTouch2PreInit,
        NULL,
        NULL,
        0
};

static XF86ModuleVersionInfo EvTouch2VersionRec =
{
    "evtouch2",
    "Nicolas Bruguier",
    MODINFOSTRING1,
    MODINFOSTRING2,
    XORG_VERSION_CURRENT,
    PACKAGE_VERSION_MAJOR, 
    PACKAGE_VERSION_MINOR, 
    PACKAGE_VERSION_PATCHLEVEL,
    ABI_CLASS_XINPUT,
    ABI_XINPUT_VERSION,
    MOD_CLASS_XINPUT,
    {0, 0, 0, 0}
};


static pointer
EvTouch2Plug (pointer module,
      pointer options,
      int *errmaj,
      int *errmin )
{
    DBGOUT(1, "EVTouch2: Plug\n");
    xf86AddInputDriver(&EVTOUCH2, module, 0);
    return module;
}


static void
EvTouch2Unplug (pointer p)
{
    DBGOUT(1, "EVTouch2: Unplug\n");
}

_X_EXPORT XF86ModuleData evtouch2ModuleData =
{
    &EvTouch2VersionRec,
    EvTouch2Plug,
    EvTouch2Unplug
};

static const char *default_options[] =
{
        "BaudRate", "9600",
        "StopBits", "1",
        "DataBits", "8",
        "Parity", "None",
        "Vmin", "5",
        "Vtime", "1",
        "FlowControl", "None"
};

/*****************************************************************************
 *        Function Definitions
 ****************************************************************************/
static CARD32
EVTouch2Emulate3Timer(OsTimerPtr timer, CARD32 now, pointer _local)
{
    int sigstate;
    LocalDevicePtr local = (LocalDevicePtr)_local;
    EVTouch2PrivatePtr priv = (EVTouch2PrivatePtr) local->private;

    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);

    sigstate = xf86BlockSIGIO();

    xf86PostMotionEvent(local->dev, TRUE, 0, 2, priv->cur_x, priv->cur_y);

    /* 
     * Emit a button press -- release is handled in EVTouch2LBRBEvent
     */
    if ( ( priv->touch_flags & LB_STAT ) &&
         !( priv->touch_flags & RB_STAT ) ) 
    {
        DBGOUT(2, "EVTouch2: Left Press\n");
        xf86PostButtonEvent (local->dev, TRUE,
                             1, 1, 0, 2, 
                             priv->cur_x, 
                             priv->cur_y);
    }

    if ( ( priv->touch_flags & RB_STAT ) &&
         !( priv->touch_flags & LB_STAT ) ) 
    {
        DBGOUT(2, "EVTouch2: Right Press\n");
        xf86PostButtonEvent (local->dev, TRUE,
                             3, 1, 0, 2, 
                             priv->cur_x, 
                             priv->cur_y);
    }

    /*
      Handling "middle" button press
    */
    if ( ( priv->touch_flags & RB_STAT ) &&
         ( priv->touch_flags & LB_STAT ) ) 
    {
        DBGOUT(2, "EVTouch2: Middle Press\n");
        xf86PostButtonEvent (local->dev, TRUE,
                             2, 1, 0, 2, 
                             priv->cur_x, 
                             priv->cur_y);
    }

    priv->emulate3.timer_expired = TRUE;
    xf86UnblockSIGIO(sigstate);
       
    return 0;
}

static void 
EVTouch2DoBtnAction(EVTouch2PrivatePtr priv) 
{
    int btn = 0;
    LocalDevicePtr local = priv->local;

    DBGOUT(2, "EVTouch2: %s btn_count=%d\n", __FUNCTION__, priv->btn_count);

    for (btn = 0; btn < priv->btn_count; btn++) 
    {
        DBGOUT(9, "EVTouch2: %s do_it = %d \n", 
               __FUNCTION__, priv->btn_actions[btn].do_it);
        if (priv->btn_actions[btn].do_it != 0) 
        {
            if (priv->emulate3.timer != NULL)
            {
                TimerFree(priv->emulate3.timer);
                priv->emulate3.timer=NULL;
                priv->emulate3.timer_expired = FALSE;
            }

            DBGOUT(2, "EVTouch2: %s btn = %d action = %d\n", 
                   __FUNCTION__, btn, 
                   priv->btn_actions[btn].action);

            xf86PostButtonEvent (local->dev, TRUE, btn, 
                                 priv->btn_actions[btn].action, 
                                 0, 2,
                                 priv->cur_x,
                                 priv->cur_y);

            priv->btn_actions[btn].do_it  = 0;
            priv->btn_actions[btn].action = 0;
        }
    }
}

static void 
EVTouch2SetBtnAction(EVTouch2PrivatePtr priv, int btn, int action)
{
    DBGOUT(2, "EVTouch2: %s btn = %d action = %d\n", __FUNCTION__,
           btn, action);
    if (btn < priv->btn_count) 
    {
        priv->btn_actions[btn].do_it  = 1;
        priv->btn_actions[btn].action = action;
    }
}

static void 
EVTouch2ProcessAbs(EVTouch2PrivatePtr priv)
{
    struct input_event *ev; /* packet being/just read */
    int pos_changed = 0;

    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);

    ev = &priv->ev;

    if ( (ev->code == ABS_X) || (ev->code == ABS_Z) ) 
    {
        priv->raw_x = ev->value;
        pos_changed = 1;
    }

    if ( (ev->code == ABS_Y) || (ev->code == ABS_RX) ) 
    {
        priv->raw_y = ev->value;
        pos_changed = 1;
	}

    if (pos_changed == 1) 
    {
#if GET_ABI_MAJOR(ABI_XINPUT_VERSION) >= 2
        EVTouch2ConvertProc(priv->local, 0, 2, 
                            priv->raw_x, priv->raw_y,
                            0, 0, 0, 0, 
                            &priv->cur_x, &priv->cur_y);
#endif

        libtouchSetPos(priv->libtouch, priv->cur_x, priv->cur_y);
        return;
    }

    if (ev->code == ABS_WHEEL) 
    {
	    LocalDevicePtr local = priv->local;

	    if (ev->value > 0) 
            {
	        for (; ev->value > 0; ev->value--) 
                {
		    xf86PostButtonEvent (local->dev, TRUE,
				         4, 1, 0, 2, 
				         priv->cur_x, 
				         priv->cur_y);
		    xf86PostButtonEvent (local->dev, TRUE,
				         4, 0, 0, 2, 
				         priv->cur_x, 
				         priv->cur_y);
	        }
	    } 
        else if (ev->value < 0) 
        {
	        for (ev->value = -ev->value; ev->value > 0; ev->value--) 
            {
		        xf86PostButtonEvent (local->dev, TRUE,
				             5, 1, 0, 2, 
				             priv->cur_x, 
				             priv->cur_y);
		        xf86PostButtonEvent (local->dev, TRUE,
				             5, 0, 0, 2, 
				             priv->cur_x, 
				             priv->cur_y);
	        }
	    }			
    }
}

static void 
EVTouch2ProcessRel(EVTouch2PrivatePtr priv)
{
    struct input_event *ev; /* packet being/just read */
    
    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);

    ev = &priv->ev;
    if ( ev->code == REL_X ) 
    {
        priv->raw_x += ev->value;
        if (priv->raw_x > priv->calibration.max_x)
            priv->raw_x = priv->calibration.max_x;
        if (priv->raw_x < priv->calibration.min_x)
            priv->raw_x = priv->calibration.min_x;
    } 
    if ( ev->code == REL_Y ) 
    {
        priv->raw_y += ev->value;
        if (priv->raw_y > priv->calibration.max_y)
            priv->raw_y = priv->calibration.max_y;
        if (priv->raw_y < priv->calibration.min_y)
            priv->raw_y = priv->calibration.min_y;
    }

#if GET_ABI_MAJOR(ABI_XINPUT_VERSION) >= 2
    EVTouch2ConvertProc(priv->local, 0, 2,
                        priv->raw_x, priv->raw_y,
                        0, 0, 0, 0,
                        &priv->cur_x, &priv->cur_y);
#endif

    libtouchSetPos(priv->libtouch, priv->cur_x, priv->cur_y);
}

static void 
EVTouch2LBRBEvent(EVTouch2PrivatePtr priv)
{
    struct input_event *ev; /* packet being/just read */
    LocalDevicePtr local = priv->local;

    ev = &priv->ev;
    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);

    if (priv->emulate3.enabled) 
    {
        if ((ev->value==1) && (priv->emulate3.timer==NULL))
            priv->emulate3.timer = TimerSet(priv->emulate3.timer, 
                                            0,
                                            priv->emulate3.timeout,
                                            EVTouch2Emulate3Timer,
                                            local);

        if ((ev->value == 1) && 
            (priv->touch_button > 0 && (ev->code == BTN_TOUCH)))
        {
            if (priv->touch_button == 1)
                priv->touch_flags |= LB_STAT;
            else if (priv->touch_button == 2)
                priv->touch_flags |= RB_STAT;
        }
        if ((ev->value == 1) && (ev->code == BTN_LEFT)) 
        {
            priv->touch_flags |= LB_STAT;
        }
        if ((ev->value == 1) && (ev->code == BTN_RIGHT)) 
        {
            priv->touch_flags |= RB_STAT;
        }

        if ((ev->value == 0) && 
            (priv->touch_flags & RB_STAT) && 
            (priv->touch_flags & LB_STAT)) 
        {
            DBGOUT(2, "EVTouch2: Middle Release\n");
            priv->touch_flags &= ~LB_STAT;
            priv->touch_flags &= ~RB_STAT;
            EVTouch2SetBtnAction(priv, 2, BTN_RELEASE);
        } 
        else if ((ev->value == 0) && 
                 (priv->touch_button > 0 && (ev->code == BTN_TOUCH)) &&
                 (priv->touch_flags & LB_STAT))
        {
            DBGOUT(2, "EVTouch2: Touch Release\n");
            if (priv->touch_button == 1)
                priv->touch_flags &= ~LB_STAT;
            else if (priv->touch_button == 2)
                priv->touch_flags &= ~RB_STAT;
            EVTouch2SetBtnAction(priv, priv->touch_button, BTN_RELEASE);
        }
        else if ((ev->value == 0) && (ev->code == BTN_LEFT) &&
                 (priv->touch_flags & LB_STAT)) 
        {
            DBGOUT(2, "EVTouch2: Left Release\n");
            priv->touch_flags &= ~LB_STAT;
            EVTouch2SetBtnAction(priv, 1, BTN_RELEASE);
        } 
        else if ((ev->value == 0) && (ev->code == BTN_RIGHT) &&
                 (priv->touch_flags & RB_STAT)) 
        {
            DBGOUT(2, "EVTouch2: Right Release\n");
            priv->touch_flags &= ~RB_STAT;
            EVTouch2SetBtnAction(priv, 3, BTN_RELEASE);
        }                                
    } 
    else 
    {
        if (priv->touch_button > 0 && (ev->code == BTN_TOUCH))
        {
            EVTouch2SetBtnAction(priv, priv->touch_button, ev->value);
        }

        if (ev->code == BTN_LEFT) 
        {
            EVTouch2SetBtnAction(priv, 1, ev->value);
        }

        if (ev->code == BTN_MIDDLE) 
        {
            EVTouch2SetBtnAction(priv, 2, ev->value);
        }

        if (ev->code == BTN_RIGHT) 
        {
            EVTouch2SetBtnAction(priv, 3, ev->value);
        }
    }
}

static void 
EVTouch2ProcessKey(EVTouch2PrivatePtr priv)
{
    struct input_event *ev; /* packet being/just read */

    ev = &priv->ev;
    DBGOUT(2, "EVTouch2: %s code = 0x%x\n", __FUNCTION__, ev->code);
    if ((ev->code == BTN_LEFT) || 
        (ev->code == BTN_RIGHT) ||
        (ev->code == BTN_MIDDLE) ||
        (priv->touch_button > 0 && (ev->code == BTN_TOUCH))) 
    {
        /* give lb and rb-events some special treatment 
           (emulate3 or not, ...) */
        EVTouch2LBRBEvent(priv);
        return;
    }

    return;
}

static Bool
EVTouch2QueryHardware (LocalDevicePtr local)
{
    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);

    return Success;
}

static Bool
EVTouch2DeviceOn (DeviceIntPtr dev)
{
    LocalDevicePtr local = (LocalDevicePtr) dev->public.devicePrivate;
    EVTouch2PrivatePtr priv = (EVTouch2PrivatePtr) (local->private);
    
    local->fd = xf86OpenSerial(local->options);

    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__ );

    if (local->fd == -1)
    {
        xf86Msg(X_WARNING, "%s: cannot open input device\n", local->name);
        return (!Success);
    }

    priv->buffer = XisbNew(local->fd, 64);

    DBG (9, XisbTrace (priv->buffer, 1));

    if (!priv->buffer) 
    {
        xf86CloseSerial(local->fd);
        local->fd = -1;
        return (!Success);
    }

    if (EVTouch2QueryHardware(local) != Success)
    {
        ErrorF ("Unable to query/initialize EVTouch hardware.\n");
            return (!Success);
    }

    xf86FlushInput(local->fd);

    if (ioctl(local->fd, EVIOCGRAB, (void *)1))
        xf86Msg(X_ERROR, "%s: Unable to grab device (%s).\n", 
                local->name, strerror(errno));


    xf86AddEnabledDevice(local);

    dev->public.on = TRUE;

    return (Success);
}

static Bool
EVTouch2DeviceOff (DeviceIntPtr dev)
{
    LocalDevicePtr local = (LocalDevicePtr) dev->public.devicePrivate;
    EVTouch2PrivatePtr priv = (EVTouch2PrivatePtr) (local->private);

    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__ );

    if (local->fd != -1)
    { 
        ioctl(local->fd, EVIOCGRAB, (void *)0);
        xf86RemoveEnabledDevice (local);
        if (priv->buffer)
        {
            XisbFree(priv->buffer);
            priv->buffer = NULL;
        }
        xf86CloseSerial(local->fd);
        local->fd = -1;
    }

    dev->public.on = FALSE;

    return (Success);
}

static Bool
EVTouch2DeviceInit (DeviceIntPtr dev)
{
    ScrnInfoPtr pScrn;
    LocalDevicePtr local = (LocalDevicePtr) dev->public.devicePrivate;
    EVTouch2PrivatePtr priv = (EVTouch2PrivatePtr) (local->private);
    unsigned char map[EVTOUCH2_MAX_BUTTONS];
    int i;

    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);

    for (i = 0; i < EVTOUCH2_MAX_BUTTONS; i++)
        map[i] = i;

    priv->btn_count = EVTOUCH2_MAX_BUTTONS;

    /* 
     * these have to be here instead of in the SetupProc, because when the
     * SetupProc is run at server startup, screenInfo is not setup yet
     */

    pScrn = xf86Screens[priv->screen.num];
    priv->screen.width  = pScrn->virtualX;     /* It's the virtual screen size ! */
    priv->screen.height = pScrn->virtualY;
    
    DBGOUT(2, "EVTouch2: Phys W,H: %d %d\n", 
           priv->phys_width, priv->phys_height);
    DBGOUT(2, "EVTouch2: Screen W,H: %d %d\n", 
           priv->screen.width, priv->screen.height);
    DBGOUT(2, "EVTouch2: MaxValue H,V: %d %d\n", 
           pScrn->maxHValue, pScrn->maxVValue);

    priv->screen.width = screenInfo.screens[priv->screen.num]->width;
    priv->screen.height = screenInfo.screens[priv->screen.num]->height;        

    /* 
     * Device reports button press for 5 buttons.
     */
    if (InitButtonClassDeviceStruct (dev, EVTOUCH2_MAX_BUTTONS, map) == FALSE)
    {
        ErrorF("Unable to allocate EVTouch touchscreen ButtonClassDeviceStruct\n");
        return BadAlloc;
    } 

    DBGOUT(2, "EVTouch2: %s btn_count=%d\n", __FUNCTION__, priv->btn_count);
    priv->btn_actions = xcalloc(priv->btn_count, sizeof(BtnAction));
    memset(priv->btn_actions, 0, priv->btn_count * sizeof(BtnAction));
    
    if (InitFocusClassDeviceStruct(dev) == FALSE) 
    {
        ErrorF("Unable to allocate EVTouch touchscreen FocusClassDeviceStruct\n");
        return !Success;
    }

    /* 
     * Device reports motions on 2 axes in absolute coordinates.
     * Axes min and max values are reported in raw coordinates.
     */
    if (InitValuatorClassDeviceStruct(dev, 2,
                                      local->history_size, Absolute) == FALSE)
    {
        ErrorF ("Unable to allocate EVTouch touchscreen ValuatorClassDeviceStruct\n");
        return !Success;
    }

    xf86InitValuatorAxisStruct(dev, 0, 0, priv->screen.width,
                               1024,
                               EVTOUCH2_AXIS_MIN_RES /* min_res */ ,
                               EVTOUCH2_AXIS_MAX_RES /* max_res */ );
    xf86InitValuatorDefaults(dev, 0);
    xf86InitValuatorAxisStruct(dev, 1, 0, priv->screen.height,
                               1024,
                               EVTOUCH2_AXIS_MIN_RES /* min_res */ ,
                               EVTOUCH2_AXIS_MAX_RES /* max_res */ );
    xf86InitValuatorDefaults(dev, 1);

    /* Initial position of pointer on screen: Centered */
    priv->cur_x = (priv->calibration.max_x - priv->calibration.min_x)/2;
    priv->cur_y = (priv->calibration.max_y - priv->calibration.min_y)/2;
    priv->raw_x = priv->cur_x;
    priv->raw_y = priv->cur_y;
    libtouchSetPos(priv->libtouch, priv->cur_x, priv->cur_y);
    
    if (InitProximityClassDeviceStruct (dev) == FALSE)
    {
        ErrorF ("Unable to allocate EVTouch touchscreen ProximityClassDeviceStruct\n");
        return !Success;
    }

    if (InitPtrFeedbackClassDeviceStruct(dev, EVTouch2PtrCtrl) == FALSE)
    {
        ErrorF ("unable to allocate EVTouch touchscreen PtrFeedbackClassDeviceStruct\n");
        return !Success;
    }

    /* 
     * Allocate the motion events buffer.
     */
    xf86MotionHistoryAllocate (local);

#ifdef HAVE_PROPERTIES
    EVTouch2InitProperty(dev);
    libtouchInitProperty(priv->libtouch, dev);
    XIRegisterPropertyHandler(dev, EVTouch2SetProperty, NULL, NULL);
#endif

    return (Success);
}

static Bool
EVTouch2DeviceControl (DeviceIntPtr dev,
                       int mode)
{
    Bool RetValue;

    switch (mode)
    {
        case DEVICE_INIT:
            RetValue = EVTouch2DeviceInit(dev);
            break;
        case DEVICE_ON:
            RetValue = EVTouch2DeviceOn(dev);
            break;
        case DEVICE_OFF:
        case DEVICE_CLOSE:
            RetValue = EVTouch2DeviceOff(dev);
            break;
        default:
            RetValue = BadValue;
    }

    return( RetValue );
}

static void
EVTouch2NewPacket (EVTouch2PrivatePtr priv)
{
    memset(&priv->ev, 0, sizeof(struct input_event));
}

static Bool
EVTouch2GetPacket (EVTouch2PrivatePtr priv)
{
    static int count = 0;
    int c;
	CARD32 now;

    if (count == 0) EVTouch2NewPacket(priv);

    while ((c = XisbRead(priv->buffer)) >= 0) 
    {
        if (count == 0) 
        {
            now = GetTimeInMillis();
            libtouchSetTime(priv->libtouch, now);
        }

        ((char *)&priv->ev)[count] = c;
        count ++;

        if (sizeof(priv->ev) == count) 
        {
            count = 0;
            EVTouch2DumpPacketToLog(priv);
            
            return Success;
        }
    }
    return (!Success);
}

static void 
EVTouch2ReadInput (LocalDevicePtr local)
{
    struct input_event *ev; /* packet being/just read */

    EVTouch2PrivatePtr priv = (EVTouch2PrivatePtr) (local->private);

    /* 
     * set blocking to -1 on the first call because we know there is data to
     * read. Xisb automatically clears it after one successful read so that
     * succeeding reads are preceeded buy a select with a 0 timeout to prevent
     * read from blocking infinately.
     */
    XisbBlockDuration (priv->buffer, -1);
    while (EVTouch2GetPacket (priv) == Success)
    {
        ev = &priv->ev;
        DBGOUT(2, "EVTouch2: %s type:%x code: 0x%x value:%d\n",
                   __FUNCTION__, ev->type, ev->code, ev->value);

        xf86XInputSetScreen(local, 
                            priv->screen.num, 
                            priv->cur_x, 
                            priv->cur_y);

        xf86PostProximityEvent(local->dev, 1, 0, 2,
                               priv->cur_x,
                               priv->cur_y);

        switch (ev->type) 
        {
            case EV_ABS:
                EVTouch2ProcessAbs(priv);
                break;
            case EV_REL:
                EVTouch2ProcessRel(priv);
                break;
            case EV_KEY:
                xf86PostMotionEvent (local->dev, TRUE, 0, 2, 
                                     priv->cur_x,
                                     priv->cur_y);

                if (priv->ev.code == BTN_TOUCH) 
                {
                    if (priv->ev.value == 1) 
                    {
                        priv->touch_flags |= TOUCHED;
                        DBGOUT(2, "EVTouch2: TOUCHED\n");
                    }
                    else 
                    {
                        priv->touch_flags &= ~TOUCHED;
                        DBGOUT(2, "EVTouch2: UNTOUCHED\n");
                    }
                }
                EVTouch2ProcessKey(priv);
                break;
            case EV_SYN:
                xf86PostMotionEvent (local->dev, TRUE, 0, 2, 
                                     priv->cur_x,
                                     priv->cur_y);

                if ( priv->touch_flags & TOUCHED )
                    libtouchTriggerSM(priv->libtouch, PEN_TOUCHED);
                else
                    libtouchTriggerSM(priv->libtouch, PEN_UNTOUCHED);
                
                EVTouch2DoBtnAction(priv);
                break;
        }

        DBGOUT( 2, "EVTouch2: setting (x/y)=(%d/%d)\n", 
                priv->cur_x, priv->cur_y);
    }
}

static Bool
EVTouch2ConvertProc ( LocalDevicePtr local,
                     int first,
                     int num,
                     int v0,
                     int v1,
                     int v2,
                     int v3,
                     int v4,
                     int v5,
                     int *x,
                     int *y )
{
    /*
      correction factors depending on current position of pointer
    */
    float cx[3];
    float cy[3];
    float dx = 0, dy = 0;

    int max_x, max_y;
    int xc, yc;
    int screen_width  = 0;
    int screen_height = 0;
    int tmp = 0;
#ifdef EVDBG
    int i = 0;
#endif

    EVTouch2PrivatePtr priv = (EVTouch2PrivatePtr) (local->private);  
	ScrnInfoPtr pScrn = xf86Screens[priv->screen.num];
	Rotation rotation = RRGetRotation(pScrn->pScreen);

    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);
    DBGOUT(2, "EVTouch2: FIRST: v0=%d v1=%d\n", v0, v1);

	/* write raw coordinates to fifo for calibration programm */
    if ((priv->calibration.fifo > 0) && (priv->calibration.enabled))
    {
        int r;
        
        DBGOUT(2, "EVTouch2: writing to FIFO\n");
        r = write (priv->calibration.fifo, &v0, sizeof(v0));
        r = write (priv->calibration.fifo, &v1, sizeof(v1));
    }

    /* correction of raw coordinates */
    if (priv->swap_axes)
    {
        tmp = v0;
        v0 = v1;
        v1 = tmp;
    }
            
    DBGOUT(2, "EVTouch2: Scaling coordinates\n");
    xc = v0 - priv->calibration.min_x;
    yc = v1 - priv->calibration.min_y;

    max_x = priv->calibration.max_x - priv->calibration.min_x;
    max_y = priv->calibration.max_y - priv->calibration.min_y;

    if (priv->rotate == EVTOUCH2_ROTATE_NONE) 
    {
        if (priv->pan_viewport.enabled) 
        {
            screen_width  = priv->pan_viewport.width;
            screen_height = priv->pan_viewport.height;
        }
        else 
        {
            screen_width  = pScrn->currentMode->HDisplay;
            screen_height = pScrn->currentMode->VDisplay;
        }
    } 
    else 
    {
        if (priv->pan_viewport.enabled) 
        {
            screen_width  = priv->pan_viewport.height;
            screen_height = priv->pan_viewport.width;
        }
        else 
        {
            screen_width  = pScrn->currentMode->VDisplay;
            screen_height = pScrn->currentMode->HDisplay;
        }
    }

    if ( rotation == RR_Rotate_90 || rotation == RR_Rotate_270 ) 
    {
        int tmp = screen_width; screen_width = screen_height;
        screen_height = tmp;
    }

    if (xc < (max_x / 2)) 
    {
        /*
          left
        */
        if (yc>(max_y / 2)) 
        {
            /*
              upper
            */
            cx[1] = ((float) xc / (max_x / 2) );
            cx[0] = (float) 1 - cx[1];
            cy[0] = ((float) (yc-(max_y/2)) / (max_y/2) );
            cy[1] = (float) 1 - cy[0];

            dx = ((float) (cx[1] * cy[0] * priv->calibration.diff[1][0]) +
                  (float)(cx[0] * cy[0] * priv->calibration.diff[0][0]) +
                  (float)(cx[1] * cy[1] * priv->calibration.diff[4][0]) +
                  (float)(cx[0] * cy[1] * priv->calibration.diff[3][0]));
            
            dy = ((float) (cx[1] * cy[0] * priv->calibration.diff[1][1]) +
                  (float)(cx[0] * cy[0] * priv->calibration.diff[0][1]) +
                  (float)(cx[1] * cy[1] * priv->calibration.diff[4][1]) +
                  (float)(cx[0] * cy[1] * priv->calibration.diff[3][1]));
        }
        else 
        {
            /*
              lower
            */
            cx[1] = ((float) xc / (max_x/2) );
            cx[0] = (float) 1 - cx[1];
            cy[0] = ((float) yc / (max_y/2) );
            cy[1] = (float) 1 - cy[0];

            dx = ((float) (cx[1] * cy[0] * priv->calibration.diff[4][0]) +
                  (float)(cx[0] * cy[0] * priv->calibration.diff[3][0]) +
                  (float)(cx[1] * cy[1] * priv->calibration.diff[7][0]) +
                  (float)(cx[0] * cy[1] * priv->calibration.diff[6][0]));
            
            dy = ((float) (cx[1] * cy[0] * priv->calibration.diff[4][1]) +
                  (float)(cx[0] * cy[0] * priv->calibration.diff[3][1]) +
                  (float)(cx[1] * cy[1] * priv->calibration.diff[7][1]) +
                  (float)(cx[0] * cy[1] * priv->calibration.diff[6][1]));
        }
    } 
    else 
    {
        /*
          right
        */
        if (yc>(max_y/2)) 
        {
            /*
              upper
            */
            cx[1] = ((float) (xc-(max_x/2)) / (max_x/2) );
            cx[0] = (float)1 - cx[1];
            cy[0] = ((float) (yc-(max_y/2)) / (max_y/2) );
            cy[1] = (float)1 - cy[0];

            dx = ((float) (cx[1] * cy[0] * priv->calibration.diff[2][0]) +
                  (float)(cx[0] * cy[0] * priv->calibration.diff[1][0]) +
                  (float)(cx[1] * cy[1] * priv->calibration.diff[5][0]) +
                  (float)(cx[0] * cy[1] * priv->calibration.diff[4][0]));
                    
            dy = ((float) (cx[1] * cy[0] * priv->calibration.diff[2][1]) +
                  (float)(cx[0] * cy[0] * priv->calibration.diff[1][1]) +
                  (float)(cx[1] * cy[1] * priv->calibration.diff[5][1]) +
                  (float)(cx[0] * cy[1] * priv->calibration.diff[4][1]));
        } 
        else 
        {
            /*
              lower
            */
            cx[1] = ((float) (xc-(max_x/2)) / (max_x/2) );
            cx[0] = (float) 1 - cx[1];
            cy[0] = ((float) yc / (max_y/2) );
            cy[1] = (float) 1 - cy[0];

            dx = ((float) (cx[1] * cy[0] * priv->calibration.diff[5][0]) +
                  (float)(cx[0] * cy[0] * priv->calibration.diff[4][0]) +
                  (float)(cx[1] * cy[1] * priv->calibration.diff[8][0]) +
                  (float)(cx[0] * cy[1] * priv->calibration.diff[7][0]));
            
            dy = ((float) (cx[1] * cy[0] * priv->calibration.diff[5][1]) +
                  (float)(cx[0] * cy[0] * priv->calibration.diff[4][1]) +
                  (float)(cx[1] * cy[1] * priv->calibration.diff[8][1]) +
                  (float)(cx[0] * cy[1] * priv->calibration.diff[7][1]));
        }
    }

#ifdef EVDBG
    for (i=0; i<3; i++) 
        xf86ErrorFVerb(2, "cx[%d]=%f   cy[%d]=%f\n", i, cx[i]
                       ,i, cy[i]);
        
    DBGOUT(2, "EVTouch2: dx=%f   dy=%f\n", dx, dy);
    if (priv->pan_viewport.enabled) 
    {
        DBGOUT(2, "EVTouch2: Pan Viewport Position (x/y) (%d/%d)\n",
               priv->pan_viewport.x, priv->pan_viewport.y);
        DBGOUT(2, "EVTouch2: Pan Viewport Geometry (w x h) (%d x %d)\n",
               priv->pan_viewport.width, priv->pan_viewport.height);
    }
#endif

    xc = ( ((float)xc / max_x) * screen_width ) + dx;
    yc = ( ((float)yc / max_y) * screen_height) + dy;

    if (priv->swap_y == TRUE)
        yc = screen_height - yc;

    xc += priv->pan_viewport.x;
    yc += priv->pan_viewport.y;
    
    /* ususally we DON'T swap x -- but if swap_x is 1 
       => go on and swap */
    if (priv->swap_x == TRUE)
        xc = screen_width - xc;

    /* rotation mixes x and y up a bit */
    if (priv->rotate == EVTOUCH2_ROTATE_CW) 
    {
        tmp = xc;
        xc = yc;
        yc = screen_width - tmp;
    } 
    else if (priv->rotate == EVTOUCH2_ROTATE_CCW) 
    {
        tmp = xc;
        xc = screen_height - yc;
        yc = tmp;
    } 
    else if (priv->rotate == EVTOUCH2_ROTATE_UD) 
    {
        xc = screen_width - xc;
        yc = screen_height - yc;
    }

    switch (rotation) 
    {
        case RR_Rotate_0:
            v0 = xc;
            v1 = yc;
            break;
        case RR_Rotate_180:
            v0 = screen_width - xc;
            v1 = screen_height - yc;
            break;
        case RR_Rotate_90:
            tmp = xc;
            v0  = screen_height - yc;
            v1  = tmp;
            break;
        case RR_Rotate_270:
            tmp = xc;
            v0 = yc;
            v1 = screen_width - tmp;
            break;
        default:
            break;
    }

    DBGOUT(2, "EVTouch2: FINAL: v0=%d   v1=%d\n", v0, v1);

    *x = v0;
    *y = v1;
    
    return (TRUE);
}

static InputInfoPtr
EVTouch2PreInit(InputDriverPtr drv, IDevPtr dev, int flags)
{
    InputInfoPtr local;
    EVTouch2PrivatePtr priv;
    ScrnInfoPtr   pScrn;

    int i = 0;
    char *s;
    char tmp_str[8];
    int timeo = 0;

    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);

    priv = xcalloc (1, sizeof (EVTouch2PrivateRec));
    if (!priv)
        return NULL;

    local = xf86AllocateInput(drv, 0);
    if (!local) 
    {
        xfree(priv);
        return NULL;
    }

    local->name = xstrdup(dev->identifier);
    local->type_name = XI_TOUCHSCREEN;
    local->device_control = EVTouch2DeviceControl;
    local->read_input = EVTouch2ReadInput;
    local->control_proc = NULL;
    local->close_proc = NULL;
    local->switch_mode = NULL;
    local->conversion_proc = EVTouch2ConvertProc;
    local->reverse_conversion_proc = NULL;
    local->fd = -1;
    local->dev = NULL;
    local->private = priv;
    priv->local = local;
    local->private_flags = 0;
    local->flags = XI86_POINTER_CAPABLE | XI86_SEND_DRAG_EVENTS;
    local->conf_idev = dev;

    xf86CollectInputOptions(local, default_options, NULL);

    xf86OptionListReport(local->options);

	priv->libtouch = xcalloc(1, sizeof(LibTouchRec));
	libtouchInit(priv->libtouch, local);

    priv->screen.num = xf86SetIntOption(local->options, "ScreenNumber", 0 );
    priv->calibration.enabled = FALSE;

    pScrn = xf86Screens[priv->screen.num];
    priv->phys_width = pScrn->currentMode->HDisplay;  /* physical screen resolution */
    priv->phys_height = pScrn->currentMode->VDisplay;

	priv->pan_viewport.x = 0;
	priv->pan_viewport.y = 0;
	priv->pan_viewport.width = 0;
	priv->pan_viewport.height = 0;
	s = xf86SetStrOption(local->options, "PanViewportGeometry", NULL );
	if (s) 
    {
		char* pos;
		if ((pos = strstr(s, "x")) != NULL || 
		    (pos = strstr(s, "X")) != NULL) 
        {
            pos[0] = '\0';
			priv->pan_viewport.width = MAX(atoi(s), 0);
			priv->pan_viewport.width = MIN(priv->pan_viewport.width, 
                                           priv->phys_width);
			priv->pan_viewport.height = MAX(atoi(pos + 1), 0);
			priv->pan_viewport.height = MIN(priv->pan_viewport.height, 
                                            priv->phys_height);
        }
        xfree(s);
    }
    
	s = xf86SetStrOption(local->options, "PanViewportPosition", NULL );
	if (s) 
    {
		char* pos;
		if ((pos = strstr(s, ",")) != NULL)
		{
		    pos[0] = '\0';
			priv->pan_viewport.x = MAX(atoi(s), 0);
			priv->pan_viewport.y = MAX(atoi(pos + 1), 0);
		}
		xfree(s);
	}
    
	priv->pan_viewport.enabled = priv->pan_viewport.width > 0 && 
                                 priv->pan_viewport.height > 0;
    if (priv->pan_viewport.enabled) 
    {
		DBGOUT(2, "EVTouch2: Pan Viewport Position (X,Y) (%d,%d)\n", 
               priv->pan_viewport.x, priv->pan_viewport.y);
		DBGOUT(2, "EVTouch2: Pan Viewport Geometry (W,H) (%d,%d)\n", 
               priv->pan_viewport.width, priv->pan_viewport.height);
	}
	else 
    {
	    priv->pan_viewport.x = 0;
	    priv->pan_viewport.y = 0;
	    priv->pan_viewport.width = 0;
	    priv->pan_viewport.height = 0;
	}
	
    priv->calibration.min_x = xf86SetIntOption(local->options, "MinX", 
                                               EVTOUCH2_DEFAULT_MINX );
    priv->calibration.max_x = xf86SetIntOption(local->options, "MaxX", 
                                               EVTOUCH2_DEFAULT_MAXX);
    priv->calibration.min_y = xf86SetIntOption(local->options, "MinY", 
                                               EVTOUCH2_DEFAULT_MINY );
    priv->calibration.max_y = xf86SetIntOption(local->options, "MaxY", 
                                               EVTOUCH2_DEFAULT_MAXY);

    priv->touch_button = xf86SetIntOption(local->options, 
                                          "TouchButtonEmulate", 
                                          EVTOUCH2_DEFAULT_TOUCH_BUTTON);
    
    priv->emulate3.enabled = xf86SetBoolOption(local->options, 
                                               "Emulate3Buttons", 
                                               EVTOUCH2_DEFAULT_EMULATE3);
    priv->emulate3.timeout = xf86SetIntOption(local->options, 
                                              "Emulate3Timeout", 
                                              EVTOUCH2_DEFAULT_EMULATE3_TIMEOUT);

    debug_level = xf86SetIntOption(local->options, "DebugLevel", 
                                   EVTOUCH2_DEFAULT_DEBUG_LEVEL);
    libtouchSetDebugLevel(debug_level);

    timeo = xf86SetIntOption(local->options, "TapTimer", 
                             LIBTOUCH_DEFAULT_TAP_TIMER);
    libtouchSetTapTimeo(priv->libtouch, timeo);

    timeo = xf86SetIntOption(local->options, "LongtouchTimer", 
                             LIBTOUCH_DEFAULT_LONGTOUCH_TIMER);
    libtouchSetLongtouchTimeo(priv->libtouch, timeo);

    libtouchSetMoveLimit(priv->libtouch, 
                         xf86SetIntOption(local->options, 
                                          "MoveLimit", 
                                          LIBTOUCH_DEFAULT_MOVE_LIMIT));

    priv->rotate = EVTOUCH2_DEFAULT_ROTATION;
    s = xf86FindOptionValue(local->options, "Rotate");
    if (s) 
    {
        if (xf86NameCmp(s, "CW") == 0) 
        {
            priv->rotate = EVTOUCH2_ROTATE_CW;
        } 
        else if (xf86NameCmp(s, "CCW") == 0 ) 
        {
            priv->rotate = EVTOUCH2_ROTATE_CCW;
        } 
    }

    priv->swap_y = xf86SetBoolOption(local->options, "SwapY", 
                                     EVTOUCH2_DEFAULT_SWAP_Y);
    priv->swap_x = xf86SetBoolOption(local->options, "SwapX", 
                                     EVTOUCH2_DEFAULT_SWAP_X);
    priv->swap_axes = xf86SetBoolOption(local->options, "SwapAxes", 
                                        EVTOUCH2_DEFAULT_SWAP_AXES);

    /* 
       get calibration parameters from XF86Config 
    */
    for (i = 0; i < 9; i++)
    {
        sprintf(tmp_str, "x%d", i);
        priv->calibration.diff[i][0] = xf86SetIntOption( local->options,
                                                        tmp_str, 0 );
        sprintf(tmp_str, "y%d", i);
        priv->calibration.diff[i][1] = xf86SetIntOption( local->options,
                                                        tmp_str, 0 );
        DBGOUT(2, "(diff[%d][0]/diff[%d][1])=(%d/%d)\n", i, i, 
               priv->calibration.diff[i][0], priv->calibration.diff[i][1]);
    }
        
    priv->touch_flags = 0;
    local->history_size = xf86SetIntOption( local->options, "HistorySize", 0 );

    /* prepare to process touch packets */
    EVTouch2NewPacket (priv);

    /* this results in an xstrdup that must be freed later */
    local->name = xf86SetStrOption( local->options, "DeviceName", "EVTouch2 TouchScreen" );
    xf86ProcessCommonOptions(local, local->options);
    local->flags |= XI86_CONFIGURED;

    xf86CloseSerial(local->fd);
    local->fd = -1;
    return (local);
}

static void
EVTouch2PtrCtrl(DeviceIntPtr device, PtrCtrl *ctrl)
{
  /* I have no clue what this does, except that registering it stops the 
     X server segfaulting in ProcGetPointerMapping()
     Ho Hum.
  */
}

#ifdef HAVE_PROPERTIES
static void
EVTouch2InitProperty(DeviceIntPtr dev)
{
    LocalDevicePtr local = (LocalDevicePtr) dev->public.devicePrivate;
    EVTouch2PrivatePtr priv = (EVTouch2PrivatePtr) (local->private);
    CARD32 pan_viewport[4];
    CARD32 calibration_axes[4];
    CARD32 calibration_axes_diff[18];
    CARD8 invert_axes[2];
    int rc, i, j, k;

    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);

    /* Init screen property */
    prop_screen_num = MakeAtom(EVTOUCH2_PROP_SCREEN, 
                               strlen(EVTOUCH2_PROP_SCREEN),
                               TRUE);

    rc = XIChangeDeviceProperty(dev, prop_screen_num, XA_INTEGER, 16,
                                PropModeReplace, 1, &priv->screen.num, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_screen_num, FALSE);

    /* Init debug level property */
    prop_debug_level = MakeAtom(EVTOUCH2_PROP_DEBUG_LEVEL, 
                                strlen(EVTOUCH2_PROP_DEBUG_LEVEL),
                                TRUE);

    rc = XIChangeDeviceProperty(dev, prop_debug_level, XA_INTEGER, 8,
                                PropModeReplace, 1, &debug_level, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_debug_level, FALSE);

    /* Init touch button property */
    prop_touch_button = MakeAtom(EVTOUCH2_PROP_TOUCH_BUTTON, 
                                 strlen(EVTOUCH2_PROP_TOUCH_BUTTON),
                                 TRUE);

    rc = XIChangeDeviceProperty(dev, prop_touch_button, XA_INTEGER, 8,
                                PropModeReplace, 1, &priv->touch_button, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_touch_button, FALSE);

    /* Init emulate middle properties */
    prop_emulate3 = MakeAtom(EVTOUCH2_PROP_EMULATE3, 
                             strlen(EVTOUCH2_PROP_EMULATE3),
                             TRUE);

    rc = XIChangeDeviceProperty(dev, prop_emulate3, XA_INTEGER, 8,
                                PropModeReplace, 1, &priv->emulate3.enabled, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_emulate3, FALSE);

    prop_emulate3_timeout = MakeAtom(EVTOUCH2_PROP_EMULATE3_TIMEOUT,
                                     strlen(EVTOUCH2_PROP_EMULATE3_TIMEOUT),
                                     TRUE);

    rc = XIChangeDeviceProperty(dev, prop_emulate3_timeout, XA_INTEGER, 16,
                                PropModeReplace, 1, &priv->emulate3.timeout, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_emulate3_timeout, FALSE);
    
    /* Init emulate invert axes property */
    invert_axes[0] = priv->swap_x;
    invert_axes[1] = priv->swap_y;
    XISetDevicePropertyDeletable(dev, prop_emulate3_timeout, FALSE);

    prop_invert_axes = MakeAtom(EVTOUCH2_PROP_INVERT_AXES, 
                                strlen(EVTOUCH2_PROP_INVERT_AXES),
                                TRUE);

    rc = XIChangeDeviceProperty(dev, prop_invert_axes, XA_INTEGER, 8,
                                PropModeReplace, 2, invert_axes, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_invert_axes, FALSE);

    /* Init swap axes property */
    prop_swap_axes = MakeAtom(EVTOUCH2_PROP_SWAP_AXES, 
                              strlen(EVTOUCH2_PROP_SWAP_AXES),
                              TRUE);

    rc = XIChangeDeviceProperty(dev, prop_swap_axes, XA_INTEGER, 8,
                                PropModeReplace, 1, &priv->swap_axes, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_swap_axes, FALSE);

    /* Init rotation property */
    prop_rotation = MakeAtom(EVTOUCH2_PROP_ROTATION, 
                             strlen(EVTOUCH2_PROP_ROTATION),
                             TRUE);

    rc = XIChangeDeviceProperty(dev, prop_rotation, XA_INTEGER, 8,
                                PropModeReplace, 1, &priv->rotate, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_rotation, FALSE);

    /* Init pan viewport property */
    pan_viewport[0] = priv->pan_viewport.x;
    pan_viewport[1] = priv->pan_viewport.y;
    pan_viewport[2] = priv->pan_viewport.width;
    pan_viewport[3] = priv->pan_viewport.height;

    prop_pan_viewport = MakeAtom(EVTOUCH2_PROP_PAN_VIEWPORT,
                                 strlen(EVTOUCH2_PROP_PAN_VIEWPORT),
                                 TRUE);

    rc = XIChangeDeviceProperty(dev, prop_pan_viewport, XA_INTEGER, 32,
                                PropModeReplace, 4, pan_viewport, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_pan_viewport, FALSE);

    /* Init calibration properties */
    prop_calibration = MakeAtom(EVTOUCH2_PROP_CALIBRATION, 
                                strlen(EVTOUCH2_PROP_CALIBRATION),
                                TRUE);

    rc = XIChangeDeviceProperty(dev, prop_calibration, XA_INTEGER, 8,
                                PropModeReplace, 1, &priv->calibration.enabled, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_calibration, FALSE);

    calibration_axes[0] = priv->calibration.min_x;
    calibration_axes[1] = priv->calibration.max_x;
    calibration_axes[2] = priv->calibration.min_y;
    calibration_axes[3] = priv->calibration.max_y;

    prop_calibration_axes = MakeAtom(EVTOUCH2_PROP_CALIBRATION_MAX_MIN, 
                                     strlen(EVTOUCH2_PROP_CALIBRATION_MAX_MIN),
                                     TRUE);

    rc = XIChangeDeviceProperty(dev, prop_calibration_axes, XA_INTEGER, 32,
                                PropModeReplace, 4, calibration_axes, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_calibration_axes, FALSE);

    for (i = 0, k = 0; i < 9; i++)
        for (j = 0; j < 2; j++, k++)
            calibration_axes_diff[k] = priv->calibration.diff[i][j];

    prop_calibration_axes_diff = MakeAtom(EVTOUCH2_PROP_CALIBRATION_DIFF, 
                                          strlen(EVTOUCH2_PROP_CALIBRATION_DIFF),
                                          TRUE);

    rc = XIChangeDeviceProperty(dev, prop_calibration_axes_diff, XA_INTEGER, 32,
                                PropModeReplace, 18, calibration_axes_diff, 
                                FALSE);
    if (rc != Success)
        return;

    XISetDevicePropertyDeletable(dev, prop_calibration_axes_diff, FALSE);
}

static void
EVTouch2WriteHalConfig(EVTouch2PrivatePtr priv)
{
    LibConfigRecPtr config;
    int i;
    char tmp[8];
    
    config = libconfigCreate(EVTOUCH2_CONFIG_FILE);
    if (!config)
    {
        xf86ErrorFVerb(2, "open " EVTOUCH2_CONFIG_FILE " failed\n");
        return;
    }

    libconfigWriteComment(config, "configuration file autogenerated do not edit directly");
    
    if (debug_level != EVTOUCH2_DEFAULT_DEBUG_LEVEL)
        libconfigWriteInt(config, "DebugLevel", debug_level);

    if (priv->touch_button != EVTOUCH2_DEFAULT_TOUCH_BUTTON)
        libconfigWriteInt(config, "TouchButtonEmulate", priv->touch_button);

    if (priv->emulate3.enabled != EVTOUCH2_DEFAULT_EMULATE3)
        libconfigWriteBool(config, "Emulate3Buttons", priv->emulate3.enabled);
    
    if (priv->emulate3.timeout != EVTOUCH2_DEFAULT_EMULATE3_TIMEOUT)
        libconfigWriteInt(config, "Emulate3Timeout", priv->emulate3.timeout);

    if (priv->swap_x != EVTOUCH2_DEFAULT_SWAP_X)
        libconfigWriteBool(config, "SwapX", priv->swap_x);

    if (priv->swap_y != EVTOUCH2_DEFAULT_SWAP_Y)
        libconfigWriteBool(config, "SwapY", priv->swap_y);
    
    if (priv->swap_axes != EVTOUCH2_DEFAULT_SWAP_AXES)
        libconfigWriteBool(config, "SwapAxes", priv->swap_axes);

    if (priv->rotate != EVTOUCH2_DEFAULT_ROTATION)
        libconfigWriteInt(config, "Rotate", priv->rotate);
    
    if (priv->pan_viewport.width > 0 && priv->pan_viewport.height > 0)
    {
        libconfigWritePairInt(config, "PanViewportGeometry", "x", 
                              priv->pan_viewport.width, 
                              priv->pan_viewport.height);

        if (priv->pan_viewport.x > 0 || priv->pan_viewport.y > 0)
            libconfigWritePairInt(config, "PanViewportPosition", ",", 
                                  priv->pan_viewport.x, 
                                  priv->pan_viewport.y);
    }
    if (priv->calibration.min_x != EVTOUCH2_DEFAULT_MINX)
        libconfigWriteInt(config, "MinX", priv->calibration.min_x);
    if (priv->calibration.max_x != EVTOUCH2_DEFAULT_MAXX)
        libconfigWriteInt(config, "MaxX", priv->calibration.max_x);
    if (priv->calibration.min_y != EVTOUCH2_DEFAULT_MINY)
        libconfigWriteInt(config, "MinY", priv->calibration.min_y);
    if (priv->calibration.max_y != EVTOUCH2_DEFAULT_MAXY)
        libconfigWriteInt(config, "MaxY", priv->calibration.max_y);

    for (i = 0; i < 9; i++)
    {
        sprintf(tmp, "x%d", i);
        if (priv->calibration.diff[i][0])
            libconfigWriteInt(config, tmp, priv->calibration.diff[i][0]);
        sprintf(tmp, "y%d", i);
        if (priv->calibration.diff[i][0])
            libconfigWriteInt(config, tmp, priv->calibration.diff[i][0]);
    } 
    libtouchWriteHalConfig(priv->libtouch, config);
        
    libconfigClose (config);
}

static int
EVTouch2SetProperty(DeviceIntPtr dev, Atom atom, XIPropertyValuePtr val,
                    BOOL checkonly)
{
    LocalDevicePtr local = (LocalDevicePtr) dev->public.devicePrivate;
    EVTouch2PrivatePtr priv = (EVTouch2PrivatePtr) (local->private);
    
    DBGOUT(2, "EVTouch2: %s\n", __FUNCTION__);

    /* set touch button property */
    if (atom == prop_touch_button)
    {
        if (val->format != 8 || val->type != XA_INTEGER || val->size != 1)
            return BadMatch;

        if (!checkonly)
            priv->touch_button = *((CARD8*)val->data);
    }
    /* set debug level property */
    else if (atom == prop_debug_level)
    {
        if (val->format != 8 || val->type != XA_INTEGER || val->size != 1)
            return BadMatch;

        if (!checkonly)
        {
            debug_level = *((CARD8*)val->data);
            libtouchSetDebugLevel(debug_level);
        }
    }
    /* set emulate middle button properties */
    else if (atom == prop_emulate3)
    {
        if (val->format != 8 || val->type != XA_INTEGER || val->size != 1)
            return BadMatch;

        if (!checkonly)
            priv->emulate3.enabled = *((BOOL*)val->data);
    }
    else if (atom == prop_emulate3_timeout)
    {
        if (val->format != 16 || val->type != XA_INTEGER || val->size != 1)
            return BadMatch;

        if (!checkonly)
            priv->emulate3.timeout = *((CARD16*)val->data);
    }
    /* set invert axes property */
    else if (atom == prop_invert_axes)
    {
        if (val->format != 8 || val->type != XA_INTEGER || val->size != 2)
            return BadMatch;

        if (!checkonly)
        {
            CARD8 *vals = (CARD8*)val->data;
            priv->swap_x = vals[0];
            priv->swap_y = vals[1];
        }
    }
    /* set rotation property */
    else if (atom == prop_rotation)
    {
        if (val->format != 8 || val->type != XA_INTEGER || val->size != 1)
            return BadMatch;

        if (!checkonly)
            priv->rotate = *((CARD8*)val->data);
    }
    /* set swap axes property */
    else if (atom == prop_swap_axes)
    {
        if (val->format != 8 || val->type != XA_INTEGER || val->size != 1)
            return BadMatch;

        if (!checkonly)
            priv->swap_axes = *((BOOL*)val->data);
    }
    /* set pan viewport property */
    else if (atom == prop_pan_viewport)
    {
        if (val->format != 32 || val->type != XA_INTEGER)
            return BadMatch;
        if (val->size != 4 && val->size != 0)
            return BadMatch;

        if (!checkonly)
        {
            if (val->size == 0)
            {
                priv->pan_viewport.enabled = FALSE;
                priv->pan_viewport.x = 0;
                priv->pan_viewport.y = 0;
                priv->pan_viewport.width = 0;
                priv->pan_viewport.height = 0;
            } 
            else if (val->size == 4)
            {
                CARD32 *vals = (CARD32*)val->data;

                priv->pan_viewport.x = vals[0];
                priv->pan_viewport.y = vals[1];
                priv->pan_viewport.width = vals[2];
                priv->pan_viewport.height = vals[3];
                priv->pan_viewport.enabled = priv->pan_viewport.width > 0 &&
                                             priv->pan_viewport.height > 0;
            }
        }
    }
    /* set calibration properties */
    else if (atom == prop_calibration)
    {
        if (val->format != 8 || val->type != XA_INTEGER || val->size != 1)
            return BadMatch;

        if (!checkonly)
        {
            char filename[256];

            snprintf(filename, 256, "/dev/evtouch2_calibrate_%d", dev->id);
            priv->calibration.enabled = *((CARD8*)val->data);

            if (priv->calibration.fifo > 0) 
            {
                close (priv->calibration.fifo);
                priv->calibration.fifo = -1;
            }
            unlink(filename);
            
            if (priv->calibration.enabled) 
            {
                if (mkfifo(filename, 0666) < 0)
                {
                    xf86ErrorFVerb(2, "create FIFO FAILED : %s\n",strerror(errno));
                    priv->calibration.enabled = FALSE;
                    return !Success;
                }
                chmod (filename, 0666);
                priv->calibration.fifo = open(filename, O_RDWR, 0);
                if (priv->calibration.fifo < 0)
                {
                    xf86ErrorFVerb(2, "open FIFO FAILED : %s\n",strerror(errno));
                    priv->calibration.enabled = FALSE;
                    return !Success;
                }
            }
        }
    }
    else if (atom == prop_calibration_axes)
    {
        if (val->format != 32 || val->type != XA_INTEGER || val->size != 4)
            return BadMatch;

        if (!checkonly)
        {
            CARD32 *vals = (CARD32*)val->data;
            
            priv->calibration.min_x = vals[0];
            priv->calibration.max_x = vals[1];
            priv->calibration.min_y = vals[2];
            priv->calibration.max_y = vals[3];
            priv->calibration.enabled = FALSE;
            if (priv->calibration.fifo > 0)
            {
                char filename[256];

                close(priv->calibration.fifo);
                priv->calibration.fifo = -1;
                snprintf(filename, 256, "/dev/evtouch2_calibrate_%d", dev->id);
                unlink(filename);
            }
        }
    }
    else if (atom == prop_calibration_axes_diff)
    {
        if (val->format != 32 || val->type != XA_INTEGER || val->size != 18)
            return BadMatch;

        if (!checkonly)
        {
            CARD32 *vals = (CARD32*)val->data;
            int i;

            for (i = 0; i < 18; i+=2)
            {
                priv->calibration.diff[i/2][0] = vals[i];
                priv->calibration.diff[i/2][1] = vals[i];
            }
            priv->calibration.enabled = FALSE;
            if (priv->calibration.fifo > 0)
            {
                char filename[256];

                close(priv->calibration.fifo);
                priv->calibration.fifo = -1;
                snprintf(filename, 256, "/dev/evtouch2_calibrate_%d", dev->id);
                unlink(filename);
            }
        }
    }

    EVTouch2WriteHalConfig(priv);
    
    return Success;
}
#endif