-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathSpectrumWidget.cpp
More file actions
8556 lines (7661 loc) · 340 KB
/
Copy pathSpectrumWidget.cpp
File metadata and controls
8556 lines (7661 loc) · 340 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 "SpectrumWidget.h"
#include "SpectrumOverlayMenu.h"
#include "VfoWidget.h"
#include "SliceColors.h"
#include "SliceColorManager.h"
#include "SliceLabel.h"
#include <QVariant>
#include <QVariantAnimation>
#ifdef AETHER_GPU_SPECTRUM
#include <rhi/qrhi.h>
#include <QFile>
#endif
#include <QPainter>
#include <QPainterPath>
#include <QResizeEvent>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QNativeGestureEvent>
#include <QMenu>
#include <QToolTip>
#include <QDialog>
#include <QFormLayout>
#include <QLineEdit>
#include <QComboBox>
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QFrame>
#include <QDoubleSpinBox>
#include <QLabel>
#include <QVBoxLayout>
#include <QWidgetAction>
#include <QApplication>
#include <QCoreApplication>
#include <QGuiApplication>
#include <QClipboard>
#include <QDesktopServices>
#include <QEvent>
#include <QStringList>
#include <QUrl>
#include "core/AppSettings.h"
#include "InteractionSettings.h"
#include "models/BandPlanManager.h"
#include "models/BandDefs.h"
#include <QDateTime>
#include <QTimeZone>
#include <QElapsedTimer>
#include <QVarLengthArray>
#include "core/LogManager.h"
#include "core/PerfTelemetry.h"
#include <QSoundEffect>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <utility>
#include "core/ThemeManager.h"
namespace AetherSDR {
bool SpectrumWidget::s_starstruckMode = false;
QSoundEffect* SpectrumWidget::s_starstruckSound = nullptr;
inline QColor kAetherBrandBlue() { return AetherSDR::ThemeManager::instance().color("color.accent"); }
inline QColor kAetherBrandGreen() { return AetherSDR::ThemeManager::instance().color("color.accent.success"); }
inline QColor kConnectionTextColor() { return AetherSDR::ThemeManager::instance().color("color.text.primary"); }
static constexpr float kMinDisplayDbm = -180.0f;
static constexpr int kWaterfallLineDurationMinMs = 1;
static constexpr int kWaterfallLineDurationMaxMs = 100;
static constexpr int kWaterfallHistoryCapacityMsPerRow = 50;
static constexpr int kWaterfallRatePercentMin = 1;
static constexpr int kWaterfallRatePercentMax = 100;
static constexpr int kNativeWaterfallFallbackMinTimeoutMs = 2000;
static constexpr int kNativeWaterfallFallbackMaxTimeoutMs = 20000;
static constexpr int kNativeWaterfallRateChangeGraceMaxMs = 14000;
static constexpr int kDbmReleaseHoldFrames = 10;
static constexpr int kDbmReleaseErrorSampleCount = 256;
static constexpr float kDbmReleasePreviewChangeThresholdDb = 0.05f;
static constexpr float kDbmReleaseRebaseMinImprovementDb = 0.75f;
static constexpr int kFilterEdgeGrabPx = 8;
static constexpr int kFilterPassbandMinBodyPx = 6;
static constexpr const char* kSliceCursorOverrideActiveProperty =
"_aetherSliceCursorOverrideActive";
static constexpr const char* kSliceCursorOverrideHadCursorProperty =
"_aetherSliceCursorOverrideHadCursor";
static constexpr const char* kSliceCursorOverrideShapeProperty =
"_aetherSliceCursorOverrideShape";
static Qt::CursorShape normalizedSpectrumCursorShape(Qt::CursorShape shape)
{
#ifdef Q_OS_MAC
switch (shape) {
case Qt::SplitVCursor:
return Qt::SizeVerCursor;
case Qt::SizeAllCursor:
return Qt::OpenHandCursor;
default:
break;
}
#endif
return shape;
}
static void setCursorOverride(QWidget* widget, Qt::CursorShape shape)
{
if (!widget) {
return;
}
if (!widget->property(kSliceCursorOverrideActiveProperty).toBool()) {
widget->setProperty(kSliceCursorOverrideHadCursorProperty,
widget->testAttribute(Qt::WA_SetCursor));
widget->setProperty(kSliceCursorOverrideShapeProperty,
static_cast<int>(widget->cursor().shape()));
widget->setProperty(kSliceCursorOverrideActiveProperty, true);
}
widget->setCursor(normalizedSpectrumCursorShape(shape));
}
static void clearCursorOverride(QWidget* widget)
{
if (!widget
|| !widget->property(kSliceCursorOverrideActiveProperty).toBool()) {
return;
}
const bool hadCursor =
widget->property(kSliceCursorOverrideHadCursorProperty).toBool();
const Qt::CursorShape previousShape = static_cast<Qt::CursorShape>(
widget->property(kSliceCursorOverrideShapeProperty).toInt());
widget->setProperty(kSliceCursorOverrideActiveProperty, false);
widget->setProperty(kSliceCursorOverrideHadCursorProperty, QVariant());
widget->setProperty(kSliceCursorOverrideShapeProperty, QVariant());
if (hadCursor) {
widget->setCursor(previousShape);
} else {
widget->unsetCursor();
}
}
static int filterInteriorGrabPx(int loX, int hiX, int grabPx)
{
const int widthPx = std::abs(hiX - loX);
if (widthPx <= kFilterPassbandMinBodyPx) {
return 0;
}
return std::min(grabPx, (widthPx - kFilterPassbandMinBodyPx - 1) / 2);
}
static int filterEdgeHitAtPixel(int mx, int loX, int hiX, int grabPx)
{
const int left = std::min(loX, hiX);
const int right = std::max(loX, hiX);
const bool insidePassband = mx >= left && mx <= right;
if (insidePassband && right - left <= kFilterPassbandMinBodyPx) {
return 0;
}
const int insideGrabPx = filterInteriorGrabPx(loX, hiX, grabPx);
const bool lowIsLeft = loX <= hiX;
const bool lowHit = lowIsLeft
? (mx >= loX - grabPx && mx <= loX + insideGrabPx)
: (mx >= loX - insideGrabPx && mx <= loX + grabPx);
const bool highHit = lowIsLeft
? (mx >= hiX - insideGrabPx && mx <= hiX + grabPx)
: (mx >= hiX - grabPx && mx <= hiX + insideGrabPx);
if (lowHit && highHit) {
return (std::abs(mx - loX) <= std::abs(mx - hiX)) ? -1 : 1;
}
if (lowHit) {
return -1;
}
if (highHit) {
return 1;
}
return 0;
}
static bool filterPassbandBodyHitAtPixel(int mx, int loX, int hiX, int grabPx)
{
const int left = std::min(loX, hiX);
const int right = std::max(loX, hiX);
return mx >= left && mx <= right
&& filterEdgeHitAtPixel(mx, loX, hiX, grabPx) == 0;
}
static constexpr int lineDurationToRatePercent(int lineDurationMs)
{
return std::clamp(lineDurationMs,
kWaterfallLineDurationMinMs,
kWaterfallLineDurationMaxMs);
}
static constexpr int ratePercentToLineDuration(int ratePercent)
{
// See SpectrumOverlayMenu.cpp: the rate control value is intentionally sent
// directly as line_duration. The tested behavior is 1 slowest, 100 fastest.
return std::clamp(ratePercent,
kWaterfallRatePercentMin,
kWaterfallRatePercentMax);
}
static_assert(ratePercentToLineDuration(1) == 1);
static_assert(ratePercentToLineDuration(100) == 100);
static_assert(lineDurationToRatePercent(1) == 1);
static_assert(lineDurationToRatePercent(100) == 100);
static float lineDurationToVisualMsPerRow(int lineDurationMs)
{
const int clamped = std::clamp(lineDurationMs,
kWaterfallLineDurationMinMs,
kWaterfallLineDurationMaxMs);
struct RateCalibration {
int ratePercent;
float msPerRow;
};
static constexpr RateCalibration kMeasuredRateCurve[] = {
{1, 6000.0f},
{8, 4000.9f},
{50, 677.2f},
{56, 473.2f},
{67, 223.0f},
{69, 192.1f},
{71, 163.9f},
{75, 120.7f},
{77, 102.0f},
{78, 90.5f},
{79, 88.8f},
{80, 81.2f},
{83, 64.2f},
{90, 46.3f},
{93, 42.0f},
{100, 42.0f},
};
if (clamped <= kMeasuredRateCurve[0].ratePercent) {
return kMeasuredRateCurve[0].msPerRow;
}
constexpr int kMeasuredRateCurveSize =
static_cast<int>(sizeof(kMeasuredRateCurve) / sizeof(kMeasuredRateCurve[0]));
for (int i = 1; i < kMeasuredRateCurveSize; ++i) {
const RateCalibration& lower = kMeasuredRateCurve[i - 1];
const RateCalibration& upper = kMeasuredRateCurve[i];
if (clamped <= upper.ratePercent) {
const float fraction = static_cast<float>(clamped - lower.ratePercent)
/ static_cast<float>(upper.ratePercent - lower.ratePercent);
const float lowerLog = std::log(lower.msPerRow);
const float upperLog = std::log(upper.msPerRow);
return std::exp(lowerLog + (upperLog - lowerLog) * fraction);
}
}
return kMeasuredRateCurve[kMeasuredRateCurveSize - 1].msPerRow;
}
static bool spotMarkersVisuallyEqual(const QVector<SpectrumWidget::SpotMarker>& lhs,
const QVector<SpectrumWidget::SpotMarker>& rhs)
{
constexpr double kFrequencyEpsilonMhz = 1.0e-6;
if (lhs.size() != rhs.size()) {
return false;
}
for (qsizetype i = 0; i < lhs.size(); ++i) {
const SpectrumWidget::SpotMarker& a = lhs.at(i);
const SpectrumWidget::SpotMarker& b = rhs.at(i);
if (a.callsign != b.callsign
|| std::abs(a.freqMhz - b.freqMhz) > kFrequencyEpsilonMhz
|| a.color != b.color
|| a.backgroundColor != b.backgroundColor
|| a.dxccColor != b.dxccColor
|| a.source != b.source) {
return false;
}
}
return true;
}
class PerfInputScope {
public:
explicit PerfInputScope(const char* kind)
: m_kind(kind),
m_enabled(PerfTelemetry::instance().enabled()),
m_startNs(m_enabled ? PerfTelemetry::nowNs() : 0)
{
}
~PerfInputScope()
{
if (!m_enabled)
return;
PerfTelemetry::instance().recordInputEvent(
m_kind,
static_cast<double>(PerfTelemetry::nowNs() - m_startNs) / 1000000.0);
}
private:
const char* m_kind;
bool m_enabled;
qint64 m_startNs;
};
class PerfUpdateScope {
public:
enum class Kind {
Panadapter,
Waterfall
};
explicit PerfUpdateScope(Kind kind)
: m_kind(kind),
m_enabled(PerfTelemetry::instance().enabled()),
m_startNs(m_enabled ? PerfTelemetry::nowNs() : 0)
{
}
~PerfUpdateScope()
{
if (!m_enabled)
return;
const double durationMs = static_cast<double>(PerfTelemetry::nowNs() - m_startNs) / 1000000.0;
if (m_kind == Kind::Waterfall)
PerfTelemetry::instance().recordWaterfallUpdate(durationMs);
else
PerfTelemetry::instance().recordPanUpdate(durationMs);
}
private:
Kind m_kind;
bool m_enabled;
qint64 m_startNs;
};
template <typename F>
class ScopeExit {
public:
explicit ScopeExit(F&& fn)
: m_fn(std::forward<F>(fn))
{
}
~ScopeExit()
{
m_fn();
}
ScopeExit(const ScopeExit&) = delete;
ScopeExit& operator=(const ScopeExit&) = delete;
private:
F m_fn;
};
template <typename F>
ScopeExit<F> makeScopeExit(F&& fn)
{
return ScopeExit<F>(std::forward<F>(fn));
}
static QString formatFlagFrequency(double freqMhz)
{
const long long hz = static_cast<long long>(std::llround(freqMhz * 1.0e6));
const int mhzPart = static_cast<int>(hz / 1000000);
const int khzPart = static_cast<int>((hz / 1000) % 1000);
const int hzPart = static_cast<int>(hz % 1000);
return QString("%1.%2.%3")
.arg(mhzPart)
.arg(khzPart, 3, 10, QChar('0'))
.arg(hzPart, 3, 10, QChar('0'));
}
static QString formatFreqScaleLabel(double freqMhz, int decimals)
{
QString label = QString::number(freqMhz, 'f', decimals);
const qsizetype dot = label.indexOf(QLatin1Char('.'));
if (dot < 0) {
return label;
}
const qsizetype minDecimals = std::min(decimals, 3);
const qsizetype minLength = dot + 1 + minDecimals;
while (label.size() > minLength && label.endsWith(QLatin1Char('0'))) {
label.chop(1);
}
return label;
}
// ─── Waterfall color scheme gradient cache ────────────────────────────────────
//
// The five preset schemes (Default, Grayscale, Blue-Green, Fire, Plasma) used
// to live as compile-time const tables. They now resolve through ThemeManager
// against `color.waterfall.colormap.{default,grayscale,blueGreen,fire,plasma}`
// gradient tokens so a theme switch (or user theme override) reshapes any of
// them. Cached once per theme load — `intensityToRgb` and `fftDbmToRgb` hit
// this hundreds of times per second per row, so we can't afford a token
// lookup on every pixel.
//
// Invalidated by ThemeManager::themeChanged via a SpectrumWidget connection
// in the constructor; first call lazily populates if the cache hasn't been
// initialized yet.
namespace {
struct WfStopsCache {
std::array<std::vector<WfGradientStop>, static_cast<int>(WfColorScheme::Count)> stops;
bool initialized = false;
};
WfStopsCache& wfStopsCache()
{
static WfStopsCache c;
return c;
}
const char* wfSchemeToken(WfColorScheme s)
{
switch (s) {
case WfColorScheme::Grayscale: return "color.waterfall.colormap.grayscale";
case WfColorScheme::BlueGreen: return "color.waterfall.colormap.blueGreen";
case WfColorScheme::Fire: return "color.waterfall.colormap.fire";
case WfColorScheme::Plasma: return "color.waterfall.colormap.plasma";
case WfColorScheme::Purple: return "color.waterfall.colormap.purple";
default: return "color.waterfall.colormap.default";
}
}
void rebuildWfStopsCacheFromTheme()
{
auto& c = wfStopsCache();
auto& tm = ThemeManager::instance();
for (int i = 0; i < static_cast<int>(WfColorScheme::Count); ++i) {
const QBrush br = tm.brush(QString::fromLatin1(
wfSchemeToken(static_cast<WfColorScheme>(i))));
std::vector<WfGradientStop> v;
if (br.gradient()) {
for (const auto& gs : br.gradient()->stops()) {
WfGradientStop s;
s.pos = static_cast<float>(gs.first);
s.r = gs.second.red();
s.g = gs.second.green();
s.b = gs.second.blue();
v.push_back(s);
}
}
// Fallback so a missing/malformed token still produces a usable
// black→white ramp instead of a divide-by-zero on the first paint.
if (v.size() < 2)
v = { {0.0f, 0, 0, 0}, {1.0f, 255, 255, 255} };
c.stops[i] = std::move(v);
}
c.initialized = true;
}
} // namespace
const WfGradientStop* wfSchemeStops(WfColorScheme scheme, int& count)
{
auto& c = wfStopsCache();
if (!c.initialized)
rebuildWfStopsCacheFromTheme();
const auto& v = c.stops[static_cast<int>(scheme)];
count = static_cast<int>(v.size());
return v.data();
}
const char* wfSchemeName(WfColorScheme scheme)
{
switch (scheme) {
case WfColorScheme::Grayscale: return "Grayscale";
case WfColorScheme::BlueGreen: return "Blue-Green";
case WfColorScheme::Fire: return "Fire";
case WfColorScheme::Plasma: return "Plasma";
case WfColorScheme::Purple: return "Purple";
default: return "Default";
}
}
// Interpolate a normalized value t (0–1) through the given gradient stops.
static QRgb interpolateGradient(float t, const WfGradientStop* stops, int n)
{
int i = 0;
while (i < n - 2 && stops[i + 1].pos < t) ++i;
const float seg = (t - stops[i].pos) / (stops[i + 1].pos - stops[i].pos);
const int r = static_cast<int>(stops[i].r + seg * (stops[i + 1].r - stops[i].r));
const int g = static_cast<int>(stops[i].g + seg * (stops[i + 1].g - stops[i].g));
const int b = static_cast<int>(stops[i].b + seg * (stops[i + 1].b - stops[i].b));
return qRgb(qBound(0, r, 255), qBound(0, g, 255), qBound(0, b, 255));
}
#ifdef AETHER_GPU_SPECTRUM
static bool qtSoftwareOpenGlRequested()
{
return qEnvironmentVariableIsSet("AETHER_NO_GPU")
|| qEnvironmentVariable("QT_OPENGL").compare(
QStringLiteral("software"), Qt::CaseInsensitive) == 0;
}
static bool qrhiDeviceNameLooksSoftware(const QString& deviceName)
{
const QString lower = deviceName.toLower();
return lower.contains(QStringLiteral("llvmpipe"))
|| lower.contains(QStringLiteral("softpipe"))
|| lower.contains(QStringLiteral("swiftshader"))
|| lower.contains(QStringLiteral("software"))
|| lower.contains(QStringLiteral("warp"))
|| lower.contains(QStringLiteral("microsoft basic render"));
}
#endif
QString SpectrumWidget::rendererDescription() const
{
#ifdef AETHER_GPU_SPECTRUM
QRhi* currentRhi = rhi();
if (!currentRhi) {
return QStringLiteral("QRhi initializing");
}
const QString backendName = QString::fromLatin1(currentRhi->backendName());
const QRhiDriverInfo driverInfo = currentRhi->driverInfo();
const QString deviceName = QString::fromUtf8(driverInfo.deviceName).trimmed();
const bool softwareOpenGl = currentRhi->backend() == QRhi::OpenGLES2
&& qtSoftwareOpenGlRequested();
const bool cpuDevice = driverInfo.deviceType == QRhiDriverInfo::CpuDevice
|| softwareOpenGl
|| qrhiDeviceNameLooksSoftware(deviceName);
QStringList details;
details << backendName;
if (!deviceName.isEmpty()) {
details << deviceName;
}
if (softwareOpenGl) {
details << QStringLiteral("software OpenGL");
}
return QStringLiteral("%1 QRhi (%2)")
.arg(cpuDevice ? QStringLiteral("CPU") : QStringLiteral("GPU"),
details.join(QStringLiteral("; ")));
#else
return QStringLiteral("CPU QPainter");
#endif
}
SpectrumWidget::SpectrumWidget(QWidget* parent)
: SPECTRUM_BASE_CLASS(parent)
{
// Container declaration — every token lookup made by this widget or
// any of its children (without their own declaration) resolves
// through the "spectrum" scope chain. Token migration into this
// scope happens in step 4 of the refactor.
theme::setContainer(this, QStringLiteral("spectrum"));
setMinimumHeight(100);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setAutoFillBackground(false);
setAccessibleName(tr("Panadapter spectrum display"));
#ifdef AETHER_GPU_SPECTRUM
// Explicitly request Metal on macOS.
# ifdef Q_OS_MAC
setApi(QRhiWidget::Api::Metal);
// WA_NativeWindow forces Qt to create a dedicated native NSView for this widget.
// Without it, QRhiWidget embedded in a QWidget hierarchy (especially one whose
// backing store was created before this widget was added) fails to obtain a QRhi
// context because the parent window's surface type is RasterSurface, not MetalSurface.
// A native window gives QRhiWidget its own Metal-capable surface to render into.
setAttribute(Qt::WA_NativeWindow);
# else
// Warn if running under XWayland — GLX context switching between the main
// window and child dialogs (e.g. Radio Setup) can trigger BadAccess (#1233).
// main.cpp normally forces native Wayland, but log it if we ended up here.
if (QGuiApplication::platformName() == QLatin1String("xcb")
&& qEnvironmentVariable("XDG_SESSION_TYPE") == QLatin1String("wayland")) {
qWarning() << "SpectrumWidget: running under XWayland with OpenGL — "
"GLX context issues may occur. Set QT_QPA_PLATFORM=wayland "
"or AETHER_NO_GPU=1 to work around (#1233)";
}
# endif
#else
setAttribute(Qt::WA_OpaquePaintEvent);
#endif
setSpectrumCursor(Qt::CrossCursor);
setMouseTracking(true);
// Floating overlay menu (child widget, stays on top)
m_overlayMenu = new SpectrumOverlayMenu(this);
m_overlayMenu->raise();
m_tnfHoverPopup = new QLabel(this);
m_tnfHoverPopup->setAttribute(Qt::WA_TransparentForMouseEvents);
m_tnfHoverPopup->setMargin(6);
m_tnfHoverPopup->hide();
m_tnfHoverPopup->raise();
m_interlockNotificationLabel = new QLabel(this);
m_interlockNotificationLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
m_interlockNotificationLabel->setAlignment(Qt::AlignCenter);
m_interlockNotificationLabel->setWordWrap(true);
AetherSDR::ThemeManager::instance().applyStyleSheet(m_interlockNotificationLabel, "QLabel { background: rgba(10,10,20,225); color: #d7fbff; "
"border: 2px solid {{color.accent}}; padding: 10px 14px; "
"font-size: 13px; font-weight: bold; }");
m_interlockNotificationLabel->hide();
m_interlockNotificationLabel->raise();
m_interlockNotificationTimer = new QTimer(this);
m_interlockNotificationTimer->setSingleShot(true);
connect(m_interlockNotificationTimer, &QTimer::timeout, this, [this]() {
m_interlockNotificationLabel->hide();
});
// Tune guide auto-hide timer (2-second inactivity timeout)
m_tuneGuideTimer = new QTimer(this);
m_tuneGuideTimer->setSingleShot(true);
m_tuneGuideTimer->setInterval(4000);
connect(m_tuneGuideTimer, &QTimer::timeout, this, [this]() {
m_tuneGuideVisible = false;
markOverlayDirty();
});
// SQL threshold line auto-hide (manual SQL only — see setSquelchLine).
// Shows for 3 s on enable or slider movement; slider re-adjust resets it.
// Auto SQL pins the line at the tracked level so the timer is skipped.
m_squelchLineHideTimer = new QTimer(this);
m_squelchLineHideTimer->setSingleShot(true);
m_squelchLineHideTimer->setInterval(3000);
connect(m_squelchLineHideTimer, &QTimer::timeout, this, [this]() {
m_squelchLineVisible = false;
markOverlayDirty();
});
m_connectionAnimationTimer = new QTimer(this);
m_connectionAnimationTimer->setInterval(40);
connect(m_connectionAnimationTimer, &QTimer::timeout, this, [this]() {
if (m_connectionAnimationVisible)
markOverlayDirty();
});
m_fpsMeterTimer = new QTimer(this);
m_fpsMeterTimer->setInterval(1000);
connect(m_fpsMeterTimer, &QTimer::timeout, this, [this]() {
updateFpsMeterValues();
});
createFpsMeterLabels();
// Load display settings (panIndex 0 by default — loadSettings() can be
// called again after setPanIndex() for multi-pan)
loadSettings();
// VFO widgets are created per-slice via addVfoWidget().
// m_vfoWidget is set by setActiveVfoWidget() as an alias to the active one.
// Bottom-left waterfall zoom buttons
static const QString kZoomBtnStyle =
"QPushButton { background: rgba(15,15,26,180); border: 1px solid #304050;"
" border-radius: 2px; color: #90a0b0; font-size: 11px; font-weight: bold;"
" padding: 0; margin: 0; min-width: 0; }"
"QPushButton:hover { background: rgba(30,50,70,200); color: #c8d8e8; }"
"QPushButton:pressed { background: #00b4d8; color: #000; }";
auto makeBtn = [&](const QString& text) {
auto* btn = new QPushButton(text, this);
btn->setFixedSize(22, 22);
btn->setStyleSheet(kZoomBtnStyle);
btn->setCursor(Qt::PointingHandCursor);
return btn;
};
m_zoomSegBtn = makeBtn("S");
m_zoomBandBtn = makeBtn("B");
m_zoomOutBtn = makeBtn("\u2212"); // minus sign U+2212
m_zoomInBtn = makeBtn("+");
// SmartSDR pcap: B sends "band_zoom=1", S sends "segment_zoom=1"
connect(m_zoomBandBtn, &QPushButton::clicked, this, [this]() {
emit bandZoomRequested();
});
connect(m_zoomSegBtn, &QPushButton::clicked, this, [this]() {
emit segmentZoomRequested();
});
// Bandwidth zoom: − zooms out (wider BW), + zooms in (narrower BW)
// Send both bandwidth AND current center to prevent the radio from
// auto-centering the panadapter (which causes band jumps).
auto emitZoom = [this](double factor) {
// Clamp to limits so the final click always reaches the exact min/max,
// matching mouse-drag which uses std::clamp (#1458).
const double newBw = std::clamp(m_bandwidthMhz * factor, m_minBwMhz, m_maxBwMhz);
if (newBw == m_bandwidthMhz) return; // already at the hard limit
// When zooming in, center on the active VFO so repeated clicks do not
// push it toward the panadapter edge (#1932).
double newCenter = m_centerMhz;
if (factor < 1.0) { // zooming in
const auto* ao = activeOverlay();
if (ao)
newCenter = ao->freqMhz;
}
newCenter = std::max(newCenter, newBw / 2.0);
reprojectWaterfall(m_centerMhz, m_bandwidthMhz, newCenter, newBw);
if (!reprojectSpectrum(m_centerMhz, m_bandwidthMhz, newCenter, newBw)) {
m_bins.clear();
m_smoothed.clear();
}
m_centerMhz = newCenter;
m_bandwidthMhz = newBw;
resetNoiseFloorBaseline();
markOverlayDirty();
emit frequencyRangeChangeRequested(newCenter, newBw);
};
connect(m_zoomOutBtn, &QPushButton::clicked, this, [emitZoom]() { emitZoom(1.5); });
connect(m_zoomInBtn, &QPushButton::clicked, this, [emitZoom]() { emitZoom(1.0 / 1.5); });
connect(&SliceColorManager::instance(), &SliceColorManager::colorsChanged,
this, [this]() { markOverlayDirty(); });
// Refresh the waterfall colormap cache when the theme changes. Existing
// already-rendered rows keep their pre-switch colours (same behaviour as
// changing the Scheme: dropdown — recolouring history would force a full
// O(rows × cols) repaint we don't currently amortise). New rows pick up
// the new palette on the next push.
connect(&ThemeManager::instance(), &ThemeManager::themeChanged,
this, [this]() {
rebuildWfStopsCacheFromTheme();
markOverlayDirty();
update();
});
// Phase 5 PR 3 — inspector coverage. SpectrumWidget paints through
// raw QPainter calls keyed off ThemeManager::instance().color(),
// bypassing the applyStyleSheet reverse-map. Declare the tokens it
// reads so an Inspect-mode click anywhere on the panadapter or
// waterfall surfaces a meaningful (if coarse) hit-list. Sub-region
// splits (trace vs grid vs waterfall vs slice triangles) come in a
// follow-up PR via declareWidgetRegions().
ThemeManager::instance().declareWidgetTokens(this, QStringList{
"color.background.0",
"color.background.1",
"color.background.2",
"color.background.3",
"color.background.spectrum",
"color.spectrum.trace",
"color.spectrum.peakHold",
"color.spectrum.average",
"color.spectrum.grid",
"color.text.primary",
"color.text.secondary",
"color.text.label",
"color.accent",
"color.accent.bright",
"color.accent.dim",
"color.accent.warning",
"color.accent.success",
"color.waterfall.colormap",
"color.slice.a", "color.slice.b", "color.slice.c", "color.slice.d",
"color.slice.e", "color.slice.f", "color.slice.g", "color.slice.h",
"color.slice.tx",
});
}
SpectrumWidget::~SpectrumWidget()
{
prepareForShutdown();
}
void SpectrumWidget::prepareForTopLevelChange()
{
#ifdef AETHER_GPU_SPECTRUM
#ifdef Q_OS_MAC
// QRhiWidget registers a cleanup callback with the current top-level
// backing-store QRhi. Direct splitter/floating-window reparenting can miss
// Qt's internal notification, leaving the old QRhi with a stale callback.
QEvent event(QEvent::WindowAboutToChangeInternal);
QCoreApplication::sendEvent(this, &event);
#endif
#endif
}
void SpectrumWidget::prepareForShutdown()
{
if (m_shutdownPrepared) {
return;
}
m_shutdownPrepared = true;
prepareForTopLevelChange();
setUpdatesEnabled(false);
hide();
#ifdef AETHER_GPU_SPECTRUM
releaseResources();
#ifdef Q_OS_MAC
// Drop the native child window while its parent backing store is still
// alive, so any remaining platform resources are gone before QWidgetWindow
// destruction runs on app exit.
destroy(true, true);
#endif
#endif
}
// ── Multi-VfoWidget management ────────────────────────────────────────────────
VfoWidget* SpectrumWidget::vfoWidget(int sliceId) const
{
return m_vfoWidgets.value(sliceId, nullptr);
}
bool SpectrumWidget::sliceHasSplitPartner(int sliceId) const
{
for (const auto& so : m_sliceOverlays) {
if (so.sliceId == sliceId)
return so.splitPartnerId >= 0;
}
return false;
}
QString SpectrumWidget::settingsKey(const QString& base) const
{
if (m_panIndex == 0)
return base; // backward compat — no suffix for pan 0
return QString("%1_%2").arg(base).arg(m_panIndex);
}
void SpectrumWidget::loadSettings()
{
auto& s = AppSettings::instance();
m_spectrumFrac = std::clamp(s.value(settingsKey("SpectrumSplitRatio"), "0.40").toFloat(), 0.10f, 0.90f);
m_fftAverage = s.value(settingsKey("DisplayFftAverage"), "0").toInt();
m_fftFps = s.value(settingsKey("DisplayFftFps"), "25").toInt();
m_fftFillAlpha = s.value(settingsKey("DisplayFftFillAlpha"), "0.70").toFloat();
m_fftWeightedAvg = s.value(settingsKey("DisplayFftWeightedAvg"), "False").toString() == "True";
const QString fillColorStr = s.value(settingsKey("DisplayFftFillColor"), "#00e5ff").toString();
QColor parsed(fillColorStr);
if (parsed.isValid())
m_fftFillColor = parsed;
m_wfColorGain = s.value(settingsKey("DisplayWfColorGain"), "50").toInt();
m_wfBlackLevel = s.value(settingsKey("DisplayWfBlackLevel"), "15").toInt();
m_wfAutoBlack = s.value(settingsKey("DisplayWfAutoBlack"), "True").toString() == "True";
m_wfAutoBlackOffset = s.value(settingsKey("DisplayWfAutoBlackOffset"), "50").toInt();
m_wfLineDuration = std::clamp(s.value(settingsKey("DisplayWfLineDuration"), "100").toInt(),
kWaterfallLineDurationMinMs,
kWaterfallLineDurationMaxMs);
PerfTelemetry::instance().setWaterfallLineDurationMs(m_wfLineDuration);
resetWfTimeScale();
// NB Waterfall Blanker (#277)
m_wfBlankerEnabled = s.value(settingsKey("WaterfallBlankingEnabled"), "False").toString() == "True";
m_wfBlankerMode = s.value(settingsKey("WaterfallBlankingMode"), "0").toInt();
m_wfBlankerThreshold = std::clamp(
s.value(settingsKey("WaterfallBlankingThreshold"), "1.15").toFloat(), 1.05f, 2.0f);
// Migrate old ShowBandPlan bool → BandPlanFontSize int
if (s.value("BandPlanFontSize").toString().isEmpty()) {
m_bandPlanFontSize = s.value("ShowBandPlan", "True").toString() == "True" ? 6 : 0;
} else {
m_bandPlanFontSize = s.value("BandPlanFontSize", "6").toInt();
}
m_bandPlanShowSpots = s.value("BandPlanShowSpots", "True").toString() == "True";
m_fftHeatMap = s.value(settingsKey("DisplayFftHeatMap"), "True").toString() == "True";
m_showGrid = s.value(settingsKey("DisplayShowGrid"), "True").toString() == "True";
m_freqGridSpacingKhz = s.value(settingsKey("DisplayFreqGridSpacing"), "0").toInt();
m_freqScaleFontPt = std::clamp(
s.value(settingsKey("DisplayFreqScaleFontPt"), "8").toInt(), 8, 14);
m_fftLineWidth = s.value(settingsKey("DisplayFftLineWidth"), "2.0").toFloat();
m_noiseFloorEnable = s.value(settingsKey("DisplayNoiseFloorEnable"), "False").toString() == "True";
m_noiseFloorPosition = std::clamp(
s.value(settingsKey("DisplayNoiseFloorPosition"), "75").toInt(), 1, 99);
// Match the enable-time fresh-frame seed used by setNoiseFloorEnable so a
// restored Floor=on locks onto the current floor without smoothing from a
// stale value.
m_noiseFloorFreshFrameCount = m_noiseFloorEnable ? 5 : 0;
applyFpsMeterVisibility(
s.value("DisplayFpsMeters", "False").toString() == "True");
m_wfColorScheme = static_cast<WfColorScheme>(
std::clamp(s.value(settingsKey("DisplayWfColorScheme"), "0").toInt(),
0, static_cast<int>(WfColorScheme::Count) - 1));
m_singleClickTune = s.value("SingleClickTune", "False").toString() == "True";
m_showTuneGuides = s.value("ShowTuneGuides", "False").toString() == "True";
m_extendedFrequencyLine = s.value("ExtendedFrequencyLine", "False").toString() == "True";
// Background image — default to bundled logo, "none" = explicitly cleared
QString bgPath = s.value(settingsKey("BackgroundImage"), ":/bg-default.jpg").toString();
if (bgPath != "none" && !bgPath.isEmpty())
setBackgroundImage(bgPath);
m_bgOpacity = s.value(settingsKey("BackgroundOpacity"), "80").toInt();
{
const QString hex = s.value(settingsKey("BackgroundFillColor"), "#0a0a14").toString();
QColor c(hex);
if (c.isValid()) m_bgFillColor = c;
}
// Sync overlay menu sliders with restored settings
if (m_overlayMenu) {
m_overlayMenu->syncDisplaySettings(m_fftAverage, m_fftFps,
static_cast<int>(m_fftFillAlpha * 100), m_fftWeightedAvg, m_fftFillColor,
m_wfColorGain, m_wfBlackLevel, m_wfAutoBlack, m_wfAutoBlackOffset,
m_wfLineDuration,
m_noiseFloorPosition, m_noiseFloorEnable,
m_fftHeatMap, static_cast<int>(m_wfColorScheme), m_showGrid,
m_fftLineWidth);
m_overlayMenu->syncExtraDisplaySettings(m_wfBlankerEnabled,
m_wfBlankerThreshold, m_bgOpacity, m_freqGridSpacingKhz, m_bgFillColor,
m_freqScaleFontPt);
}
// Refresh the noise-floor target so the slider position takes effect
// even when the overlay menu is built but not yet shown.
refreshNoiseFloorTarget();
}
VfoWidget* SpectrumWidget::addVfoWidget(int sliceId)
{
if (m_vfoWidgets.contains(sliceId))
return m_vfoWidgets[sliceId];
auto* w = new VfoWidget(this);
installVfoCursorEventFilter(w);
m_vfoWidgets[sliceId] = w;
w->show();
w->raise();
m_overlayMenu->raiseAll(); // keep overlay + panels on top of all VFO widgets
if (m_interlockNotificationLabel && m_interlockNotificationLabel->isVisible())
m_interlockNotificationLabel->raise();
return w;
}
void SpectrumWidget::installVfoCursorEventFilter(VfoWidget* widget)
{
if (!widget) {
return;
}
widget->setMouseTracking(true);
widget->installEventFilter(this);
const QList<QWidget*> children = widget->findChildren<QWidget*>();
for (QWidget* child : children) {
child->setMouseTracking(true);
child->installEventFilter(this);
}
}
void SpectrumWidget::setVfoCursorOverride(Qt::CursorShape shape)
{
for (QMap<int, VfoWidget*>::const_iterator it = m_vfoWidgets.cbegin();
it != m_vfoWidgets.cend(); ++it) {
VfoWidget* widget = it.value();
if (!widget) {
continue;
}
setCursorOverride(widget, shape);
const QList<QWidget*> children = widget->findChildren<QWidget*>();
for (QWidget* child : children) {
setCursorOverride(child, shape);
}
}
}
void SpectrumWidget::clearVfoCursorOverride()
{
for (QMap<int, VfoWidget*>::const_iterator it = m_vfoWidgets.cbegin();
it != m_vfoWidgets.cend(); ++it) {
VfoWidget* widget = it.value();
if (!widget) {
continue;
}
clearCursorOverride(widget);
const QList<QWidget*> children = widget->findChildren<QWidget*>();
for (QWidget* child : children) {
clearCursorOverride(child);
}
}
}
void SpectrumWidget::removeVfoWidget(int sliceId)
{
if (auto* w = m_vfoWidgets.take(sliceId)) {
if (m_vfoWidget == w)
m_vfoWidget = nullptr;
delete w;
}
}
void SpectrumWidget::setActiveVfoWidget(int sliceId)
{
m_vfoWidget = m_vfoWidgets.value(sliceId, nullptr);
if (m_vfoWidget) {
m_vfoWidget->raise();
m_overlayMenu->raiseAll(); // keep overlay above VFO
if (m_interlockNotificationLabel && m_interlockNotificationLabel->isVisible())
m_interlockNotificationLabel->raise();
}
}
// ── Display control setters (save to AppSettings on each change) ──────────────
void SpectrumWidget::setBandPlanManager(BandPlanManager* mgr) {
m_bandPlanMgr = mgr;
if (mgr)
connect(mgr, &BandPlanManager::planChanged, this, QOverload<>::of(&QWidget::update));
}
void SpectrumWidget::setFftAverage(int frames) {
m_fftAverage = frames;
auto& s = AppSettings::instance();