-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathMainWindow.cpp
More file actions
8524 lines (7689 loc) · 358 KB
/
Copy pathMainWindow.cpp
File metadata and controls
8524 lines (7689 loc) · 358 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
// ─────────────────────────────────────────────────────────────────────────────
// ⚠️ MainWindow is DECOMPOSED (#3351). This file is NOT the default home for new
// feature code. Feature lifecycle/handlers belong in the matching
// MainWindow_*.cpp sibling TU; per-object signal wiring belongs in
// MainWindow_Wiring.cpp. Add here only for genuinely cross-cutting state
// (central members, the constructor's wireXxx() calls, a guard inside a
// function that itself can't move). When in doubt, see the map + decision
// guide: docs/architecture/mainwindow-decomposition.md
// ─────────────────────────────────────────────────────────────────────────────
#include "MainWindow.h"
#include "MainWindowHelpers.h"
#include "CwDecodeSettings.h"
#include "DisplaySettings.h"
#ifdef HAVE_MQTT
#include "MqttApplet.h"
#include "MqttSettingsDialog.h"
#include "core/MqttAntennaAlias.h"
#include "core/MqttSettings.h"
#endif
#include "ConnectionPanel.h"
#include "Theme.h"
#include "ClientDisconnectDialog.h"
#include "ConnectedStationsDialog.h"
#include "TitleBar.h"
#include "PanadapterApplet.h"
#include "PanadapterStack.h"
#include "PanLayoutDialog.h"
#include "core/RadioMessageTypes.h" // MessageSeverity for onRadioMessage
#include "core/LogManager.h"
#include "core/PerfTelemetry.h"
#include "core/PeripheralSettings.h"
#include "core/VoiceSignalDetector.h"
#include "core/MemoryRecallPolicy.h"
#include "core/StreamStatus.h"
#include "models/PanadapterModel.h"
#include "models/RadioStatusOwnership.h"
#include "SpectrumWidget.h"
#ifdef AETHER_GPU_SPECTRUM
#include <QRhiWidget>
#endif
#include "SpectrumOverlayMenu.h"
#include "VfoWidget.h"
#include "MeterSmoother.h" // global lean-mode meter repaint throttle (#3283)
#include "AppletPanel.h"
#include "containers/ContainerManager.h"
#include "RxApplet.h"
#include "SMeterWidget.h"
#include "TunerApplet.h"
#include "TxApplet.h"
#include "PhoneCwApplet.h"
#include "PhoneApplet.h"
#include "EqApplet.h"
#include "WaveApplet.h"
#include "ClientEqApplet.h"
#include "ClientEqEditor.h"
#include "ClientCompApplet.h"
#include "ClientCompEditor.h"
#include "ClientGateApplet.h"
#include "ClientGateEditor.h"
#include "ClientDeEssApplet.h"
#include "ClientTubeApplet.h"
#include "ClientTubeEditor.h"
#include "ClientPuduApplet.h"
#include "ClientPuduEditor.h"
#include "ClientReverbApplet.h"
#include "AetherialAudioStrip.h"
#include "StripFinalOutputPanel.h"
#include "ClientChainApplet.h"
#include "core/ClientComp.h"
#include "core/ClientEq.h"
#include "core/ClientGate.h"
#include "core/ClientDeEss.h"
#include "core/ClientTube.h"
#include "core/ClientPudu.h"
#include "core/ClientReverb.h"
#include "core/CwTrace.h"
#include "core/CwSidetoneGenerator.h"
#include "core/CwxLocalKeyer.h"
#include "core/IambicKeyer.h"
#include "core/KiwiSdrManager.h"
#include "CatControlApplet.h"
#include "DaxApplet.h"
#include "TciApplet.h"
#include "DaxIqApplet.h"
#include "AntennaGeniusApplet.h"
#include "ShackSwitchApplet.h"
#include "RadioSetupDialog.h"
#include "AgcCalibrationDialog.h"
#include "AudioDeviceChangeDialog.h"
#include "NetworkDiagnosticsDialog.h"
#include "PropDashboardDialog.h"
#include "MemoryCommands.h"
#include "MemoryDialog.h"
#include "SwrSweepLicenseDialog.h"
#include "DxClusterDialog.h"
#ifdef HAVE_WEBSOCKETS
#include "FreeDvReporterDialog.h"
#endif
#include "Ax25HfPacketDecodeDialog.h"
#include "FlexControlDialog.h"
#include "CwxPanel.h"
#include "DvkPanel.h"
#include "core/DvkWavTransfer.h"
#include "AmpApplet.h"
#include "MeterApplet.h"
#include "HealthApplet.h"
#include "PersistentDialog.h"
#include "ProfileManagerDialog.h"
#include "ProfileImportExportDialog.h"
#include "TxBandDialog.h"
#include "SupportDialog.h"
#include "SliceTroubleshootingDialog.h"
#include "ShortcutDialog.h"
#include "MultiFlexDialog.h"
#include "HelpDialog.h"
#include "ThemeEditorDialog.h"
#include "WhatsNewDialog.h"
#include "models/SliceModel.h"
#include "models/MeterModel.h"
#include "models/BandDefs.h"
#include "models/BandPlanManager.h"
#include "models/XvtrPolicy.h"
#include "core/BandStackSettings.h"
#include "gui/BandStackPanel.h"
#include "models/TunerModel.h"
#include "models/TransmitModel.h"
#include "models/EqualizerModel.h"
#ifdef HAVE_MIDI
#include "core/MidiSettings.h"
#include "MidiMappingDialog.h"
#endif
#ifdef HAVE_HIDAPI
#include "RC28MappingDialog.h"
#endif
#include "core/UlanziDialBackend.h"
#include "UlanziDialMapperDialog.h"
#include "AetherDspDialog.h"
#include "AetherDspWidget.h"
#include "WaveformsDialog.h"
#include "ClientRxDspApplet.h"
#include "DspParamPopup.h"
#include "GuardedSlider.h"
#include "MeterSlider.h"
#include "FramelessResizer.h"
#include "FramelessWindowTitleBar.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <limits>
#include <memory>
#include <functional>
#include <QApplication>
#include <QAudioDevice>
#include <QGuiApplication>
#include <QProcess>
#include <QScreen>
#include <QTimer>
#include <QDateTime>
#include <QPropertyAnimation>
#include <QIcon>
#include <QCursor>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QHelpEvent>
#include <QWindow>
#include <QPixmap>
#include <QImage>
#include <QBuffer>
#include <QFont>
#include <QWidgetAction>
#include <QPainter>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSplitter>
#include <QMenuBar>
#include <QDialog>
#include <QGridLayout>
#include <QLineEdit>
#include <QCheckBox>
#include <QMenu>
#include <QAction>
#include <QActionGroup>
#include <QAbstractSlider>
#include <QLabel>
#include <QCloseEvent>
#include <QMessageBox>
#include <QPushButton>
#include <QShortcut>
#include <QScrollArea>
#include <QSizeGrip>
#include <QStatusBar>
#include <QFrame>
#include <QFileDialog>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "core/VersionNumber.h"
#include "core/UpdateChecker.h"
#include <QDesktopServices>
#include <QPointer>
#include <QTextEdit>
#include <QPlainTextEdit>
#include <QSpinBox>
#include <QComboBox>
#include <QProgressBar>
#include <QThread>
#include <QToolTip>
#include <QMediaDevices>
#include "core/AppSettings.h"
#include "core/SpotCommandPolicy.h"
#include "core/SpotModeResolver.h"
#ifdef HAVE_RADE
#include "core/RADEEngine.h"
#include "RadeApplet.h"
#endif
#include "core/PanadapterStream.h"
#if defined(Q_OS_MAC)
#include "core/VirtualAudioBridge.h"
#include <QFileInfo>
#elif defined(HAVE_PIPEWIRE)
#include "core/PipeWireAudioBridge.h"
#endif
#include <QDebug>
#ifdef Q_OS_WIN
#ifndef NOMINMAX
#define NOMINMAX // guard against redefinition when an earlier include/toolchain predefines it (#4031)
#endif
#include <windows.h>
#include <windowsx.h>
#include <psapi.h>
#else
#include <sys/resource.h>
#ifdef Q_OS_MAC
#include <mach/mach.h>
#include <mach/task.h>
#include <mach/task_info.h>
#endif
#endif
#include <QLocale>
#include <QFile>
#include <QStandardPaths>
#include "core/ThemeManager.h"
// CMake captures the short git SHA at configure time and passes it as a
// preprocessor definition (see CMakeLists.txt). Defaulted to "unknown" so
// non-CMake builds (e.g. raw clang invocations during local experiments)
// still compile. See issue #2991 for the rationale on hoisting this to
// file scope rather than the inline definition inside buildMenuBar().
#ifndef AETHER_GIT_SHA
#define AETHER_GIT_SHA "unknown"
#endif
namespace AetherSDR {
namespace {
// Pan-follow edge-margin constants moved to MainWindow_Wiring.cpp (#3351 Phase 1d).
// kPanFollowAnimationDurationMs moved to MainWindow_Wiring.cpp (#3351 Phase 1d).
// kSliderShortcutLeaseMs moved to MainWindow_Shortcuts.cpp (#3351 Phase 1c).
constexpr int kPanadapterSliceCapacityStatusMs = 4000;
// Pan pixel-dimension constants + helpers moved to MainWindowHelpers
// (#3351 Phase 1d) — shared with MainWindow_Wiring.cpp.
// kPanLayoutRestore* constants moved to MainWindowHelpers.h (#3351 Phase 2c).
// kSwrSweep* constants moved to MainWindowHelpers.h (#3351 Phase 1e) —
// shared between the constructor timer setup here and MainWindow_SwrSweep.cpp.
constexpr const char* kSuppressAudioDeviceNotificationsKey =
"SuppressAudioDeviceNotifications";
constexpr int kTMate2DefaultUserInteractionTimeoutMs = 2000;
constexpr const char* kStatusBarCompactLabelObjectName = "statusBarCompactLabel";
QString statusBarCompactLabelStyle(const QString& color)
{
return QStringLiteral(
"QLabel#statusBarCompactLabel { color: %1; font-size: 12px; background: transparent; }")
.arg(color);
}
void applyStatusBarCompactLabelStyle(QLabel* label, const QString& color)
{
if (!label) {
return;
}
label->setObjectName(kStatusBarCompactLabelObjectName);
AetherSDR::ThemeManager::instance().applyStyleSheet(label, statusBarCompactLabelStyle(color));
}
void setStatusBarStationText(QLabel* label, const QString& text)
{
if (!label) {
return;
}
label->setText(text);
label->ensurePolished();
label->setMinimumWidth(label->sizeHint().width() + 2);
}
QString vfoFrequencyText(double mhz)
{
const long long hz = static_cast<long long>(std::round(mhz * 1e6));
return QString("%1.%2.%3")
.arg(static_cast<int>(hz / 1000000))
.arg(static_cast<int>((hz / 1000) % 1000), 3, 10, QChar('0'))
.arg(static_cast<int>(hz % 1000), 3, 10, QChar('0'));
}
#ifdef HAVE_HIDAPI
// tmate2*DefaultAction helpers moved to MainWindow_Controllers.cpp (#3351 Phase 2a).
#endif
bool isTransientAudioDeviceId(const QByteArray& id)
{
#ifdef Q_OS_LINUX
// PipeWire/pulse-shim churns these constantly (monitor sources, per-app
// loopbacks, fallback auto-null sink, echo-cancel/combine virtuals).
// They are never useful as a PC mic or local speaker target; treating
// them as "new devices" is what re-fires the dialog in #2864.
if (id.contains(".monitor")) return true;
if (id.startsWith("pulse_input_loopback")) return true;
if (id.contains("auto_null")) return true;
if (id.contains("echo-cancel")) return true;
if (id.contains("combined")) return true;
#else
Q_UNUSED(id);
#endif
return false;
}
QList<QByteArray> audioDeviceIds(const QList<QAudioDevice>& devices)
{
QList<QByteArray> ids;
ids.reserve(devices.size());
for (const QAudioDevice& device : devices) {
if (isTransientAudioDeviceId(device.id()))
continue;
ids.append(device.id());
}
return ids;
}
bool containsAudioDeviceId(const QList<QByteArray>& ids, const QByteArray& id)
{
return std::any_of(ids.cbegin(), ids.cend(),
[&id](const QByteArray& candidate) {
return candidate == id;
});
}
QList<QByteArray> newlyAddedAudioDeviceIds(const QList<QAudioDevice>& devices,
const QList<QByteArray>& knownIds)
{
QList<QByteArray> added;
for (const QAudioDevice& device : devices) {
if (isTransientAudioDeviceId(device.id()))
continue;
if (!containsAudioDeviceId(knownIds, device.id()))
added.append(device.id());
}
return added;
}
QList<QByteArray> removedAudioDeviceIds(const QList<QByteArray>& knownIds,
const QList<QByteArray>& currentIds)
{
QList<QByteArray> removed;
for (const QByteArray& id : knownIds) {
if (!containsAudioDeviceId(currentIds, id))
removed.append(id);
}
return removed;
}
bool audioDevicePresent(const QList<QAudioDevice>& devices,
const QAudioDevice& target)
{
if (target.isNull())
return true;
return std::any_of(devices.cbegin(), devices.cend(),
[&target](const QAudioDevice& device) {
return device.id() == target.id();
});
}
bool sameAudioDeviceSelection(const QAudioDevice& lhs, const QAudioDevice& rhs)
{
if (lhs.isNull() && rhs.isNull())
return true;
if (lhs.isNull() || rhs.isNull())
return false;
return lhs.id() == rhs.id();
}
// memoryRevealTargetMatches moved to MainWindow_Wiring.cpp (#3351 Phase 1d).
#ifdef Q_OS_WIN
bool mainWindowCustomFrameEnabled()
{
return AppSettings::instance()
.value("FramelessWindow", "True").toString() == "True";
}
int windowsResizeBorderThickness(HWND hwnd)
{
const UINT dpi = GetDpiForWindow(hwnd);
return GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi)
+ GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
}
#endif
// flexWheelModeForAction / flexControlButtonAction moved to
// MainWindow_Controllers.cpp (#3351 Phase 1a) — only controller code calls them.
// panCountForLayoutId moved to MainWindowHelpers (#3351 Phase 1c).
// defaultPanLayoutForCount moved to MainWindow_Session.cpp (#3351 Phase 2c).
// xvtrPolicyBandsFrom / xvtrListSummary / xvtrForBandSummary moved to
// MainWindowHelpers (#3351 Phase 1d) — shared with MainWindow_Wiring.cpp.
// parseStatusHandle / streamStatusBelongsToUs → core/StreamStatus.h
// logXvtrWaterfallDecision moved to MainWindow_Session.cpp (#3351 Phase 2c).
// quantizeIncrementalFollowDelta moved to MainWindow_Wiring.cpp (#3351 Phase 1d).
} // namespace
// Pure formatting / parsing helpers formerly defined here as file-scope
// statics now live in MainWindowHelpers.{h,cpp} (#3351 Phase 0). Only
// helpers coupled to the mutable shortcut-lease state below remain.
bool MainWindow::isSameDiversityReceivePair(const SliceModel* slice,
const SliceModel* other)
{
if (!slice || !other || slice == other
|| !slice->diversity() || !other->diversity()) {
return false;
}
const bool parentChildPair =
(slice->isDiversityParent() && other->isDiversityChild())
|| (slice->isDiversityChild() && other->isDiversityParent());
if (parentChildPair) {
return true;
}
return !slice->panId().isEmpty() && slice->panId() == other->panId();
}
// ─── Shortcut guard (file-scope for use as std::function<bool()>) ───────────
static constexpr const char* kPaTempUnitSettingKey = "PaTempDisplayUnit";
// kCw*ActionId/Name constants moved to MainWindowHelpers.h (#3351 Phase 1a)
// — now shared with the MIDI/HID registries in MainWindow_Controllers.cpp.
// s_keyboardShortcutsEnabled / s_sliderShortcutLeaseActive definitions lives in MainWindow_Shortcuts.cpp (#3351 Phase 1c).
// isCwMomentaryActionId moved to MainWindow_Controllers.cpp (#3351 Phase 2a).
// Shortcut-state helpers (textInputCaptured/shortcutGuard/...) lives in MainWindow_Shortcuts.cpp (#3351 Phase 1c).
bool MainWindow::confirmClientSlotAvailability(const RadioInfo& info,
QList<quint32>* disconnectHandles)
{
if (disconnectHandles)
disconnectHandles->clear();
const auto clients = buildDisconnectClients(info);
// When multiFLEX is disabled, any connected client blocks us — show the
// Connected Stations dialog so the user can disconnect them first.
if (!info.multiFlexEnabled && !clients.isEmpty()) {
ConnectedStationsDialog::RadioMeta meta;
meta.model = info.model;
meta.nickname = info.nickname;
meta.callsign = info.callsign;
QList<ConnectedStationsDialog::Client> sdClients;
for (const auto& c : clients) {
ConnectedStationsDialog::Client sc;
sc.handle = c.handle;
sc.program = c.program;
sc.station = c.station;
sdClients.append(sc);
}
ConnectedStationsDialog dialog(meta, sdClients, this);
if (dialog.exec() != QDialog::Accepted)
return false;
const quint32 handle = dialog.selectedHandle();
if (handle == 0)
return false;
if (disconnectHandles)
*disconnectHandles = {handle};
return true;
}
const int maxSlices = RadioModel::maxSlicesForModel(info.model);
if (clients.isEmpty() || clients.size() < maxSlices)
return true;
ClientDisconnectDialog dialog(clients, maxSlices, this);
if (dialog.exec() != QDialog::Accepted)
return false;
if (disconnectHandles)
*disconnectHandles = dialog.selectedHandles();
return !dialog.selectedHandles().isEmpty();
}
bool MainWindow::confirmClientSlotAvailability(const WanRadioInfo& info,
QList<quint32>* disconnectHandles)
{
if (disconnectHandles)
disconnectHandles->clear();
const auto clients = buildDisconnectClients(info);
// licensedClients == 1 means the radio's multiFLEX license allows only one
// simultaneous client — effectively mf_enable=0 from the SmartLink perspective.
// WanRadioInfo defaults to 1 when licensed_clients is absent from the SmartLink
// response (older firmware, partial parse), so this gate is fail-safe: it blocks
// rather than allows. Log when we hit the default so field reports are diagnosable.
if (info.licensedClients <= 1 && !clients.isEmpty()) {
if (info.licensedClients == 1)
qCWarning(lcGui) << "MainWindow: WAN licensedClients=1 (may be default) — "
"showing conflict dialog as a precaution";
ConnectedStationsDialog::RadioMeta meta;
meta.model = info.model;
meta.nickname = info.nickname;
meta.callsign = info.callsign;
QList<ConnectedStationsDialog::Client> sdClients;
for (const auto& c : clients) {
ConnectedStationsDialog::Client sc;
sc.handle = c.handle;
sc.program = c.program;
sc.station = c.station;
sdClients.append(sc);
}
ConnectedStationsDialog dialog(meta, sdClients, this);
if (dialog.exec() != QDialog::Accepted)
return false;
const quint32 handle = dialog.selectedHandle();
if (handle == 0)
return false;
if (disconnectHandles)
*disconnectHandles = {handle};
return true;
}
const int maxSlices = RadioModel::maxSlicesForModel(info.model);
if (clients.isEmpty() || clients.size() < maxSlices)
return true;
ClientDisconnectDialog dialog(clients, maxSlices, this);
if (dialog.exec() != QDialog::Accepted)
return false;
if (disconnectHandles)
*disconnectHandles = dialog.selectedHandles();
return !dialog.selectedHandles().isEmpty();
}
bool MainWindow::sendWanRadioClientDisconnects(const QString& serial,
const QList<quint32>& handles)
{
if (!m_smartLink.isConnected()) {
m_connPanel->setStatusText("SmartLink is not connected");
statusBar()->showMessage("SmartLink is not connected.", 4000);
return false;
}
if (serial.trimmed().isEmpty()) {
m_connPanel->setStatusText("SmartLink radio serial unavailable");
return false;
}
if (handles.isEmpty()) {
m_connPanel->setStatusText("No remote clients to disconnect");
return false;
}
m_smartLink.disconnectRadioClients(serial, handles);
return true;
}
void MainWindow::disconnectWanRadioClients(const WanRadioInfo& info)
{
const auto clients = buildDisconnectClients(info);
if (clients.isEmpty()) {
m_connPanel->setStatusText("No remote clients to disconnect");
statusBar()->showMessage("No remote clients are currently reported for that radio.", 4000);
return;
}
ClientDisconnectDialog dialog(clients,
RadioModel::maxSlicesForModel(info.model),
this,
ClientDisconnectDialog::Mode::RemoteClientDisconnect);
if (dialog.exec() != QDialog::Accepted)
return;
const QList<quint32> handles = dialog.selectedHandles();
if (handles.isEmpty())
return;
if (sendWanRadioClientDisconnects(info.serial, handles)) {
m_connPanel->setStatusText("Disconnect request sent");
statusBar()->showMessage("Remote client disconnect request sent through SmartLink.", 4000);
}
}
void MainWindow::showMultiFlexDialog()
{
MultiFlexDialog dlg(&m_radioModel, this);
connect(&dlg, &MultiFlexDialog::disconnectClientRequested,
this, &MainWindow::handleMultiFlexClientDisconnect);
dlg.exec();
}
void MainWindow::handleMultiFlexClientDisconnect(quint32 handle, const QString& displayName)
{
if (handle == 0 || handle == m_radioModel.ourClientHandle())
return;
QString name = cleanClientDisplayText(displayName);
if (name.isEmpty())
name = QString("client 0x%1").arg(handle, 8, 16, QChar('0')).toUpper();
if (m_radioModel.isWan()) {
const QString serial = !m_pendingWanRadio.serial.isEmpty()
? m_pendingWanRadio.serial
: m_radioModel.serial();
if (sendWanRadioClientDisconnects(serial, {handle})) {
m_connPanel->setStatusText("Disconnect request sent");
statusBar()->showMessage(
QString("SmartLink disconnect request sent for %1.").arg(name), 4000);
}
return;
}
if (m_radioModel.disconnectClient(handle))
statusBar()->showMessage(QString("Disconnect request sent for %1.").arg(name), 4000);
}
void MainWindow::startWanRadioConnect(const WanRadioInfo& info, bool promptForClientSlots)
{
QList<quint32> disconnectHandles;
if (promptForClientSlots && !confirmClientSlotAvailability(info, &disconnectHandles)) {
m_connPanel->setStatusText("Connection canceled");
setPanadapterConnectionAnimation(false);
return;
}
m_userDisconnected = false;
m_radioModel.setKnownGuiClients(splitClientField(info.guiClientHandles),
splitClientField(info.guiClientPrograms),
splitClientField(info.guiClientStations),
splitClientField(info.guiClientIps),
splitClientField(info.guiClientHosts));
m_radioModel.setPendingClientDisconnects(disconnectHandles);
m_connPanel->setStatusText("Requesting SmartLink connection…");
setPanadapterConnectionAnimation(true, "Connecting to remote radio…");
// Store WAN radio info for when connect_ready arrives
m_pendingWanRadio = info;
// Pre-bind UDP socket for VITA-49 reception BEFORE requesting
// connection, so we can pass our port to the SmartLink server.
// The server tells the radio our public IP:port for UDP streaming.
quint16 udpPort = m_radioModel.panStream()->localPort();
if (udpPort == 0) {
// Not yet bound — start WAN early to get a port
const quint16 radioUdpPort = static_cast<quint16>(
info.publicUdpPort > 0 ? info.publicUdpPort : 4993);
auto* ps = m_radioModel.panStream();
QMetaObject::invokeMethod(ps, [ps, info, radioUdpPort]() {
ps->startWan(QHostAddress(info.publicIp), radioUdpPort);
}, Qt::BlockingQueuedConnection);
udpPort = ps->localPort();
}
qDebug() << "MainWindow: pre-bound UDP port" << udpPort << "for WAN hole punch";
auto requestSmartLinkConnect = [this, serial = info.serial, udpPort] {
if (serial != m_pendingWanRadio.serial)
return;
m_smartLink.requestConnect(serial, udpPort);
};
if (!disconnectHandles.isEmpty()) {
sendWanRadioClientDisconnects(info.serial, disconnectHandles);
QTimer::singleShot(350, this, requestSmartLinkConnect);
} else {
requestSmartLinkConnect();
}
}
void MainWindow::requestWanReconnect()
{
if (m_userDisconnected || m_radioModel.isConnected()
|| m_pendingWanRadio.serial.isEmpty()) {
m_wanReconnectTimer.stop();
m_wanReconnectAttemptInProgress = false;
return;
}
if (m_wanReconnectAttemptInProgress) {
m_wanReconnectTimer.start();
return;
}
m_connPanel->setStatusText("Reconnecting via SmartLink…");
setPanadapterConnectionAnimation(true, "Reconnecting to remote radio…");
m_wanReconnectAttemptInProgress = true;
if (!m_smartLink.isConnected()) {
m_smartLink.reconnect();
m_wanReconnectTimer.start();
return;
}
startWanRadioConnect(m_pendingWanRadio, false);
m_wanReconnectTimer.start();
}
void MainWindow::showForcedDisconnectDialog(bool wasWan,
const RadioInfo& radioInfo,
const WanRadioInfo& wanInfo)
{
if (m_reconnectDlg) {
QDialog* reconnectDialog = m_reconnectDlg;
m_reconnectDlg = nullptr;
reconnectDialog->close();
reconnectDialog->deleteLater();
}
auto* dialog = new QDialog(this);
m_reconnectDlg = dialog;
dialog->setWindowTitle(tr("Radio Disconnected"));
dialog->setModal(true);
dialog->setWindowModality(Qt::ApplicationModal);
dialog->setWindowFlags(dialog->windowFlags() & ~Qt::WindowContextHelpButtonHint);
dialog->setFixedWidth(460);
AetherSDR::ThemeManager::instance().applyStyleSheet(dialog, "QDialog { background: {{color.background.0}}; }"
"QFrame#forcedDisconnectHeader {"
" background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
" stop:0 #103626, stop:1 #10283a);"
" border-bottom: 1px solid {{color.accent}};"
"}"
"QLabel { color: {{color.text.primary}}; background: transparent; }"
"QLabel#eyebrow { color: #40ff80; background: transparent; font-weight: bold; }"
"QLabel#title { color: {{color.text.primary}}; background: transparent; font-size: 18px; font-weight: bold; }"
"QLabel#body { color: {{color.text.primary}}; background: transparent; }"
"QPushButton {"
" background: {{color.background.1}};"
" border: 1px solid {{color.background.2}};"
" border-radius: 3px;"
" color: {{color.text.primary}};"
" padding: 7px 16px;"
"}"
"QPushButton:hover { background: {{color.background.1}}; border-color: {{color.accent}}; }"
"QPushButton#primaryButton {"
" background: {{color.accent}};"
" border-color: {{color.accent.bright}};"
" color: {{color.background.0}};"
" font-weight: bold;"
"}"
"QPushButton#primaryButton:hover { background: {{color.accent.bright}}; }");
auto* outer = new QVBoxLayout(dialog);
outer->setContentsMargins(0, 0, 0, 0);
outer->setSpacing(0);
auto* header = new QFrame(dialog);
header->setObjectName("forcedDisconnectHeader");
auto* headerLayout = new QVBoxLayout(header);
headerLayout->setContentsMargins(18, 14, 18, 14);
headerLayout->setSpacing(4);
auto* eyebrow = new QLabel(tr("CONNECTION ENDED"), header);
eyebrow->setObjectName("eyebrow");
headerLayout->addWidget(eyebrow);
auto* title = new QLabel(tr("Disconnected by another client"), header);
title->setObjectName("title");
headerLayout->addWidget(title);
outer->addWidget(header);
auto* content = new QWidget(dialog);
auto* layout = new QVBoxLayout(content);
layout->setContentsMargins(18, 16, 18, 18);
layout->setSpacing(14);
auto* body = new QLabel(
tr("Another client requested this AetherSDR session to disconnect. "
"Automatic reconnect has been paused so the other operator can use the radio safely."),
content);
body->setObjectName("body");
body->setWordWrap(true);
layout->addWidget(body);
auto* buttons = new QHBoxLayout;
buttons->setSpacing(10);
auto* quit = new QPushButton(tr("Quit"), content);
quit->setCursor(Qt::PointingHandCursor);
quit->setMinimumHeight(34);
buttons->addWidget(quit);
auto* reconnect = new QPushButton(tr("Reconnect"), content);
reconnect->setObjectName("primaryButton");
reconnect->setCursor(Qt::PointingHandCursor);
reconnect->setMinimumHeight(34);
buttons->addWidget(reconnect);
layout->addLayout(buttons);
outer->addWidget(content);
connect(dialog, &QObject::destroyed, this, [this, dialog] {
if (m_reconnectDlg == dialog)
m_reconnectDlg = nullptr;
});
connect(quit, &QPushButton::clicked, this, [this, dialog] {
m_userDisconnected = true;
if (m_reconnectDlg == dialog)
m_reconnectDlg = nullptr;
dialog->close();
dialog->deleteLater();
QApplication::quit();
});
connect(reconnect, &QPushButton::clicked, this, [this, dialog, wasWan, radioInfo, wanInfo] {
if (m_reconnectDlg == dialog)
m_reconnectDlg = nullptr;
dialog->close();
dialog->deleteLater();
m_userDisconnected = false;
m_connPanel->setStatusText("Reconnecting…");
setPanadapterConnectionAnimation(true, "Reconnecting to radio…");
QTimer::singleShot(300, this, [this, wasWan, radioInfo, wanInfo] {
if (wasWan && !wanInfo.serial.isEmpty()) {
startWanRadioConnect(wanInfo);
return;
}
if (radioInfo.address.isNull()) {
setPanadapterConnectionAnimation(false);
m_connPanel->setStatusText("Select a radio to reconnect");
m_connPanel->show();
return;
}
QList<quint32> disconnectHandles;
if (!confirmClientSlotAvailability(radioInfo, &disconnectHandles)) {
m_userDisconnected = true;
m_connPanel->setStatusText("Connection canceled");
setPanadapterConnectionAnimation(false);
return;
}
m_radioModel.setPendingClientDisconnects(disconnectHandles);
m_radioModel.connectToRadio(radioInfo);
});
});
dialog->adjustSize();
if (QScreen* screen = windowHandle() ? windowHandle()->screen() : QApplication::primaryScreen()) {
const QRect area = screen->availableGeometry();
dialog->move(area.center() - dialog->rect().center());
}
dialog->show();
dialog->raise();
dialog->activateWindow();
}
namespace {
// One session at startup (#3445 Camp B: the multi-radio seam is this vector).
std::vector<std::unique_ptr<RadioSession>> makeInitialSessions()
{
std::vector<std::unique_ptr<RadioSession>> sessions;
sessions.push_back(std::make_unique<RadioSession>());
sessions.front()->setSessionId(0);
return sessions;
}
} // namespace
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, m_sessions(makeInitialSessions())
, m_session(m_sessions.front().get())
, m_radioModel(m_session->radioModel())
{
// Status bar is the only top-level shell besides the spectrum / applet
// rail / titlebar that the operator can directly retheme. Declare its
// container here — statusBar() lazy-creates the QStatusBar on first
// call, so this is also the construction point.
theme::setContainer(statusBar(), QStringLiteral("statusbar"));
setWindowTitle(QString("AetherSDR v%1").arg(QCoreApplication::applicationVersion()));
setWindowIcon(QIcon(":/icon.png"));
setMinimumSize(1024, 400);
resize(1400, 800);
// Apply frameless flag before first show() so the window is created
// without chrome from the start — avoids the flash + re-create that
// setWindowFlags() after show would cause (#framleess via View menu).
// Default ON: TitleBar provides drag, double-click-maximize, and the
// min/max/close trio at the far right. View → Frameless Window can
// still toggle it off as an escape hatch.
{
auto& s = AppSettings::instance();
// One-shot migration: existing installs have FramelessWindow=False
// saved from when frameless was opt-in. Force ON for the
// transition so users see the new chrome by default; the View
// menu toggle still lets them flip it off afterwards.
if (!s.contains("FramelessMigratedV0823")) {
s.setValue("FramelessWindow", "True");
s.setValue("FramelessMigratedV0823", "True");
s.save();
}
if (s.value("FramelessWindow", "True").toString() == "True") {
#ifndef Q_OS_WIN
setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
#endif
}
// Theming layer-0 backdrop (Phase 5 PR 3 — "fade to desktop"
// experiment). Disabling the default opaque window background
// lets MainWindow::paintEvent() honour color.background.app's
// alpha. Today's installs see no visual change because the
// bundled themes ship the token fully opaque (#0f0f1a / #f5f5f8) —
// the architectural hook just lets operators dial alpha down
// through the Theme Editor to A/B test which applets/docks still
// need their own opaque backgrounds.
setAttribute(Qt::WA_TranslucentBackground, true);
setAutoFillBackground(false);
connect(&ThemeManager::instance(), &ThemeManager::themeChanged,
this, qOverload<>(&QWidget::update));
// 8-axis edge resize for frameless mode — same install pattern
// as the floating dialogs (SpotHub, RadioSetup, MemoryDialog).
// Filter sits on the native QWindow so it doesn't compete with
// the TitleBar's drag-to-move handler (the 6 px resize margin
// is well clear of the 18+ px title-bar height). Stays
// installed across frameless toggles — when the system frame is
// back on, the platform owns resize and our filter no-ops.
FramelessResizer::install(this);
// One-shot migration: collapse the legacy "CwDecodeOverlay" flat
// key into the nested AppSettings["CwDecoder"] blob (#2417). The
// legacy key only encoded RX-side decode; the new blob also holds
// the independent TX-side toggle.
CwDecodeSettings::migrateLegacy();
// One-shot migration: remove persisted per-slice audio mute state.
// The radio does not persist audio_mute, so restoring it from
// AppSettings caused Slice A to start muted on every reconnect.
if (!s.contains("SliceAudioMutedMigratedV0999")) {
// Cover A-H for FLEX-6700/M owners — the now-removed setter
// computed QChar('A' + sliceId) for sliceId 0..7, so 8-slice
// radios could have left up to eight orphan keys behind.
for (const QChar letter : {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'})
s.remove(QString("SliceAudioMuted_%1").arg(letter));
s.setValue("SliceAudioMutedMigratedV0999", "True");
s.save();
}
}
applyDarkTheme();
m_perfHeartbeatTimer.setInterval(50);
connect(&m_perfHeartbeatTimer, &QTimer::timeout, this, [] {
PerfTelemetry::instance().recordUiHeartbeat();
});
m_perfHeartbeatTimer.start();
// Audio worker thread (#502) — AudioEngine runs on its own thread so
// audio processing never competes with paintEvent for main thread CPU.
m_audioThread = new QThread(this);
// Lean render mode (#3283): read persisted state early so panadapters
// created during startup seed their Lean button/widget correctly, then
// apply once after construction to cover VFOs + the WAVE applet.
// Persistence is the nested "Display" blob (Principle V); the legacy
// flat "LeanMode" key is migrated into it on first read.
DisplaySettings::migrateLegacy();
m_leanMode = DisplaySettings::leanMode();