-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettingsdialog.cpp
More file actions
2281 lines (2041 loc) · 95.3 KB
/
Copy pathsettingsdialog.cpp
File metadata and controls
2281 lines (2041 loc) · 95.3 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 "settingsdialog.h"
#include "a11y.h"
#include "logging.h"
#include "onscreenkeyboard.h"
#include "settingsjson.h"
#include "translations/tsparser.h"
#include "audioclicklistener.h"
#include "clickinjector.h"
#include <QApplication>
#include <QClipboard>
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QInputDialog>
#include <QJsonDocument>
#include <QScrollArea>
#include <QSettings>
#include <QGuiApplication>
#include <QKeySequenceEdit>
#include <QCursor>
#include <QEvent>
#include <QFrame>
#include <QGraphicsOpacityEffect>
#include <QProgressBar>
#include <QTimer>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QFormLayout>
#include <QListWidget>
#include <QGroupBox>
#include <QLabel>
#include <QPainter>
#include <QAbstractButton>
#include <QPushButton>
#include <QSvgRenderer>
#include <QTabWidget>
#include <QMessageBox>
#include <QProcess>
#include <QProgressDialog>
#include <QStandardPaths>
#include <QSysInfo>
#include <cmath>
// Unconditional since the log section's "Open log folder" needs them on every
// platform; they used to be macOS-only (the Accessibility settings shortcut).
#include <QDesktopServices>
#include <QLocale>
#include <QUrl>
// ── TrackIR palette ──────────────────────────────────────────
// Settings-window font zoom: the base font size (at 100%) plus the bounds and
// step of the "+/-" zoom control that sits next to the language selector. The
// stylesheet font-size is regenerated from this base whenever the user zooms.
static constexpr int kBaseFontPx = 12;
static constexpr int kZoomMinPct = 80;
static constexpr int kZoomMaxPct = 200;
static constexpr int kZoomStepPct = 10;
// The version as shown to users, with the CI build number appended when the
// build defined one. The version itself comes from applicationVersion(), which
// main.cpp seeds from the TRACKCLICK_VERSION compile definition — CMake's
// project(VERSION …) is the single source, so nothing here repeats the literal.
// Both the About header and the Diagnostics read-out call this, so the two can
// never disagree.
#ifdef BUILD_NUMBER
# define TC_STR_(x) #x
# define TC_STR(x) TC_STR_(x)
#endif
static QString displayVersion()
{
#ifdef BUILD_NUMBER
return QCoreApplication::applicationVersion()
+ QStringLiteral(" (build " TC_STR(BUILD_NUMBER) ")");
#else
return QCoreApplication::applicationVersion();
#endif
}
// Build the dialog stylesheet with every text element sized at fontPx, so the
// zoom control can scale the whole settings window just by re-applying it.
// The @FS@ token is substituted with the requested pixel size below.
static QString buildStyle(int fontPx)
{
return QString(R"(
QDialog {
background: #2D2D2D;
color: #E6E6E6;
font-family: "Segoe UI", Arial, sans-serif;
font-size: @FS@px;
}
QGroupBox {
color: #FFA600;
border: 1px solid #3A3A3A;
border-radius: 4px;
margin-top: 10px;
padding-top: 6px;
font-size: @FS@px;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 8px;
padding: 0 4px;
}
QLabel { color: #E6E6E6; font-size: @FS@px; }
QCheckBox { color: #E6E6E6; spacing: 6px; font-size: @FS@px; }
QCheckBox::indicator {
width: 25px; height: 11px;
border: none;
border-radius: 0;
background: transparent;
image: url(:/icons/toggle_off.svg);
}
QCheckBox::indicator:checked {
image: url(:/icons/toggle_on.svg);
}
QListWidget {
background: #1A1A1A;
color: #E6E6E6;
border: 1px solid #555;
border-radius: 3px;
font-size: @FS@px;
outline: none;
}
/* A background on the base item rule is deliberate: it forces every row through
the stylesheet render path so the 25px QSS indicator width below is honoured
for text layout. Without it, unselected rows fall back to the native style
(which reserves only its ~13px indicator metric) and the wide toggle overhangs
the label on Windows — while selected rows, matching the :selected background
rule, lay out correctly. #1A1A1A matches the list background, so no visual
change; it only fixes the text/toggle overlap. */
QListWidget::item { padding: 3px 4px; background: #1A1A1A; }
QListWidget::item:selected { background: #3D3D3D; color: #FFA600; }
QListWidget::indicator {
width: 25px; height: 11px;
background: transparent;
image: url(:/icons/toggle_off.svg);
}
QListWidget::indicator:checked {
image: url(:/icons/toggle_on.svg);
}
QSpinBox, QDoubleSpinBox, QComboBox, QLineEdit, QKeySequenceEdit {
background: #1A1A1A;
color: #E6E6E6;
border: 1px solid #555;
border-radius: 3px;
padding: 2px 4px;
font-size: @FS@px;
}
QLineEdit:focus, QKeySequenceEdit:focus {
border: 1px solid #FFA600;
}
QComboBox::drop-down { border: none; width: 18px; }
QComboBox QAbstractItemView {
background: #2D2D2D;
color: #E6E6E6;
border: 1px solid #555;
selection-background-color: #FFA600;
selection-color: #1A1A1A;
font-size: @FS@px;
}
QSlider::groove:horizontal {
height: 4px;
background: #555;
border-radius: 2px;
}
QSlider::handle:horizontal {
width: 14px; height: 14px;
background: #FFA600;
border-radius: 7px;
margin: -5px 0;
}
QSlider::sub-page:horizontal { background: #FFA600; border-radius: 2px; }
QPushButton {
background: #FFA600;
color: #1A1A1A;
border: none;
border-radius: 4px;
padding: 6px 18px;
font-weight: bold;
font-size: @FS@px;
}
QPushButton:hover { background: #FFB833; }
QPushButton:pressed{ background: #CC8400; }
QPushButton[flat=true] {
background: #3D3D3D;
color: #FFFFFF;
}
QPushButton[flat=true]:hover { background: #4D4D4D; }
QTabWidget::pane {
border: 1px solid #555;
border-radius: 4px;
top: -1px;
background: #2D2D2D;
}
QTabBar::tab {
background: #1A1A1A;
color: #E6E6E6;
padding: 6px 14px;
border: 1px solid #555;
border-bottom: none;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
margin-right: 2px;
font-size: @FS@px;
}
QTabBar::tab:selected { background: #2D2D2D; color: #FFA600; }
QTabBar::tab:hover { color: #FFB833; }
)").replace(QLatin1String("@FS@"), QString::number(fontPx));
}
// ── Reorderable click buttons ────────────────────────────────────────────────
// Canonical/default toolbar order. Right Double / Right Drag are included so
// the order model is complete and MainWindow can still lay them out if ever
// re-enabled in code, but they are read-only placeholders (kept off) and are
// not shown in the settings reorder list.
const QVector<ClickButtonDesc>& clickButtonDescs()
{
static const QVector<ClickButtonDesc> v = {
{ "no_click", &AppSettings::showNoClick },
{ "left_click", &AppSettings::showLeftClick },
{ "left_double", &AppSettings::showLeftDouble },
{ "left_drag", &AppSettings::showLeftDrag },
{ "right_click", &AppSettings::showRightClick },
{ "right_double", &AppSettings::showRightDouble },
{ "right_drag", &AppSettings::showRightDrag },
{ "middle_click", &AppSettings::showMiddleClick },
{ "middle_double", &AppSettings::showMiddleDouble},
{ "scroll_up", &AppSettings::showScrollUp },
{ "scroll_down", &AppSettings::showScrollDown },
{ "scroll_horiz", &AppSettings::showScrollHoriz },
{ "ctrl", &AppSettings::showModCtrl },
{ "alt", &AppSettings::showModAlt },
{ "shift", &AppSettings::showModShift },
{ "dwell_active", &AppSettings::showDwellActiveBtn },
{ "quit", &AppSettings::showQuitButton },
{ "keyboard", &AppSettings::showKeyboardButton },
};
return v;
}
// Number of custom hotkey slots; their reorder ids are "hotkey_0".."hotkey_2".
static constexpr int kHotkeyCount = 3;
int hotkeyIndexForId(const QString& id)
{
if (!id.startsWith(QLatin1String("hotkey_"))) return -1;
bool ok = false;
const int idx = id.mid(7).toInt(&ok);
return (ok && idx >= 0 && idx < kHotkeyCount) ? idx : -1;
}
// Full canonical id set / default order: the bool-backed buttons, then the
// hotkey slots — but Dwell Active and Quit are pushed to the very bottom so by
// default they sit at the end of the list (below the hotkeys).
static QStringList canonicalButtonIds()
{
QStringList ids;
for (const auto& d : clickButtonDescs()) {
const QString id = QLatin1String(d.id);
if (id == QLatin1String("dwell_active") || id == QLatin1String("quit")
|| id == QLatin1String("keyboard"))
continue; // appended at the very end below
ids << id;
}
for (int i = 0; i < kHotkeyCount; ++i)
ids << QStringLiteral("hotkey_%1").arg(i);
ids << QStringLiteral("dwell_active") << QStringLiteral("keyboard")
<< QStringLiteral("quit");
return ids;
}
QStringList orderedClickButtonIds(const AppSettings& s)
{
const QStringList canon = canonicalButtonIds();
QStringList result;
// Saved order first (recognised ids, no duplicates).
for (const QString& id : s.buttonOrder)
if (canon.contains(id) && !result.contains(id))
result << id;
// Then any canonical ids the saved order didn't cover (new/unsaved buttons).
for (const QString& id : canon)
if (!result.contains(id))
result << id;
return result;
}
// The AppSettings visibility flag controlled by a bool-backed id (nullptr for an
// unknown or hotkey-backed id).
static bool AppSettings::* showMemberForId(const QString& id)
{
for (const auto& d : clickButtonDescs())
if (id == QLatin1String(d.id))
return d.show;
return nullptr;
}
// Whether a reorder-list id is currently enabled/visible. Handles both the
// bool-backed buttons and the hotkey slots (hotkeys[i].enabled).
static bool buttonEnabled(const AppSettings& s, const QString& id)
{
const int hk = hotkeyIndexForId(id);
if (hk >= 0) return s.hotkeys[hk].enabled;
if (bool AppSettings::* memb = showMemberForId(id)) return s.*memb;
return false;
}
static void setButtonEnabled(AppSettings& s, const QString& id, bool on)
{
const int hk = hotkeyIndexForId(id);
if (hk >= 0) { s.hotkeys[hk].enabled = on; return; }
if (bool AppSettings::* memb = showMemberForId(id)) s.*memb = on;
}
// ── Sensitivity Tester ────────────────────────────────────────────────────────
class CrosshairWidget : public QWidget
{
public:
explicit CrosshairWidget(QWidget* parent = nullptr) : QWidget(parent)
{
setFixedSize(120, 120);
}
void setHighlighted(bool h) { if (m_hl != h) { m_hl = h; update(); } }
QPoint centerInScreen() const
{
return mapToGlobal(QPoint(width() / 2, height() / 2));
}
protected:
void paintEvent(QPaintEvent*) override
{
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
p.fillRect(rect(), QColor(0x1A, 0x1A, 0x1A));
p.setPen(QPen(QColor("#555555"), 1));
p.drawRect(rect().adjusted(0, 0, -1, -1));
int cx = width() / 2, cy = height() / 2;
QColor col = m_hl ? QColor("#FFD000") : QColor("#FFA600");
p.setPen(QPen(col, 1));
p.drawLine(0, cy, width() - 1, cy);
p.drawLine(cx, 0, cx, height() - 1);
p.setBrush(Qt::NoBrush);
p.drawEllipse(QPoint(cx, cy), 8, 8);
p.setPen(Qt::NoPen);
p.setBrush(col);
p.drawEllipse(QPoint(cx, cy), 2, 2);
}
private:
bool m_hl = false;
};
class SensitivityTesterDialog : public QDialog
{
Q_OBJECT
public:
explicit SensitivityTesterDialog(QWidget* parent = nullptr);
signals:
void sensitivityChosen(int px);
private slots:
void onStart();
void onPoll();
private:
void finishMeasurement();
enum class Phase { Idle, Waiting, Measuring, Done };
CrosshairWidget* m_crosshair;
QLabel* m_infoLbl;
QProgressBar* m_bar;
QLabel* m_resultLbl;
QPushButton* m_startBtn;
QTimer m_timer;
Phase m_phase = Phase::Idle;
QPoint m_lastPos;
double m_sumDelta = 0.0;
int m_samples = 0;
int m_elapsedMs = 0;
static constexpr int k_durationMs = 8000;
static constexpr int k_hoverPx = 30;
static constexpr int k_pollMs = 50;
};
SensitivityTesterDialog::SensitivityTesterDialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("Sensitivity Tester"));
setModal(true);
setStyleSheet(buildStyle(kBaseFontPx));
setFixedWidth(280);
auto* root = new QVBoxLayout(this);
root->setSpacing(10);
root->setContentsMargins(16, 16, 16, 16);
m_infoLbl = new QLabel(
tr("Click Start, then move your mouse over\nthe crosshairs and keep it still."));
m_infoLbl->setAlignment(Qt::AlignCenter);
m_infoLbl->setWordWrap(true);
root->addWidget(m_infoLbl);
auto* crossRow = new QHBoxLayout;
m_crosshair = new CrosshairWidget;
crossRow->addStretch();
crossRow->addWidget(m_crosshair);
crossRow->addStretch();
root->addLayout(crossRow);
m_bar = new QProgressBar;
m_bar->setRange(0, 100);
m_bar->setValue(0);
m_bar->setTextVisible(false);
m_bar->setFixedHeight(8);
// Unlabelled bar: the surrounding text explains the exercise but nothing
// names the bar itself, and its value is the whole point of the dialog.
a11y::setName(m_bar, tr("Measured cursor movement"));
m_bar->setStyleSheet(
"QProgressBar{background:#1A1A1A;border:1px solid #555;border-radius:3px;}"
"QProgressBar::chunk{background:#FFA600;border-radius:2px;}");
root->addWidget(m_bar);
m_resultLbl = new QLabel;
m_resultLbl->setAlignment(Qt::AlignCenter);
m_resultLbl->setStyleSheet("color:#FFA600; font-weight:bold;");
m_resultLbl->hide();
root->addWidget(m_resultLbl);
auto* btnRow = new QHBoxLayout;
m_startBtn = new QPushButton(tr("Start"));
auto* closeBtn = new QPushButton(tr("Close"));
closeBtn->setProperty("flat", true);
btnRow->addStretch();
btnRow->addWidget(m_startBtn);
btnRow->addWidget(closeBtn);
btnRow->addStretch();
root->addLayout(btnRow);
connect(m_startBtn, &QPushButton::clicked, this, &SensitivityTesterDialog::onStart);
connect(closeBtn, &QPushButton::clicked, this, &QDialog::accept);
m_timer.setInterval(k_pollMs);
connect(&m_timer, &QTimer::timeout, this, &SensitivityTesterDialog::onPoll);
}
void SensitivityTesterDialog::onStart()
{
m_phase = Phase::Waiting;
m_sumDelta = 0.0;
m_samples = 0;
m_elapsedMs = 0;
m_lastPos = QCursor::pos();
m_startBtn->setEnabled(false);
m_resultLbl->hide();
m_bar->setValue(0);
m_infoLbl->setText(tr("Move your mouse over the crosshairs\nand keep it still."));
m_timer.start();
}
void SensitivityTesterDialog::onPoll()
{
QPoint cur = QCursor::pos();
QPoint center = m_crosshair->centerInScreen();
double dist = std::hypot(double(cur.x() - center.x()),
double(cur.y() - center.y()));
bool nearCenter = dist <= k_hoverPx;
m_crosshair->setHighlighted(nearCenter);
if (m_phase == Phase::Waiting) {
if (nearCenter) {
m_phase = Phase::Measuring;
m_lastPos = cur;
m_sumDelta = 0.0;
m_samples = 0;
m_elapsedMs = 0;
m_infoLbl->setText(tr("Measuring — keep your mouse still…"));
}
} else if (m_phase == Phase::Measuring) {
double d = std::hypot(double(cur.x() - m_lastPos.x()),
double(cur.y() - m_lastPos.y()));
m_sumDelta += d;
m_samples++;
m_lastPos = cur;
m_elapsedMs += k_pollMs;
m_bar->setValue(m_elapsedMs * 100 / k_durationMs);
if (m_elapsedMs >= k_durationMs)
finishMeasurement();
}
}
void SensitivityTesterDialog::finishMeasurement()
{
m_timer.stop();
m_phase = Phase::Done;
m_crosshair->setHighlighted(false);
m_bar->setValue(100);
double avg = m_samples > 0 ? m_sumDelta / m_samples : 1.0;
// Recommend ~2x what the earlier factor produced: measured jitter alone was
// running too low to filter real-world cursor tremor, so scale it up.
int recommended = qBound(1, static_cast<int>(std::ceil(avg * 4.0)), 100);
m_resultLbl->setText(tr("Sensitivity set to %1 px").arg(recommended));
m_resultLbl->show();
m_startBtn->setText(tr("Retest"));
m_startBtn->setEnabled(true);
emit sensitivityChosen(recommended);
}
// ─────────────────────────────────────────────────────────────────────────────
SettingsDialog::SettingsDialog(const AppSettings& current,
QTranslator* appTranslator,
QWidget* parent)
: QDialog(parent), m_settings(current), m_appTranslator(appTranslator)
{
setWindowTitle(tr("TrackClick — Settings"));
setModal(true);
setStyleSheet(buildStyle(kBaseFontPx));
buildUi();
loadFrom(current);
// Seize sole control of the qApp translator for the dialog's lifetime.
// Removing MainWindow's translator here ensures that when the user picks
// English the preview system can install nothing and tr() correctly falls
// through to source strings — even if the app was previously in another
// language. Screen repaints are deferred until the event loop runs, so
// the two rapid LanguageChange events below produce no visible flicker.
if (m_appTranslator)
qApp->removeTranslator(m_appTranslator);
// Warm up the preview for the starting language so the dialog reflects
// the current language immediately. Connected AFTER this call so the
// combo's initial value doesn't fire a duplicate preview.
applyLanguagePreview(current.language);
connect(m_cmbLanguage, &QComboBox::currentIndexChanged, this, [this](){
applyLanguagePreview(m_cmbLanguage->currentData().toString());
});
connect(m_buttons, &QDialogButtonBox::accepted, this, [this](){
m_settings = readUi();
accept();
});
connect(m_buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
connect(m_resetBtn, &QPushButton::clicked, this, [this](){
// "Reset to Defaults" covers appearance and behaviour. Carry the privacy
// opt-out across untouched: silently re-enabling reporting for someone who
// turned it off would be a choice they never made.
AppSettings defaults;
defaults.usageReporting = m_chkUsageReporting->isChecked();
loadFrom(defaults);
});
// ── Live input-level meter (calibration) ──────────────────
m_meterTimer.setInterval(40);
connect(&m_meterTimer, &QTimer::timeout, this, [this](){
m_meterTarget *= 0.82; // smooth decay so the bar falls back gently
m_audioMeter->setValue(static_cast<int>(qBound(0.0, m_meterTarget, 1.0) * 100));
});
#ifdef HAVE_MULTIMEDIA
m_meterListener = new AudioClickListener(this);
connect(m_meterListener, &AudioClickListener::level, this, [this](double l){
if (l > m_meterTarget) m_meterTarget = l; // instant rise, timed fall
});
// Only open the microphone while the Audio Click tab (index 3) is showing.
connect(m_tabs, &QTabWidget::currentChanged, this, [this](int idx){
if (idx == 3) startAudioMeter();
else stopAudioMeter();
});
#endif
}
// ── Language preview ──────────────────────────────────────────────────────────
void SettingsDialog::applyLanguagePreview(const QString& lang)
{
// Swap only the preview translator — do NOT restore m_appTranslator here.
// m_appTranslator stays out of qApp for the entire dialog lifetime so that
// choosing English (no preview translator) correctly shows English rather
// than falling back to the previously-active language.
if (m_previewTranslator) {
qApp->removeTranslator(m_previewTranslator);
delete m_previewTranslator;
m_previewTranslator = nullptr;
}
if (lang != "en") {
m_previewTranslator = loadBestTranslator(lang, this);
if (m_previewTranslator)
qApp->installTranslator(m_previewTranslator);
}
// Qt automatically broadcasts QEvent::LanguageChange to this dialog when
// the translator list changes, which triggers changeEvent → retranslateUi().
}
void SettingsDialog::cleanupPreviewTranslator()
{
if (m_previewTranslator) {
qApp->removeTranslator(m_previewTranslator);
delete m_previewTranslator;
m_previewTranslator = nullptr;
}
// Hand the app translator back to qApp so that after the dialog closes
// the main window reverts to its previous language (on Cancel) or
// MainWindow::installLanguage can remove and replace it (on Accept).
if (m_appTranslator) {
qApp->installTranslator(m_appTranslator);
m_appTranslator = nullptr; // ownership stays with MainWindow
}
}
void SettingsDialog::done(int result)
{
// Always clean up before closing so that MainWindow::installLanguage()
// (called on Accept) starts with only its own translator installed, and
// on Cancel the app reverts to whatever translator was active before the
// dialog opened.
cleanupPreviewTranslator();
stopAudioMeter(); // release the microphone when the dialog closes
QDialog::done(result);
}
// ── Retranslation ─────────────────────────────────────────────────────────────
void SettingsDialog::changeEvent(QEvent* e)
{
QDialog::changeEvent(e);
if (e->type() == QEvent::LanguageChange)
retranslateUi();
}
void SettingsDialog::retranslateUi()
{
setWindowTitle(tr("TrackClick — Settings"));
m_tabs->setTabText(0, tr("Dwell Clicking"));
m_lblDwellTime->setText(tr("Dwell time:"));
m_lblSensitivity->setText(tr("Sensitivity:"));
m_btnSensTester->setText(tr("Sensitivity Tester…"));
m_lblHoverSelect->setText(tr("Hover to switch:"));
m_hoverSelectPct->setToolTip(tr("How long a toolbar button must be hovered before the "
"selection switches to it, as a percentage of the dwell time."));
m_lblScrollRepeat->setText(tr("Scroll repeat:"));
m_lblRepeatMode->setText(tr("Repeat click:"));
m_lblReturnToLeft->setText(tr("Return to left click after click:"));
#ifdef Q_OS_MAC
m_lblPermissions->setText(tr("Permissions:"));
m_btnAccessibility->setText(tr("Open Accessibility Settings…"));
#endif
m_tabs->setTabText(1, tr("Buttons"));
m_lblVisibleButtons->setText(tr("Visible Buttons (check to show, Move Up/Down to reorder)"));
m_btnMoveUp->setText(tr("Move Up"));
m_btnMoveDown->setText(tr("Move Down"));
for (int i = 0; i < m_btnOrderList->count(); ++i) {
QListWidgetItem* it = m_btnOrderList->item(i);
it->setText(clickButtonLabel(it->data(Qt::UserRole).toString()));
}
m_lblCustomHotkeys->setText(tr("Custom Hotkeys"));
for (int i = 0; i < 3; ++i) {
m_lblHotkey[i]->setText(tr("Hotkey %1").arg(i + 1));
m_edtHotkeyLabel[i]->setPlaceholderText(tr("Label (optional)"));
}
m_tabs->setTabText(2, tr("Window"));
m_grpWinBehavior->setTitle(tr("Window Behavior"));
m_grpButtonControls->setTitle(tr("Button Controls"));
m_grpFeedback->setTitle(tr("Feedback"));
m_lblEdgeLock->setText(tr("Lock to screen edge:"));
m_cmbEdgeLock->setItemText(0, tr("None"));
m_cmbEdgeLock->setItemText(1, tr("Left edge"));
m_cmbEdgeLock->setItemText(2, tr("Right edge"));
m_chkEdgeHide->setText(tr("Slide off screen when idle"));
m_chkAlwaysOnTop->setText(tr("Always on top"));
m_chkStartMinimized->setText(tr("Start minimized to tray"));
m_chkXMinimizesApp->setText(tr("Top X minimizes app"));
m_chkLaunchOnStartup->setText(tr("Launch on system startup (Windows)"));
m_chkMinimalWidth->setText(tr("Minimal width"));
m_lblMinimalWidthPx->setText(tr("Width limit (px):"));
m_spinMinimalWidthPx->setSpecialValueText(tr("Auto (fit content)"));
m_chkAudio->setText(tr("Audio feedback on click"));
m_chkClickIndicator->setText(tr("Show click indicator ring (Windows)"));
m_chkShowLabels->setText(tr("Show button labels"));
m_chkLargeButtons->setText(tr("Large buttons"));
m_lblOpacity->setText(tr("Opacity:"));
m_lblBtnLayout->setText(tr("Button layout:"));
m_cmbLayout->setItemText(0, tr("Rectangle (grid)"));
m_cmbLayout->setItemText(1, tr("Horizontal (one row)"));
m_cmbLayout->setItemText(2, tr("Vertical (one column)"));
m_cmbLayout->setItemText(3, tr("Vertical (two columns)"));
m_lblLanguage->setText(tr("Language:"));
m_lblZoom->setText(tr("Zoom:"));
m_okBtn->setText(tr("OK"));
m_cancelBtn->setText(tr("Cancel"));
m_resetBtn->setText(tr("Reset to Defaults"));
m_btnOnScreenKbd->setText(tr("Open On-Screen Keyboard"));
m_tabs->setTabText(3, tr("Audio Click"));
m_chkAudioClick->setText(tr("Trigger the selected action with a loud sound"));
m_lblAudioClickInfo->setText(audioClickInfoText());
m_lblAudioDevice->setText(tr("Input device:"));
m_cmbAudioDevice->setItemText(0, tr("System default"));
m_lblAudioThreshold->setText(tr("Loudness threshold:"));
m_lblAudioMeter->setText(tr("Input level:"));
m_tabs->setTabText(4, tr("Diagnostics"));
m_lblDiagIntro->setText(
tr("If clicking isn't working, this information helps pin down why."));
m_btnCopyDiag->setText(tr("Copy diagnostics"));
m_lblSelfTestHelp->setText(
tr("Click self-test: TrackClick moves the pointer to the target below and "
"injects a real click. If the target lights up green, click injection "
"is working end-to-end."));
m_btnSelfTest->setText(tr("Run click self-test"));
m_diagTarget->setText(tr("Target"));
m_lblLogHeading->setText(tr("Log file"));
m_lblLogHelp->setText(logHelpText());
m_chkLogging->setText(tr("Write a log file"));
m_btnOpenLogFolder->setText(tr("Open log folder"));
m_btnClearLog->setText(tr("Clear log"));
refreshLogStatus(); // carries the translatable "empty" marker
m_lblProfilesHeading->setText(tr("Profiles and backup"));
m_lblProfilesHelp->setText(profilesHelpText());
m_lblProfile->setText(tr("Profile:"));
m_btnProfileLoad->setText(tr("Load"));
m_btnProfileSave->setText(tr("Save as…"));
m_btnProfileDelete->setText(tr("Delete"));
m_btnExportSettings->setText(tr("Export to file…"));
m_btnImportSettings->setText(tr("Import from file…"));
// Re-render the "(no saved profiles)" placeholder in the new language.
// Any status message stays as-is: it reports a past action, and there is
// nothing sensible to re-render it from.
refreshProfileList(m_cmbProfiles->isEnabled() ? m_cmbProfiles->currentText()
: QString());
m_chkUsageReporting->setText(tr("Send anonymous usage statistics"));
m_lblUsageReporting->setText(usageReportingInfoText());
refreshDiagnostics();
// Last: the accessible names are derived from the label texts set above.
syncAccessibleNames();
}
// ── Profiles / export-import ─────────────────────────────────────────────────
// These live on the Diagnostics tab rather than beside OK/Cancel because they
// are occasional operations — troubleshooting, or matching one machine to
// another — not part of the ordinary edit-and-accept flow.
// The QSettings pair MainWindow persists to; profiles ride along in it.
static QSettings profileStore()
{
return QSettings(QStringLiteral("TrackClick"), QStringLiteral("TrackClick"));
}
QString SettingsDialog::profilesHelpText() const
{
// Kept short on purpose: the Diagnostics tab is the tallest one, and every
// wrapped line here raises the whole dialog's minimum height.
return tr("Name a copy of these settings, or move them between computers as a "
"file. Loading only fills in this window; nothing is applied until "
"you press OK.");
}
QString SettingsDialog::logHelpText() const
{
// Short for the same reason as profilesHelpText(): this is the tallest tab.
// Says where it goes and that it stays there — the app already looks
// suspicious enough (INTERNAL §1) without an unexplained file appearing.
// Off by default, so the text has to teach the order of operations — a user
// who copies diagnostics first gets an empty log and no hint why.
return tr("Off by default. Switch it on, reproduce the problem, then use Copy "
"diagnostics. Kept on this computer and never sent anywhere; nothing "
"you type is recorded.");
}
void SettingsDialog::buildProfilesSection(QVBoxLayout* v)
{
auto* sep = new QFrame;
sep->setFrameShape(QFrame::HLine);
sep->setStyleSheet("QFrame { color:#555; }");
v->addWidget(sep);
m_lblProfilesHeading = new QLabel(tr("Profiles and backup"));
m_lblProfilesHeading->setStyleSheet("font-weight:bold;");
v->addWidget(m_lblProfilesHeading);
m_lblProfilesHelp = new QLabel(profilesHelpText());
m_lblProfilesHelp->setWordWrap(true);
m_lblProfilesHelp->setStyleSheet("color:#AAA;");
// Wrapped labels report a single-line width hint, which would widen the
// whole dialog; let it wrap into the width the tab already has instead.
m_lblProfilesHelp->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Minimum);
v->addWidget(m_lblProfilesHelp);
auto* profileRow = new QHBoxLayout;
m_lblProfile = new QLabel(tr("Profile:"));
m_cmbProfiles = new QComboBox;
m_cmbProfiles->setMinimumWidth(140);
m_cmbProfiles->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
m_btnProfileLoad = new QPushButton(tr("Load"));
m_btnProfileSave = new QPushButton(tr("Save as…"));
m_btnProfileDelete = new QPushButton(tr("Delete"));
profileRow->addWidget(m_lblProfile);
profileRow->addWidget(m_cmbProfiles, 1);
profileRow->addWidget(m_btnProfileLoad);
profileRow->addWidget(m_btnProfileSave);
profileRow->addWidget(m_btnProfileDelete);
v->addLayout(profileRow);
auto* fileRow = new QHBoxLayout;
m_btnExportSettings = new QPushButton(tr("Export to file…"));
m_btnImportSettings = new QPushButton(tr("Import from file…"));
fileRow->addWidget(m_btnExportSettings);
fileRow->addWidget(m_btnImportSettings);
fileRow->addStretch(1);
v->addLayout(fileRow);
// Single line, not wrapped: it reports file paths, and letting it wrap would
// make the dialog's height depend on how long a path the user happened to
// pick. Long text is elided by the style instead.
m_lblProfileStatus = new QLabel;
m_lblProfileStatus->setStyleSheet("color:#AAA;");
m_lblProfileStatus->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
v->addWidget(m_lblProfileStatus);
connect(m_btnProfileSave, &QPushButton::clicked, this, &SettingsDialog::onSaveProfile);
connect(m_btnProfileLoad, &QPushButton::clicked, this, &SettingsDialog::onLoadProfile);
connect(m_btnProfileDelete, &QPushButton::clicked, this, &SettingsDialog::onDeleteProfile);
connect(m_btnExportSettings, &QPushButton::clicked, this, &SettingsDialog::onExportSettings);
connect(m_btnImportSettings, &QPushButton::clicked, this, &SettingsDialog::onImportSettings);
refreshProfileList();
}
void SettingsDialog::refreshProfileList(const QString& select)
{
QSettings store = profileStore();
const QStringList names = settingsProfileNames(store);
m_cmbProfiles->clear();
m_cmbProfiles->addItems(names);
if (!select.isEmpty()) {
const int idx = m_cmbProfiles->findText(select);
if (idx >= 0) m_cmbProfiles->setCurrentIndex(idx);
}
// Nothing saved yet: keep the combo visible (so the feature is discoverable)
// but make clear there is nothing to act on.
const bool any = !names.isEmpty();
m_cmbProfiles->setEnabled(any);
m_btnProfileLoad->setEnabled(any);
m_btnProfileDelete->setEnabled(any);
if (!any)
m_cmbProfiles->addItem(tr("(no saved profiles)"));
}
void SettingsDialog::onSaveProfile()
{
const QStringList existing = [&]{ QSettings s = profileStore();
return settingsProfileNames(s); }();
bool ok = false;
const QString name = QInputDialog::getText(
this, tr("Save profile"), tr("Profile name:"), QLineEdit::Normal,
m_cmbProfiles->isEnabled() ? m_cmbProfiles->currentText() : QString(), &ok)
.trimmed();
if (!ok || name.isEmpty())
return;
if (existing.contains(name)
&& QMessageBox::question(this, tr("Save profile"),
tr("A profile named \"%1\" already exists. Replace it?").arg(name))
!= QMessageBox::Yes)
return;
QSettings store = profileStore();
saveSettingsProfile(store, name, readUi());
store.sync();
refreshProfileList(name);
m_lblProfileStatus->setText(tr("Saved the current settings as \"%1\".").arg(name));
}
void SettingsDialog::onLoadProfile()
{
const QString name = m_cmbProfiles->currentText();
if (name.isEmpty() || !m_cmbProfiles->isEnabled())
return;
QSettings store = profileStore();
AppSettings loaded;
// Anything the profile does not carry keeps what is on screen right now.
if (!loadSettingsProfile(store, name, readUi(), loaded)) {
m_lblProfileStatus->setText(tr("Could not read the profile \"%1\".").arg(name));
return;
}
applyImported(loaded, tr("Loaded \"%1\". Press OK to apply.").arg(name));
}
void SettingsDialog::onDeleteProfile()
{
const QString name = m_cmbProfiles->currentText();
if (name.isEmpty() || !m_cmbProfiles->isEnabled())
return;
if (QMessageBox::question(this, tr("Delete profile"),
tr("Delete the profile \"%1\"? This cannot be undone.").arg(name))
!= QMessageBox::Yes)
return;
QSettings store = profileStore();
deleteSettingsProfile(store, name);
store.sync();
refreshProfileList();
m_lblProfileStatus->setText(tr("Deleted the profile \"%1\".").arg(name));
}
void SettingsDialog::onExportSettings()
{
QString path = QFileDialog::getSaveFileName(
this, tr("Export settings"),
QDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation))
.filePath(QStringLiteral("trackclick-settings.json")),
tr("TrackClick settings (*.json)"));
if (path.isEmpty())
return;
if (!path.endsWith(QLatin1String(".json"), Qt::CaseInsensitive))
path += QLatin1String(".json");
QFile f(path);
if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
QMessageBox::warning(this, tr("Export settings"),
tr("Could not write to %1.\n\n%2").arg(QDir::toNativeSeparators(path),
f.errorString()));
return;
}
// Indented rather than compact: these files get opened in a text editor and
// pasted into bug reports.
const QByteArray json = QJsonDocument(settingsToJson(readUi())).toJson();
if (f.write(json) != json.size()) {
QMessageBox::warning(this, tr("Export settings"),
tr("Could not write to %1.\n\n%2").arg(QDir::toNativeSeparators(path),
f.errorString()));
return;
}
f.close();
m_lblProfileStatus->setText(tr("Exported to %1.").arg(QDir::toNativeSeparators(path)));
}
void SettingsDialog::onImportSettings()
{
const QString path = QFileDialog::getOpenFileName(
this, tr("Import settings"),
QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
tr("TrackClick settings (*.json)"));
if (path.isEmpty())
return;
QFile f(path);
if (!f.open(QIODevice::ReadOnly)) {
QMessageBox::warning(this, tr("Import settings"),
tr("Could not read %1.\n\n%2").arg(QDir::toNativeSeparators(path),
f.errorString()));
return;
}
QJsonParseError err {};
const QJsonDocument doc = QJsonDocument::fromJson(f.readAll(), &err);
f.close();
if (err.error != QJsonParseError::NoError || !doc.isObject()) {
QMessageBox::warning(this, tr("Import settings"),
tr("%1 is not a valid settings file.").arg(QDir::toNativeSeparators(path)));
return;
}
// Reject an unrelated .json outright rather than "importing" it as a set of
// defaults, which would silently wipe the user's configuration.
if (!isSettingsJson(doc.object())) {
QMessageBox::warning(this, tr("Import settings"),
tr("%1 is not a TrackClick settings file, or it was written by a "
"newer version.").arg(QDir::toNativeSeparators(path)));
return;
}
applyImported(settingsFromJson(doc.object(), readUi()),
tr("Imported from %1. Press OK to apply.")
.arg(QDir::toNativeSeparators(path)));
}