-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathctgui_mainwindow.cpp
More file actions
3351 lines (2697 loc) · 111 KB
/
ctgui_mainwindow.cpp
File metadata and controls
3351 lines (2697 loc) · 111 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 <QDebug>
#include <QFileDialog>
#include <QVector>
#include <QProcess>
#include <QtCore>
#include <QSettings>
#include <QFile>
#include <QTime>
#include <unistd.h>
#include <QApplication>
#include <QMessageBox>
#include <QStandardPaths>
#include <functional>
#include <poptmx.h>
#include "additional_classes.h"
#include "ctgui_mainwindow.h"
#include "ui_ctgui_mainwindow.h"
using namespace std;
static const QString warnStyle = "background-color: rgba(255, 0, 0, 128);";
static const QString ssText = "Start experiment";
const QString MainWindow::storedState =
QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/.ctgui";
class HWstate {
private:
Detector * det;
Shutter * shutSec;
Shutter::State shutSecSate;
Shutter * shutPri;
Shutter::State shutPriSate;
QString dettifname;
QString dethdfname;
bool detinrun;
int detimode;
int dettmode;
float detperiod;
public:
HWstate(Detector *_det, Shutter * _shutS, Shutter * _shutP)
: det(_det), shutSec(_shutS), shutPri(_shutP)
{
store();
}
void store() {
shutSecSate = shutSec->state();
shutPriSate = shutPri->state();
dettifname = det->name(Detector::TIF);
dethdfname = det->name(Detector::HDF);
detinrun = det->isAcquiring();
detimode = det->imageMode();
dettmode = det->triggerMode();
detperiod = det->period();
}
void restore() {
// shutSec->setState(shutSecState);
// shutPri->setState(shutPriState);
det->setName(Detector::TIF, dettifname) ;
det->setName(Detector::HDF, dethdfname) ;
if (detinrun) det->start(); else det->stop();
det->setImageMode(detimode);
det->setTriggerMode(dettmode);
det->setPeriod(detperiod);
}
};
static HWstate * preVideoState = 0;
QString configName(QObject * obj) {
if (const Shutter* shut = qobject_cast<const Shutter*>(obj))
return configName(shut->ui->selection);
else if (QCaMotorGUI* mot = qobject_cast<QCaMotorGUI*>(obj))
return configName(mot->setupButton());
else if (const QTableWidgetOtem* wdgitm = qobject_cast<const QTableWidgetOtem*>(obj))
return configName(wdgitm->tableWidget()) + "/" + wdgitm->property(configProp).toString();
else if (const QButtonGroup* btns = qobject_cast<const QButtonGroup*>(obj)) {
if (btns->buttons().size())
return configName(btns->buttons().first()) + "/" + btns->property(configProp).toString();
} else if (QWidget * wdg = qobject_cast<QWidget*>(obj)) {
QStringList toRet;
QObject * curO = wdg;
while (curO) {
if (curO->property(configProp).isValid())
toRet.push_front(curO->property(configProp).toString());
curO = curO->parent();
}
return toRet.join('/');
}
return QString();
};
QString obj2str (QObject* obj, bool clean=true) {
auto quoteNonEmpty = [&clean](const QString & str){ return clean || str.isEmpty() ? str : "'" + str + "'"; };
auto specValue = [&clean](variant<QSpinBox*, QDoubleSpinBox*, QTimeEdit*> specValWdg) {
return visit( [&clean](auto &x) { return ( ! clean && x->specialValueText() == x->text() ) ? " (" + x->text() + ")" : "" ; } , specValWdg);
};
if (!obj)
return "";
else if (QLineEdit* cobj = qobject_cast<QLineEdit*>(obj))
return quoteNonEmpty(cobj->text());
else if (QPlainTextEdit* cobj = qobject_cast<QPlainTextEdit*>(obj))
return quoteNonEmpty(cobj->toPlainText());
else if (QAbstractButton* cobj = qobject_cast<QAbstractButton*>(obj))
return cobj->isChecked() ? "true" : "false";
else if (QComboBox* cobj = qobject_cast<QComboBox*>(obj))
return quoteNonEmpty(cobj->currentText());
else if (QSpinBox* cobj = qobject_cast<QSpinBox*>(obj))
return QString::number(cobj->value()) + specValue(cobj);
else if (QDoubleSpinBox* cobj = qobject_cast<QDoubleSpinBox*>(obj))
return QString::number(cobj->value()) + specValue(cobj);
else if (QTimeEdit* cobj = qobject_cast<QTimeEdit*>(obj))
return cobj->time().toString() + specValue(cobj);
else if (QLabel* cobj = qobject_cast<QLabel*>(obj))
return quoteNonEmpty(cobj->text());
else if (UScript* cobj = qobject_cast<UScript*>(obj))
return quoteNonEmpty(cobj->script->path());
else if (QCaMotorGUI* cobj = qobject_cast<QCaMotorGUI*>(obj))
return cobj->motor()->getPv();
else if (QButtonGroup* cobj = qobject_cast<QButtonGroup*>(obj))
return cobj->checkedButton() ? quoteNonEmpty(cobj->checkedButton()->text()) : "";
else if (QTableWidgetOtem* cobj = qobject_cast<QTableWidgetOtem*>(obj)){
QTableWidget * wdg = cobj->tableWidget();
// following commented line returns -1 for headeritem: have to get it manually
// const int column = cobj->column();
const int column = [&wdg,&cobj]() {
for (int col=0; col < wdg->columnCount() ; col++)
if (wdg->horizontalHeaderItem(col)==cobj)
return col;
qDebug() << "Can't find column in tablewidget with given horizontal header item.";
return -1;
} ();
if (column<0)
return "";
QStringList list;
for (int row = 0 ; row < wdg->rowCount() ; row++)
if ( QCheckBox* chBox = wdg->cellWidget(row, column)->findChild<QCheckBox*>() )
list << ( chBox->isChecked() ? "true" : "false" );
else
list << wdg->item(row, column)->text();
return clean ? list.join(',') : "["+list.join(',')+"]" ;
} else
qDebug() << "Cannot get default value of object" << obj
<< ": unsupported type" << obj->metaObject()->className();
return "";
}
int str2obj (QObject* obj, const QString & sval) {
QVariant rval = sval;
if (!obj) {
qDebug() << "Zero QObject";
return 0;
} else if (QLineEdit* cobj = qobject_cast<QLineEdit*>(obj))
cobj->setText(sval);
else if (QPlainTextEdit* cobj = qobject_cast<QPlainTextEdit*>(obj))
cobj->setPlainText(sval);
else if (QAbstractButton* cobj = qobject_cast<QAbstractButton*>(obj)) {
if ( rval.convert(QMetaType::Bool) )
cobj->setChecked(rval.toBool());
else {
qDebug() << sval << "can't convert to bool";
return 0;
}
} else if (QComboBox* cobj = qobject_cast<QComboBox*>(obj)) {
const int idx = cobj->findText(sval);
if ( idx >= 0 )
cobj->setCurrentIndex(idx);
else if ( cobj->isEditable() )
cobj->setEditText(sval);
else {
QStringList knownFields;
for (int cidx=0 ; cidx < cobj->count() ; cidx++ )
knownFields << cobj->itemText(cidx);
qDebug() << cobj->metaObject()->className() << sval << "not in existing values:" << knownFields;
return 0;
}
} else if (QSpinBox* cobj = qobject_cast<QSpinBox*>(obj)) {
if ( rval.convert(QMetaType::Int) )
cobj->setValue(rval.toInt());
else {
qDebug() << sval << "can't convert to integer";
return 0;
}
} else if (QDoubleSpinBox* cobj = qobject_cast<QDoubleSpinBox*>(obj)) {
if ( rval.convert(QMetaType::Double) )
cobj->setValue(rval.toDouble());
else {
qDebug() << sval << "can't convert to float";
return 0;
}
} else if (QTimeEdit* cobj = qobject_cast<QTimeEdit*>(obj)) {
if ( rval.convert(QMetaType::QTime) )
cobj->setTime(rval.toTime());
else {
qDebug() << sval << "can't convert to QTime";
return 0;
}
} else if (QLabel* cobj = qobject_cast<QLabel*>(obj))
cobj->setText(sval);
else if (UScript* cobj = qobject_cast<UScript*>(obj))
cobj->script->setPath(sval);
else if (QCaMotorGUI* cobj = qobject_cast<QCaMotorGUI*>(obj))
cobj->motor()->setPv(sval);
else if (QButtonGroup* cobj = qobject_cast<QButtonGroup*>(obj)) {
QStringList knownFields;
foreach (QAbstractButton * but, cobj->buttons()) {
knownFields << but->text();
if (but->text() == sval) {
but->setChecked(true);
return 1;
}
}
qDebug() << cobj->metaObject()->className() << sval << "not in existing values:" << knownFields;
return 0;
} else if (QTableWidgetOtem* cobj = qobject_cast<QTableWidgetOtem*>(obj)){
QTableWidget * wdg = cobj->tableWidget();
const int rows = wdg->rowCount();
const int column = cobj->column();
const QStringList list = sval.split(',');
if (list.size() != rows) {
QString msg = "Warning. List size " + QString::number(list.size()) + " produced from string \""
+ sval + "\" is not same as table size " + QString::number(rows) + ".";
if (PositionList * lst = qobject_cast<PositionList*>(wdg->parentWidget()))
msg += " Possibly size option " + configName(lst->ui->nof) + " is set after the content (option "
+ configName(cobj) + ")?";
qDebug() << msg;
}
for (int row = 0 ; row < min(rows, list.size()) ; row++) {
if ( list[row].isEmpty() )
continue;
if ( QCheckBox* chBox = wdg->cellWidget(row, column)->findChild<QCheckBox*>() ) {
QVariant curv = QVariant::fromValue(list[row]);
if (curv.convert(QMetaType::Bool))
chBox->setChecked(curv.toBool());
else
qDebug() << sval << "can't convert to bool. Skipping row" << row ;
} else
wdg->item(row, column)->setText(list[row]);
}
} else {
qDebug() << "Cannot parse value of object" << obj
<< "into cli arguments: unsupported type" << obj->metaObject()->className();
return 0;
}
return 1;
}
std::string type_desc (QObject* obj) {
if (!obj) {
qDebug() << "Zero QObject";
return "";
} else if (qobject_cast<const QLineEdit*>(obj))
return "string";
else if (qobject_cast<const QPlainTextEdit*>(obj))
return "text";
else if (qobject_cast<const QAbstractButton*>(obj))
return "bool";
else if (const QComboBox* cobj = qobject_cast<const QComboBox*>(obj))
return cobj->isEditable() ? "string" : "enum";
else if (qobject_cast<const QSpinBox*>(obj))
return "int";
else if (qobject_cast<const QDoubleSpinBox*>(obj))
return "float";
else if (qobject_cast<const QTimeEdit*>(obj))
return "QTime";
else if (qobject_cast<const QLabel*>(obj))
return "string";
else if (qobject_cast<const UScript*>(obj))
return "command";
else if (qobject_cast<const QCaMotorGUI*>(obj))
return "EpicsPV";
else if (qobject_cast<const QButtonGroup*>(obj))
return "enum";
else if (qobject_cast<const QTableWidgetOtem*>(obj))
return "list";
else
qDebug() << "Cannot add value of object" << obj
<< "into cli arguments: unsupported type" << obj->metaObject()->className();
return obj->metaObject()->className();
};
int _conversion (QObject* _val, const string & in) {
str2obj(_val, QString::fromStdString(in));
return 1;
}
void addOpt( poptmx::OptionTable & otable, QObject * sobj, const QString & sname
, const string & preShort="", const string & preLong="" ){
if (Shutter* cobj = qobject_cast<Shutter*>(sobj)) {
addOpt( otable, cobj->ui->selection, sname
, cobj->whatsThis().toStdString(), cobj->toolTip().toStdString());
return;
}
string shortDesc;
string longDesc;
QString ttAdd = "\n\n--" + sname ;
if (QButtonGroup* cobj = qobject_cast< QButtonGroup*>(sobj)) {
QStringList knownFields;
foreach (QAbstractButton * but, cobj->buttons()) {
but->setToolTip(but->toolTip() + ttAdd + " \"" + but->text() + "\"");
knownFields << "'" + but->text() + "'";
}
shortDesc = cobj->property("whatsThis").toString().toStdString();
const QString tt = cobj->property("toolTip").toString();
longDesc = "Possible values: " + knownFields.join(", ").toStdString() + ".\n"
+ tt.toStdString();
cobj->setProperty("toolTip", tt + ttAdd );
} else if (QComboBox* cobj = qobject_cast<QComboBox*>(sobj)) {
QStringList knownFields;
for (int cidx=0 ; cidx < cobj->count() ; cidx++ )
knownFields << "'" + cobj->itemText(cidx) + "'";
longDesc = "Possible values: " + knownFields.join(", ").toStdString()
+ (cobj->isEditable() ? " or any text" : "") + ".\n";
} else if ( QAbstractSpinBox* cobj = qobject_cast<QAbstractSpinBox*>(sobj) ) {
QString specialValText = cobj->specialValueText();
if (!specialValText.isEmpty()) {
QString specialVal;
if (QSpinBox* sbobj = qobject_cast<QSpinBox*>(sobj))
specialVal = QString::number(sbobj->minimum());
else if (QDoubleSpinBox* sbobj = qobject_cast<QDoubleSpinBox*>(sobj))
specialVal = QString::number(sbobj->minimum());
else if (QTimeEdit* sbobj = qobject_cast<QTimeEdit*>(sobj))
specialVal = sbobj->minimumTime().toString();
longDesc = ("Special value " + specialVal + " for '" + specialValText + "'.\n")
.toStdString();
}
}
if ( qobject_cast<QWidget*>(sobj) || qobject_cast<QTableWidgetOtem*>(sobj)) {
variant<QWidget*, QTableWidgetOtem*> ctrlWdg = (QWidget*) nullptr;
if (QCaMotorGUI* cobj = qobject_cast<QCaMotorGUI*>(sobj))
ctrlWdg = cobj->setupButton();
else if (QWidget * wdg = qobject_cast<QWidget*>(sobj))
ctrlWdg = wdg;
else if (QTableWidgetOtem * item = qobject_cast<QTableWidgetOtem*>(sobj))
ctrlWdg = item;
shortDesc = visit( [](auto &x) { return x->whatsThis(); }, ctrlWdg).toStdString();
longDesc += visit( [](auto &x) { return x->toolTip(); }, ctrlWdg).toStdString();
ttAdd += " " + QString::fromStdString(type_desc(sobj));
visit( [&ttAdd](auto &x) { x->setToolTip( x->toolTip() + ttAdd ); }, ctrlWdg);
}
// adding option to parse table
if (shortDesc.empty() && preShort.empty())
qDebug() << "Empty whatsThis for " << sobj << QString::fromStdString(longDesc);
const string svalue = obj2str(sobj, false).toStdString();
otable.add( poptmx::OPTION, sobj, 0, sname.toStdString()
, shortDesc + preShort, longDesc + preLong
, svalue.empty() ? "<none>" : svalue);
};
#define innearList qobject_cast<PositionList*> ( ui->innearListPlace->layout()->itemAt(0)->widget() )
#define outerList qobject_cast<PositionList*> ( ui->outerListPlace->layout()->itemAt(0)->widget() )
#define loopList qobject_cast<PositionList*> ( ui->loopListPlace->layout()->itemAt(0)->widget() )
#define sloopList qobject_cast<PositionList*> ( ui->sloopListPlace->layout()->itemAt(0)->widget() )
MainWindow::MainWindow(int argc, char *argv[], QWidget *parent) :
QMainWindow(parent),
isLoadingState(false),
ui(new Ui::MainWindow),
bgOrigin(0),
bgAcquire(0),
bgEnter(0),
det(new Detector(this)),
tct(new TriggCT(this)),
thetaMotor(new QCaMotorGUI),
spiralMotor(new QCaMotorGUI),
bgMotor(new QCaMotorGUI),
dynoMotor(new QCaMotorGUI),
dyno2Motor(new QCaMotorGUI),
stopMe(true)
{
// Prepare UI
{
ui->setupUi(this);
foreach ( QWidget * sprl , findChildren<QWidget*>(
QRegularExpression("spiral", QRegularExpression::CaseInsensitiveOption)) )
sprl->hide(); // until spiral CT is implemented
ui->control->finilize();
ui->control->setCurrentIndex(0);
foreach ( QMDoubleSpinBox * spb , findChildren<QMDoubleSpinBox*>() )
spb->setConfirmationRequired(false);
foreach ( QMSpinBox * spb , findChildren<QMSpinBox*>() )
spb->setConfirmationRequired(false);
prsSelection << ui->aqsSpeed << ui->stepTime << ui->flyRatio;
selectPRS(); // initial selection only
foreach (QMDoubleSpinBox* _prs, prsSelection)
connect( _prs, SIGNAL(entered()), SLOT(selectPRS()) );
ColumnResizer * resizer;
resizer = new ColumnResizer(this);
ui->preRunScript->addToColumnResizer(resizer);
ui->postRunScript->addToColumnResizer(resizer);
resizer = new ColumnResizer(this);
ui->preScanScript->addToColumnResizer(resizer);
ui->postScanScript->addToColumnResizer(resizer);
resizer = new ColumnResizer(this);
ui->preSubLoopScript->addToColumnResizer(resizer);
ui->postSubLoopScript->addToColumnResizer(resizer);
resizer = new ColumnResizer(this);
ui->preAqScript->addToColumnResizer(resizer);
ui->postAqScript->addToColumnResizer(resizer);
ui->startStop->setText(ssText);
ui->statusBar->setObjectName("StatusBar");
ui->statusBar->setStyleSheet("#StatusBar {color: rgba(255, 0, 0, 128);}");
QPushButton * save = new QPushButton("Save");
save->setFlat(true);
connect(save, SIGNAL(clicked()), SLOT(saveConfiguration()));
ui->statusBar->addPermanentWidget(save);
QPushButton * load = new QPushButton("Load");
load->setFlat(true);
connect(load, SIGNAL(clicked()), SLOT(loadConfiguration()));
ui->statusBar->addPermanentWidget(load);
for (int caqmod=0 ; caqmod < AQMODEEND ; caqmod++)
ui->aqMode->insertItem(caqmod, AqModeString( AqMode(caqmod) ));
ui->scanProgress->hide();
ui->dynoProgress->hide();
ui->serialProgress->hide();
ui->multiProgress->hide();
ui->stepTime->setSuffix("s");
ui->exposureInfo->setSuffix("s");
ui->detExposure->setSuffix("s");
ui->detPeriod->setSuffix("s");
foreach (Detector::Camera cam , Detector::knownCameras)
ui->detSelection->addItem(Detector::cameraName(cam));
auto placeMotor = [this](QCaMotorGUI *mot, QWidget *ctrlHere, QWidget *posHere){
mot->setupButton()->setToolTip(ctrlHere->toolTip());
mot->setupButton()->setWhatsThis(ctrlHere->whatsThis());
if (ctrlHere->property(configProp).isValid()) {
mot->setupButton()->setProperty(
configProp, ctrlHere->property(configProp));
ctrlHere->setProperty(configProp,QVariant());
}
QString nm = ctrlHere->objectName();
if (nm.startsWith("place"))
nm.remove(0,5);
mot->setObjectName(nm);
place(mot->setupButton(), ctrlHere);
mot->currentPosition(true)->setObjectName(nm+"Position");
place(mot->currentPosition(true), posHere);
allMotors << mot;
};
placeMotor(thetaMotor, ui->placeThetaMotor, ui->placeScanCurrent);
placeMotor(spiralMotor, ui->placeSpiralMotor, ui->placeSpiralCurrent);
placeMotor(bgMotor, ui->placeBGmotor, ui->placeBGcurrent);
placeMotor(dynoMotor, ui->placeDynoMotor, ui->placeDynoCurrent);
placeMotor(dyno2Motor, ui->placeDyno2Motor, ui->placeDyno2Current);
foreach( PositionList * lst, findChildren<PositionList*>() ) {
QCaMotorGUI * mot = lst->motui;
QString nm = lst->objectName() + "Motor";
mot->setObjectName(nm);
mot->currentPosition(true)->setObjectName(nm + "Position");
mot->setupButton()->setToolTip("Motor to position list item.");
allMotors << mot;
}
}
// Update Ui's
{
updateUi_expPath();
updateUi_pathSync();
updateUi_serials();
updateUi_ffOnEachScan();
updateUi_scanRange();
updateUi_aqsPP();
updateUi_scanStep();
updateUi_expOverStep();
updateUi_thetaMotor();
updateUi_bgTravel();
updateUi_bgInterval();
updateUi_dfInterval();
updateUi_bgMotor();
updateUi_loops();
updateUi_dynoSpeed();
updateUi_dynoMotor();
updateUi_dyno2Speed();
updateUi_dyno2Motor();
updateUi_detector();
updateUi_aqMode();
updateUi_hdf();
onSerialCheck();
onFFcheck();
onDynoCheck();
onMultiCheck();
onDyno2();
onDetectorSelection();
}
// Connect signals from UI elements
{
connect(ui->browseExpPath, &QPushButton::clicked, [this]() {
QDir startView( QDir::current() );
startView.cdUp();
const QString newdir = QFileDialog::getExistingDirectory(0, "Working directory", startView.path() );
if ( ! newdir.isEmpty() )
ui->expPath->setText(newdir);
} );
connect(ui->checkSerial, SIGNAL(toggled(bool)), SLOT(onSerialCheck()));
connect(ui->checkFF, SIGNAL(toggled(bool)), SLOT(onFFcheck()));
connect(ui->checkDyno, SIGNAL(toggled(bool)), SLOT(onDynoCheck()));
connect(ui->checkMulti, SIGNAL(toggled(bool)), SLOT(onMultiCheck()));
connect(ui->testSerial, SIGNAL(clicked(bool)), SLOT(onSerialTest()));
connect(ui->testFF, SIGNAL(clicked()), SLOT(onFFtest()));
connect(ui->testScan, SIGNAL(clicked()), SLOT(onScanTest()));
connect(ui->testMulti, SIGNAL(clicked()), SLOT(onLoopTest()));
connect(ui->testDyno, SIGNAL(clicked()), SLOT(onDynoTest()));
connect(ui->dynoDirectionLock, SIGNAL(toggled(bool)), SLOT(onDynoDirectionLock()));
connect(ui->dynoSpeedLock, SIGNAL(toggled(bool)), SLOT(onDynoSpeedLock()));
connect(ui->dyno2, SIGNAL(toggled(bool)), SLOT(onDyno2()));
connect(ui->testDetector, SIGNAL(clicked()), SLOT(onDetectorTest()));
connect(ui->vidStartStop, SIGNAL(clicked()), SLOT(onVideoRecord()));
connect(ui->vidReady, SIGNAL(clicked()), SLOT(onVideoGetReady()));
connect(ui->startStop, SIGNAL(clicked()), SLOT(onStartStop()));
connect(ui->swapSerialLists, SIGNAL(clicked(bool)), SLOT(onSwapSerial()));
connect(ui->swapLoopLists, SIGNAL(clicked(bool)), SLOT(onSwapLoops()));
}
// Populate list of configuration parameters with elements of the UI
// which have configProp ("saveToConfig") property set.
{
QList<QObject*> addThemAfterNof;
QWidget * wdg = ui->control;
while ( wdg = wdg->nextInFocusChain() ,
wdg && wdg != ui->control )
{
if ( ui->control->tabs().contains(wdg) )
continue;
QObject * obj = wdg;
if ( QAbstractButton * but = qobject_cast<QAbstractButton*>(wdg)
; but && but->group() && but->group()->property(configProp).isValid() )
obj = but->group();
if ( ! obj->property(configProp).isValid() )
continue;
if (QCaMotorGUI* mot = motorFromButton(wdg))
obj=mot;
if ( configs.contains(obj) )
continue;
if (PositionList* cobj = qobject_cast<PositionList*>(obj)) {
// Data in the columns must be loaded after correct number of raws are set via ui->nof of the list.
// Therefore instead of adding following to configs immediately, they are put aside and added
// later when table is resized.
if (addThemAfterNof.size()) {
qDebug() << "Bug. PositionList table must be empty by now. How did I get here?";
configs.append(addThemAfterNof);
addThemAfterNof.clear();
}
addThemAfterNof << dynamic_cast<QTableWidgetOtem*>(cobj->ui->list->horizontalHeaderItem(0))
<< dynamic_cast<QTableWidgetOtem*>(cobj->ui->list->horizontalHeaderItem(3));
} else {
configs << obj;
if ( PositionList * parentPositionList = qobject_cast<PositionList*>(obj->parent())
; parentPositionList && parentPositionList->ui->nof == obj ) {
if (!addThemAfterNof.size())
qDebug() << "Bug. PositionList is empty wwhen must not be. How did I get here?";
else
configs.append(addThemAfterNof);
addThemAfterNof.clear();
}
}
}
}
// Load configuration and parse cmd options
{
string configFile = storedState.toStdString();
string fakestr;
bool fakebool;
auto constructOptionTable = [this,&configFile,&fakestr,&fakebool](bool fake) {
poptmx::OptionTable table("CT acquisition..", "Executes CT experiment.");
table
.add(poptmx::NOTE, "ARGUMENTS:")
.add(poptmx::ARGUMENT, &configFile, "configuration", "Configuration file.",
"Ini file to be loaded on start.", configFile)
.add(poptmx::NOTE, "OPTIONS:");
QString lastSection = "";
foreach (auto obj, configs) {
QString sname = configName(obj);
if ( QString section = sname.split('/').first()
; section != lastSection )
{
table.add(poptmx::NOTE, "Section " + section.toStdString());
lastSection = section;
}
if (fake)
table.add(poptmx::OPTION, &fakestr, 0, configName(obj).toStdString(), "shortDesc", "");
else
addOpt(table, obj, sname);
}
table
.add(poptmx::NOTE, "ACTIONS:")
.add(poptmx::OPTION, &startExp, 0, "startExp", "Starts the experiment.",
"Launches execution of the experiment as if manually pressing \"Start\".")
.add(poptmx::OPTION, &startVid, 0, "startVid", "Starts video recording.",
"Launches video recording as if \"Get ready\" and \"Record\" buttons were pressed manually.")
.add(poptmx::OPTION, &reportHealth, 0, "health", "Check if configuration allows start.",
"Check if loaded configuration is self consistent to allow experiment execution."
" Returns 0 if everything is fine, non-zero otherwise.")
.add(poptmx::OPTION, &failAfter, 0, "fail", "Maximum time in seconds to wait for readiness.",
"If the system does not become available for requested action withing specified time,"
" consider it a failure. Default is 1 second.")
.add(poptmx::OPTION, &keepUi, 0, "keepui", "Keeps UI open on completion.",
"Has no effect if no launchers were started. By default application."
" exits after a launcher has finished. This option allows to keep it open.")
.add(poptmx::OPTION, &headless, 0, "headless", "Starts launcher without UI.",
"Only makes sense with one of the above processing launchers;"
" without it the flag is ignored and UI shows.");
if (fake)
table
.add(poptmx::OPTION, &fakebool, 'h', "help", " ", "")
.add(poptmx::OPTION, &fakebool, 'u', "usage", " ", "")
.add(poptmx::OPTION, &fakebool, 'v', "verbose", " ", "");
else
table.add_standard_options(&beverbose);
return table;
};
// Parse and load configuration file
poptmx::OptionTable ftable = constructOptionTable(true);
ftable.parse(argc,argv);
loadConfiguration(QString::fromStdString(configFile));
// Only after loading configFile, I prepare and parse argv properly.
poptmx::OptionTable otable = constructOptionTable(false);
// using QApplication::exit instead of bare exit sometimes causes segfault
#define justExit(retVal, msg) {\
if (!msg.empty()) \
qDebug() << QString::fromStdString(msg); \
QTimer::singleShot(0, [](){exit(retVal);}); \
return; \
}
if (!otable.parse(argc, argv))
justExit(0, string());
if ( ! startExp && ! startVid && ! reportHealth ) {
for (void * var : initializer_list<void*>{&headless, &keepUi, &failAfter} )
if (otable.count(var))
justExit(1, string("Option " + otable.desc(var) + " can only be used together with "
+ otable.desc(&reportHealth) + ", " + otable.desc(&startExp)
+ " or " + otable.desc(&startVid) +"."))
;
keepUi=true;
headless=false;
} else if ( reportHealth ) {
keepUi=false;
headless=true;
} else {
if (!otable.count(&headless))
headless=false;
if (!otable.count(&keepUi))
keepUi=false;
}
if ( 1 < otable.count(&startExp) + otable.count(&startVid) + otable.count(&reportHealth) )
justExit(1, string("Only one of the following options can be used at a time: " +
otable.desc(&startExp) + otable.desc(&startVid) + otable.desc(&reportHealth) + ".") );
if (otable.count(&headless) && otable.count(&keepUi))
justExit(1, string("Incompatible options " + otable.desc(&headless) + " and " + otable.desc(&keepUi) + "."));
}
#undef justExit
storeCurrentState();
// connect changes in the configuration elements to store state
foreach (auto obj, configs) {
const char * sig = 0;
if ( qobject_cast<QLineEdit*>(obj) ||
qobject_cast<QPlainTextEdit*>(obj) ||
qobject_cast<UScript*>(obj) ||
qobject_cast<QSpinBox*>(obj) ||
qobject_cast<QAbstractSpinBox*>(obj) )
sig = SIGNAL(editingFinished());
else if (qobject_cast<QComboBox*>(obj))
sig = SIGNAL(currentIndexChanged(int));
else if (qobject_cast<QAbstractButton*>(obj))
sig = SIGNAL(toggled(bool));
else if ( qobject_cast<QButtonGroup*>(obj))
sig = SIGNAL(buttonClicked(int));
else if (qobject_cast<QCaMotorGUI*>(obj)) {
obj = qobject_cast<QCaMotorGUI*>(obj)->motor();
sig = SIGNAL(changedPv());
} else if (qobject_cast<QTableWidgetOtem*>(obj)) {
obj = qobject_cast<QTableWidgetOtem*>(obj)->tableWidget();
sig = SIGNAL(itemChanged(QTableWidgetItem*));
} else if (qobject_cast<Shutter*>(obj))
sig = SIGNAL(shutterChanged());
else
qDebug() << "Do not know how to connect object " << obj
<< "to slot" << SLOT(storeCurrentState());
if (sig)
connect (obj, sig, SLOT(storeCurrentState()));
}
// Whithout this trick, further qtWait functions are all stuck until "afterStart"
// returns. I do not understand why this is the case - it has something to do
// with the way QCoreApplication and QEventLoop are executed.
// It took me two full days to get to this single line of code :====
qtWait(0);
QTimer::singleShot(0, this, &MainWindow::afterStart);
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::afterStart() {
if ( ! headless )
show();
if (!startExp && !startVid && !reportHealth)
return;
if (! readyToStartCT )
qtWait(this, SIGNAL(readyForActionChanged()), failAfter*1000);
if (! readyToStartCT ) {
qDebug() << "System is NOT ready for action. QObjects reporting error are as follows:";
if (beverbose) {
foreach ( QObject * elm, preReq.keys())
if ( ! preReq[elm].first ) {
QString desc;
if (QCaMotorGUI* mot = motorFromButton(elm)) {
desc = " class: QCaMotor,"
" name: " + mot->objectName();
if (configs.contains(mot))
desc += ", option: " + configName(mot);
} else {
desc = QString() + " class: " + elm->metaObject()->className()
+ ", name: " + elm->objectName();
if (configs.contains(elm))
desc += ", option: " + configName(elm);
}
qDebug().noquote() << desc;
}
}
QTimer::singleShot(0, [this](){exit(1);});
return;
}
if (reportHealth) {
if (beverbose)
qDebug() << "System is ready for action.";
QTimer::singleShot(0, [this](){exit(0);});
} else if (startExp)
QTimer::singleShot(0, [this](){
onStartStop();
if (!keepUi)
close();
});
else if (startVid)
QTimer::singleShot(0, [this](){
onVideoRecord();
if (!keepUi)
close();
});
};
QCaMotorGUI * MainWindow::motorFromButton(const QObject * obj){
const QPushButton * but = qobject_cast<const QPushButton*>(obj);
if (!but)
return nullptr;
foreach( QCaMotorGUI* mot, allMotors )
if (mot->setupButton() == but)
return mot;
return nullptr;
};
void MainWindow::saveConfiguration(QString fileName) {
if ( fileName.isEmpty() )
fileName = QFileDialog::getSaveFileName(0, "Save configuration", QDir::currentPath());
QSettings config(fileName, QSettings::IniFormat);
config.clear();
config.setValue("version", QString::number(APP_VERSION));
foreach (auto obj, configs) {
QString fname = configName(obj);
if (fname.startsWith("general/", Qt::CaseInsensitive))
fname.remove(0,8);
if (const PositionList *pl = qobject_cast<const PositionList*>(obj)) {
config.setValue(fname + "/positions", obj2str(dynamic_cast<QTableWidgetOtem*>(pl->ui->list->horizontalHeaderItem(0))));
config.setValue(fname + "/todos", obj2str(dynamic_cast<QTableWidgetOtem*>(pl->ui->list->horizontalHeaderItem(3))));
} else if (const Shutter * shut = qobject_cast<const Shutter*>(obj)) {
config.setValue(fname, obj2str(shut->ui->selection));
config.setValue(fname+"_custom", shut->readCustomDialog());
} else
config.setValue(fname, obj2str(obj));
}
if (const QMDoubleSpinBox * prs = selectedPRS())
config.setValue("scan/fixprs", prs->objectName());
if (det) {
config.setValue("hardware/detectorpv", det->pv());
config.setValue("hardware/detectorexposure", det->exposure());
config.setValue("hardware/detectorsavepath", det->path(uiImageFormat()));
}
setenv("SERIALMOTORIPV", innearList->motui->motor()->getPv().toLatin1() , 1);
setenv("SERIALMOTOROPV", outerList->motui->motor()->getPv().toLatin1() , 1);
setenv("LOOPMOTORIPV", loopList->motui->motor()->getPv().toLatin1() , 1);
setenv("SUBLOOPMOTOROPV", sloopList->motui->motor()->getPv().toLatin1() , 1);
}
void MainWindow::loadConfiguration(QString fileName) {
if ( fileName.isEmpty() )
fileName = QFileDialog::getOpenFileName(0, "Load configuration", QDir::currentPath());
QSettings config(fileName, QSettings::IniFormat);
isLoadingState=true;
auto fromConf2Obj = [](QObject * obj, QString key, const QSettings & config){
if (key.startsWith("general/", Qt::CaseInsensitive))
key.remove(0,8);
if (!config.contains(key))
qDebug() << "Key" << key << "not found in config file" << config.fileName();
else {
QString val = config.value(key).toString();
if (!val.isEmpty())
str2obj(obj, val);
}
};
//const QString ver = config.value("version").toString();
if (config.contains("scan/fixprs")) {
const QString fixprsName = config.value("scan/fixprs").toString();
foreach (QAbstractSpinBox* prs, prsSelection)
if ( fixprsName == prs->objectName() )
selectPRS(prs);
selectPRS(selectedPRS()); // if nothing found
}
foreach (auto obj, configs) {
const QString fname = configName(obj);
if (const PositionList *pl = qobject_cast<const PositionList*>(obj)) {
fromConf2Obj(dynamic_cast<QTableWidgetOtem*>(pl->ui->list->horizontalHeaderItem(0)), fname + "/positions",config);
fromConf2Obj(dynamic_cast<QTableWidgetOtem*>(pl->ui->list->horizontalHeaderItem(3)), fname + "/todos",config);
} else if (Shutter * shut = qobject_cast<Shutter*>(obj) ) {
const QString cname = fname+"_custom";
if (config.contains(cname)) {
shut->loadCustomDialog(config.value(cname).toStringList());
fromConf2Obj(shut->ui->selection, fname, config);
shut->setShutter();
}
} else
fromConf2Obj(obj, fname, config);
}
if ( ui->expPath->text().isEmpty() || fileName.isEmpty() )
ui->expPath->setText( QFileInfo(fileName).absolutePath());
isLoadingState=false;
}
Detector::ImageFormat MainWindow::uiImageFormat() const {
if (ui->tiffFormat->isChecked())
return Detector::TIF;
else if (ui->hdfFormat->isChecked())
return Detector::HDF;
else
return Detector::UNDEFINED; // should never happen
}
static QString lastPathComponent(const QString & pth) {
QString lastComponent = pth;
if ( lastComponent.endsWith("\\") ) {
lastComponent.chop(1);
lastComponent.replace("\\", "/");
} else if ( lastComponent.endsWith("/") ) // can be win or lin path delimiter
lastComponent.chop(1);
lastComponent = QFileInfo(lastComponent).fileName();
return lastComponent;
}
void MainWindow::updateUi_expPath() {
if ( ! sender() ) { // called from the constructor;
const char* thisSlot = SLOT(updateUi_expPath());
connect( ui->expPath, SIGNAL(textChanged(QString)), thisSlot );
connect( ui->detPathSync, SIGNAL(toggled(bool)), thisSlot );
connect( det, SIGNAL(connectionChanged(bool)), thisSlot);
}
const QString pth = ui->expPath->text();
bool isOK;
if (QDir::isAbsolutePath(pth)) {
QFileInfo fi(pth);
isOK = fi.isDir() && fi.isWritable();
} else
isOK = false;
if (isOK) {
QDir::setCurrent(pth);
if ( ui->detPathSync->isChecked() && det->isConnected() ) {
QString lastComponent = lastPathComponent(pth);
QString detDir = det->path(uiImageFormat());
if ( detDir.endsWith("/") || detDir.endsWith("\\") ) // can be win or lin path delimiter
detDir.chop(1);
const int delidx = detDir.lastIndexOf( QRegExp("[/\\\\]") );
if ( delidx >=0 )
detDir.truncate(delidx+1);
det->setPath(detDir + lastComponent);
}
}
check(ui->expPath, isOK);
}
void MainWindow::updateUi_pathSync() {
if ( ! sender() ) { // called from the constructor;
const char* thisSlot = SLOT(updateUi_pathSync());
connect( ui->expPath, SIGNAL(textChanged(QString)), thisSlot );
connect( ui->detPathSync, SIGNAL(toggled(bool)), thisSlot );
connect( det, SIGNAL(parameterChanged()), thisSlot);
}
check( ui->detPathSync,
! ui->detPathSync->isChecked() ||
! ui->detSelection->currentIndex() ||
lastPathComponent(det->path(uiImageFormat())) == lastPathComponent(ui->expPath->text()));
}
void MainWindow::updateUi_aqMode() {
if ( ! sender() ) { // called from the constructor;
const char* thisSlot = SLOT(updateUi_aqMode());
connect( tct, SIGNAL(connectionChanged(bool)), thisSlot);
connect( tct, SIGNAL(runningChanged(bool)), thisSlot);
connect( ui->aqMode, SIGNAL(currentIndexChanged(int)), thisSlot);
}
const AqMode aqmd = (AqMode) ui->aqMode->currentIndex();
if ( sender() == ui->aqMode ) {
if ( aqmd == FLYHARD2B ) {