-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
2133 lines (1943 loc) · 93.5 KB
/
Copy pathmainwindow.cpp
File metadata and controls
2133 lines (1943 loc) · 93.5 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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "mainwindow.h"
#include "a11y.h"
#include "autostart.h"
#include "clickindicator.h"
#include "inputaccess.h"
#include "onscreenkeyboard.h"
#include "screenlayout.h"
#include "userid.h"
#include <QApplication>
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
# define GLOBAL_POS(ev) (ev)->globalPosition().toPoint()
#else
# define GLOBAL_POS(ev) (ev)->globalPos()
#endif
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QStyle>
#include <QMouseEvent>
#include <QPainter>
#include <QScreen>
#include <QGuiApplication>
#include <QDebug>
#include <QToolTip>
#include <QAction>
#include <QMessageBox>
#include <QFont>
#include <QToolButton>
#include <QIcon>
#include <QSize>
#include <QProcess>
#include <QSysInfo>
#include "translations/tsparser.h"
#ifdef Q_OS_MAC
# include "macos_utils.h"
# include <QDesktopServices>
# include <QUrl>
# include <QSysInfo>
#endif
// ─────────────────────────────────────────────────────────────
// Palette constants
// ─────────────────────────────────────────────────────────────
static const QColor COL_BG ("#2D2D2D");
static const QColor COL_ACCENT ("#FFA600");
static const QColor COL_BG_BTN ("#3A3A3A");
static const QColor COL_TEXT ("#FFFFFF");
static const QColor COL_SUBTEXT ("#AAAAAA");
static const QColor COL_DANGER ("#CC3333");
static const char* BASE_STYLE = R"(
QWidget {
background: #2D2D2D;
color: #FFFFFF;
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
font-size: 11px;
}
QProgressBar {
border: 1px solid #FFA600;
border-radius: 3px;
background: rgba(0,0,0,0.5);
text-align: center;
color: #FFA600;
font-size: 9px;
}
QProgressBar::chunk {
background: #FFA600;
border-radius: 2px;
}
QToolTip {
background: #1A1A1A;
color: #FFA600;
border: 1px solid #FFA600;
padding: 3px 6px;
}
)";
// ─────────────────────────────────────────────────────────────
// ClickButton
// ─────────────────────────────────────────────────────────────
ClickButton::ClickButton(const QString& label, ClickType type, QWidget* parent)
: QToolButton(parent), m_type(type)
{
setText(label);
setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
setMinimumSize(32, 44);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setCheckable(false);
#ifdef Q_OS_MAC
// macOS native style applies invisible layout-item margins around QToolButton
// that cause the grid to mis-align rows relative to Windows/Linux.
// WA_LayoutUsesWidgetRect tells the layout to use the visual rect instead.
setAttribute(Qt::WA_LayoutUsesWidgetRect);
#endif
updateStyle();
connect(this, &QToolButton::clicked, this, [this](){
emit clickTypePressed(m_type);
});
}
void ClickButton::setSelected(bool sel)
{
m_selected = sel;
updateStyle();
updateIcon();
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
void ClickButton::enterEvent(QEnterEvent* ev)
#else
void ClickButton::enterEvent(QEvent* ev)
#endif
{
QToolButton::enterEvent(ev);
emit clickTypeHovered(m_type);
}
void ClickButton::leaveEvent(QEvent* ev)
{
QToolButton::leaveEvent(ev);
emit clickTypeLeft();
}
void ClickButton::setButtonIcon(const QString& iconName)
{
m_iconName = iconName;
updateIcon();
}
void ClickButton::setLargeMode(bool large)
{
m_large = large;
updateStyle();
if (!m_iconName.isEmpty()) {
const int sz = large ? 54 : 36;
setIconSize(QSize(sz, sz));
}
}
void ClickButton::updateIcon()
{
if (m_iconName.isEmpty()) return;
const QString path = m_selected
? ":/icons/selected/" + m_iconName + ".svg"
: ":/icons/" + m_iconName + ".svg";
setIcon(QIcon(path));
}
void ClickButton::updateStyle()
{
const char* fs = m_large ? "14px" : "11px";
const char* pad = m_large ? "6px 4px" : "4px 2px";
if (m_selected) {
setStyleSheet(QString(
"QToolButton {"
" background: #FFA600;"
" color: #1A1A1A;"
" border: 2px solid #FFB833;"
" border-radius: 5px;"
" font-weight: bold;"
" font-size: %1;"
" padding: %2;"
"}"
"QToolButton:hover { background: #FFB833; }"
"QToolButton:pressed { background: #CC8400; }"
).arg(fs).arg(pad));
} else {
setStyleSheet(QString(
"QToolButton {"
" background: #3A3A3A;"
" color: #DDDDDD;"
" border: 2px solid #555555;"
" border-radius: 5px;"
" font-size: %1;"
" padding: %2;"
"}"
"QToolButton:hover {"
" background: #4A4A4A;"
" border: 2px solid #FFA600;"
" color: #FFA600;"
"}"
"QToolButton:pressed { background: #2A2A2A; }"
).arg(fs).arg(pad));
}
}
// The click-confirmation overlay moved to clickindicator.{h,cpp}: its placement
// rules are subtle and platform-specific, and they read better as their own unit
// than as a nested class in the middle of the window code.
// ─────────────────────────────────────────────────────────────
// MainWindow
// ─────────────────────────────────────────────────────────────
MainWindow::MainWindow(QTranslator* startupTranslator, QWidget* parent)
: QWidget(parent)
, m_persist("TrackClick", "TrackClick")
{
// Load persisted settings
m_settings.dwellMs = m_persist.value("dwell/ms", 1000).toInt();
m_settings.sensitivityPx = m_persist.value("dwell/sensitivity", 5).toInt();
m_settings.windowOpacity = m_persist.value("window/opacity", 1.0).toDouble();
m_settings.alwaysOnTop = m_persist.value("window/alwaysOnTop", true).toBool();
m_settings.showNoClick = m_persist.value("show/noClick", true).toBool();
m_settings.showLeftClick = m_persist.value("show/leftClick", true).toBool();
m_settings.showLeftDouble = m_persist.value("show/leftDouble", true).toBool();
m_settings.showLeftDrag = m_persist.value("show/leftDrag", true).toBool();
m_settings.showRightClick = m_persist.value("show/rightClick", true).toBool();
m_settings.showRightDouble = m_persist.value("show/rightDouble", true).toBool();
m_settings.showRightDrag = m_persist.value("show/rightDrag", true).toBool();
// Right Double / Right Drag are disabled actions (unusual). Force them off
// regardless of any persisted or default "on" value, so the toolbar buttons
// never appear. They're also omitted from the Settings reorder list. To
// re-enable, remove these two overrides and add them to that list.
m_settings.showRightDouble = false;
m_settings.showRightDrag = false;
m_settings.showMiddleClick = m_persist.value("show/middleClick", true).toBool();
m_settings.showMiddleDouble= m_persist.value("show/middleDouble",false).toBool();
m_settings.showScrollUp = m_persist.value("show/scrollUp", true).toBool();
m_settings.showScrollDown = m_persist.value("show/scrollDown", true).toBool();
m_settings.showScrollHoriz = m_persist.value("show/scrollHoriz", false).toBool();
m_settings.showModCtrl = m_persist.value("show/modCtrl", true).toBool();
m_settings.showModAlt = m_persist.value("show/modAlt", true).toBool();
m_settings.showModShift = m_persist.value("show/modShift", true).toBool();
m_settings.showQuitButton = m_persist.value("show/quitButton", true).toBool();
m_settings.showDwellActiveBtn= m_persist.value("show/dwellActiveBtn", true).toBool();
m_settings.showKeyboardButton= m_persist.value("show/keyboardButton", false).toBool();
m_settings.startMinimized = m_persist.value("window/startMin", false).toBool();
m_settings.xMinimizesApp = m_persist.value("window/xMinimizesApp", false).toBool();
// Top X minimizes app is a read-only option locked off: the top X always
// quits. Force it off regardless of any persisted value. To re-enable,
// remove this override — see settingsdialog.cpp buildUi.
m_settings.xMinimizesApp = false;
m_settings.launchOnStartup = m_persist.value("window/launchOnStartup", false).toBool();
m_settings.minimalWidth = m_persist.value("window/minimalWidth", false).toBool();
m_settings.minimalWidthPx = m_persist.value("window/minimalWidthPx", 0).toInt();
m_settings.audioFeedback = m_persist.value("audio/enabled", false).toBool();
m_settings.showClickIndicator = m_persist.value("visual/clickIndicator", AppSettings{}.showClickIndicator).toBool();
m_settings.usageReporting = m_persist.value("privacy/usageReporting", true).toBool();
m_settings.audioClickEnabled = m_persist.value("audioClick/enabled", false).toBool();
m_settings.audioClickThreshold = m_persist.value("audioClick/threshold", 50).toInt();
m_settings.audioInputDevice = m_persist.value("audioClick/device", "").toString();
m_settings.iconsOnly = m_persist.value("show/iconsOnly", false).toBool();
m_settings.largeButtons = m_persist.value("show/largeButtons", false).toBool();
m_settings.buttonLayout = static_cast<ButtonLayout>(m_persist.value("show/buttonLayout", static_cast<int>(ButtonLayout::Vertical)).toInt());
m_settings.language = m_persist.value("language", "en").toString();
m_settings.settingsFontScale = m_persist.value("settings/fontScale", 100).toInt();
m_settings.buttonOrder = m_persist.value("show/buttonOrder").toStringList();
m_settings.scrollRepeat = m_persist.value("scroll/repeat", 7).toInt();
m_settings.repeatOnDwell = m_persist.value("dwell/repeatOnDwell", false).toBool();
m_settings.returnToLeftAfterClick = m_persist.value("dwell/returnToLeftAfterClick", false).toBool();
m_settings.hoverSelectPercent = m_persist.value("dwell/hoverSelectPercent", 60).toInt();
m_settings.edgeLock = static_cast<EdgeLock>(m_persist.value("window/edgeLock", 0).toInt());
m_settings.edgeHide = m_persist.value("window/edgeHide", false).toBool();
for (int i = 0; i < 3; ++i) {
const QString base = QString("hotkey/%1/").arg(i);
m_settings.hotkeys[i].enabled = m_persist.value(base + "enabled", false).toBool();
m_settings.hotkeys[i].label = m_persist.value(base + "label", "").toString();
m_settings.hotkeys[i].keySequence = m_persist.value(base + "seq", "").toString();
}
// Adopt any translator already installed at startup so installLanguage()
// can remove it when the user later switches languages (e.g. back to English).
if (startupTranslator) {
m_translator = startupTranslator;
m_translator->setParent(this); // transfer ownership from QApplication
}
// Window flags: frameless, stays on top
Qt::WindowFlags flags = Qt::Window | Qt::FramelessWindowHint | Qt::Tool;
if (m_settings.alwaysOnTop) flags |= Qt::WindowStaysOnTopHint;
setWindowFlags(flags);
setAttribute(Qt::WA_TranslucentBackground, false);
// On macOS, Qt::Tool creates an NSPanel that hides when another app becomes
// active (hidesOnDeactivation = true by default). This attribute disables
// that behaviour so the toolbar stays visible regardless of focus.
setAttribute(Qt::WA_MacAlwaysShowToolWindow);
#ifdef Q_OS_MAC
// Keep the window visible during Mission Control / Exposé and on all Spaces.
// Must be called after setWindowFlags (which can recreate the native handle).
applyMacOSWindowBehavior(winId());
#endif
setStyleSheet(BASE_STYLE);
setWindowTitle(tr("TrackClick"));
setWindowOpacity(m_settings.windowOpacity);
m_dwell = new DwellManager(this);
m_dwell->setDwellMs(m_settings.dwellMs);
m_dwell->setSensitivityPx(m_settings.sensitivityPx);
m_dwell->setScrollRepeat(m_settings.scrollRepeat);
m_dwell->setRepeatOnDwell(m_settings.repeatOnDwell);
// Quitting mid-drag (Quit button, tray menu, window close) would otherwise
// leave the mouse button held down system-wide with nothing left running to
// release it — an unrecoverable state for a user whose only pointing device
// is this app. Release here, while the event loop and the platform injector
// are still healthy; ~DwellManager repeats it as a no-op safety net.
// This covers the graceful paths only: an uncaught signal or a crash still
// skips both, and the in-poll 10-second safety release cannot help once the
// process is gone. A signal handler would be the way to close that gap.
connect(qApp, &QCoreApplication::aboutToQuit, m_dwell,
[this]{ m_dwell->releaseHeldButton(); });
#ifdef HAVE_MULTIMEDIA
m_clickSound = new QSoundEffect(this);
m_clickSound->setSource(QUrl("qrc:/sounds/click-noise.wav"));
// Audio click: a loud sound fires the armed action instead of the dwell
// timer. The listener is only started while dwell-active is on (see
// updateAudioClick()); here we just wire the trigger.
m_audioClick = new AudioClickListener(this);
connect(m_audioClick, &AudioClickListener::noiseDetected, this, [this]{
if (m_settings.audioClickEnabled && m_autoEnabled)
m_dwell->fireNow();
});
#endif
m_hoverTimer = new QTimer(this);
m_hoverTimer->setSingleShot(true);
connect(m_hoverTimer, &QTimer::timeout, this, [this](){
if (m_hoveredHotkey >= 0) {
onHotkeySelected(m_hoveredHotkey);
} else if (m_hoveredType != ClickType::None) {
setClickType(m_hoveredType);
if (m_autoEnabled)
m_dwell->arm(m_hoveredType, m_modifiers);
}
});
connect(m_dwell, &DwellManager::dwellProgress, this, &MainWindow::onDwellProgress);
connect(m_dwell, &DwellManager::dwellFired, this, &MainWindow::onDwellFired);
m_clickIndicator = new ClickIndicatorOverlay();
buildUi();
buildTray();
loadWindowSettings();
// Recover from display-layout changes at runtime. Deferred to the next event
// loop pass: when screenRemoved fires the window system has not necessarily
// finished reshuffling the remaining screens, and the QScreen being removed is
// deleted right after, so anything measured inside the handler can be stale.
for (auto sig : { &QGuiApplication::screenRemoved, &QGuiApplication::screenAdded })
connect(qApp, sig, this, [this](QScreen*) {
QTimer::singleShot(0, this, [this]{ ensureOnScreen(); });
});
// Swallow tooltip pop-ups over the toolbar (see eventFilter).
qApp->installEventFilter(this);
// If launch-on-startup is enabled, make sure the OS registration still
// exists and points at the current executable (self-heals after updates).
syncLaunchOnStartup();
// Put the dwell manager into audio-trigger mode if the persisted setting
// asks for it (the microphone only opens once dwell-active is turned on).
updateAudioClick();
// ── Usage reporting ──────────────────────────────────────────────────────
// Count this launch against the active-user statistics, along with the
// clicking mode it starts in. Asynchronous and best-effort: a failed or
// blocked report never surfaces in the UI.
m_usage = new UsageReportingManager(this);
// Apply the persisted opt-out before the first report, so a user who has
// opted out never sends anything on subsequent launches.
m_usage->setReportingEnabled(m_settings.usageReporting);
// Stable across launches, but salted with a local random value that is never
// reported, so the digest cannot be walked back to this machine (userid.h).
// Only minted when the user has not opted out — an opted-out install writes
// no identifier at all.
if (m_settings.usageReporting)
m_usage->setUserId(UserId::hashedUserId(m_persist));
{
StartupReportPayload payload;
payload.operatingSystem = QSysInfo::prettyProductName();
payload.softwareType = QStringLiteral("TrackClick");
payload.softwareVersion = QCoreApplication::applicationVersion();
payload.clickingMode = currentClickingMode();
m_usage->setStartupPayload(payload);
}
m_usage->sendStartupReport();
// Send anything still unreported while the event loop is alive; the
// manager's destructor would otherwise have to do it during teardown.
connect(qApp, &QCoreApplication::aboutToQuit, m_usage, [this]{ m_usage->shutdown(); });
}
void MainWindow::promptForInputAccessIfNeeded()
{
#ifdef Q_OS_LINUX
if (ClickInjector::hasInputDeviceAccess())
return;
// Respect a previous "Don't ask again" choice.
if (m_persist.value("linux/skipInputAccessPrompt", false).toBool())
return;
QMessageBox box(this);
box.setIcon(QMessageBox::Question);
box.setWindowTitle(tr("Enable cursor tracking"));
box.setText(tr("TrackClick needs permission to read mouse movement."));
box.setInformativeText(tr(
"Without it, dwell-clicking only works while the cursor is over the "
"TrackClick window. Granting permission installs a small system rule "
"and shows a password prompt — no terminal required."));
QPushButton* grant = box.addButton(tr("Grant Permission…"), QMessageBox::AcceptRole);
box.addButton(tr("Not Now"), QMessageBox::RejectRole);
QPushButton* never = box.addButton(tr("Don't Ask Again"), QMessageBox::ActionRole);
box.setDefaultButton(grant);
box.exec();
if (box.clickedButton() == never)
m_persist.setValue("linux/skipInputAccessPrompt", true);
// Only proceed on an explicit Grant; "Not Now", "Don't Ask Again" and
// dismissing the dialog all leave permissions unchanged.
if (box.clickedButton() != grant)
return;
// Grant: install the bundled udev rule as root. The privileged work itself
// lives in inputaccess.cpp so that "what do we run as root?" is answerable
// from one short, UI-free file (docs/INTERNAL.md §3); every message stays
// here, which also keeps these strings in the MainWindow translation context.
switch (InputAccess::installUdevRule()) {
case InputAccess::InstallResult::RuleUnavailable:
QMessageBox::warning(this, tr("TrackClick"),
tr("Internal error: the permission rule could not be loaded."));
return;
case InputAccess::InstallResult::TempFileFailed:
QMessageBox::warning(this, tr("TrackClick"),
tr("Could not create a temporary file for the permission rule."));
return;
case InputAccess::InstallResult::HelperMissing:
// pkexec unavailable — fall back to copyable manual instructions.
QMessageBox::information(this, tr("TrackClick"),
tr("Could not launch the graphical authentication helper (pkexec).\n\n"
"To enable full cursor tracking, install this file as root:\n %1\n\n"
"with the following contents:\n\n%2")
.arg(InputAccess::ruleDestinationPath(), InputAccess::bundledRuleText()));
return;
case InputAccess::InstallResult::Installed:
QMessageBox::information(this, tr("TrackClick"),
tr("Permission granted. Please restart TrackClick to enable cursor "
"tracking across all windows."));
return;
case InputAccess::InstallResult::Refused:
QMessageBox::warning(this, tr("TrackClick"),
tr("Permission was not granted. TrackClick will ask again next time "
"it starts. (On an X11/Xorg session this permission is not needed.)"));
return;
}
#elif defined(Q_OS_MAC)
if (ClickInjector::hasInputDeviceAccess())
return; // already trusted for Accessibility
// Respect a previous "Don't ask again" choice.
if (m_persist.value("mac/skipAccessibilityPrompt", false).toBool())
return;
QMessageBox box(this);
box.setIcon(QMessageBox::Question);
box.setWindowTitle(tr("Enable clicking"));
box.setText(tr("TrackClick needs Accessibility permission to move and click the mouse."));
box.setInformativeText(tr(
"Until it's granted in System Settings ▸ Privacy & Security ▸ Accessibility, "
"the dwell countdown runs but no click is performed. You can also reach this "
"later from the Settings dialog."));
QPushButton* grant = box.addButton(tr("Open Accessibility Settings…"), QMessageBox::AcceptRole);
box.addButton(tr("Not Now"), QMessageBox::RejectRole);
QPushButton* never = box.addButton(tr("Don't Ask Again"), QMessageBox::ActionRole);
box.setDefaultButton(grant);
box.exec();
if (box.clickedButton() == never)
m_persist.setValue("mac/skipAccessibilityPrompt", true);
if (box.clickedButton() != grant)
return;
// Register TrackClick in the Accessibility list and trigger macOS's own
// prompt, then open the pane so the user can flip the switch. The grant
// only takes effect after a relaunch.
macAccessibilityTrusted(/*promptIfNeeded=*/true);
QDesktopServices::openUrl(QUrl(
"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"));
QMessageBox::information(this, tr("TrackClick"),
tr("Enable TrackClick in the Accessibility list, then restart the app."));
#endif
}
void MainWindow::buildUi()
{
setMouseTracking(true); // needed for cursor updates without a button held
auto* root = new QVBoxLayout(this);
root->setSpacing(0);
root->setContentsMargins(0, 0, 0, 0);
// ── Title bar ─────────────────────────────────────────────
m_titleBar = new QWidget;
m_titleBar->setObjectName("titleBar");
m_titleBar->setFixedHeight(30);
m_titleBar->setStyleSheet(
"#titleBar { background: #1A1A1A; border-bottom: 2px solid #FFA600; }"
"QLabel { color: #FFA600; font-weight: bold; font-size: 12px;"
" background: transparent; border: none; }"
);
auto* tbLayout = new QHBoxLayout(m_titleBar);
tbLayout->setContentsMargins(8, 0, 4, 0);
tbLayout->setSpacing(4);
m_titleIcon = new QLabel;
m_titleIcon->setPixmap(QIcon(":/icons/app.svg").pixmap(16, 16));
m_titleIcon->setFixedSize(20, 20);
m_titleIcon->setAlignment(Qt::AlignCenter);
tbLayout->addWidget(m_titleIcon);
m_titleLabel = new QLabel(tr("TrackClick"));
m_titleLabel->setMinimumWidth(0); // let it clip rather than force window wider
tbLayout->addWidget(m_titleLabel);
// Injection-status dot: a small circle that turns red when TrackClick cannot
// deliver clicks (most commonly a missing OS permission). Clicking it opens
// the permission flow when blocked, or the Settings ▸ Diagnostics tab when
// healthy, so a confused user has an obvious next step.
m_statusDot = new QPushButton;
m_statusDot->setFixedSize(14, 14);
m_statusDot->setFocusPolicy(Qt::NoFocus);
m_statusDot->setCursor(Qt::PointingHandCursor);
connect(m_statusDot, &QPushButton::clicked, this, [this]() {
if (!ClickInjector::hasInputDeviceAccess())
promptForInputAccessIfNeeded();
else
onSettingsClicked();
});
tbLayout->addWidget(m_statusDot);
tbLayout->addStretch(1); // always pushes the action buttons to the right
// Auto button
m_autoBtn = new QPushButton;
m_autoBtn->setIcon(QIcon(":/icons/auto.svg"));
m_autoBtn->setIconSize(QSize(18, 18));
m_autoBtn->setCheckable(true);
m_autoBtn->setFixedSize(38, 22);
m_autoBtn->setToolTip(tr("Toggle AutoMouse dwell-clicking"));
m_autoBtn->setStyleSheet(
"QPushButton { background:#3A3A3A; color:#DDDDDD; border:1px solid #555; border-radius:3px; font-size:10px; font-weight:bold; }"
"QPushButton:checked { background:#FFA028; color:#1A1A1A; border:1px solid #FFB040; }"
"QPushButton:hover { border:1px solid #FFA028; }"
);
connect(m_autoBtn, &QPushButton::toggled, this, &MainWindow::onAutoToggled);
tbLayout->addWidget(m_autoBtn);
// Settings button
m_settingsBtn = new QPushButton;
m_settingsBtn->setIcon(QIcon(":/icons/settings.svg"));
m_settingsBtn->setIconSize(QSize(16, 16));
m_settingsBtn->setFixedSize(22, 22);
m_settingsBtn->setToolTip(tr("Settings"));
m_settingsBtn->setStyleSheet(
"QPushButton { background:#3A3A3A; color:#CCC; border:1px solid #555; border-radius:3px; font-size:14px; }"
"QPushButton:hover { background:#4A4A4A; color:#FFA600; border:1px solid #FFA600; }"
"QPushButton:pressed { background:#2A2A2A; }"
);
connect(m_settingsBtn, &QPushButton::clicked, this, &MainWindow::onSettingsClicked);
tbLayout->addWidget(m_settingsBtn);
// Close/hide button
m_exitBtn = new QPushButton;
m_exitBtn->setIcon(QIcon(":/icons/close.svg"));
m_exitBtn->setIconSize(QSize(14, 14));
m_exitBtn->setFixedSize(22, 22);
m_exitBtn->setToolTip(tr("Hide to tray (right-click tray icon to quit)"));
m_exitBtn->setStyleSheet(
"QPushButton { background:#3A3A3A; color:#CCC; border:1px solid #555; border-radius:3px; font-size:12px; }"
"QPushButton:hover { background:#CC3333; color:#FFF; border:1px solid #CC3333; }"
"QPushButton:pressed { background:#991111; }"
);
connect(m_exitBtn, &QPushButton::clicked, this, &MainWindow::onExitClicked);
tbLayout->addWidget(m_exitBtn);
root->addWidget(m_titleBar);
// ── Button area ───────────────────────────────────────────
m_btnArea = new QWidget;
m_btnArea->setContentsMargins(6, 6, 6, 6);
root->addWidget(m_btnArea);
rebuildButtons();
// ── Dwell progress bar ────────────────────────────────────
m_dwellBar = new QProgressBar;
m_dwellBar->setRange(0, 100);
m_dwellBar->setValue(0);
m_dwellBar->setFixedHeight(8);
m_dwellBar->setTextVisible(false);
m_dwellBar->setMinimumWidth(0);
m_dwellBar->setVisible(false);
root->addWidget(m_dwellBar);
// ── Audio level meter ─────────────────────────────────────
// Same footprint as the dwell bar but a distinct (green) colour, shown in its
// place while audio-click mode is active so the two modes read differently.
m_audioMeter = new QProgressBar;
m_audioMeter->setRange(0, 100);
m_audioMeter->setValue(0);
m_audioMeter->setFixedHeight(8);
m_audioMeter->setTextVisible(false);
m_audioMeter->setMinimumWidth(0);
// Cyan (vs the dwell bar's orange) so the active mode is obvious at a glance,
// and matched to the settings calibration meter for cross-screen correlation.
m_audioMeter->setStyleSheet(
"QProgressBar { border: 1px solid #00A5B8; border-radius: 3px;"
" background: rgba(0,0,0,0.5); }"
"QProgressBar::chunk { background: #00EBFF; border-radius: 2px; }");
m_audioMeter->setVisible(false);
root->addWidget(m_audioMeter);
#ifdef HAVE_MULTIMEDIA
if (m_audioClick) {
connect(m_audioClick, &AudioClickListener::level, this, [this](double v){
if (m_audioMeter->isVisible())
m_audioMeter->setValue(static_cast<int>(qBound(0.0, v, 1.0) * 100));
});
}
#endif
// ── Status label ──────────────────────────────────────────
m_statusLabel = new QLabel("Ready — hover to dwell-click");
m_statusLabel->setStyleSheet(
"QLabel { color: #888888; font-size: 9px; padding: 2px 6px; "
"background: #1A1A1A; border-top: 1px solid #3A3A3A; }"
);
m_statusLabel->setFixedHeight(18);
m_statusLabel->setMinimumWidth(0);
m_statusLabel->setVisible(false);
root->addWidget(m_statusLabel);
// Keep the injection-status dot current: access can be granted while the app
// runs (e.g. the user flips the macOS Accessibility switch), so poll it.
m_statusTimer = new QTimer(this);
m_statusTimer->setInterval(2000);
connect(m_statusTimer, &QTimer::timeout, this, &MainWindow::updateStatusDot);
m_statusTimer->start();
updateAccessibleNames();
updateStatusDot();
adjustSize();
}
void MainWindow::updateAccessibleNames()
{
// Names stay short — they are announced every time focus reaches the control
// — with the sentence-length explanation going in the description, which is
// the same text sighted users get as a tooltip.
a11y::setName(m_statusDot, tr("Injection status"));
// Description is state-dependent and set by updateStatusDot().
a11y::setName(m_autoBtn, tr("AutoMouse"),
tr("Toggle AutoMouse dwell-clicking"));
a11y::setName(m_settingsBtn, tr("Settings"));
a11y::setName(m_exitBtn,
m_settings.xMinimizesApp ? tr("Hide to tray") : tr("Close"),
m_settings.xMinimizesApp
? tr("Hide to tray (right-click tray icon to quit)")
: tr("Close application"));
// Progress bars report their value themselves; what they lack is any way to
// say which of the two is on screen — they occupy the same slot and differ
// only by colour.
a11y::setName(m_dwellBar, tr("Dwell progress"));
a11y::setName(m_audioMeter, tr("Microphone level"));
}
void MainWindow::updateStatusDot()
{
if (!m_statusDot)
return;
const bool ok = ClickInjector::hasInputDeviceAccess();
// hasInputDeviceAccess() means different things per platform, so tailor the
// tooltip: on macOS it is the Accessibility grant that gates clicking; on
// Linux it is pointer-tracking (evdev) access used on Wayland; on Windows
// injection is always available.
QString tip;
if (ok) {
tip = tr("Click injection is available. Click for diagnostics.");
} else {
#if defined(Q_OS_MAC)
tip = tr("Clicks are disabled — Accessibility permission not granted. "
"Click to fix.");
#elif defined(Q_OS_LINUX)
tip = tr("Pointer-tracking access is unavailable (needed on Wayland). "
"Click to fix.");
#else
tip = tr("Click injection is unavailable. Click for diagnostics.");
#endif
}
m_statusDot->setToolTip(tip);
// The dot conveys its state through colour alone, so the state has to reach a
// screen reader some other way: the name stays "Injection status" and the
// description carries the healthy/blocked text.
m_statusDot->setAccessibleDescription(tip);
const QString colour = ok ? "#3FB950" : "#E5534B"; // green / red
const QString ring = ok ? "#2A6E33" : "#7A2A26";
m_statusDot->setStyleSheet(QString(
"QPushButton { background: %1; border: 1px solid %2; border-radius: 7px; }"
"QPushButton:hover { border: 1px solid #FFA600; }"
).arg(colour, ring));
}
// Attaches hover-toggle behaviour to a modifier QPushButton: the button toggles
// once the cursor has rested on it for the hover-select interval — the same
// timing used to switch the active click type (see hoverSelectMs()). The
// interval is supplied as a callback so it is read fresh on each hover.
// Parented to the button so it is deleted automatically with it.
class ModHoverFilter : public QObject {
public:
explicit ModHoverFilter(QPushButton* btn, std::function<int()> intervalFn)
: QObject(btn), m_intervalFn(std::move(intervalFn))
{
m_timer = new QTimer(this);
m_timer->setSingleShot(true);
QObject::connect(m_timer, &QTimer::timeout, btn, [btn](){ btn->toggle(); });
btn->installEventFilter(this);
}
protected:
bool eventFilter(QObject*, QEvent* ev) override
{
if (ev->type() == QEvent::Enter)
m_timer->start(m_intervalFn());
else if (ev->type() == QEvent::Leave)
m_timer->stop();
return false;
}
private:
QTimer* m_timer;
std::function<int()> m_intervalFn;
};
// Forwards Enter/Leave events for a hotkey button to lambdas so the shared
// hover-select timer can select the hotkey just like a ClickButton selection.
class HotkeyHoverFilter : public QObject {
public:
HotkeyHoverFilter(QWidget* btn,
std::function<void()> onEnter,
std::function<void()> onLeave)
: QObject(btn), m_onEnter(std::move(onEnter)), m_onLeave(std::move(onLeave))
{ btn->installEventFilter(this); }
protected:
bool eventFilter(QObject*, QEvent* ev) override
{
if (ev->type() == QEvent::Enter) m_onEnter();
else if (ev->type() == QEvent::Leave) m_onLeave();
return false;
}
private:
std::function<void()> m_onEnter, m_onLeave;
};
// Returns the stylesheet for a modifier/hotkey button in its selected or
// unselected state. Used by rebuildButtons, setClickType, and onHotkeySelected.
static QString modBtnStyle(bool selected, bool large)
{
const char* fs = large ? "14px" : "11px";
const char* pad = large ? "4px" : "2px";
return selected
? QString("QPushButton { background:#FFA600; color:#1A1A1A; border:2px solid #FFB833; "
"border-radius:4px; font-weight:bold; font-size:%1; padding:%2; }"
"QPushButton:hover { background:#FFB833; }").arg(fs).arg(pad)
: QString("QPushButton { background:#3A3A3A; color:#DDDDDD; border:1px solid #555; "
"border-radius:4px; font-size:%1; padding:%2; }"
"QPushButton:hover { background:#4A4A4A; border:1px solid #FFA600; color:#FFA600; }").arg(fs).arg(pad);
}
// Style for the on-screen-keyboard toggle button. "on" (keyboard open) uses the
// same amber highlight as the Dwell Active toggle; "off" matches the modifier
// buttons. Shared by makeKeyboard() and refreshKeyboardButton() so the look
// stays in sync whether the state changes by click or by the keyboard closing.
static QString kbdBtnStyle(bool on, bool large)
{
const char* fs = large ? "14px" : "11px";
const char* pad = large ? "4px" : "2px";
return on
? QString("QPushButton { background:#FFA028; color:#1A1A1A; border:2px solid #FFB040; "
"border-radius:4px; font-weight:bold; font-size:%1; padding:%2; }"
"QPushButton:hover { background:#FFB040; }").arg(fs).arg(pad)
: QString("QPushButton { background:#3A3A3A; color:#DDDDDD; border:1px solid #555; "
"border-radius:4px; font-size:%1; padding:%2; }"
"QPushButton:hover { background:#4A4A4A; border:1px solid #FFA028; color:#FFA028; }").arg(fs).arg(pad);
}
// Uniform minimum cell size for every toolbar button, so click buttons,
// modifiers, Dwell Active, Quit and hotkeys share the same footprint and line
// up in the grid regardless of which are shown. Width is 0 in the vertical
// modes (the single/double columns stretch); fixed otherwise.
static QSize toolbarButtonMinSize(ButtonLayout layout, bool large)
{
switch (layout) {
case ButtonLayout::Horizontal: return QSize(60, large ? 72 : 54);
case ButtonLayout::Rectangle: return QSize(48, large ? 64 : 48);
case ButtonLayout::Vertical:
case ButtonLayout::VerticalTwo:
default: return QSize(0, large ? 54 : 36);
}
}
void MainWindow::rebuildButtons()
{
// Clear existing
if (m_btnArea->layout()) {
while (m_btnArea->layout()->count()) {
auto* item = m_btnArea->layout()->takeAt(0);
if (item->widget()) { item->widget()->deleteLater(); }
delete item;
}
delete m_btnArea->layout();
}
m_clickButtons.clear();
m_ctrlBtn = m_altBtn = m_shiftBtn = m_dwellActiveBtn = nullptr;
m_keyboardBtn = nullptr;
m_hotkeyBtns[0] = m_hotkeyBtns[1] = m_hotkeyBtns[2] = nullptr;
auto* grid = new QGridLayout(m_btnArea);
grid->setSpacing(4);
// Vertical modes: total horizontal margin (1+1+1+1 = 4 px) equals the column
// spacing (4 px), so VerticalOne = exactly half the width of VerticalTwo.
const bool isVerticalMode = (m_settings.buttonLayout == ButtonLayout::Vertical ||
m_settings.buttonLayout == ButtonLayout::VerticalTwo);
const bool vertOne = (m_settings.buttonLayout == ButtonLayout::Vertical);
// In single-column vertical mode, collapse the title label and shrink the
// auto button to match the settings/exit buttons — this halves the window
// width relative to every other layout mode.
m_titleLabel->setVisible(!vertOne);
m_autoBtn->setFixedSize(vertOne ? 22 : 38, 22);
if (isVerticalMode) {
m_btnArea->setContentsMargins(1, 4, 1, 4);
grid->setContentsMargins(1, 4, 1, 4);
} else {
m_btnArea->setContentsMargins(6, 6, 6, 6);
grid->setContentsMargins(4, 4, 4, 4);
}
int row = 0, col = 0;
const int COLS = (m_settings.buttonLayout == ButtonLayout::Vertical) ? 1
: (m_settings.buttonLayout == ButtonLayout::VerticalTwo) ? 2
: (m_settings.buttonLayout == ButtonLayout::Horizontal) ? 99
: 3;
// Factory: create a click button (signals + m_clickButtons), no placement.
auto makeClickButton = [&](const QString& lbl, const QString& name, const QString& tip,
ClickType t, const QString& icon) -> QWidget* {
auto* btn = makeButton(lbl, tip, t, icon);
// The visible label is abbreviated to fit the button ("L Dbl") and is
// absent entirely in icons-only mode, so neither is usable as a spoken
// name — give the full one explicitly.
a11y::setName(btn, name, tip);
m_clickButtons.append(btn);
connect(btn, &ClickButton::clickTypePressed, this, &MainWindow::onClickButtonPressed);
connect(btn, &ClickButton::clickTypeHovered, this, [this](ClickType type){
m_hoveredType = type;
m_hoverTimer->start(hoverSelectMs());
});
connect(btn, &ClickButton::clickTypeLeft, this, [this](){
m_hoverTimer->stop();
m_hoveredType = ClickType::None;
});
return btn;
};
// Shared look/sizing for the modifier, Dwell Active, Quit and hotkey buttons
// — the same footprint as the click buttons so everything aligns in the grid.
const bool large = m_settings.largeButtons;
auto modStyle = [large](bool on) -> QString { return modBtnStyle(on, large); };
const QSize modSize = toolbarButtonMinSize(m_settings.buttonLayout, large);
// Factory: a checkable modifier button (Ctrl/Alt/Shift). Assigns the member
// pointer and toggles the given modifier bit.
auto makeModifier = [&](QPushButton*& member, const QString& text,
const QString& tip, int flag) -> QWidget* {
auto* btn = new QPushButton(text, m_btnArea);
member = btn;
btn->setCheckable(true);
btn->setMinimumSize(modSize);
btn->setToolTip(tip);
// Key names are not translated (the physical key is "Ctrl" everywhere),
// so the text doubles as the name; the tooltip explains the one-shot
// behaviour. Checked state is reported by Qt from setCheckable().
a11y::setName(btn, text, tip);
btn->setStyleSheet(modStyle(false));
connect(btn, &QPushButton::toggled, this, [this, btn, modStyle, flag](bool on){
if (on) m_modifiers |= flag; else m_modifiers &= ~flag;
btn->setStyleSheet(modStyle(on));
if (m_autoEnabled) m_dwell->setModifiers(m_modifiers);
});
new ModHoverFilter(btn, [this]{ return hoverSelectMs(); });
return btn;
};
// Factory: the Dwell Active toggle (mirrors the title-bar Auto button).
auto makeDwellActive = [&]() -> QWidget* {
auto dwellActiveStyle = [large](bool on) -> QString {
const char* fs = large ? "14px" : "11px";
const char* pad = large ? "4px" : "2px";
return on
? QString("QPushButton { background:#FFA028; color:#1A1A1A; border:2px solid #FFB040; "
"border-radius:4px; font-weight:bold; font-size:%1; padding:%2; }"
"QPushButton:hover { background:#FFB040; }").arg(fs).arg(pad)
: QString("QPushButton { background:#3A3A3A; color:#DDDDDD; border:1px solid #555; "
"border-radius:4px; font-size:%1; padding:%2; }"
"QPushButton:hover { background:#4A4A4A; border:1px solid #FFA028; color:#FFA028; }").arg(fs).arg(pad);
};
auto* btn = new QPushButton(tr("Dwell Active"), m_btnArea);
m_dwellActiveBtn = btn;
btn->setCheckable(true);
btn->setMinimumSize(modSize);
btn->setToolTip(tr("Enable dwell-clicking (same as the Auto button)"));
a11y::setName(btn, tr("Dwell Active"),
tr("Enable dwell-clicking (same as the Auto button)"));
btn->setChecked(m_autoEnabled);
btn->setStyleSheet(dwellActiveStyle(m_autoEnabled));
connect(btn, &QPushButton::toggled, this, [this, dwellActiveStyle](bool on){
m_dwellActiveBtn->setStyleSheet(dwellActiveStyle(on));
m_autoBtn->setChecked(on); // drive the canonical Auto button
});
new ModHoverFilter(btn, [this]{ return hoverSelectMs(); });
return btn;
};
// Factory: the red Quit button.
auto makeQuit = [&]() -> QWidget* {
auto* quitBtn = new QPushButton(tr("Quit Program"), m_btnArea);
quitBtn->setStyleSheet(
QString("QPushButton { background:#3A1A1A; color:#FF6B6B; border:1px solid #7A3333; "
"border-radius:4px; font-size:%1; padding:%2; }"
"QPushButton:hover { background:#5C2222; border-color:#FF6B6B; }")
.arg(large ? "13px" : "11px")
.arg(large ? "4px" : "2px"));
quitBtn->setMinimumSize(modSize);
connect(quitBtn, &QPushButton::clicked, qApp, &QApplication::quit);
return quitBtn;
};
// Factory: the on-screen-keyboard toggle. Checkable so it reflects whether
// the keyboard we launched is currently open; hover-select enabled so dwell
// users can trigger it without a physical click (like the modifier buttons).
auto makeKeyboard = [&]() -> QWidget* {
auto* btn = new QPushButton(m_btnArea);
m_keyboardBtn = btn;
btn->setCheckable(true);
btn->setMinimumSize(modSize);
btn->setIcon(QIcon(":/icons/keyboard.svg"));
btn->setIconSize(large ? QSize(28, 24) : QSize(20, 17));
if (!m_settings.iconsOnly)
btn->setText(tr("Keyboard"));
btn->setToolTip(tr("Show or hide the on-screen keyboard"));
// Named unconditionally: in icons-only mode the button has no text at
// all, which is exactly when Qt has nothing to derive a name from.
a11y::setName(btn, tr("Keyboard"), tr("Show or hide the on-screen keyboard"));
refreshKeyboardButton(); // set initial checked state + style
connect(btn, &QPushButton::toggled, this, [this](bool on){
// Apply the request, then re-sync the look to the real keyboard
// state (on macOS the button is momentary — see setOnScreenKeyboard).
setOnScreenKeyboard(on);
refreshKeyboardButton();
});
new ModHoverFilter(btn, [this]{ return hoverSelectMs(); });
return btn;
};
// Factory: a custom-hotkey button for slot i, or nullptr if that slot is off
// or has no key assigned. Flows inline with the other reorderable buttons.
auto makeHotkey = [&](int i) -> QWidget* {
const auto& slot = m_settings.hotkeys[i];
if (!slot.enabled || slot.keySequence.isEmpty()) return nullptr;
QKeySequence seq(slot.keySequence, QKeySequence::PortableText);
const QString displayLabel = slot.label.isEmpty()
? seq.toString(QKeySequence::NativeText) : slot.label;
if (displayLabel.isEmpty()) return nullptr;
auto* btn = new QPushButton(displayLabel, m_btnArea);
btn->setMinimumSize(modSize);
btn->setToolTip(seq.toString(QKeySequence::NativeText));
// The user's own label names the button; the key combination it sends is
// the description, since the label alone ("Copy") does not say what fires.
a11y::setName(btn, displayLabel, seq.toString(QKeySequence::NativeText));
btn->setStyleSheet(modBtnStyle(m_selectedHotkey == i, large));
connect(btn, &QPushButton::clicked, this, [this, i]{ onHotkeySelected(i); });
new HotkeyHoverFilter(btn,
[this, i]{ m_hoveredHotkey = i; m_hoverTimer->start(hoverSelectMs()); },
[this] { m_hoveredHotkey = -1; m_hoverTimer->stop(); });
m_hotkeyBtns[i] = btn;
return btn;
};
// Placement: column-flow with wrap (Horizontal has COLS large, so one row).
auto place = [&](QWidget* w){
grid->addWidget(w, row, col++);
if (col >= COLS) { col = 0; row++; }
};