forked from Plippo/twofing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
twofingemu.c
1374 lines (1148 loc) · 37.4 KB
/
twofingemu.c
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
/*
Copyright (C) 2010, 2011 Philipp Merkel <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
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.
*/
#include <linux/input.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <X11/Xutil.h>
#include <X11/X.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <X11/extensions/XTest.h>
#include <X11/keysym.h>
#include <X11/extensions/XInput2.h>
#include <X11/extensions/Xrandr.h>
#include "twofingemu.h"
#include "gestures.h"
#include "easing.h"
#include "devices.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <time.h>
#include <signal.h>
#include <pthread.h>
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
int debugMode = 0;
int inDebugMode() {
return debugMode;
}
/* Daemonize. Source: http://www-theorie.physik.unizh.ch/~dpotter/howto/daemonize (public domain) */
static void daemonize(void) {
pid_t pid, sid;
/* already a daemon */
if (getppid() == 1)
return;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* At this point we are executing as the child process */
/* Change the file mode mask */
umask(0);
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
exit(EXIT_FAILURE);
}
/* Change the current working directory. This prevents the current
directory from being locked; hence not being able to remove it. */
if ((chdir("/")) < 0) {
exit(EXIT_FAILURE);
}
/* Redirect standard files to /dev/null */
void* r;
r = freopen("/dev/null", "r", stdin);
r = freopen("/dev/null", "w", stdout);
r = freopen("/dev/null", "w", stderr);
r = r;
}
/* Finger information */
FingerInfo fingerInfos[2] = { { .rawX=0, .rawY=0, .rawZ=0, .id = -1, .slotUsed = 0, .setThisTime = 0 }, { .rawX=0, .rawY=0, .rawZ=0,
.id = -1, .slotUsed = 0, .setThisTime = 0 } };
/* X stuff */
Display* display;
Window root;
int screenNum;
int deviceID;
int calibrateDeviceID;
Atom WM_CLASS;
pthread_t xLoopThread;
int randrEvBase;
int randrErrBase;
int xinputEvBase;
int xinputErrBase;
int disableOnGrab = 0;
/* Calibration data */
int calibMinX, calibMaxX, calibMinY, calibMaxY;
unsigned char calibSwapX, calibSwapY, calibSwapAxes;
float calibMatrix[6];
int calibMatrixUse = 0;
/* The width and height of the screen in pixels */
unsigned int screenWidth, screenHeight;
/* Finger data */
int fingersDown = 0;
int fingersWereDown = 0;
/* Has button press of first button been called in XTest? */
int buttonDown = 0;
/* Does the device use the legacy MT protocol? */
int useLegacyProtocol = 0;
/* Blocking Device */
int blockingDeviceID = -1;
int blockingIntervalMilliseconds = BLOCKING_INTERVAL_MS_DEFAULT;
TimeVal lastBlockingInputTime = { 0, 0};
int currentTouchBlocked = 0;
int alsoBlockTwoFingerTouches = 0;
/* Ability to move mouse back after touches */
int moveMouseBackAfterTouches = 0;
int prevMouseX = 0;
int prevMouseY = 0;
/* Signal handling */
pthread_t signalThread;
sigset_t signalSet;
int stopSignalReceived = 0;
/* Handle errors by, well, throwing them away. */
int invalidWindowHandler(Display *dsp, XErrorEvent *err) {
return 0;
}
/* Grab the device so input is captured */
void grab(Display* display, int grabDeviceID) {
if (disableOnGrab) {
if(debugMode) printf("Disabling device instead of grabbing\n");
XDevice *dev = XOpenDevice(display, grabDeviceID);
if(dev) {
unsigned char cEnable = (unsigned char) 0;
XChangeDeviceProperty(display, dev, XInternAtom(display,
"Device Enabled", 0), XA_INTEGER, 8, PropModeReplace, &cEnable, 1);
XCloseDevice(display, dev);
} else {
if(debugMode) printf("Couldn't open device: %i\n", grabDeviceID);
}
} else {
XIEventMask device_mask;
unsigned char mask_data[8] = { 0,0,0,0,0,0,0,0 };
device_mask.mask_len = sizeof(mask_data);
device_mask.mask = mask_data;
XISetMask(device_mask.mask, XI_Motion);
XISetMask(device_mask.mask, XI_ButtonPress);
/* Experiments with X MT support, not working yet */
// XISetMask(device_mask.mask, XI_TouchBegin);
// XISetMask(device_mask.mask, XI_TouchUpdate);
// XISetMask(device_mask.mask, XI_TouchEnd);
// XIGrabModifiers modifiers;
// modifiers.modifiers = XIAnyModifier;
// int r = XIGrabButton(display, grabDeviceID, XIAnyButton, root, None, GrabModeSync,
// GrabModeAsync, True, &device_mask, 1, &modifiers);
// int r = XIGrabTouchBegin(display, grabDeviceID, root, None, &device_mask, 0, modifiers);
int r = XIGrabDevice(display, grabDeviceID, root, CurrentTime, None, GrabModeAsync, GrabModeAsync, False, &device_mask);
if(debugMode) printf("Grab Result: %i\n", r);
}
}
/* Ungrab the device so input can be handled by application directly */
void ungrab(Display* display, int grabDeviceID) {
/* Experiments with X MT support, not working yet */
// XIGrabModifiers modifiers[1] = { { 0, 0 } };
// XIUngrabButton(display, grabDeviceID, 1, root, 1, modifiers);
if (disableOnGrab) {
if(debugMode) printf("Enabling device instead of ungrabbing\n");
XDevice *dev = XOpenDevice(display, grabDeviceID);
if(dev) {
unsigned char cEnable = (unsigned char) 1;
XChangeDeviceProperty(display, dev, XInternAtom(display,
"Device Enabled", 0), XA_INTEGER, 8, PropModeReplace, &cEnable, 1);
XCloseDevice(display, dev);
if(debugMode) printf("Device Enabled: %i\n", grabDeviceID);
} else {
if(debugMode) printf("Couldn't open device: %i\n", grabDeviceID);
}
} else {
XIUngrabDevice(display, grabDeviceID, CurrentTime);
}
}
TimeVal getCurrentTime() {
TimeVal time;
gettimeofday(&time, NULL);
return time;
}
int timeDiff(TimeVal start, TimeVal end)
{
long seconds = end.tv_sec - start.tv_sec;
long microSeconds = end.tv_usec - start.tv_usec;
return (seconds * 1000 + microSeconds/1000);
}
/* Send an XTest event to release the first button if it is currently pressed */
void releaseButton() {
if (buttonDown) {
buttonDown = 0;
XTestFakeButtonEvent(display, 1, False, CurrentTime);
XFlush(display);
/* Experiments with Pressure Sensitivity, not working yet */
/* XDevice * dev = XOpenDevice(display, deviceID);
int axes[3] = {fingerInfos[0].rawX, fingerInfos[0].rawY, fingerInfos[0].rawZ};
XTestFakeDeviceButtonEvent(display, dev, 1, False, axes, 3, 0);
XCloseDevice(display, dev);
XFlush(display);
grab(display, deviceID);*/
}
}
/* Send an XTest event to press the first button if it is not pressed yet */
void pressButton() {
if(!buttonDown) {
/* Experiments with Pressure Sensitivity, not working yet */
/* XDevice * dev = XOpenDevice(display, deviceID);
int axes[3] = {fingerInfos[0].rawX, fingerInfos[0].rawY, fingerInfos[0].rawZ};
XTestFakeDeviceButtonEvent(display, dev, 1, False, axes, 3, 0);
XCloseDevice(display, dev);
XFlush(display);
ungrab(display, deviceID);
XFlush(display);
printf("PRESS!\n");
dev = XOpenDevice(display, deviceID);
XTestFakeDeviceButtonEvent(display, dev, 1, True, axes, 3, 0);
XCloseDevice(display, dev);
*/
buttonDown = 1;
XTestFakeButtonEvent(display, 1, True, CurrentTime);
XFlush(display);
}
}
/* Is the first button currently pressed? */
int isButtonDown() {
return buttonDown;
}
/* Moves the pointer to the given position */
void movePointer(int x, int y, int z) {
/* Experiments with XI events, not working yet */
// int axes[3] = {x, y, z};
// XDevice * dev = XOpenDevice(display, 17);
// XTestFakeDeviceMotionEvent(display, dev, False, 0, axes, 2, 0);
// XCloseDevice(display, dev);
XTestFakeMotionEvent(display, -1, x, y, CurrentTime);
XFlush(display);
}
/* Executes the given action -- synthesizes key/button press, release or both, depending
* on value of whatToDo (EXECUTEACTION_PRESS/_RELEASE/_BOTH). */
void executeAction(Action* action, int whatToDo) {
if (whatToDo & EXECUTEACTION_PRESS) {
if (action->actionType != ACTIONTYPE_NONE && action->modifier != 0) {
if (action->modifier & MODIFIER_SHIFT) {
XTestFakeKeyEvent(display,
XKeysymToKeycode(display, XK_Shift_L), True,
CurrentTime);
XFlush(display);
}
if (action->modifier & MODIFIER_CONTROL) {
XTestFakeKeyEvent(display, XKeysymToKeycode(display,
XK_Control_L), True, CurrentTime);
XFlush(display);
}
if (action->modifier & MODIFIER_ALT) {
XTestFakeKeyEvent(display, XKeysymToKeycode(display, XK_Alt_L),
True, CurrentTime);
XFlush(display);
}
if (action->modifier & MODIFIER_SUPER) {
XTestFakeKeyEvent(display,
XKeysymToKeycode(display, XK_Super_L), True,
CurrentTime);
XFlush(display);
}
}
switch (action->actionType) {
case ACTIONTYPE_BUTTONPRESS:
XTestFakeButtonEvent(display, action->keyButton, True, CurrentTime);
XFlush(display);
break;
case ACTIONTYPE_KEYPRESS:
XTestFakeKeyEvent(display, XKeysymToKeycode(display,
action->keyButton), True, CurrentTime);
XFlush(display);
break;
}
}
if (whatToDo & EXECUTEACTION_RELEASE) {
switch (action->actionType) {
case ACTIONTYPE_BUTTONPRESS:
XTestFakeButtonEvent(display, action->keyButton, False, CurrentTime);
XFlush(display);
break;
case ACTIONTYPE_KEYPRESS:
XTestFakeKeyEvent(display, XKeysymToKeycode(display,
action->keyButton), False, CurrentTime);
XFlush(display);
break;
}
if (action->actionType != ACTIONTYPE_NONE && action->modifier != 0) {
if (action->modifier & MODIFIER_SHIFT) {
XTestFakeKeyEvent(display,
XKeysymToKeycode(display, XK_Shift_L), False,
CurrentTime);
XFlush(display);
}
if (action->modifier & MODIFIER_CONTROL) {
XTestFakeKeyEvent(display, XKeysymToKeycode(display,
XK_Control_L), False, CurrentTime);
XFlush(display);
}
if (action->modifier & MODIFIER_ALT) {
XTestFakeKeyEvent(display, XKeysymToKeycode(display, XK_Alt_L),
False, CurrentTime);
XFlush(display);
}
if (action->modifier & MODIFIER_SUPER) {
XTestFakeKeyEvent(display,
XKeysymToKeycode(display, XK_Super_L), False,
CurrentTime);
XFlush(display);
}
}
}
}
Window getParentWindow(Window w) {
Window root, parent;
Window* childWindows = NULL;
unsigned int childCount;
if(XQueryTree(display, w, &root, &parent, &childWindows, &childCount)) {
if (childWindows != NULL)
XFree(childWindows);
return parent;
} else {
return None;
}
}
Window getLastChildWindow(Window w) {
Window root, parent;
Window* childWindows = NULL;
unsigned int childCount;
if(XQueryTree(display, w, &root, &parent, &childWindows, &childCount)) {
if (childWindows != NULL) {
if(childCount > 0) {
Window child = childWindows[childCount - 1];
XFree(childWindows);
return child;
}
XFree(childWindows);
}
return None;
} else {
return None;
}
}
void storePrevMousePos() {
Window root_return, child_return;
int root_x_return = 0, root_y_return = 0;
int win_x_return = 0, win_y_return = 0;
unsigned int mask_return = 0;
if (XQueryPointer(display, root, &root_return, &child_return, &root_x_return, &root_y_return,
&win_x_return, &win_y_return, &mask_return) == True) {
prevMouseX = root_x_return;
prevMouseY = root_y_return;
}
}
Window getActiveWindow() {
/* Window *root_return = None, *child_return = None;
int *root_x_return = 0, *root_y_return = 0;
int *win_x_return = 0, *win_y_return = 0;
unsigned int *mask_return = 0;
XQueryPointer(display, root, root_return, child_return, root_x_return, root_y_return,
win_x_return, win_y_return, mask_return);
return *child_return;*/
return getCurrentWindow();
}
/* Returns the active top-level window. A top-level window is one that has WM_CLASS set.
* May also return None. */
Window getCurrentWindow() {
/* First get the window that has the input focus */
Window currentWindow;
int revert;
XGetInputFocus(display, ¤tWindow, &revert);
if (currentWindow == None) {
//if(debugMode) printf("Leave getCurrentWindow\n");
return currentWindow;
}
/* Now go through parent windows until we find one with WM_CLASS set. */
XClassHint* classHint = XAllocClassHint();
if(classHint == NULL) {
if(debugMode) printf("Couldn't allocate class hint!!\n");
return None;
}
int i = 0;
while (1) {
//if(debugMode) printf("in Loop\n");
i++;
if(i >= 5) {
if(debugMode) printf("Too many iterations in getCurrentWindow\n");
XFree(classHint);
//if(debugMode) printf("Leave getCurrentWindow\n");
return None;
}
if (currentWindow == root || currentWindow == None) {
//if(debugMode) printf("Reached root!\n");
/* No top-level window available. Should never happen. */
XFree(classHint);
//if(debugMode) printf("Leave getCurrentWindow\n");
return currentWindow;
}
//if(debugMode) printf("Call XGetClassHint!\n");
if (XGetClassHint(display, currentWindow, classHint) == 0) {
//if(debugMode) printf("Has no Class!\n");
/* Has no WM_CLASS, thus no top-level window */
Window parent = getParentWindow(currentWindow);
if(parent == None || currentWindow == parent) {
/* something wrong */
XFree(classHint);
return currentWindow;
}
/* Continue with parent until we find WM_CLASS */
currentWindow = parent;
} else {
//if(debugMode) printf("Clean up class name!\n");
if(classHint->res_class != NULL) XFree(classHint->res_class);
if(classHint->res_name != NULL) XFree(classHint->res_name);
XFree(classHint);
//if(debugMode) printf("Leave getCurrentWindow\n");
return currentWindow;
}
}
}
/* Sets the calibrated x, y coordinates from the raw coordinates in the given FingerInfo */
void calibrate(FingerInfo* fingerInfo) {
float xf; float yf;
if (calibSwapAxes) {
xf = ((float)(fingerInfo->rawY - calibMinX))/((float) (calibMaxX-calibMinX));
yf = ((float)(fingerInfo->rawX - calibMinY))/((float) (calibMaxY-calibMinY));
} else {
xf = ((float)(fingerInfo->rawX - calibMinX))/((float) (calibMaxX-calibMinX));
yf = ((float)(fingerInfo->rawY - calibMinY))/((float) (calibMaxY-calibMinY));
}
if (calibSwapX) xf = 1 - xf;
if (calibSwapY) yf = 1 - yf;
if(calibMatrixUse) {
float xfold = xf;
/* Apply matrix transformation */
xf = xf * calibMatrix[0] + yf * calibMatrix[1] + calibMatrix[2];
yf = xfold * calibMatrix[3] + yf * calibMatrix[4] + calibMatrix[5];
}
fingerInfo->x = xf * screenWidth;
fingerInfo->y = yf * screenHeight;
if (fingerInfo->x < 0)
fingerInfo->x = 0;
if (fingerInfo->y < 0)
fingerInfo->y = 0;
if (fingerInfo->x > screenWidth)
fingerInfo->x = screenWidth;
if (fingerInfo->y > screenHeight)
fingerInfo->y = screenHeight;
}
/* Process the finger data gathered from the last set of events */
void processFingers() {
int i;
fingersDown = 0;
for(i = 0; i < 2; i++) {
if(fingerInfos[i].slotUsed) {
calibrate(&(fingerInfos[i]));
fingersDown++;
}
}
if(fingersWereDown == 0 &&
fingersDown > 0 &&
blockingDeviceID != -1 &&
timeDiff(lastBlockingInputTime, getCurrentTime()) < blockingIntervalMilliseconds) {
currentTouchBlocked = 1;
if(debugMode) printf("Touch blocked.\n");
}
if(moveMouseBackAfterTouches && !currentTouchBlocked && fingersDown > 0 && fingersWereDown == 0) {
storePrevMousePos();
}
if(!currentTouchBlocked || !alsoBlockTwoFingerTouches) {
processFingerGesture(fingerInfos, fingersDown, fingersWereDown, currentTouchBlocked);
}
if(fingersDown == 0) {
currentTouchBlocked = 0;
if(fingersWereDown > 0 && moveMouseBackAfterTouches) {
movePointer(prevMouseX, prevMouseY, 0);
}
}
/* Save number of fingers to compare next time */
fingersWereDown = fingersDown;
}
/* Returns a pointer to the profile of the currently selected
* window, or defaultProfile if there is no specific profile for it or the window is invalid. */
char* getWindowClass(Window w) {
char * result = NULL;
if (w != None) {
XClassHint* classHint = XAllocClassHint();
/* Read WM_CLASS member */
if (XGetClassHint(display, w, classHint)) {
if(classHint->res_class != NULL) {
result = malloc((strlen(classHint->res_name) + 1) * sizeof(char));
if(result != NULL) {
strcpy(result, classHint->res_name);
}
XFree(classHint->res_class);
}
if(classHint->res_name != NULL) XFree(classHint->res_name);
XFree(classHint);
}
}
return result;
}
/* Returns whether the given window is blacklisted */
int isWindowBlacklisted(Window w) {
if(w == None) return 0;
return isWindowBlacklistedForGestures(w);
}
void setScreenSize(XRRScreenChangeNotifyEvent * evt) {
screenWidth = evt->width;
screenHeight = evt->height;
if(debugMode) {
printf("New screen size: %i x %i\n", screenWidth, screenHeight);
}
}
/* X thread that processes X events in parallel to kernel device loop */
void handleXEvent() {
XEvent ev;
XNextEvent(display, &ev);
//if(debugMode) printf("Handle event\n");
if (XGetEventData(display, &(ev.xcookie))) {
XGenericEventCookie *cookie = &(ev.xcookie);
if (cookie->evtype == XI_Motion || cookie->evtype == XI_ButtonPress) {
XIDeviceEvent * devEvt = (XIDeviceEvent*) cookie->data;
if(blockingDeviceID != -1 && devEvt->deviceid == blockingDeviceID) {
// Blocking event received
if(debugMode) printf("Blocking for next %i milliseconds.\n", blockingIntervalMilliseconds);
lastBlockingInputTime = getCurrentTime();
}
}
if (cookie->evtype == XI_PropertyEvent) {
/* Device properties changed -> recalibrate. */
if(debugMode) printf("Device properties changed.\n");
readCalibrationData(0, NULL);
}
/*if (cookie->evtype == XI_Motion) {
//if(debugMode) printf("Motion event\n");
//int r = XIAllowEvents(display, deviceID, XIReplayDevice, CurrentTime);
//printf("XIAllowEvents result: %i\n", r);
} else if(cookie->evtype == XI_ButtonPress) {
//if(debugMode) printf("Button Press\n");
//int r = XIAllowEvents(display, deviceID, XIReplayDevice, CurrentTime);
//printf("XIAllowEvents result: %i\n", r);
}*/
// In an ideal world, the following would work. But unfortunately the touch events
// delivered by evdev are often crap on the eGalax screen, with missing events when there
// should be some. So we still have to read directly from the input device, as bad as that is.
//if (cookie->evtype == XI_TouchBegin || cookie->evtype == XI_TouchUpdate || cookie->evtype == XI_TouchEnd) {
// XIDeviceEvent * devEvt = (XIDeviceEvent*) cookie->data;
// printf("Detail: %i\n", devEvt->detail);
// printf("Mask[0]: %i\n", (int) devEvt->valuators.mask[0]);
//
// /* Look for slot to put the data into by looking at the tracking ids */
// int index = -1;
// int i;
// for(i = 0; i < 2; i++) {
// if(fingerInfos[i].id == devEvt->detail) {
// index = i;
// break;
// }
// }
//
// /* No slot for this id found, look for free one */
// if(index == -1) {
// for(i = 0; i < 2; i++) {
// if(!fingerInfos[i].slotUsed) {
// /* "Empty" slot, so we can add it. */
// index = i;
// fingerInfos[i].id = devEvt->detail;
// break;
// }
// }
// }
//
// /* We have found a slot */
// if(index != -1) {
// fingerInfos[index].slotUsed = (cookie->evtype != XI_TouchEnd ? 1 : 0);
//
// i = 0;
// if((devEvt->valuators.mask[0] & 1) == 1)
// {
// fingerInfos[index].rawX = (int) devEvt->valuators.values[i++];
// }
// if((devEvt->valuators.mask[0] & 2) == 2)
// {
// fingerInfos[index].rawY = (int) devEvt->valuators.values[i++];
// }
// if((devEvt->valuators.mask[0] & 4) == 4)
// {
// fingerInfos[index].rawZ = (int) devEvt->valuators.values[i++];
// }
// }
//
// processFingers();
//}
XFreeEventData(display, &(ev.xcookie));
} else {
if(ev.type == randrEvBase + RRScreenChangeNotify) {
setScreenSize((XRRScreenChangeNotifyEvent *) &ev);
}
}
}
/* Reads the calibration data from evdev, should be self-explanatory. */
void readCalibrationData(int exitOnFail, char* deviceName) {
if(debugMode) {
printf("Start calibration\n");
}
Atom retType;
int retFormat;
unsigned long retItems, retBytesAfter;
unsigned int* data;
if(XIGetProperty(display, calibrateDeviceID, XInternAtom(display,
"Evdev Axis Calibration", 0), 0, 4 * 32, False, XA_INTEGER,
&retType, &retFormat, &retItems, &retBytesAfter,
(unsigned char**) &data) != Success) {
data = NULL;
}
if (data == NULL || retItems != 4 || data[0] == data[1] || data[2] == data[3]) {
/* evdev might not be ready yet after resume. Let's wait a second and try again. */
sleep(1);
if(XIGetProperty(display, calibrateDeviceID, XInternAtom(display,
"Evdev Axis Calibration", 0), 0, 4 * 32, False, XA_INTEGER,
&retType, &retFormat, &retItems, &retBytesAfter,
(unsigned char**) &data) != Success) {
retItems = 0;
return;
}
if (retItems != 4 || data[0] == data[1] || data[2] == data[3]) {
if(debugMode) {
printf("No calibration data found, use default values.\n");
}
/* Get minimum/maximum of axes */
if (strcmp(deviceName, "ELAN9009:00 04F3:29DE") == 0) {
if(debugMode) {
printf("Using fixed values for ELAN device for now.\n");
}
calibMaxX = 3600;
calibMaxY = 960;
} else {
int nDev;
XIDeviceInfo * deviceInfo = XIQueryDevice(display, calibrateDeviceID, &nDev);
int c;
for(c = 0; c < deviceInfo->num_classes; c++) {
if(deviceInfo->classes[c]->type == XIValuatorClass) {
XIValuatorClassInfo* valuatorInfo = (XIValuatorClassInfo *) deviceInfo->classes[c];
if(valuatorInfo->mode == XIModeAbsolute) {
if(valuatorInfo->label == XInternAtom(display, "Abs X", 0)
|| valuatorInfo->label == XInternAtom(display, "Abs MT Position X", 0))
{
calibMinX = valuatorInfo->min;
calibMaxX = valuatorInfo->max;
}
else if(valuatorInfo->label == XInternAtom(display, "Abs Y", 0)
|| valuatorInfo->label == XInternAtom(display, "Abs MT Position Y", 0))
{
calibMinY = valuatorInfo->min;
calibMaxY = valuatorInfo->max;
}
}
}
}
XIFreeDeviceInfo(deviceInfo);
}
} else {
calibMinX = data[0];
calibMaxX = data[1];
calibMinY = data[2];
calibMaxY = data[3];
}
} else {
calibMinX = data[0];
calibMaxX = data[1];
calibMinY = data[2];
calibMaxY = data[3];
}
if(data != NULL) {
XFree(data);
}
float * data4 = NULL;
if(XIGetProperty(display, calibrateDeviceID, XInternAtom(display,
"Coordinate Transformation Matrix", 0), 0, 9 * 32, False, XInternAtom(display,
"FLOAT", 0),
&retType, &retFormat, &retItems, &retBytesAfter,
(unsigned char **) &data4) != Success) {
data4 = NULL;
}
calibMatrixUse = 0;
if(data4 != NULL && retItems == 9) {
int i;
for(i = 0; i < 6; i++) {
/* We only take the first two rows of the matrix, the rest is unimportant anyway */
calibMatrix[i] = data4[i];
}
calibMatrixUse = 1;
}
if(data4 != NULL) {
XFree(data4);
}
unsigned char* data2;
if(XIGetProperty(display, calibrateDeviceID, XInternAtom(display,
"Evdev Axis Inversion", 0), 0, 2 * 8, False, XA_INTEGER, &retType,
&retFormat, &retItems, &retBytesAfter, (unsigned char**) &data2) != Success) {
retItems = 0;
}
if (retItems != 2) {
if (debugMode) {
printf("No valid axis inversion data found, assuming no inversion.\n");
}
calibSwapX = 0;
calibSwapY = 0;
} else {
calibSwapX = data2[0];
calibSwapY = data2[1];
}
XFree(data2);
if(XIGetProperty(display, calibrateDeviceID,
XInternAtom(display, "Evdev Axes Swap", 0), 0, 8, False,
XA_INTEGER, &retType, &retFormat, &retItems, &retBytesAfter,
(unsigned char**) &data2) != Success) {
retItems = 0;
}
if (retItems != 1) {
if (debugMode)
{
printf("No valid axes swap data found, assuming no swap.\n");
}
calibSwapAxes = 0;
}
else
{
calibSwapAxes = data2[0];
}
XFree(data2);
if(debugMode)
{
printf("Calibration: MinX: %i; MaxX: %i; MinY: %i; MaxY: %i\n", calibMinX, calibMaxX, calibMinY, calibMaxY);
printf("Invert X Axis: %s\n", calibSwapX ? "Yes" : "No");
printf("Invert Y Axis: %s\n", calibSwapY ? "Yes" : "No");
printf("Swap Axes: %s\n", calibSwapAxes ? "Yes" : "No");
if(calibMatrixUse)
{
printf("Calibration Matrix: \t%f\t%f\t%f\n \t%f\t%f\t%f\n", calibMatrix[0], calibMatrix[1], calibMatrix[2], calibMatrix[3], calibMatrix[4], calibMatrix[5]);
}
}
}
int isEasingEnabled()
{
return !moveMouseBackAfterTouches;
}
void * signalThreadFunction(void *arg) {
int sig;
while(1) {
sigwait ( &signalSet, &sig );
/* Trigger update of profile settings */
stopSignalReceived = 1;
return 0;
}
}
/* Main function, contains kernel driver event loop */
int main(int argc, char **argv) {
char* devname = 0;
int doDaemonize = 1;
int doWait = 0;
int clickMode = 2;
int justVersion = 0;
char* blockingDevName = 0;
int i;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--debug") == 0) {
doDaemonize = 0;
debugMode = 1;
} else if (strcmp(argv[i], "--version") == 0) {
justVersion = 1;
} else if (strcmp(argv[i], "--wait") == 0) {
doWait = 1;
} else if (strcmp(argv[i], "--click=first") == 0) {
clickMode = 0;
} else if (strcmp(argv[i], "--click=second") == 0) {
clickMode = 1;
} else if (strcmp(argv[i], "--click=center") == 0) {
clickMode = 2;
} else if (strcmp(argv[i], "--blockingdevice") == 0) {
if(i + 1 < argc) {
blockingDevName = argv[++i];
}
} else if (strcmp(argv[i], "--also-block-twofingers") == 0) {
alsoBlockTwoFingerTouches = 1;
} else if (strcmp(argv[i], "--grab-by-disabling") == 0) {
disableOnGrab = 1;
} else if (strcmp(argv[i], "--blockinginterval") == 0) {
if(i + 1 < argc) {
blockingIntervalMilliseconds = atoi(argv[++i]);
}
} else if (strcmp(argv[i], "--moveback") == 0) {
moveMouseBackAfterTouches = 1;
} else if (strcmp(argv[i], "--screenpad") == 0) {
blockingDevName = "ELAN9009:00 04F3:29DE Pen (0)";
disableOnGrab = 1;
alsoBlockTwoFingerTouches = 1;
moveMouseBackAfterTouches = 1;
} else {
devname = argv[i];
}
}
if(debugMode || justVersion)
{
printf("twofing, the two-fingered daemon\nVersion %s\n\n", VERSION);
}
if(justVersion)
{
return 0;
}
initGestures(clickMode);
if (blockingDevName != 0)
{
lastBlockingInputTime = getCurrentTime();
}
if (doDaemonize) {
daemonize();
}
if (doWait) {
/* Wait until all necessary things are loaded */
sleep(10);
}
/* Connect to X server */
if ((display = XOpenDisplay(NULL)) == NULL) {
fprintf(stderr, "ERROR: Couldn't connect to X server\n");
exit(1);
}
/* Read X data */
screenNum = DefaultScreen(display);
root = RootWindow(display, screenNum);
// realDisplayWidth = DisplayWidth(display, screenNum);
// realDisplayHeight = DisplayHeight(display, screenNum);
WM_CLASS = XInternAtom(display, "WM_CLASS", 0);