Repository navigation
Expand file tree
/
Copy pathdriverparametersdialog.cpp
More file actions
1115 lines (965 loc) · 42.7 KB
/
Copy pathdriverparametersdialog.cpp
File metadata and controls
1115 lines (965 loc) · 42.7 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
/*
* KFilter6
* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (C) 2002-2026 Martin Erdtmann
*/
#include "driverparametersdialog.h"
#include "driver.h"
#include "driverparametervalidation.h"
#include "kfilterdriverio.h"
#include "kfilterdoc.h"
#include "networkvalueutils.h"
#include <QAbstractSpinBox>
#include <QCheckBox>
#include <QColor>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QDir>
#include <QDoubleSpinBox>
#include <QFileDialog>
#include <QFileInfo>
#include <QFormLayout>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QLocale>
#include <QMessageBox>
#include <QPalette>
#include <QPushButton>
#include <QSettings>
#include <QSignalBlocker>
#include <QString>
#include <QTabWidget>
#include <QTimer>
#include <QVariant>
#include <QVBoxLayout>
#include <QValidator>
#include <QWidget>
#include <algorithm>
#include <cmath>
#include <limits>
namespace
{
QString stripSpinBoxAffixes(const QDoubleSpinBox *spinBox, const QString& text)
{
QString stripped = text.trimmed();
const QString prefix = spinBox->prefix();
if (!prefix.isEmpty() && stripped.startsWith(prefix)) {
stripped.remove(0, prefix.size());
stripped = stripped.trimmed();
}
const QString suffix = spinBox->suffix();
if (!suffix.isEmpty() && stripped.endsWith(suffix)) {
stripped.chop(suffix.size());
stripped = stripped.trimmed();
} else {
const QString trimmedSuffix = suffix.trimmed();
if (!trimmedSuffix.isEmpty() && stripped.endsWith(trimmedSuffix)) {
stripped.chop(trimmedSuffix.size());
stripped = stripped.trimmed();
}
}
return stripped;
}
bool parseSpinBoxText(const QDoubleSpinBox *spinBox,
const QString& text,
double& value,
double minimum,
double maximum)
{
return NetworkValueUtils::parseDisplayValue(stripSpinBoxAffixes(spinBox, text),
value,
minimum,
maximum);
}
bool isIncompleteNumber(const QString& text, double minimum)
{
if (text.isEmpty()) {
return true;
}
if (text == QLatin1String("+") || text == QLatin1String(".") || text == QLatin1String(",")) {
return true;
}
if (text == QLatin1String("-")) {
return minimum < 0.0;
}
if (text == QLatin1String("+.") || text == QLatin1String("+,")) {
return true;
}
if (text == QLatin1String("-.") || text == QLatin1String("-,")) {
return minimum < 0.0;
}
if (text.endsWith(QLatin1Char('.')) || text.endsWith(QLatin1Char(','))) {
double parsedPrefix = 0.0;
return NetworkValueUtils::parseDisplayValue(text.left(text.size() - 1),
parsedPrefix,
-std::numeric_limits<double>::max(),
std::numeric_limits<double>::max());
}
return false;
}
class DriverValueSpinBox : public QDoubleSpinBox
{
public:
explicit DriverValueSpinBox(QWidget *parent = nullptr)
: QDoubleSpinBox(parent)
{
setCorrectionMode(QAbstractSpinBox::CorrectToPreviousValue);
}
protected:
double valueFromText(const QString& text) const override
{
double parsed = 0.0;
if (parseSpinBoxText(this, text, parsed, minimum(), maximum())) {
return parsed;
}
return value();
}
QValidator::State validate(QString& input, int& pos) const override
{
Q_UNUSED(pos);
const QString stripped = stripSpinBoxAffixes(this, input);
if (isIncompleteNumber(stripped, minimum())) {
return QValidator::Intermediate;
}
double parsed = 0.0;
if (parseSpinBoxText(this, input, parsed, minimum(), maximum())) {
return QValidator::Acceptable;
}
if (parseSpinBoxText(this,
input,
parsed,
-std::numeric_limits<double>::max(),
std::numeric_limits<double>::max())) {
return QValidator::Intermediate;
}
return QValidator::Invalid;
}
};
QDoubleSpinBox *createSpinBox(double minimum,
double maximum,
int decimals,
double singleStep,
const QString& suffix = QString())
{
auto *spinBox = new DriverValueSpinBox;
spinBox->setRange(minimum, maximum);
spinBox->setDecimals(decimals);
spinBox->setSingleStep(singleStep);
spinBox->setKeyboardTracking(false);
if (!suffix.isEmpty()) {
spinBox->setSuffix(suffix);
}
return spinBox;
}
void addRow(QFormLayout *layout, const QString& label, QWidget *editor)
{
layout->addRow(label, editor);
}
double linearGainToDb(double gain)
{
if (gain <= 0.0 || !std::isfinite(gain)) {
return 0.0;
}
return 20.0 * std::log10(gain);
}
double dbToLinearGain(double db)
{
return std::pow(10.0, db / 20.0);
}
double calculateBassReflexTubeLengthCm(double diameterCm, double fbHz, double vbLiter)
{
if (diameterCm <= 0.0 || fbHz <= 0.0 || vbLiter <= 0.0 ||
!std::isfinite(diameterCm) || !std::isfinite(fbHz) || !std::isfinite(vbLiter)) {
return 0.0;
}
constexpr double pi = 3.14159265358979323846;
const double tubeAreaCm2 = pi * std::pow(diameterCm * 0.5, 2.0);
const double effectiveLengthCm = 29830.0 * tubeAreaCm2 / (fbHz * fbHz * vbLiter);
return effectiveLengthCm - 0.825 * std::sqrt(tubeAreaCm2);
}
double calculateBassReflexTubeDiameterCm(double lengthCm, double fbHz, double vbLiter)
{
if (lengthCm <= 0.0 || fbHz <= 0.0 || vbLiter <= 0.0 ||
!std::isfinite(lengthCm) || !std::isfinite(fbHz) || !std::isfinite(vbLiter)) {
return 0.0;
}
constexpr double pi = 3.14159265358979323846;
constexpr double endCorrectionFactor = 0.825;
const double areaCoefficient = 29830.0 / (fbHz * fbHz * vbLiter);
const double discriminant = endCorrectionFactor * endCorrectionFactor +
4.0 * areaCoefficient * lengthCm;
if (areaCoefficient <= 0.0 || !std::isfinite(areaCoefficient) ||
discriminant < 0.0 || !std::isfinite(discriminant)) {
return 0.0;
}
// With x = sqrt(tube area), the forward formula becomes
// areaCoefficient*x^2 - 0.825*x - length = 0. The positive root is the
// only physical solution for a positive tube length.
const double areaRoot = (endCorrectionFactor + std::sqrt(discriminant)) /
(2.0 * areaCoefficient);
const double diameterCm = 2.0 * areaRoot / std::sqrt(pi);
return diameterCm > 0.0 && std::isfinite(diameterCm) ? diameterCm : 0.0;
}
QString tubeDiameterSettingsKey(int driverIndex)
{
return QStringLiteral("DriverParameters/tubeDiameter%1").arg(driverIndex + 1);
}
QString driverSlotFileFilter(const QObject *context)
{
return context->tr("KFilter Driver Files (*.kfd);;JSON Files (*.json);;All Files (*)");
}
QString sanitizedFileNamePart(QString text)
{
text = text.trimmed();
if (text.isEmpty()) {
return QStringLiteral("driver");
}
QString result;
result.reserve(text.size());
for (const QChar character : text) {
if (character.isLetterOrNumber() || character == QLatin1Char('-') || character == QLatin1Char('_')) {
result.append(character);
} else if (!result.endsWith(QLatin1Char('_'))) {
result.append(QLatin1Char('_'));
}
}
result = result.trimmed();
while (result.endsWith(QLatin1Char('_'))) {
result.chop(1);
}
if (result.isEmpty()) {
return QStringLiteral("driver");
}
return result;
}
QString suggestedDriverSlotPath(const driver& drv, int driverIndex)
{
const QString titlePart = sanitizedFileNamePart(drv.getTitle());
return QDir::home().filePath(QStringLiteral("kfilter_driver_%1_%2.kfd")
.arg(driverIndex + 1)
.arg(titlePart));
}
}
DriverParametersDialog::DriverParametersDialog(KFilterDoc& document,
QWidget *parent,
int initialDriverIndex)
: QDialog(parent),
m_document(document),
m_drivers(document.m_driverDriver)
{
setWindowTitle(tr("Driver parameters"));
resize(740, 520);
m_previewTimer = new QTimer(this);
m_previewTimer->setSingleShot(true);
m_previewTimer->setInterval(150);
connect(m_previewTimer, &QTimer::timeout, this, &DriverParametersDialog::emitPreview);
auto *mainLayout = new QVBoxLayout(this);
m_tabs = new QTabWidget(this);
m_tabs->setObjectName(QStringLiteral("driverParametersTabs"));
for (int index = 0; index < KFilterProjectIo::DriverCount; ++index) {
m_tabs->addTab(createDriverPage(index), tr("Driver %1").arg(index + 1));
}
const int safeInitialDriverIndex =
std::clamp(initialDriverIndex, 0, KFilterProjectIo::DriverCount - 1);
m_tabs->setCurrentIndex(safeInitialDriverIndex);
auto *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok |
QDialogButtonBox::Apply |
QDialogButtonBox::Cancel,
this);
connect(buttonBox, &QDialogButtonBox::accepted, this, &DriverParametersDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &DriverParametersDialog::reject);
connect(buttonBox->button(QDialogButtonBox::Apply), &QPushButton::clicked,
this, &DriverParametersDialog::applyClicked);
mainLayout->addWidget(m_tabs);
mainLayout->addWidget(buttonBox);
loadFromDrivers();
rememberCommittedState();
}
int DriverParametersDialog::currentDriverIndex() const
{
return m_tabs ? m_tabs->currentIndex() : 0;
}
QWidget *DriverParametersDialog::createDriverPage(int index)
{
DriverPage& page = m_pages.at(index);
page.page = new QWidget(this);
page.title = new QLineEdit(page.page);
page.rdc = createSpinBox(0.001, 1000.0, 4, 0.1, tr(" Ohm"));
page.lspMilliHenry = createSpinBox(0.0, 1000.0, 6, 0.01, tr(" mH"));
page.f0 = createSpinBox(0.0, 100000.0, 3, 1.0, tr(" Hz"));
page.qts = createSpinBox(0.001, 1000.0, 5, 0.01);
page.qes = createSpinBox(0.001, 1000.0, 5, 0.01);
page.qms = createSpinBox(0.001, 1000.0, 5, 0.01);
page.vas = createSpinBox(0.0, 100000.0, 3, 1.0, tr(" l"));
page.dm = createSpinBox(0.0, 1000.0, 3, 0.1, tr(" cm"));
page.vb = createSpinBox(0.0, 100000.0, 3, 1.0, tr(" l"));
page.ql = createSpinBox(0.001, 1000.0, 5, 0.1);
page.fb = createSpinBox(0.0, 100000.0, 3, 1.0, tr(" Hz"));
page.tubeDiameter = createSpinBox(0.0, 1000.0, 3, 0.1, tr(" cm"));
page.tubeLength = createSpinBox(0.0, 100000.0, 1, 0.1, tr(" cm"));
page.tubeLength->setSpecialValueText(tr("n. a."));
page.v2 = createSpinBox(0.0, 100000.0, 3, 1.0, tr(" l"));
page.gainDb = createSpinBox(-60.0, 60.0, 2, 0.5, tr(" dB"));
const QString controlSuffix = QString::number(index + 1);
page.vb->setObjectName(QStringLiteral("driverVbSpin") + controlSuffix);
page.ql->setObjectName(QStringLiteral("driverQlSpin") + controlSuffix);
page.fb->setObjectName(QStringLiteral("driverFbSpin") + controlSuffix);
page.tubeDiameter->setObjectName(QStringLiteral("driverTubeDiameterSpin") + controlSuffix);
page.tubeLength->setObjectName(QStringLiteral("driverTubeLengthSpin") + controlSuffix);
page.qts->setObjectName(QStringLiteral("driverQtsSpin") + controlSuffix);
page.qes->setObjectName(QStringLiteral("driverQesSpin") + controlSuffix);
page.qms->setObjectName(QStringLiteral("driverQmsSpin") + controlSuffix);
page.v2->setObjectName(QStringLiteral("driverV2Spin") + controlSuffix);
page.gainDb->setObjectName(QStringLiteral("driverGainSpin") + controlSuffix);
const int enclosureEditorWidth = page.gainDb->sizeHint().width();
page.vb->setFixedWidth(enclosureEditorWidth);
page.ql->setFixedWidth(enclosureEditorWidth);
page.fb->setFixedWidth(enclosureEditorWidth);
page.tubeDiameter->setFixedWidth(enclosureEditorWidth);
page.tubeLength->setFixedWidth(enclosureEditorWidth);
page.v2->setFixedWidth(enclosureEditorWidth);
page.alignmentProposal = new QComboBox(page.page);
page.alignmentProposal->addItem(tr("Open baffle driver"), 0);
page.alignmentProposal->addItem(tr("Sealed enclosure"), 1);
page.alignmentProposal->addItem(tr("Vented enclosure"), 2);
page.alignmentProposal->addItem(tr("Bandpass enclosure"), 3);
page.alignmentProposal->setObjectName(QStringLiteral("driverEnclosureTypeCombo") + controlSuffix);
page.pressureActive = new QCheckBox(tr("Show SPL curve"), page.page);
page.impedanceActive = new QCheckBox(tr("Show impedance curve"), page.page);
page.summaryActive = new QCheckBox(tr("Include in vector SPL sum"), page.page);
page.scalarSummaryActive = new QCheckBox(tr("Include in energetic SPL sum"), page.page);
page.impedanceSummaryActive = new QCheckBox(tr("Include in total impedance"), page.page);
page.invertPhase = new QCheckBox(tr("Invert polarity"), page.page);
page.fullCircuit = new QCheckBox(tr("Use full crossover simulation"), page.page);
page.pressureActive->setToolTip(tr("Show this driver's sound pressure level curve."));
page.impedanceActive->setToolTip(tr("Show this driver's impedance curve."));
page.summaryActive->setToolTip(tr("Include this driver's SPL curve in the phase-aware vector sum."));
page.scalarSummaryActive->setToolTip(tr("Include this driver's SPL curve in the energetic SPL sum. Unlike the vector SPL sum, phase cancellation and addition are ignored."));
page.impedanceSummaryActive->setToolTip(tr("Include this driver's impedance curve in the total parallel impedance seen by the amplifier."));
page.invertPhase->setToolTip(tr("Invert this driver's polarity by 180 degrees for the SPL calculation."));
page.fullCircuit->setToolTip(tr("Use the full crossover network for this driver instead of the simplified calculation."));
page.ql->setToolTip(tr("Enclosure loss damping factor. It affects sealed, vented, and bandpass calculations. Must be greater than zero."));
page.tubeDiameter->setToolTip(tr("Inner diameter of one round bass reflex tube. Editing it recalculates the tube length from Vb and Fb."));
page.tubeLength->setToolTip(tr("Physical bass reflex tube length. Editing it recalculates the tube diameter from Vb and Fb."));
auto *leftForm = new QFormLayout;
addRow(leftForm, tr("Driver name"), page.title);
addRow(leftForm, tr("Rdc"), page.rdc);
addRow(leftForm, tr("Lsp"), page.lspMilliHenry);
addRow(leftForm, tr("Fs"), page.f0);
auto *qtsLayoutWidget = new QWidget(page.page);
auto *qtsLayout = new QHBoxLayout(qtsLayoutWidget);
qtsLayout->setContentsMargins(0, 0, 0, 0);
qtsLayout->addWidget(page.qts);
page.qtsConsistencyHint = new QLabel(qtsLayoutWidget);
page.qtsConsistencyHint->setObjectName(QStringLiteral("driverQtsConsistencyHint") + controlSuffix);
QPalette hintPalette = page.qtsConsistencyHint->palette();
hintPalette.setColor(QPalette::WindowText, QColor(0xd0, 0x30, 0x30));
page.qtsConsistencyHint->setPalette(hintPalette);
qtsLayout->addWidget(page.qtsConsistencyHint);
qtsLayout->addStretch(1);
addRow(leftForm, tr("Qts"), qtsLayoutWidget);
addRow(leftForm, tr("Qes"), page.qes);
addRow(leftForm, tr("Qms"), page.qms);
addRow(leftForm, tr("Vas"), page.vas);
addRow(leftForm, tr("Diameter"), page.dm);
page.qtsButton = new QPushButton(tr("Calculate Qts from Qes and Qms"), page.page);
page.qtsButton->setObjectName(QStringLiteral("driverQtsButton") + controlSuffix);
connect(page.qtsButton, &QPushButton::clicked, this, [this, index]() {
updateQtsForPage(m_pages.at(index));
});
leftForm->addRow(QString(), page.qtsButton);
auto *driverIoWidget = new QWidget(page.page);
auto *driverIoLayout = new QHBoxLayout(driverIoWidget);
driverIoLayout->setContentsMargins(0, 0, 0, 0);
auto *importButton = new QPushButton(tr("Import Driver..."), driverIoWidget);
auto *exportButton = new QPushButton(tr("Export Driver..."), driverIoWidget);
importButton->setToolTip(tr("Import a complete driver slot including network, measurement, active-filter, baffle, and floor-reflection state into this driver."));
exportButton->setToolTip(tr("Export this complete driver slot including network, measurement, active-filter, baffle, and floor-reflection state."));
driverIoLayout->addWidget(importButton);
driverIoLayout->addWidget(exportButton);
leftForm->addRow(QString(), driverIoWidget);
connect(importButton, &QPushButton::clicked, this, [this, index]() {
importDriver(index);
});
connect(exportButton, &QPushButton::clicked, this, [this, index]() {
exportDriver(index);
});
auto *boxForm = new QFormLayout;
auto *vbLayoutWidget = new QWidget(page.page);
auto *vbLayout = new QHBoxLayout(vbLayoutWidget);
vbLayout->setContentsMargins(0, 0, 0, 0);
vbLayout->addWidget(page.vb);
auto *qlLabel = new QLabel(tr("Ql"), vbLayoutWidget);
vbLayout->addWidget(qlLabel);
vbLayout->addWidget(page.ql);
vbLayout->addStretch(1);
addRow(boxForm, tr("Vb"), vbLayoutWidget);
auto *fbLayoutWidget = new QWidget(page.page);
auto *fbLayout = new QHBoxLayout(fbLayoutWidget);
fbLayout->setContentsMargins(0, 0, 0, 0);
fbLayout->addWidget(page.fb);
auto *qlLabelSpacer = new QWidget(fbLayoutWidget);
qlLabelSpacer->setFixedWidth(qlLabel->sizeHint().width());
fbLayout->addWidget(qlLabelSpacer);
page.hogeButton = new QPushButton(tr("Hoge"), fbLayoutWidget);
page.hogeButton->setObjectName(QStringLiteral("driverHogeButton") + controlSuffix);
page.hogeButton->setFixedWidth(enclosureEditorWidth);
page.hogeButton->setToolTip(tr("Calculate Vb and Fb from Fs, Qts, and Vas using the legacy Hoge formula."));
fbLayout->addWidget(page.hogeButton);
fbLayout->addStretch(1);
addRow(boxForm, tr("Fb"), fbLayoutWidget);
connect(page.hogeButton, &QPushButton::clicked, this, [this, index]() {
calculateHogeForPage(m_pages.at(index));
});
auto *tubeLayoutWidget = new QWidget(page.page);
auto *tubeLayout = new QHBoxLayout(tubeLayoutWidget);
tubeLayout->setContentsMargins(0, 0, 0, 0);
tubeLayout->addWidget(page.tubeDiameter);
auto *tubeColumnSpacer = new QWidget(tubeLayoutWidget);
tubeColumnSpacer->setFixedWidth(qlLabel->sizeHint().width());
tubeLayout->addWidget(tubeColumnSpacer);
tubeLayout->addWidget(page.tubeLength);
addRow(boxForm, tr("Tube D / L"), tubeLayoutWidget);
addRow(boxForm, tr("V2"), page.v2);
addRow(boxForm, tr("Gain"), page.gainDb);
addRow(boxForm, tr("Enclosure type"), page.alignmentProposal);
auto *optionsLayout = new QVBoxLayout;
optionsLayout->addWidget(page.pressureActive);
optionsLayout->addWidget(page.impedanceActive);
optionsLayout->addWidget(page.summaryActive);
optionsLayout->addWidget(page.scalarSummaryActive);
optionsLayout->addWidget(page.impedanceSummaryActive);
optionsLayout->addWidget(page.invertPhase);
optionsLayout->addWidget(page.fullCircuit);
optionsLayout->addStretch(1);
auto *leftGroup = new QGroupBox(tr("Thiele/Small parameters"), page.page);
leftGroup->setLayout(leftForm);
auto *boxGroup = new QGroupBox(tr("Enclosure and gain"), page.page);
boxGroup->setLayout(boxForm);
auto *optionsGroup = new QGroupBox(tr("Curves and totals"), page.page);
optionsGroup->setLayout(optionsLayout);
auto *grid = new QGridLayout(page.page);
grid->addWidget(leftGroup, 0, 0, 2, 1);
grid->addWidget(boxGroup, 0, 1);
grid->addWidget(optionsGroup, 1, 1);
grid->setColumnStretch(0, 1);
grid->setColumnStretch(1, 1);
connect(page.vb, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
this, [this, index](double) { updateTubeLengthForPage(m_pages.at(index)); });
connect(page.fb, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
this, [this, index](double) { updateTubeLengthForPage(m_pages.at(index)); });
connect(page.tubeDiameter, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
this, [this, index](double) { updateTubeLengthForPage(m_pages.at(index)); });
connect(page.tubeLength, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
this, [this, index](double) {
updateTubeDiameterForPage(m_pages.at(index));
schedulePreview();
});
for (QDoubleSpinBox *qualityFactor : {page.qts, page.qes, page.qms}) {
connect(qualityFactor,
static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
this, [this, index](double) { updateQtsConsistencyForPage(m_pages.at(index)); });
}
connectPreviewSignals(page, index);
updateEnclosureFieldStates(page);
updateQtsConsistencyForPage(page);
return page.page;
}
void DriverParametersDialog::connectPreviewSignals(DriverPage& page, int index)
{
auto connectSpinBox = [this](QDoubleSpinBox *spinBox) {
connect(spinBox, &QDoubleSpinBox::textChanged,
this, &DriverParametersDialog::schedulePreview);
connect(spinBox,
static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
this,
[this](double) { schedulePreview(); });
};
connect(page.title, &QLineEdit::textEdited,
this, &DriverParametersDialog::schedulePreview);
connectSpinBox(page.rdc);
connectSpinBox(page.lspMilliHenry);
connectSpinBox(page.f0);
connectSpinBox(page.qts);
connectSpinBox(page.qes);
connectSpinBox(page.qms);
connectSpinBox(page.vas);
connectSpinBox(page.dm);
connectSpinBox(page.vb);
connectSpinBox(page.ql);
connectSpinBox(page.fb);
connectSpinBox(page.tubeDiameter);
connectSpinBox(page.v2);
connectSpinBox(page.gainDb);
connect(page.alignmentProposal,
static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this,
[this, index](int) {
updateEnclosureFieldStates(m_pages.at(index));
schedulePreview();
});
connect(page.pressureActive, &QCheckBox::toggled,
this, &DriverParametersDialog::schedulePreview);
connect(page.impedanceActive, &QCheckBox::toggled,
this, &DriverParametersDialog::schedulePreview);
connect(page.summaryActive, &QCheckBox::toggled,
this, &DriverParametersDialog::schedulePreview);
connect(page.scalarSummaryActive, &QCheckBox::toggled,
this, &DriverParametersDialog::schedulePreview);
connect(page.impedanceSummaryActive, &QCheckBox::toggled,
this, &DriverParametersDialog::schedulePreview);
connect(page.invertPhase, &QCheckBox::toggled,
this, &DriverParametersDialog::schedulePreview);
connect(page.fullCircuit, &QCheckBox::toggled,
this, &DriverParametersDialog::schedulePreview);
}
bool DriverParametersDialog::readSpinBoxValue(const QDoubleSpinBox *spinBox,
const QString& label,
int driverIndex,
double& value,
QString *errorMessage) const
{
double parsedValue = 0.0;
const bool ok = spinBox != nullptr &&
parseSpinBoxText(spinBox,
spinBox->text(),
parsedValue,
spinBox->minimum(),
spinBox->maximum()) &&
std::isfinite(parsedValue);
if (!ok) {
if (errorMessage != nullptr && errorMessage->isEmpty()) {
*errorMessage = tr("Driver %1: invalid value for %2.")
.arg(driverIndex + 1)
.arg(label);
}
return false;
}
value = parsedValue;
return true;
}
void DriverParametersDialog::loadPageFromDriver(int index,
bool useTubeDiameterOverride,
double tubeDiameterCm)
{
if (index < 0 || index >= KFilterProjectIo::DriverCount) {
return;
}
const bool wasLoading = m_loadingFromDrivers;
m_loadingFromDrivers = true;
QSettings settings;
DriverPage& page = m_pages.at(index);
driver& drv = m_drivers[index];
page.title->setText(drv.getTitle());
page.rdc->setValue(drv.getRdc());
page.lspMilliHenry->setValue(drv.getLsp() * 1000.0);
page.f0->setValue(drv.getF0());
page.qts->setValue(drv.getQts());
page.qes->setValue(drv.getQes());
page.qms->setValue(drv.getQms());
page.vas->setValue(drv.getVas());
page.dm->setValue(drv.getDm());
page.vb->setValue(drv.getVb());
page.ql->setValue(drv.getQl());
page.fb->setValue(drv.getFb());
page.tubeDiameter->setValue(useTubeDiameterOverride
? tubeDiameterCm
: settings.value(tubeDiameterSettingsKey(index), 0.0).toDouble());
page.v2->setValue(drv.getV2());
page.gainDb->setValue(linearGainToDb(drv.getGainLinear()));
const int alignmentIndex = page.alignmentProposal->findData(static_cast<int>(drv.getEnclosureTypeProposal()));
page.alignmentProposal->setCurrentIndex(alignmentIndex >= 0 ? alignmentIndex : 0);
updateEnclosureFieldStates(page);
const DriverPlotState& plotState = drv.plotState();
page.pressureActive->setChecked(plotState.pressure);
page.impedanceActive->setChecked(plotState.impedance);
page.summaryActive->setChecked(plotState.vectorSummary);
page.scalarSummaryActive->setChecked(plotState.scalarSummary);
page.impedanceSummaryActive->setChecked(plotState.impedanceSummary);
page.invertPhase->setChecked(drv.isPhaseInverted());
page.fullCircuit->setChecked(drv.getFullCircuit());
updateTubeLengthForPage(page);
m_loadingFromDrivers = wasLoading;
}
void DriverParametersDialog::loadFromDrivers()
{
const bool wasLoading = m_loadingFromDrivers;
m_loadingFromDrivers = true;
for (int index = 0; index < KFilterProjectIo::DriverCount; ++index) {
loadPageFromDriver(index);
}
m_loadingFromDrivers = wasLoading;
}
bool DriverParametersDialog::applyToDrivers(ApplyMode mode, QString *errorMessage)
{
struct ParsedPage
{
QString title;
double rdc = 0.0;
double lspMilliHenry = 0.0;
double f0 = 0.0;
double qts = 0.0;
double qes = 0.0;
double qms = 0.0;
double vas = 0.0;
double dm = 0.0;
double vb = 0.0;
double ql = 0.0;
double fb = 0.0;
double tubeDiameterCm = 0.0;
double v2 = 0.0;
int alignmentProposal = 0;
double gainDb = 0.0;
bool pressureActive = false;
bool impedanceActive = false;
bool summaryActive = false;
bool scalarSummaryActive = false;
bool impedanceSummaryActive = false;
bool invertPhase = false;
bool fullCircuit = false;
};
if (errorMessage != nullptr) {
errorMessage->clear();
}
std::array<ParsedPage, KFilterProjectIo::DriverCount> parsedPages;
for (int index = 0; index < KFilterProjectIo::DriverCount; ++index) {
const DriverPage& page = m_pages.at(index);
ParsedPage& parsed = parsedPages.at(index);
if (!readSpinBoxValue(page.rdc, tr("Rdc"), index, parsed.rdc, errorMessage) ||
!readSpinBoxValue(page.lspMilliHenry, tr("Lsp"), index, parsed.lspMilliHenry, errorMessage) ||
!readSpinBoxValue(page.f0, tr("Fs"), index, parsed.f0, errorMessage) ||
!readSpinBoxValue(page.qts, tr("Qts"), index, parsed.qts, errorMessage) ||
!readSpinBoxValue(page.qes, tr("Qes"), index, parsed.qes, errorMessage) ||
!readSpinBoxValue(page.qms, tr("Qms"), index, parsed.qms, errorMessage) ||
!readSpinBoxValue(page.vas, tr("Vas"), index, parsed.vas, errorMessage) ||
!readSpinBoxValue(page.dm, tr("Diameter"), index, parsed.dm, errorMessage) ||
!readSpinBoxValue(page.vb, tr("Vb"), index, parsed.vb, errorMessage) ||
!readSpinBoxValue(page.ql, tr("Ql"), index, parsed.ql, errorMessage) ||
!readSpinBoxValue(page.fb, tr("Fb"), index, parsed.fb, errorMessage) ||
!readSpinBoxValue(page.tubeDiameter, tr("Tube diameter"), index, parsed.tubeDiameterCm, errorMessage) ||
!readSpinBoxValue(page.v2, tr("V2"), index, parsed.v2, errorMessage) ||
!readSpinBoxValue(page.gainDb, tr("Gain"), index, parsed.gainDb, errorMessage)) {
return false;
}
parsed.title = page.title->text();
parsed.alignmentProposal = page.alignmentProposal->currentData().toInt();
parsed.pressureActive = page.pressureActive->isChecked();
parsed.impedanceActive = page.impedanceActive->isChecked();
parsed.summaryActive = page.summaryActive->isChecked();
parsed.scalarSummaryActive = page.scalarSummaryActive->isChecked();
parsed.impedanceSummaryActive = page.impedanceSummaryActive->isChecked();
parsed.invertPhase = page.invertPhase->isChecked();
parsed.fullCircuit = page.fullCircuit->isChecked();
}
QSettings settings;
for (int index = 0; index < KFilterProjectIo::DriverCount; ++index) {
const ParsedPage& parsed = parsedPages.at(index);
driver& drv = m_drivers[index];
drv.setTitle(parsed.title);
drv.setRdc(parsed.rdc);
drv.setLsp(parsed.lspMilliHenry / 1000.0);
drv.setF0(parsed.f0);
drv.setQts(parsed.qts);
drv.setQes(parsed.qes);
drv.setQms(parsed.qms);
drv.setVas(parsed.vas);
drv.setDm(parsed.dm);
drv.setVb(parsed.vb);
drv.setQl(parsed.ql);
drv.setFb(parsed.fb);
drv.setV2(parsed.v2);
drv.setEnclosureTypeProposal(static_cast<EnclosureType>(parsed.alignmentProposal));
drv.setGainLinear(dbToLinearGain(parsed.gainDb));
if (mode == ApplyMode::Commit) {
if (parsed.tubeDiameterCm > 0.0) {
settings.setValue(tubeDiameterSettingsKey(index), parsed.tubeDiameterCm);
} else {
settings.remove(tubeDiameterSettingsKey(index));
}
}
drv.setPlotState(DriverPlotState{parsed.pressureActive,
parsed.impedanceActive,
parsed.summaryActive,
parsed.scalarSummaryActive,
parsed.impedanceSummaryActive});
drv.setPhaseInverted(parsed.invertPhase);
drv.setFullCircuit(parsed.fullCircuit);
}
return true;
}
void DriverParametersDialog::rememberCommittedState()
{
for (int index = 0; index < KFilterProjectIo::DriverCount; ++index) {
const std::size_t arrayIndex = static_cast<std::size_t>(index);
m_committedDrivers[arrayIndex] = m_drivers[index];
m_committedMeasurementCurves[arrayIndex] = m_document.splCorrectionCurve(index);
m_committedMeasurementHiddenStates[arrayIndex] =
m_document.measurementHiddenForDriver(index);
m_committedActiveFilterChains[arrayIndex] = m_document.activeFilterChain(index);
m_committedBaffleSettings[arrayIndex] = m_document.baffleSettings(index);
m_committedFloorReflectionSettings[arrayIndex] =
m_document.floorReflectionSettings(index);
}
m_committedMeasurementMergeEnabled = m_document.measurementMergeEnabled();
}
void DriverParametersDialog::restoreCommittedState()
{
m_restoringDrivers = true;
for (int index = 0; index < KFilterProjectIo::DriverCount; ++index) {
const std::size_t arrayIndex = static_cast<std::size_t>(index);
m_drivers[index] = m_committedDrivers[arrayIndex];
m_document.splCorrectionCurve(index) = m_committedMeasurementCurves[arrayIndex];
m_document.activeFilterChain(index) = m_committedActiveFilterChains[arrayIndex];
m_document.baffleSettings(index) = m_committedBaffleSettings[arrayIndex];
m_document.floorReflectionSettings(index) = m_committedFloorReflectionSettings[arrayIndex];
m_document.setMeasurementHiddenForDriver(
index, m_committedMeasurementHiddenStates[arrayIndex]);
}
m_document.setMeasurementMergeEnabled(m_committedMeasurementMergeEnabled);
m_restoringDrivers = false;
}
void DriverParametersDialog::schedulePreview()
{
if (m_previewTimer == nullptr || m_loadingFromDrivers || m_restoringDrivers) {
return;
}
m_previewTimer->start(150);
}
void DriverParametersDialog::emitPreview()
{
if (m_loadingFromDrivers || m_restoringDrivers) {
return;
}
if (applyToDrivers(ApplyMode::Preview)) {
emit parametersPreviewed();
}
}
void DriverParametersDialog::applyClicked()
{
if (m_previewTimer != nullptr) {
m_previewTimer->stop();
}
QString errorMessage;
if (!applyToDrivers(ApplyMode::Commit, &errorMessage)) {
QMessageBox::warning(this, tr("Driver parameters"), errorMessage);
return;
}
rememberCommittedState();
emit parametersApplied();
}
void DriverParametersDialog::accept()
{
if (m_previewTimer != nullptr) {
m_previewTimer->stop();
}
QString errorMessage;
if (!applyToDrivers(ApplyMode::Commit, &errorMessage)) {
QMessageBox::warning(this, tr("Driver parameters"), errorMessage);
return;
}
rememberCommittedState();
emit parametersApplied();
QDialog::accept();
}
void DriverParametersDialog::reject()
{
if (m_previewTimer != nullptr) {
m_previewTimer->stop();
}
restoreCommittedState();
emit parametersRestored();
QDialog::reject();
}
void DriverParametersDialog::exportDriver(int index)
{
if (index < 0 || index >= KFilterProjectIo::DriverCount) {
return;
}
if (m_previewTimer != nullptr) {
m_previewTimer->stop();
}
QString errorMessage;
if (!applyToDrivers(ApplyMode::Preview, &errorMessage)) {
QMessageBox::warning(this, tr("Export driver"), errorMessage);
return;
}
emit parametersPreviewed();
KFilterDriverIo::DriverSlot slot;
slot.driverData = m_drivers[index];
slot.measurementCurve = m_document.splCorrectionCurve(index);
slot.measurementHidden = m_document.measurementHiddenForDriver(index);
slot.mergeMeasurementsEnabled = m_document.measurementMergeEnabled();
slot.activeFilterChain = m_document.activeFilterChain(index);
slot.baffleSettings = m_document.baffleSettings(index);
slot.floorReflectionSettings = m_document.floorReflectionSettings(index);
slot.hasTubeDiameterCm = true;
slot.tubeDiameterCm = m_pages.at(index).tubeDiameter->value();
QString filePath = QFileDialog::getSaveFileName(this,
tr("Export driver"),
suggestedDriverSlotPath(slot.driverData, index),
driverSlotFileFilter(this));
if (filePath.isEmpty()) {
return;
}
QFileInfo fileInfo(filePath);
if (fileInfo.suffix().isEmpty()) {
filePath += QStringLiteral(".kfd");
}
if (!KFilterDriverIo::saveDriverSlotToFile(filePath, slot, &errorMessage)) {
QMessageBox::warning(this, tr("Export driver"), errorMessage);
return;
}
}
void DriverParametersDialog::importDriver(int index)
{
if (index < 0 || index >= KFilterProjectIo::DriverCount) {
return;
}
if (m_previewTimer != nullptr) {
m_previewTimer->stop();
}
const QString filePath = QFileDialog::getOpenFileName(this,
tr("Import driver"),
QDir::homePath(),
driverSlotFileFilter(this));
if (filePath.isEmpty()) {
return;
}
QString errorMessage;
KFilterDriverIo::DriverSlot slot;
if (!KFilterDriverIo::loadDriverSlotFromFile(filePath, slot, &errorMessage)) {
QMessageBox::warning(this, tr("Import driver"), errorMessage);
return;
}
const QMessageBox::StandardButton answer = QMessageBox::question(
this,
tr("Import driver"),
tr("Importing this file will replace Driver %1 including network values, measurements, "
"active filters, baffle settings, and floor-reflection settings.\n\nContinue?")
.arg(index + 1),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (answer != QMessageBox::Yes) {
return;
}
if (!KFilterDriverIo::applyDriverSlotToDocument(m_document, index, slot)) {
QMessageBox::warning(this, tr("Import driver"), tr("The selected driver slot is invalid."));
return;
}
loadPageFromDriver(index, slot.hasTubeDiameterCm, slot.tubeDiameterCm);
m_tabs->setCurrentIndex(index);
emit parametersPreviewed();
}
void DriverParametersDialog::updateQtsForPage(DriverPage& page)
{
const double qes = page.qes->value();
const double qms = page.qms->value();
const double denominator = qes + qms;
if (denominator > 0.0) {
page.qts->setValue((qes * qms) / denominator);
}
}
void DriverParametersDialog::updateQtsConsistencyForPage(DriverPage& page)
{