-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclickinjector.cpp
More file actions
979 lines (884 loc) · 37.1 KB
/
Copy pathclickinjector.cpp
File metadata and controls
979 lines (884 loc) · 37.1 KB
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
#include "clickinjector.h"
#include "clickplan.h"
#include <QKeySequence>
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
# include <QKeyCombination>
#endif
// ─────────────────────────────────────────────────────────────
// WINDOWS
// ─────────────────────────────────────────────────────────────
#if defined(PLATFORM_WINDOWS)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
static void sendMouseEvent(DWORD flags, int x, int y, DWORD data = 0)
{
INPUT in = {};
in.type = INPUT_MOUSE;
in.mi.dx = static_cast<LONG>((x * 65536) / GetSystemMetrics(SM_CXVIRTUALSCREEN));
in.mi.dy = static_cast<LONG>((y * 65536) / GetSystemMetrics(SM_CYVIRTUALSCREEN));
in.mi.mouseData = data;
in.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK | flags;
SendInput(1, &in, sizeof(INPUT));
}
static void sendKeyEvent(WORD vk, bool down)
{
INPUT in = {};
in.type = INPUT_KEYBOARD;
in.ki.wVk = vk;
in.ki.dwFlags = down ? 0 : KEYEVENTF_KEYUP;
SendInput(1, &in, sizeof(INPUT));
}
void ClickInjector::pressModifiers(int mods)
{
if (mods & ModCtrl) sendKeyEvent(VK_CONTROL, true);
if (mods & ModAlt) sendKeyEvent(VK_MENU, true);
if (mods & ModShift) sendKeyEvent(VK_SHIFT, true);
}
void ClickInjector::releaseModifiers(int mods)
{
if (mods & ModShift) sendKeyEvent(VK_SHIFT, false);
if (mods & ModAlt) sendKeyEvent(VK_MENU, false);
if (mods & ModCtrl) sendKeyEvent(VK_CONTROL, false);
}
void ClickInjector::moveCursor(QPoint pos)
{
sendMouseEvent(MOUSEEVENTF_MOVE, pos.x(), pos.y());
}
QPoint ClickInjector::cursorPos()
{
POINT p{};
GetCursorPos(&p);
return QPoint(p.x, p.y);
}
bool ClickInjector::hasInputDeviceAccess() { return true; }
void ClickInjector::performClick(ClickType type, QPoint pos, int mods)
{
// Move first
sendMouseEvent(MOUSEEVENTF_MOVE, pos.x(), pos.y());
pressModifiers(mods);
// Down/up flag pair per button.
struct WinButton { DWORD down; DWORD up; };
auto winButton = [](clickplan::Button b) -> WinButton {
switch (b) {
case clickplan::Button::Right:
return { MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP };
case clickplan::Button::Middle:
return { MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP };
case clickplan::Button::Left:
case clickplan::Button::NoButton:
break;
}
return { MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP };
};
const clickplan::Plan plan = clickplan::planFor(type);
switch (plan.action) {
case clickplan::Action::Click: {
// Windows has no click-count field on a mouse event: a double-click is
// literally two press/release cycles, and the shell decides from the
// timing. (macOS is the odd one out here — see clickplan.h.)
const WinButton b = winButton(plan.button);
for (int i = 0; i < plan.clickCount; ++i) {
sendMouseEvent(b.down, pos.x(), pos.y());
sendMouseEvent(b.up, pos.x(), pos.y());
}
break;
}
case clickplan::Action::Press:
sendMouseEvent(winButton(plan.button).down, pos.x(), pos.y());
break;
case clickplan::Action::Release:
sendMouseEvent(winButton(plan.button).up, pos.x(), pos.y());
break;
case clickplan::Action::Scroll: {
const DWORD flag = (plan.axis == clickplan::ScrollAxis::Horizontal)
? MOUSEEVENTF_HWHEEL : MOUSEEVENTF_WHEEL;
sendMouseEvent(flag, pos.x(), pos.y(),
static_cast<DWORD>(WHEEL_DELTA * plan.direction));
break;
}
case clickplan::Action::NoAction:
break;
}
releaseModifiers(mods);
}
static WORD qtKeyToVK(int qtKey)
{
if (qtKey >= Qt::Key_A && qtKey <= Qt::Key_Z)
return static_cast<WORD>('A' + (qtKey - Qt::Key_A));
if (qtKey >= Qt::Key_0 && qtKey <= Qt::Key_9)
return static_cast<WORD>('0' + (qtKey - Qt::Key_0));
if (qtKey >= Qt::Key_F1 && qtKey <= Qt::Key_F24)
return static_cast<WORD>(VK_F1 + (qtKey - Qt::Key_F1));
switch (qtKey) {
case Qt::Key_Escape: return VK_ESCAPE;
case Qt::Key_Tab: return VK_TAB;
case Qt::Key_Return:
case Qt::Key_Enter: return VK_RETURN;
case Qt::Key_Space: return VK_SPACE;
case Qt::Key_Backspace: return VK_BACK;
case Qt::Key_Delete: return VK_DELETE;
case Qt::Key_Insert: return VK_INSERT;
case Qt::Key_Home: return VK_HOME;
case Qt::Key_End: return VK_END;
case Qt::Key_PageUp: return VK_PRIOR;
case Qt::Key_PageDown: return VK_NEXT;
case Qt::Key_Left: return VK_LEFT;
case Qt::Key_Right: return VK_RIGHT;
case Qt::Key_Up: return VK_UP;
case Qt::Key_Down: return VK_DOWN;
case Qt::Key_Print: return VK_PRINT;
case Qt::Key_Pause: return VK_PAUSE;
default: return 0;
}
}
void ClickInjector::injectKeySequence(const QKeySequence& seq)
{
if (seq.isEmpty()) return;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QKeyCombination combo = seq[0];
int qtKey = static_cast<int>(combo.key());
Qt::KeyboardModifiers qtMods = combo.keyboardModifiers();
#else
int combined = seq[0];
int qtKey = combined & ~Qt::KeyboardModifierMask;
Qt::KeyboardModifiers qtMods = Qt::KeyboardModifiers(combined & Qt::KeyboardModifierMask);
#endif
WORD vk = qtKeyToVK(qtKey);
if (!vk) return;
if (qtMods & Qt::ControlModifier) sendKeyEvent(VK_CONTROL, true);
if (qtMods & Qt::AltModifier) sendKeyEvent(VK_MENU, true);
if (qtMods & Qt::ShiftModifier) sendKeyEvent(VK_SHIFT, true);
if (qtMods & Qt::MetaModifier) sendKeyEvent(VK_LWIN, true);
sendKeyEvent(vk, true);
sendKeyEvent(vk, false);
if (qtMods & Qt::MetaModifier) sendKeyEvent(VK_LWIN, false);
if (qtMods & Qt::ShiftModifier) sendKeyEvent(VK_SHIFT, false);
if (qtMods & Qt::AltModifier) sendKeyEvent(VK_MENU, false);
if (qtMods & Qt::ControlModifier) sendKeyEvent(VK_CONTROL, false);
}
// ─────────────────────────────────────────────────────────────
// macOS
// ─────────────────────────────────────────────────────────────
#elif defined(PLATFORM_MACOS)
#include <ApplicationServices/ApplicationServices.h>
#include <QCursor>
// NOTE: makeMouseEvent()/postMouse() used to live here. Both were dead — nothing
// called postMouse, and it was makeMouseEvent's only caller. performClick() posts
// its own events through a local `post` lambda that also carries the click count
// for double-clicks, which these two could not express. Removed rather than left
// in place: this file is the first thing an auditor reads (docs/INTERNAL.md §1),
// and unreachable event-injection helpers are exactly the wrong thing to find.
static void postKey(CGKeyCode key, bool down, CGEventFlags flags = 0)
{
CGEventRef ev = CGEventCreateKeyboardEvent(nullptr, key, down);
if (flags) CGEventSetFlags(ev, flags);
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
}
static CGEventFlags modsToCGFlags(int mods)
{
CGEventFlags f = 0;
if (mods & ModCtrl) f |= kCGEventFlagMaskControl;
if (mods & ModAlt) f |= kCGEventFlagMaskAlternate;
if (mods & ModShift) f |= kCGEventFlagMaskShift;
return f;
}
void ClickInjector::pressModifiers(int) {} // handled via CGEventFlags
void ClickInjector::releaseModifiers(int) {}
QPoint ClickInjector::cursorPos()
{
return QCursor::pos();
}
// Posting synthetic events with CGEventPost requires Accessibility permission;
// without it the events are silently dropped. Report the real trust state so the
// app can prompt the user instead of appearing to do nothing.
bool ClickInjector::hasInputDeviceAccess() { return AXIsProcessTrusted(); }
void ClickInjector::moveCursor(QPoint pos)
{
CGPoint pt{ static_cast<CGFloat>(pos.x()), static_cast<CGFloat>(pos.y()) };
CGEventRef ev = CGEventCreateMouseEvent(nullptr, kCGEventMouseMoved, pt, kCGMouseButtonLeft);
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
}
void ClickInjector::performClick(ClickType type, QPoint pos, int mods)
{
CGEventFlags flags = modsToCGFlags(mods);
CGPoint pt{ static_cast<CGFloat>(pos.x()), static_cast<CGFloat>(pos.y()) };
auto post = [&](CGEventType evType, CGMouseButton btn, int clickCount = 1) {
CGEventRef ev = CGEventCreateMouseEvent(nullptr, evType, pt, btn);
CGEventSetIntegerValueField(ev, kCGMouseEventClickState, clickCount);
if (flags) CGEventSetFlags(ev, flags);
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
};
// Per-button event types. kCGMouseButtonCenter is posted as "Other".
struct CGButton { CGEventType down; CGEventType up; CGMouseButton btn; };
auto cgButton = [](clickplan::Button b) -> CGButton {
switch (b) {
case clickplan::Button::Right:
return { kCGEventRightMouseDown, kCGEventRightMouseUp, kCGMouseButtonRight };
case clickplan::Button::Middle:
return { kCGEventOtherMouseDown, kCGEventOtherMouseUp, kCGMouseButtonCenter };
case clickplan::Button::Left:
case clickplan::Button::NoButton:
break;
}
return { kCGEventLeftMouseDown, kCGEventLeftMouseUp, kCGMouseButtonLeft };
};
const clickplan::Plan plan = clickplan::planFor(type);
switch (plan.action) {
case clickplan::Action::Click: {
// One down/up pair carrying the click count, *not* two pairs: Cocoa
// recognises a double-click from kCGMouseEventClickState, and repeating
// the pair produces two single clicks instead. See clickplan.h.
const CGButton b = cgButton(plan.button);
post(b.down, b.btn, plan.clickCount);
post(b.up, b.btn, plan.clickCount);
break;
}
case clickplan::Action::Press: {
const CGButton b = cgButton(plan.button);
post(b.down, b.btn);
break;
}
case clickplan::Action::Release: {
const CGButton b = cgButton(plan.button);
post(b.up, b.btn);
break;
}
case clickplan::Action::Scroll: {
const int amount = 10 * plan.direction;
const int vert = (plan.axis == clickplan::ScrollAxis::Vertical) ? amount : 0;
const int horiz = (plan.axis == clickplan::ScrollAxis::Horizontal) ? amount : 0;
CGEventRef ev = CGEventCreateScrollWheelEvent(
nullptr, kCGScrollEventUnitLine, 2, vert, horiz);
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
break;
}
case clickplan::Action::NoAction:
break;
}
}
static CGKeyCode qtKeyToCGKeyCode(int qtKey)
{
// US-layout key codes for letters (position-based; layout-independent for modifiers+letter)
static const CGKeyCode letterCodes[26] = {
0,11,8,2,14,3,5,4,34,38,40,37,46,45,31,35,12,15,1,17,32,9,13,7,16,6
};
if (qtKey >= Qt::Key_A && qtKey <= Qt::Key_Z)
return letterCodes[qtKey - Qt::Key_A];
static const CGKeyCode digitCodes[10] = {29,18,19,20,21,23,22,26,28,25};
if (qtKey >= Qt::Key_0 && qtKey <= Qt::Key_9)
return digitCodes[qtKey - Qt::Key_0];
static const CGKeyCode fKeyCodes[20] = {
122,120,99,118,96,97,98,100,101,109,103,111, // F1–F12
105,107,113,106,64,79,80,90 // F13–F20
};
if (qtKey >= Qt::Key_F1 && qtKey <= Qt::Key_F20)
return fKeyCodes[qtKey - Qt::Key_F1];
switch (qtKey) {
case Qt::Key_Escape: return 53;
case Qt::Key_Tab: return 48;
case Qt::Key_Return:
case Qt::Key_Enter: return 36;
case Qt::Key_Space: return 49;
case Qt::Key_Backspace: return 51;
case Qt::Key_Delete: return 117;
case Qt::Key_Home: return 115;
case Qt::Key_End: return 119;
case Qt::Key_PageUp: return 116;
case Qt::Key_PageDown: return 121;
case Qt::Key_Left: return 123;
case Qt::Key_Right: return 124;
case Qt::Key_Up: return 126;
case Qt::Key_Down: return 125;
default: return 0xFFFF;
}
}
void ClickInjector::injectKeySequence(const QKeySequence& seq)
{
if (seq.isEmpty()) return;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QKeyCombination combo = seq[0];
int qtKey = static_cast<int>(combo.key());
Qt::KeyboardModifiers qtMods = combo.keyboardModifiers();
#else
int combined = seq[0];
int qtKey = combined & ~Qt::KeyboardModifierMask;
Qt::KeyboardModifiers qtMods = Qt::KeyboardModifiers(combined & Qt::KeyboardModifierMask);
#endif
CGKeyCode kc = qtKeyToCGKeyCode(qtKey);
if (kc == 0xFFFF) return;
// On macOS, Qt maps physical Cmd → Qt::ControlModifier, physical Ctrl → Qt::MetaModifier
CGEventFlags flags = 0;
if (qtMods & Qt::ControlModifier) flags |= kCGEventFlagMaskCommand;
if (qtMods & Qt::MetaModifier) flags |= kCGEventFlagMaskControl;
if (qtMods & Qt::AltModifier) flags |= kCGEventFlagMaskAlternate;
if (qtMods & Qt::ShiftModifier) flags |= kCGEventFlagMaskShift;
postKey(kc, true, flags);
postKey(kc, false, flags);
}
// ─────────────────────────────────────────────────────────────
// Linux — uinput (Wayland + X11) with XTest fallback (X11 only)
// ─────────────────────────────────────────────────────────────
#elif defined(PLATFORM_LINUX)
// Qt headers must come before X11 headers (X11 defines Bool/Status macros)
#include <QCursor>
#include <QGuiApplication>
// ── uinput ────────────────────────────────────────────────────
#include <linux/input.h>
#include <linux/uinput.h>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <vector>
// ── XTest (X11 fallback) ──────────────────────────────────────
#include <X11/Xlib.h>
#include <X11/extensions/XTest.h>
#include <X11/keysym.h>
// ── XInput2 raw-motion (Wayland stale-position fix) ──────────
#ifdef HAVE_XI2
#include <X11/extensions/XInput2.h>
#endif
// ── uinput virtual pointer device ────────────────────────────
namespace {
struct UInputDev {
int fd = -1;
bool tryOpen()
{
fd = ::open("/dev/uinput", O_WRONLY | O_NONBLOCK);
if (fd < 0) return false;
ioctl(fd, UI_SET_EVBIT, EV_KEY);
ioctl(fd, UI_SET_EVBIT, EV_REL);
ioctl(fd, UI_SET_EVBIT, EV_SYN);
for (int b : {REL_X, REL_Y, REL_WHEEL, REL_HWHEEL})
ioctl(fd, UI_SET_RELBIT, b);
for (int b : {BTN_LEFT, BTN_RIGHT, BTN_MIDDLE})
ioctl(fd, UI_SET_KEYBIT, b);
struct uinput_setup us{};
us.id.bustype = BUS_USB;
us.id.vendor = 0x1234;
us.id.product = 0x5678;
std::strncpy(us.name, "TrackClick Virtual Mouse", UINPUT_MAX_NAME_SIZE - 1);
if (ioctl(fd, UI_DEV_SETUP, &us) < 0) { destroy(); return false; }
if (ioctl(fd, UI_DEV_CREATE) < 0) { destroy(); return false; }
return true;
}
void destroy()
{
if (fd >= 0) { ioctl(fd, UI_DEV_DESTROY); ::close(fd); fd = -1; }
}
bool isOpen() const { return fd >= 0; }
void send(uint16_t type, uint16_t code, int32_t val) const
{
struct input_event ev{};
ev.type = type;
ev.code = code;
ev.value = val;
(void)::write(fd, &ev, sizeof(ev));
}
void syn() const { send(EV_SYN, SYN_REPORT, 0); }
};
// Separate keyboard-only device so libinput classifies it as a keyboard and
// routes KEY_LEFTCTRL/ALT/SHIFT to the compositor's modifier state. A pointer
// device (EV_REL) is NOT classified as a keyboard by libinput even if it
// declares EV_KEY modifier keys, so modifier events from the mouse device are
// silently ignored on Wayland.
struct UInputKeyDev {
int fd = -1;
bool tryOpen()
{
fd = ::open("/dev/uinput", O_WRONLY | O_NONBLOCK);
if (fd < 0) return false;
ioctl(fd, UI_SET_EVBIT, EV_KEY);
ioctl(fd, UI_SET_EVBIT, EV_SYN);
for (int k : {KEY_LEFTCTRL, KEY_LEFTALT, KEY_LEFTSHIFT})
ioctl(fd, UI_SET_KEYBIT, k);
struct uinput_setup us{};
us.id.bustype = BUS_USB;
us.id.vendor = 0x1234;
us.id.product = 0x5679;
std::strncpy(us.name, "TrackClick Keyboard", UINPUT_MAX_NAME_SIZE - 1);
if (ioctl(fd, UI_DEV_SETUP, &us) < 0) { destroy(); return false; }
if (ioctl(fd, UI_DEV_CREATE) < 0) { destroy(); return false; }
// No extra sleep — the mouse device's 200 ms window covers both.
return true;
}
void destroy()
{
if (fd >= 0) { ioctl(fd, UI_DEV_DESTROY); ::close(fd); fd = -1; }
}
bool isOpen() const { return fd >= 0; }
void sendKey(int code, bool down) const
{
struct input_event ev{};
ev.type = EV_KEY;
ev.code = static_cast<uint16_t>(code);
ev.value = down ? 1 : 0;
(void)::write(fd, &ev, sizeof(ev));
struct input_event syn{};
syn.type = EV_SYN;
syn.code = SYN_REPORT;
(void)::write(fd, &syn, sizeof(syn));
}
};
UInputKeyDev& ukeydev()
{
static UInputKeyDev dev;
static bool tried = false;
if (!tried) { tried = true; dev.tryOpen(); }
return dev;
}
// Initialised on first use — tries uinput, falls back to XTest if denied.
// Both the mouse and keyboard devices are created before sleeping so one
// 200 ms compositor window covers both.
UInputDev& udev()
{
static UInputDev dev;
static bool tried = false;
if (!tried) {
tried = true;
if (dev.tryOpen()) {
ukeydev(); // create keyboard device in the same wake-up window
usleep(200'000);
}
}
return dev;
}
// ── XTest fallback helpers ────────────────────────────────────
Display* getDisplay()
{
static Display* dpy = XOpenDisplay(nullptr);
return dpy;
}
// ── Compositor-independent pointer motion via evdev ──────────────────────────
// XQueryPointer — and XWayland's XI2 raw motion — only report movement while the
// cursor is over an XWayland surface. Over native Wayland surfaces (a GTK
// browser, the file manager, …) they freeze, so the DwellManager never sees the
// cursor move and the dwell countdown fails to reset. Reading relative/absolute
// motion straight from the kernel's evdev nodes works no matter which compositor
// owns the pointer or which surface it is over. Requires read access to
// /dev/input/event* — the same "input" group access class that grants
// /dev/uinput — and falls back gracefully (to XI2, then XQueryPointer) when the
// nodes cannot be opened.
struct EvdevMotion {
struct Dev { int fd; int lastX; int lastY; bool haveLast; };
std::vector<Dev> devs;
bool opened = false;
void openAll()
{
opened = true;
int denied = 0, examined = 0;
for (int i = 0; i < 64; ++i) {
char path[32];
std::snprintf(path, sizeof(path), "/dev/input/event%d", i);
int fd = ::open(path, O_RDONLY | O_NONBLOCK);
if (fd < 0) {
if (errno == EACCES || errno == EPERM) ++denied;
continue;
}
++examined;
unsigned long relBits = 0, absBits = 0;
ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relBits)), &relBits);
ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBits)), &absBits);
const bool hasRel = (relBits & (1UL << REL_X)) && (relBits & (1UL << REL_Y));
const bool hasAbs = (absBits & (1UL << ABS_X)) && (absBits & (1UL << ABS_Y));
if (hasRel || hasAbs)
devs.push_back({fd, 0, 0, false}); // mouse / trackball / touchpad / tablet
else
::close(fd);
}
// One-time diagnostic — without a readable pointer device the dwell
// timer cannot detect motion over non-XWayland surfaces and will keep
// counting down regardless of how the cursor moves.
if (devs.empty()) {
qWarning("TrackClick: evdev motion tracking DISABLED — no readable "
"pointer device under /dev/input/event* (%d examined, %d "
"permission-denied). On Wayland the dwell timer can only "
"track motion while the cursor is over the TrackClick "
"window. Grant read access (e.g. add your user to the "
"'input' group) to track motion everywhere.", examined, denied);
} else {
qInfo("TrackClick: evdev motion tracking active on %d pointer "
"device(s).", static_cast<int>(devs.size()));
}
}
bool isOpen() const { return !devs.empty(); }
// Accumulated motion since the previous call, in device units. The exact
// scale is irrelevant — the DwellManager only needs to know the cursor
// moved. REL devices contribute their deltas directly; ABS devices
// contribute the change in absolute axis value.
QPoint drain()
{
int dx = 0, dy = 0;
struct input_event ev{};
for (auto& d : devs) {
while (::read(d.fd, &ev, sizeof(ev)) == static_cast<ssize_t>(sizeof(ev))) {
if (ev.type == EV_REL) {
if (ev.code == REL_X) dx += ev.value;
else if (ev.code == REL_Y) dy += ev.value;
} else if (ev.type == EV_ABS) {
if (ev.code == ABS_X) {
if (d.haveLast) dx += ev.value - d.lastX;
d.lastX = ev.value;
d.haveLast = true;
} else if (ev.code == ABS_Y) {
if (d.haveLast) dy += ev.value - d.lastY;
d.lastY = ev.value;
d.haveLast = true;
}
}
}
}
return QPoint(dx, dy);
}
};
EvdevMotion& evdev()
{
static EvdevMotion m;
if (!m.opened) m.openAll();
return m;
}
// ── XInput2 raw-motion (fallback when evdev nodes are not readable) ──────────
// Provides the same root-window hardware deltas as evdev for X11 sessions and
// XWayland surfaces. Only used when /dev/input/event* cannot be opened.
#ifdef HAVE_XI2
int g_xi2Opcode = -1;
bool g_xi2Subscribed = false;
void xi2Subscribe(Display* dpy)
{
int event, error;
if (!XQueryExtension(dpy, "XInputExtension", &g_xi2Opcode, &event, &error))
return;
int major = 2, minor = 0;
if (XIQueryVersion(dpy, &major, &minor) != Success)
return;
unsigned char bits[XIMaskLen(XI_RawMotion)] = {};
XIEventMask mask;
mask.deviceid = XIAllMasterDevices;
mask.mask = bits;
mask.mask_len = sizeof(bits);
XISetMask(bits, XI_RawMotion);
XISelectEvents(dpy, DefaultRootWindow(dpy), &mask, 1);
XFlush(dpy);
g_xi2Subscribed = true;
}
// Accumulated raw motion (dx, dy) since the previous call.
QPoint xi2DrainDelta(Display* dpy)
{
int dx = 0, dy = 0;
if (!g_xi2Subscribed || g_xi2Opcode < 0) return QPoint(0, 0);
while (XPending(dpy) > 0) {
XEvent ev;
XNextEvent(dpy, &ev);
if (ev.type != GenericEvent || ev.xcookie.extension != g_xi2Opcode) continue;
if (!XGetEventData(dpy, &ev.xcookie)) continue;
if (ev.xcookie.evtype == XI_RawMotion) {
const XIRawEvent* raw = static_cast<const XIRawEvent*>(ev.xcookie.data);
int idx = 0;
for (int a = 0; a < raw->valuators.mask_len * 8; ++a) {
if (XIMaskIsSet(raw->valuators.mask, a)) {
if (a == 0) dx += static_cast<int>(raw->raw_values[idx]);
if (a == 1) dy += static_cast<int>(raw->raw_values[idx]);
++idx;
}
}
}
XFreeEventData(dpy, &ev.xcookie);
}
return QPoint(dx, dy);
}
#endif // HAVE_XI2
void xtestFakeButton(int button, bool press, int mods = 0)
{
Display* dpy = getDisplay();
if (!dpy) return;
// Never send a motion event before the button event — on Wayland the
// compositor overrides the pointer position from the motion, causing
// snap-back. The cursor is already at the right location.
if (press) {
if (mods & ModCtrl) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Control_L), True, 0);
if (mods & ModAlt) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Alt_L), True, 0);
if (mods & ModShift) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Shift_L), True, 0);
}
XTestFakeButtonEvent(dpy, button, press ? True : False, 0);
if (!press) {
if (mods & ModShift) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Shift_L), False, 0);
if (mods & ModAlt) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Alt_L), False, 0);
if (mods & ModCtrl) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Control_L), False, 0);
}
XFlush(dpy);
}
void xtestClick(int button, int mods = 0)
{
xtestFakeButton(button, true, mods);
xtestFakeButton(button, false, mods);
}
} // namespace
// ── ClickInjector ─────────────────────────────────────────────
void ClickInjector::pressModifiers(int) {}
void ClickInjector::releaseModifiers(int) {}
QPoint ClickInjector::cursorPos()
{
Display* dpy = getDisplay();
if (!dpy) return QCursor::pos();
#ifdef HAVE_XI2
if (!g_xi2Subscribed) xi2Subscribe(dpy);
#endif
// Pull any pending motion from the compositor-independent source (evdev),
// falling back to XInput2 raw motion when the evdev nodes are not readable.
// estPos tracks the cursor across native Wayland surfaces where
// XQueryPointer freezes; it is re-anchored to XQueryPointer whenever that
// reading advances (cursor over an XWayland surface, or any X11 session).
static bool haveEst = false;
static QPoint estPos;
static QPoint lastXQuery;
static bool gotXQuery = false;
bool haveMotionSrc = false;
QPoint delta(0, 0);
if (evdev().isOpen()) {
delta = evdev().drain();
haveMotionSrc = true;
}
#ifdef HAVE_XI2
else {
delta = xi2DrainDelta(dpy);
haveMotionSrc = true;
}
#endif
if (haveEst && haveMotionSrc)
estPos += delta;
Window root = DefaultRootWindow(dpy);
Window root_ret, child_ret;
int rx, ry, wx, wy;
unsigned int mask;
if (!XQueryPointer(dpy, root, &root_ret, &child_ret, &rx, &ry, &wx, &wy, &mask))
return haveEst ? estPos : QCursor::pos();
const QPoint absPos(rx, ry);
const bool fresh = !gotXQuery || (absPos != lastXQuery);
lastXQuery = absPos;
gotXQuery = true;
// Without a kernel-level motion source we can only trust XQueryPointer. On
// X11 that is always accurate; on Wayland it is accurate while the cursor is
// over an XWayland surface — the best obtainable without evdev/XI2.
if (!haveMotionSrc)
return absPos;
if (fresh) {
// XQueryPointer advanced — authoritative reading (cursor over an
// XWayland surface, or any surface on X11). Re-anchor, clearing drift.
estPos = absPos;
haveEst = true;
return absPos;
}
// XQueryPointer is frozen — cursor is over a native Wayland surface. Use the
// motion-tracked estimate so the DwellManager still sees movement and resets.
if (!haveEst) { estPos = absPos; haveEst = true; }
return estPos;
}
bool ClickInjector::hasInputDeviceAccess() { return evdev().isOpen(); }
void ClickInjector::moveCursor(QPoint pos)
{
if (udev().isOpen()) {
QPoint cur = ClickInjector::cursorPos();
int dx = pos.x() - cur.x();
int dy = pos.y() - cur.y();
if (dx || dy) {
udev().send(EV_REL, REL_X, dx);
udev().send(EV_REL, REL_Y, dy);
udev().syn();
}
} else {
Display* dpy = getDisplay();
if (!dpy) return;
XTestFakeMotionEvent(dpy, -1, pos.x(), pos.y(), 0);
XFlush(dpy);
}
}
void ClickInjector::performClick(ClickType type, QPoint pos, int mods)
{
// Do not move the cursor before clicking. For a dwell clicker the cursor
// is already at the target; moving it causes snap-back on Wayland because
// QCursor::pos() is unreliable there and the computed delta is wrong.
Q_UNUSED(pos)
if (udev().isOpen()) {
auto& d = udev();
// Route modifier keys through the separate keyboard device so libinput
// classifies them correctly on Wayland. Each modifier gets its own
// SYN_REPORT so the compositor sees it before the mouse button event.
auto key = [&](int code, bool down) {
if (ukeydev().isOpen()) {
ukeydev().sendKey(code, down);
} else {
d.send(EV_KEY, static_cast<uint16_t>(code), down ? 1 : 0);
}
};
auto btn = [&](int code, bool down) {
if (down && (mods & ModCtrl)) key(KEY_LEFTCTRL, true);
if (down && (mods & ModAlt)) key(KEY_LEFTALT, true);
if (down && (mods & ModShift)) key(KEY_LEFTSHIFT, true);
d.send(EV_KEY, static_cast<uint16_t>(code), down ? 1 : 0);
d.syn();
if (!down && (mods & ModShift)) key(KEY_LEFTSHIFT, false);
if (!down && (mods & ModAlt)) key(KEY_LEFTALT, false);
if (!down && (mods & ModCtrl)) key(KEY_LEFTCTRL, false);
if (!down && !ukeydev().isOpen()) d.syn();
};
auto click = [&](int code) { btn(code, true); btn(code, false); };
auto evdevCode = [](clickplan::Button b) -> int {
switch (b) {
case clickplan::Button::Right: return BTN_RIGHT;
case clickplan::Button::Middle: return BTN_MIDDLE;
case clickplan::Button::Left:
case clickplan::Button::NoButton: break;
}
return BTN_LEFT;
};
const clickplan::Plan plan = clickplan::planFor(type);
switch (plan.action) {
case clickplan::Action::Click:
// Two full cycles for a double-click, as before — evdev carries no
// click-count field; the toolkit above infers it from timing.
for (int i = 0; i < plan.clickCount; ++i)
click(evdevCode(plan.button));
break;
case clickplan::Action::Press:
btn(evdevCode(plan.button), true);
break;
case clickplan::Action::Release:
btn(evdevCode(plan.button), false);
break;
case clickplan::Action::Scroll: {
const uint16_t axis = (plan.axis == clickplan::ScrollAxis::Horizontal)
? REL_HWHEEL : REL_WHEEL;
d.send(EV_REL, axis, plan.direction);
d.syn();
break;
}
case clickplan::Action::NoAction:
break;
}
} else {
// XTest fallback (X11 sessions without uinput access)
// X11 button map: 1=left 2=middle 3=right 4=scroll↑ 5=scroll↓ 6=scroll← 7=scroll→
auto x11Button = [](clickplan::Button b) -> int {
switch (b) {
case clickplan::Button::Middle: return 2;
case clickplan::Button::Right: return 3;
case clickplan::Button::Left:
case clickplan::Button::NoButton: break;
}
return 1;
};
// X11 has no wheel axis — scrolling is a click of buttons 4-7.
auto x11ScrollButton = [](clickplan::ScrollAxis axis, int dir) -> int {
if (axis == clickplan::ScrollAxis::Horizontal)
return dir > 0 ? 7 : 6; // right : left
return dir > 0 ? 4 : 5; // up : down
};
const clickplan::Plan plan = clickplan::planFor(type);
switch (plan.action) {
case clickplan::Action::Click:
for (int i = 0; i < plan.clickCount; ++i)
xtestClick(x11Button(plan.button), mods);
break;
case clickplan::Action::Press:
xtestFakeButton(x11Button(plan.button), true, mods);
break;
case clickplan::Action::Release:
xtestFakeButton(x11Button(plan.button), false, mods);
break;
case clickplan::Action::Scroll:
xtestClick(x11ScrollButton(plan.axis, plan.direction), mods);
break;
case clickplan::Action::NoAction:
break;
}
}
}
static KeySym qtKeyToKeySym(int qtKey)
{
if (qtKey >= Qt::Key_A && qtKey <= Qt::Key_Z)
return XK_a + (qtKey - Qt::Key_A);
if (qtKey >= Qt::Key_0 && qtKey <= Qt::Key_9)
return XK_0 + (qtKey - Qt::Key_0);
if (qtKey >= Qt::Key_F1 && qtKey <= Qt::Key_F12)
return XK_F1 + (qtKey - Qt::Key_F1);
if (qtKey >= Qt::Key_F13 && qtKey <= Qt::Key_F24)
return XK_F13 + (qtKey - Qt::Key_F13);
switch (qtKey) {
case Qt::Key_Escape: return XK_Escape;
case Qt::Key_Tab: return XK_Tab;
case Qt::Key_Return:
case Qt::Key_Enter: return XK_Return;
case Qt::Key_Space: return XK_space;
case Qt::Key_Backspace: return XK_BackSpace;
case Qt::Key_Delete: return XK_Delete;
case Qt::Key_Insert: return XK_Insert;
case Qt::Key_Home: return XK_Home;
case Qt::Key_End: return XK_End;
case Qt::Key_PageUp: return XK_Page_Up;
case Qt::Key_PageDown: return XK_Page_Down;
case Qt::Key_Left: return XK_Left;
case Qt::Key_Right: return XK_Right;
case Qt::Key_Up: return XK_Up;
case Qt::Key_Down: return XK_Down;
case Qt::Key_Print: return XK_Print;
case Qt::Key_Pause: return XK_Pause;
default: return NoSymbol;
}
}
void ClickInjector::injectKeySequence(const QKeySequence& seq)
{
if (seq.isEmpty()) return;
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QKeyCombination combo = seq[0];
int qtKey = static_cast<int>(combo.key());
Qt::KeyboardModifiers qtMods = combo.keyboardModifiers();
#else
int combined = seq[0];
int qtKey = combined & ~Qt::KeyboardModifierMask;
Qt::KeyboardModifiers qtMods = Qt::KeyboardModifiers(combined & Qt::KeyboardModifierMask);
#endif
// Use XTest for key injection — works on X11 and XWayland.
// On pure Wayland without XWayland, getDisplay() returns nullptr and this is a no-op.
Display* dpy = getDisplay();
if (!dpy) return;
KeySym ks = qtKeyToKeySym(qtKey);
if (ks == NoSymbol) return;
KeyCode kc = XKeysymToKeycode(dpy, ks);
if (!kc) return;
if (qtMods & Qt::ControlModifier) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Control_L), True, 0);
if (qtMods & Qt::AltModifier) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Alt_L), True, 0);
if (qtMods & Qt::ShiftModifier) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Shift_L), True, 0);
if (qtMods & Qt::MetaModifier) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Super_L), True, 0);
XTestFakeKeyEvent(dpy, kc, True, 0);
XTestFakeKeyEvent(dpy, kc, False, 0);
if (qtMods & Qt::MetaModifier) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Super_L), False, 0);
if (qtMods & Qt::ShiftModifier) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Shift_L), False, 0);
if (qtMods & Qt::AltModifier) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Alt_L), False, 0);
if (qtMods & Qt::ControlModifier) XTestFakeKeyEvent(dpy, XKeysymToKeycode(dpy, XK_Control_L), False, 0);
XFlush(dpy);
}
// ─────────────────────────────────────────────────────────────
// Fallback (unsupported platform — no-op)
// ─────────────────────────────────────────────────────────────
#else
#include <QDebug>
void ClickInjector::pressModifiers(int) {}
void ClickInjector::releaseModifiers(int) {}
void ClickInjector::moveCursor(QPoint) {}
QPoint ClickInjector::cursorPos() { return QCursor::pos(); }
bool ClickInjector::hasInputDeviceAccess() { return true; }
void ClickInjector::performClick(ClickType, QPoint, int)
{
qWarning() << "ClickInjector: unsupported platform — click not sent";
}
void ClickInjector::injectKeySequence(const QKeySequence&)
{
qWarning() << "ClickInjector::injectKeySequence: unsupported platform";
}
#endif