File: dsrgui.cpp

package info (click to toggle)
shelxle 1.0.1472-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 17,408 kB
  • sloc: cpp: 48,244; ansic: 560; makefile: 6
file content (1655 lines) | stat: -rw-r--r-- 56,854 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
/*
 ----------------------------------------------------------------------------
 "THE BEER-WARE LICENSE" (Revision 42):
 <dkratzert@gmx.de> wrote this file. As long as you retain
 this notice you can do whatever you want with this stuff. If we meet some day,
 and you think this stuff is worth it, you can buy me a beer in return.
 Daniel Kratzert
 ----------------------------------------------------------------------------
*/

//#include "bits/stdc++.h"
#include <QtGui>
#include <QDir>
#include <QNetworkAccessManager>
#include "dsrgui.h"
#include "window.h"
#include "dsrglwindow.h"
#include "dsreditwindow.h"
#include "deprecation.h"
#include "itsme.h"

#if defined(Q_OS_WIN) || defined(Q_WS_WIN32)
   static const QString mysystem = "win";
#else
   static const QString mysystem = "unix";
#endif

/*
Explanations

- This GUI is for DSR https://dkratzert.de/dsr.html
- DSR stores the information for pre-defined molecular fragments and their
  restraints in a text database in $DSR_DB_DIR.
- This GUI uses that information to provide a convenient interface for DSR.
- DSR is controlled by a special command in the SHELXL res file starting with REM DSR ...
  and by commandline options.
- A special command line option -ah tells DSR to print the information about a
  fragment in a special format for this GUI.
  It is a list of html-like tags <tag> data </tag> with ;; separated values containing for
  example the unit cell information and coordinates of the fragment. The first line
  contains the version number of DSR.
- The GUI first runs dsr with -lc to get a list of all fragment names in the database.
  A mouse click on a fragment in the list invokes "dsr -ah name" to get the details of
  the selected fragment (and stores it in struct DSRMol). This details are also used to
  edit the fragment ("edit fragment" button).
- The text widget below the search field displays some status output from DSR,
  especially the text output from DSR during the fragment transfer/fit to the target structure.

- merging: go into shelxle-kratzert and svn merge -r 165:HEAD /Users/daniel/Downloads/shelxle-trunk
       "-r (latest own commit):HEAD"    svn merge -r 165:HEAD d:\downloads\shelxle-svn\trunk
*/


/*
 * TODO:
*/


DSRGui::DSRGui(Molecule *mole, QString shelxlPath, Window *parent): QWidget(parent) {
  m_shelxle = parent;
  m_molecule = mole;
  m_shelxlPath = shelxlPath;
  this->setWindowFlags(Qt::Window|Qt::WindowStaysOnTopHint);
  //printf("I am DSR and this are my flags:%d\n",windowFlags ());
  setWindowTitle(QString(tr("DSR GUI")));
  if (mysystem == QString("win")) {
    dsrpath = getDSRDir()+"/dsr.bat";
    dsr_db_path = getDSRdbDir();
  } else if (mysystem == QString("unix")){
    dsrpath = QDir::cleanPath(getDSRDir()+"/dsr");
    dsr_db_path = QDir::cleanPath(getDSRdbDir());
  }
  this->hide();
  dsrVersion = "";
  replace = false;
  norefine = false; // this has to stay here
  runext = false;
  invert = false;
  rigid = false;
  cf3 = false;
  splitmode = false;
  fragmentsList = new QVector<QStringList>;
  fragmentNameTag.clear();
  header = new DSRMol;
  mainLayout = new QGridLayout(this);
  editLayout = new QHBoxLayout();
  //chooserLayout = new QGridLayout;
  searchLayout = new QHBoxLayout();
  //partLayout = new QHBoxLayout();
  //fvarLayout = new QHBoxLayout();
  //occLayout = new QHBoxLayout();
  resclassLayout = new QHBoxLayout();
  optionsLayout2 = new QVBoxLayout();
  optionsLayout3 = new QVBoxLayout();
  groupBox1 = new QGroupBox();
  optionsLayout1 = new QGridLayout(groupBox1);
  groupBox2 = new QGroupBox();
  residueOptionsBox = new QGroupBox(tr("Use a Residue"));
  buttonLayout = new QVBoxLayout();
  optionboxes = new QHBoxLayout();
  fitDSRButton = new QPushButton(tr("Fit Fragment!"));
  splitButton = new QPushButton(tr("Split Atoms"));
  fitDSRButton->setStyleSheet("QPushButton {"
                              "font-weight: bold; "
                              "color: #209920}");
  exportFragButton = new QPushButton(tr("Export Fragment"));
  editButton = new QPushButton(tr("Edit Fragment"));
  editButton->setStyleSheet("QPushButton {"
                            "font-weight: bold; "
                            "color: rgb(8, 82, 182)}");
  openLastButton = new QPushButton(tr("Restore last .res"));
  runExtBox = new QCheckBox(tr("External Restraints"));
  invertFragBox = new QCheckBox(tr("Invert Coordinates"));
  dfixBox = new QCheckBox(tr("Calculate DFIX"));
  rigidBox = new QCheckBox(tr("Rigid Group (no restraints)"));
  replaceModeBox = new QCheckBox(tr("Replace Target"));
  splitModeBox = new QCheckBox(tr("Split Target"));
  searchLabel = new QLabel(tr("Search:"));
  SearchInp = new QLineEdit;//(tr("Search a fragment here"));
  partLabel = new QLabel(tr("PART"));
  fvarLabel = new QPushButton(tr("Free Variable"));  // Is a QPushbutton to have a clicked() signal
  fvarLabel->setStyleSheet("QPushButton {border-style: outset; border-width: 0px; text-align:left;}");  // remove border to appear like a label
  fvarLabel->setToolTip("Click here to invert the current free variable");
  occLabel = new QLabel(tr("Occupancy"));
  classLabel = new QLabel(tr("Residue Class"));
  usermanualLabel = new QLabel(tr("<a href=\"https://github.com/dkratzert/DSR/raw/master/manuals/DSR-manual.pdf\"> DSR User Manual </a>"));
  usermanualLabel->setOpenExternalLinks(true);
  resnumbertext = new QString(tr("A residue number will be\nchosen automatically."));
  resiTextLabel = new QLabel();
  resiTextLabel->setText(*resnumbertext);
  outtext = new QTextBrowser;
  outtext->setOpenExternalLinks(true);
  info = new QTextBrowser;
  //this->move(-this->width(), -this->height());
  info->setMinimumWidth(235);  
  info->hide();
  //info->setMaximumWidth(235);
  fragmentTableView = new QTableView;
  occEdit = new QLineEdit;
  partspinner = new QSpinBox;
  fvarspinner = new QSpinBox;
  resiclassEdit = new QLineEdit;
  // layout for the interactions
  optionboxes->addWidget(groupBox1);
  //optionboxes->addStretch();
  optionboxes->addWidget(groupBox2);
  //optionboxes->addStretch();
  optionboxes->addWidget(residueOptionsBox);
  //optionboxes->addStretch();
  optionboxes->addLayout(buttonLayout);
  //buttonLayout->setSizeConstraint(QLayout::SetMaximumSize);
  // The search field:

  SearchInp->setFocus();  // searching should be the default
  SearchInp->setMinimumWidth(getCharWidth(9));
  fragmentNameTag.clear();
  // The OpenGL widget with the molecule:
  mygl = new DSRGlWindow(this, m_molecule, *header, fragmentNameTag);
  m_molecule->loadSettings();
  mygl->showFit = new QCheckBox(tr("show fitted target overlay"));
  mygl->showFit->setChecked(true);
  mygl->showFitLabel = new QCheckBox(tr("labels on target overlay"));
  mygl->showFitLabel->setChecked(true);
  // Table of fragments and 3D window:

  editLayout->addWidget(outtext);
  editLayout->addWidget(info);
  editLayout->setStretchFactor(outtext, 2);
  editLayout->setStretchFactor(info, 1);
  outtext->setReadOnly(true);
  QFont font("Courier");
  font.setStyleHint(QFont::TypeWriter);
  outtext->setFont(font);
  outtext->setMinimumHeight(170);
  partspinner->setRange(-99, 99);
  partspinner->setValue(0);
  fvarspinner->setRange(-99, 99);
  fvarspinner->setValue(1);
  occEdit->setValidator(new QDoubleValidator(0, 99, 5, occEdit));
  occEdit->setMaximumWidth(getCharWidth(5));
  occEdit->setMinimumWidth(getCharWidth(5));
  // box1
  optionsLayout1->addWidget(partspinner,0,0);
  optionsLayout1->addWidget(partLabel,0,1);

  optionsLayout1->addWidget(fvarspinner,1,0);
  optionsLayout1->addWidget(fvarLabel  ,1,1);

  optionsLayout1->addWidget(occEdit ,2,0);
  optionsLayout1->addWidget(occLabel,2,1);

  optionsLayout1->addWidget(replaceModeBox, 3,0,1,2  );
  optionsLayout1->addWidget(splitModeBox,   4,0,1,2  );
  splitModeBox->hide();
  //optionsLayout1->addStretch();
  groupBox1->setLayout(optionsLayout1);
  // box2
  optionsLayout2->addWidget(invertFragBox);
  optionsLayout2->addWidget(runExtBox);
  optionsLayout2->addWidget(dfixBox);
  optionsLayout2->addWidget(rigidBox);
  //optionsLayout2->addStretch();
  groupBox2->setLayout(optionsLayout2);
  // box3
  resclassLayout->addWidget(resiclassEdit);
  resclassLayout->addWidget(classLabel);
  resiclassEdit->setMaximumWidth(getCharWidth(8));
  resiclassEdit->setMinimumWidth(getCharWidth(6));
  optionsLayout3->addLayout(resclassLayout);
  optionsLayout3->addWidget(resiTextLabel);
  optionsLayout3->addWidget(usermanualLabel);
  optionsLayout3->addStretch();
  residueOptionsBox->setLayout(optionsLayout3);
  residueOptionsBox->setCheckable(true);
  // buttons:
  buttonLayout->addWidget(fitDSRButton);
  buttonLayout->addWidget(exportFragButton);
  exportFragButton->setEnabled(false);
  buttonLayout->addWidget(splitButton);
  splitButton->setDisabled(true);
  splitButton->hide();  // there is no DSR version that can do this until now.
  buttonLayout->addWidget(editButton);
  buttonLayout->addWidget(openLastButton);
  // tooltips:
  setToolTips();
  QPixmap pix = QPixmap(250, 50);
  pix.fill(); // need to fill in order to see the text.
  QPainter painter(&pix);
  QRectF rectangle(0, 0, 250-1, 49);
  painter.setFont(QFont("Sans-Serif", 12));
  painter.drawRect(rectangle);
  painter.drawText(QPoint(12, 30), "Loading fragment list...");
  QGroupBox *glGroupBox = new QGroupBox();
  glo = new QGridLayout(glGroupBox);
  glo->addWidget(mygl,0,0,1,2);
  glo->addWidget(mygl->showFit,1,0,1,1);
  glo->addWidget(mygl->showFitLabel,1,1,1,1);

  glGroupBox->setFlat(true);
  QGroupBox *fGroupBox = new QGroupBox();
  flo = new QGridLayout(fGroupBox);
  mainLayout->addWidget(fGroupBox,          0, 0, 3, 2);
  mainLayout->addWidget(glGroupBox,         0, 2, 3, 5);
  flo->addWidget(fragmentTableView ,0,0,1,2);
  flo->addWidget(searchLabel ,1,0,1,1);
  flo->addWidget(SearchInp   ,1,1,1,1);
  mainLayout->setRowMinimumHeight(3,200);
  mainLayout->addLayout(editLayout,  3,0,1,7);
  mainLayout->addLayout(optionboxes, 6,0,1,7);
  QSplashScreen *splash = new QSplashScreen(pix);
  splash->show();
  splash->showMessage("");
  target_atoms = getSelectedAtomsList(); // must be before signals
  // request version.txt to warn for updates:

#if !defined(Q_OS_MAC) && (QT_VERSION >= 0x050000)
  getVersionFromServer();
#endif  
  // Signal slot connections:
  connect_signals_and_slots();
  splitDecide();
  occEdit->setText("1");
  checkForDSRexecutable(splash);
  splash->finish(this);
  // call last, because keyboard focus is reated to tab order,
  // which is based on the order the widgets are created:
  SearchInp->setFocus();
  // Has to be here, otherwise fragmentTableView is not initialized:
  QItemSelectionModel *sm = fragmentTableView->selectionModel();
  this->show();
  if (!(sm == nullptr)){  // prevents error about missing connection if DSR is not present
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(setFragName(QModelIndex)), Qt::UniqueConnection);
  }
  //int scn=QApplication::desktop()->screenNumber(m_shelxle);//find out where the main window is
  QScreen *screen = m_shelxle->window()->windowHandle()->screen();
  //QGuiApplication::screens().at(scn)->geometry()
  this->move(screen->geometry().x()+
             screen->geometry().width()-this->width()-30, 30);

  //printf("test\n");
  //this->resize(this->width()-2, this->height()-2);  // a trick to redraw the gl windows
  // this raises an 'Unable to set geometry' error
  mygl->update();
  //printf("test2\n");
  if (!(dsrVersion.toLatin1() == "0")) {
    outtext->append(QString("\nFound DSR version %1.").arg(dsrVersion));
    if (dsrVersion.toInt() > 9999) {  // To be changed later
        splitButton->show();  // logic turned, because a non-replying web server turned this button on
    }
  }
  update();
}


DSRGui::~DSRGui() {
  delete mygl;
}

void DSRGui::aboutDSR() {
  QMessageBox::about(this, QString(tr("About DSR Plugin")),//only one about dlg in macOS
      QString(
        tr("<p><b>DSR plugin for ShelXle</b></p>"
          "This plugin is a graphical interface for DSR.<br>"
          "The GUI part and the interaction with DSR was developed by <b>Daniel Kratzert</b>, "
          "while the 3D OpenGL part was developed by <b>Christian H&uuml;bschle</b>.<br>"
          "DSR is a refinement tool with a database of molecular fragments and corresponding restraints.<br>"
          "Place these fragments in a molecular structure to model disorder or just quickly rename "
          "groups of atoms.<br><br>"
          "Please cite DSR as:<br>"
          "<a href=https://dkratzert.de/files/dsr/documents/dsr_2_reprint.pdf> D. Kratzert, I. Krossing, <i>J. Appl. Cryst.</i><b> 2018</b>, <i>51</i>, 928-934.<br></a>"
          "<a href=https://doi.org/10.1107/S1600576718004508> doi:10.1107/S1600576718004508 </a><br><br>"
          "If you have additional fragments for the DSR database or a bug to report, please send them to "
          "<a href=\"dkratzert@gmx.de\"> dkratzert@gmx.de </a> <br>"
          "Please find the most recent version of DSR at <br>"
          "<a href=\"https://dkratzert.de/dsr.html\"> https://dkratzert.de/dsr.html </a><br><br>"
          "All DSR related software is developed at GitHub:<br>"
          "<a href=\"https://github.com/dkratzert/DSR\"> https://github.com/dkratzert/DSR </a><br><br>"
          "Please refer to the <a href=\"http://www.xs3-data.uni-freiburg.de/data/DSR-manual.pdf\"> manual </a> if you have any questions."
          )));
}

void DSRGui::connect_signals_and_slots() {
  //! Handles most of the signal slot connections
    connect(this, SIGNAL(fragmentSelected(void)),
            this, SLOT(activateFitButton(void)));
    connect(this, SIGNAL(fragmentSelected()),
            this, SLOT(resetSelection()));
    connect(fitDSRButton, SIGNAL (clicked(bool)),
            this, SLOT (fitDSR()));
    connect(fitDSRButton, SIGNAL (clicked(bool)),
            this->info, SLOT(hide()));
    connect(runExtBox, SIGNAL (clicked(bool)),
            this, SLOT (fitDSRExtern(bool)));
    connect(dfixBox, SIGNAL (clicked(bool)),
            this, SLOT (DFIX(bool)));
    connect(invertFragBox, SIGNAL (clicked(bool)),
            this, SLOT (invertFrag(bool)));
    connect(rigidBox, SIGNAL (clicked(bool)),
            this, SLOT (rigid_group(bool)));
    connect(replaceModeBox, SIGNAL(clicked(bool)),
            this, SLOT(replaceOrNot(bool)));
    connect(SearchInp, SIGNAL(textChanged(QString)),
            this, SLOT(searchFragment(QString)));
    connect(occEdit, SIGNAL(textChanged(QString)),
            this, SLOT(setFvarOcc(void)));
    connect(fvarspinner, SIGNAL(valueChanged(int)),
            this, SLOT(setFvarOcc(void)));
    connect(resiclassEdit, SIGNAL(textChanged(QString)),
            this, SLOT(setResiClass(QString)));
    connect(residueOptionsBox, SIGNAL(toggled(bool)),
            this, SLOT(combineOptionstext()));
    connect(splitModeBox, SIGNAL(toggled(bool)),
            this, SLOT(combineOptionstext()));
    connect(partspinner, SIGNAL(valueChanged(int)),
            this, SLOT(setPART(int)));
    connect(exportFragButton, SIGNAL(clicked(bool)),
            this, SLOT(setExportDirDialog(void)));
    connect(fragmentTableView, SIGNAL(clicked(QModelIndex)),
            this, SLOT(setFragName(QModelIndex)));
    connect(this, SIGNAL(optionTextChanged(void)),
            this, SLOT(combineOptionstext(void)));
    connect(editButton, SIGNAL(clicked(bool)),
            this, SLOT(runEditWindow()));
    connect(openLastButton, SIGNAL(clicked(bool)),
            this, SLOT(open_last_fileversion()));
    connect(this, SIGNAL(exportDirChanged(QString)),
            this, SLOT(exportFrag(QString)));
    // sigslot for uppdating the 3D view
    connect(this, SIGNAL(currentFragmentChanged(DSRMol)),
            mygl, SLOT(display_fragment(DSRMol)));
    connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
            mygl, SLOT(update()));
    connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
            this, SLOT(updateTarget()));
    connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
            this, SLOT(update()));
    connect(mygl->showFitLabel, SIGNAL(stateChanged(int)),
            mygl, SLOT(update()));
    connect(mygl->showFitLabel, SIGNAL(stateChanged(int)),
            mygl, SLOT(update()));
    connect(mygl->showFit, SIGNAL(stateChanged(int)),
            mygl, SLOT(update()));
    connect(mygl->showFit, SIGNAL(stateChanged(int)),
            mygl, SLOT(update()));
    connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
            mygl, SLOT(makeInfo()));
    connect(mygl, SIGNAL(sourceStringChanged()),
            this, SLOT(combineOptionstext()));
    connect(mygl, SIGNAL(updateInfo(QString)),
            this, SLOT(setInfo(QString)));
#if !defined(Q_OS_MAC) && (QT_VERSION >= 0x050000)
    connect(net_manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(isDSRUpToDate(QNetworkReply*)));
#endif 
    connect(fvarLabel, SIGNAL(clicked(bool)),
            this, SLOT(invertFvar()));
    connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
            this, SLOT(splitDecide(void)));
    connect(splitButton, SIGNAL(clicked(bool)),
            this, SLOT(splitSelectedAtoms(void)));
}

QSize DSRGui::minimumSizeHint() const {
  return QSize(700, 700);
}

QSize DSRGui::sizeHint() const {
  return QSize(700, 780);
}

void DSRGui::getVersionFromServer() {
  //! Writes the proposed version number of DSR into reply
    net_manager = new QNetworkAccessManager(this);
    QNetworkRequest request;
    request.setUrl(QUrl("http://www.xs3-data.uni-freiburg.de/data/version.txt"));
    request.setRawHeader("User-Agent", "DSRGui");
    reply = net_manager->get(request);
  }

/*
bool DSRGui::runTCPServer() {
  //! Socket server to get messages from DSR. Might be used in future.
  tcpServer = new QTcpServer(this);
  //connect(tcpServer, SIGNAL(newConnection()), this, SLOT(ReadClientData()));
  if (!tcpServer->listen(QHostAddress::LocalHost, 51234)) {
      tcpServer->close();
      return false;
  } else {
    if (tcpServer->waitForNewConnection()) {
      if (tcpServer->hasPendingConnections()) {
        ReadClientData();
      }
    }
  }
  return true;
}
*/
/*
void DSRGui::ReadClientData() {
  //! Reads DSR client data from a tcp soccet connection.
  QByteArray data_buffer;
  QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
  connect(clientConnection, SIGNAL(readyRead()), clientConnection, SLOT(deleteLater()));
  // this wait is essential to retrieve data:
  clientConnection->waitForReadyRead();
  while (clientConnection->bytesAvailable() > 0) {
      data_buffer = clientConnection->readAll();
  }
  //close tcpServer after reading data:
  tcpServer->deleteLater();
  outtext->append(data_buffer);
  //dsrResulttext.append(data_buffer);
}
*/

void DSRGui::isDSRUpToDate(QNetworkReply* reply) {
  /*
   *! Displays a warning if the current DSR version is too old.
  */
  QString latestRev_str = reply->readAll();
  bool ok;
  bool ok2;
  QMessageBox info;
  info.addButton(QMessageBox::Close);
  int dsrv = dsrVersion.toInt(&ok2, 10);
  QPushButton *updateButton = info.addButton(tr("Update now"), QMessageBox::ActionRole);
  if (dsrv < 193) {  // This is the first version with self-update mechanism
    updateButton->hide();
  }
  int latestrev_int = latestRev_str.toInt(&ok,10);
  if ((ok&&ok2)&&(latestrev_int)>(dsrv)){
    info.setText(QString(
                   "<h3>You should probably update DSR!</h3>"
                   "This is revision: <b>%1</b><br> "
                   "The latest version is: <b>%2</b> <br><br>"
                   "New versions can be downloaded here: <br>"
                   "<a href=\"https://dkratzert.de/dsr.html\">"
                   "https://dkratzert.de/dsr.html</a><br><br>"
                   "Please contact the author Daniel Kratzert"
                   " <a href=\"mailto:dkratzert@gmx.de\">dkratzert@gmx.de</a> "
                   "if you find any bugs.<br> Thank you!")
                    .arg(dsrVersion.toInt())
                    .arg(latestrev_int));
    info.exec();
    if (info.clickedButton() == updateButton) {
      updateDSR();
    }
  }
  reply->close();
  reply->deleteLater();
  disconnect(net_manager, SIGNAL(finished(QNetworkReply*)), NULL, NULL);
}

void DSRGui::updateTarget() {
  //! updates the target atoms list
  target_atoms = getSelectedAtomsList();
  combineOptionstext();
}

void DSRGui::writeFavorites(QString name) {
  //! Stores favorites in dsrgui.ini
  QSettings dsr_settings( QSettings::IniFormat, QSettings::UserScope, PROGRAM_NAME, "dsrgui" );
  dsr_settings.beginGroup("LastFragment");
  dsr_settings.setValue("last", name);
  dsr_settings.endGroup();
}

QString DSRGui::loadFavoriteFragment() {
  //! Loads Favorites from dsrgui.ini
  QSettings dsr_settings( QSettings::IniFormat, QSettings::UserScope, PROGRAM_NAME, "dsrgui" );
  dsr_settings.beginGroup("LastFragment");
  QString last = dsr_settings.value("last").toString();
  dsr_settings.endGroup();
  if (last == QString("cf6")) {
    splitModeBox->show();
  }
  if (last == QString("")) {
    last = QString("benzene");
  }
  return last;
}

QStringList DSRGui::which(QString programName) {
  //! Implements a which like method
  //! It returns all paths where programName is found in
  //! the system path variable
  QStringList foundInPath;
  QStringList execlist;
  QStringList pathList;
  pathList.clear();
  foundInPath.clear();
  execlist.clear();
  if (mysystem == "win") {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
    pathList = QString(qEnvironmentVariable("PATH")).split(";");
#else
    pathList = QString(qgetenv("PATH")).split(";");
#endif
  } else {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
    pathList = QString(qEnvironmentVariable("PATH")).split(":");
#else
    pathList = QString(qgetenv("PATH")).split(":");
#endif
    pathList.append("/usr/local/bin/");
  }
  execlist << ".bat" << ".exe" << "";
  foreach (QString exec, execlist) {
    foreach (QString path, pathList) {
      QString fullpath = path+"/"+programName+exec;
      QFileInfo fi(fullpath);
      if (QFile::exists(fullpath) && (fi.isExecutable())){
        foundInPath.append(QDir::cleanPath(fullpath));
      }
    }
  }
  return foundInPath;
}

void DSRGui::checkForDSRexecutable(QSplashScreen *splash) {
  //! list fragments only if the path of dsr installation is found:
  if (QFile::exists(dsrpath)) {
    if (listDSRdbFragments("None")) {
      outtext->append(tr("\n* Please pick a fragment first."));
      outtext->append(tr("* Then select at least three atoms from "
                        "the main structure and the fragment respectively. (STRG+click)"));
      outtext->append(tr("* Do not forget to apply a part number and free "
                         "variable in case of disorder."));
      outtext->append(tr("* The fragment will be placed after FVAR in the SHELX file."));
    }
  } else {
    outtext->clear();
    outtext->append(QString(tr("Unable to find DSR executable."
                "\nIs DSR_DIR environment variable set correctly?")));
    outtext->append(QString(tr("Please find the most recent version of DSR at "
                               "<a href=\"https://dkratzert.de/dsr.html\">"
                               "https://dkratzert.de/dsr.html</a>")));
    splash->finish(this);
  }
}

void DSRGui::setToolTips() {
  partspinner->setToolTip(tr("The PART of a fragment controls the binding of atoms.\n"
                             "For example two fragments in PART 1 and PART 2 do not\n"
                             "bind each other but to PART 0. Negative PARTs only bind themselves."));
  replaceModeBox->setToolTip(tr("Toggle replacement of target atoms and all atoms of "
                             "PART 0 \nin 1.3A distance around the fitted fragment atoms."));
  occEdit->setToolTip(tr("The occupancy of the fragment\n"));
  fvarspinner->setToolTip(tr("The Free Variable for the fragment.\n"
                             "Free Variable and Occupancy will be combined occording to the SHELXL syntax.\n"
                             "For example, 21.0 means second free variable with occupancy of 1."));
  invertFragBox->setToolTip(tr("Invert the fragment coordinates during fit."));
  runExtBox->setToolTip(tr("Write restraints to external file."));
  dfixBox->setToolTip(tr("Calculate DFIX/DANG/FLAT restraints "
                         "\naccording to fragment geometry. \n"
                         "Database restraints will be ignored."));
  rigidBox->setToolTip(tr("Keep the fragment as rigid (AFIX 9) group. \n"
                          "Apply no restraints."));
  residueOptionsBox->setToolTip(tr("Enables residues. Usually, you can leave the default.\n"
                           "It will always take the next free residue number."));
  fitDSRButton->setToolTip("Run DSR to fit the fragment into the structure.");
  exportFragButton->setToolTip("Export the current fragment to a .res file.");
  editButton->setToolTip("Edit the current fragment or create a new one.");
  openLastButton->setToolTip("Opens the .res file state before the last DSR fragment fit.");
}

QString DSRGui::textWrap(QString inText, QString indent) {
  //! returns a SHELXL compatible wrapped string (string =\\n string) in case of over 77 characters
  //! line length.
  //! The default of subsequent_indent is "=\n  "
  int length = 70;  // 70 should be save in any case
  QStringList line_list;
  QStringList wrapped;
  QStringList inText_list = inText.split(" ");
  for (int i=0; i<inText_list.length(); i++) {
    QString word = inText_list.at(i);
    QString testline = line_list.join(" ") + " ";
      if (QString(word + testline + indent).length() >= length) {
        if (i < inText_list.length()-2) {
          line_list.append(word + " " + indent);
        } else {
          line_list.append(word);
        }
        wrapped.append(line_list.join(" "));
        line_list.clear();
      } else{
        line_list.append(word);
      }
  }
  if (!line_list.isEmpty()) {
    wrapped.append(line_list.join(" "));
  }
  //qDebug() << wrapped.join(" ");
  return wrapped.join(" ");
}

bool DSRGui::open_last_fileversion() {
    //! Opens the last res file version before the last DSR action from the save history (./Shelxsaves/SAVEHIST)
    QFileInfo fi(m_shelxle->dirName);
    if (!fi.isReadable()) {
        outtext->append("No last .res file found to load.");
        return false;
    }
    QFile currentpath(fi.absolutePath());
    QString saveHistFileName=QString("%1/%2saves/SAVEHIST").arg(currentpath.fileName()).arg(PROGRAM_NAME);
    QFile savehist(saveHistFileName);
    savehist.open(QIODevice::ReadOnly|QIODevice::Text);
    if (!savehist.isReadable()) {
        outtext->append("No last .res file found to load.");
        return false;
    }
    QString savehist_content = savehist.readAll();  //Entry|@|2011-03-08T13:32:19|@|b11.res|@|
    savehist.close();
    QRegularExpression re = QRegularExpression("Entry\\|@\\|\\w+-\\w+-\\w+:\\w+:\\w+\\|@\\|[^@]+@\\|");
    QStringList entries = savehist_content.split(re, skipEmptyParts);
    QFile f(m_shelxle->dirName);
    bool success = f.open(QIODevice::WriteOnly|QIODevice::Text);
    if (success){
      f.write(entries.last().toLatin1().replace(0, 1, ""));
      f.close();
    } else {
      return false;
    }
    outtext->append("Successfully restored last file version.");
    m_shelxle->loadFile(m_shelxle->dirName);
    return true;
}

void DSRGui::invertFvar(){
    //! Inverts the value of FVAR in the OptionsLayout1
    int fvar;
    fvar = fvarspinner->text().toInt();
    fvarspinner->setValue(-fvar);
}

void DSRGui::resetSelection() {
  //! reset the selection of source atoms
  mygl->source_atoms.clear();
  combineOptionstext();
  info->hide();
}

void DSRGui::setInfo(QString s) {
  //! shows an info table with bond distances
  if (mygl->selFragAt.size()<1) {
    info->hide();
  }
  else {
    info->show();
    info->setText(s);
  }
}

void DSRGui::splitDecide(void) {
    //! Enables the "split atoms" button if at least one atom is selected.
    if (target_atoms.length() >= 1) {
        splitButton->setEnabled(true);
    }
}

void DSRGui::splitSelectedAtoms(void) {
    //! Runs DSR to split the currebtly selected atoms along the principal axis of the ellipsoid.
    QFileInfo resfip(m_shelxle->dirName);
    QString option = " -splt ";
    option = option + getSelectedAtomsList();
    option = option + " -r " + resfip.completeBaseName();
    this->runDSR(option);
}

void DSRGui::runEditWindow(void) {
  //! Starts the edit window in order to edit a fragment
  editwindow = new DSREditWindow(m_molecule, header, dsr_db_path,
                                 fragmentNameTag, *fragmentsList, this);
  editwindow->move(60, 50);
  editwindow->show();
  editwindow->setFocus();
  editwindow->setMinimumWidth(800);
  outtext->clear();
  connect(editwindow, SIGNAL(updated(QString)),
          this, SLOT(listDSRdbFragments(QString)));
}

void DSRGui::closeEvent(QCloseEvent *event) {
//! close event is emmited during DSRGui closing to reset its pointer
  emit closed();
  (void)event; // prevent compiler warning
}

int DSRGui::findFVARlines(QStringList *reslist) {
  //! finds the line number of last FVAR or the first atom
  //! I restrict the use of this plugin to stuctures with a valid
  //! FVAR, because a missing FVAR makes it all too error prone.
  int fvarline;
  // I need lastIndexOf() here, because in case of
  // several FVAR lines indexOf() would fail:
  fvarline = reslist->lastIndexOf(QRegularExpression("^FVAR.*", QRegularExpression::CaseInsensitiveOption));
  if (fvarline > 0) {
    return fvarline;
  } else {
    return 0;
  }
}

QVector<int> DSRGui::findDSRLines(QStringList *reslist) {
  //! Find line with "rem DSR ..." in res file and return line number
  //! if it exists.
  QVector<int> lineNums;
  int Num = 0;
  foreach (QString line, *reslist) {
    if (line.contains(QRegularExpression("^rem\\s{1,6}DSR\\s{1,6}.*", QRegularExpression::CaseInsensitiveOption))) {
      lineNums.append(Num);
    }
    Num++;
  }
  return lineNums;
}

int DSRGui::decideDSRInsertLine(QStringList *reslist) {
  //! decides where to instert the DSR command
  int fvarline = findFVARlines(reslist);
  if (fvarline > 0) {
    return fvarline;
  } else if (m_shelxle->firstAtomLine > 0) {
    // in this case, no FVAR is present and we put the DSR command line
    // before the first atom
    combiDSRline = QString("FVAR 1\n") + combiDSRline; // dummy FVAR is added for DSR
    return m_shelxle->firstAtomLine - 1;
  } else {
    return 0;
  }
}

QStringList DSRGui::readResfile() {
  //! read the entire res file into a stringlist
  QFileInfo fi(m_shelxle->dirName);
  QFile file(fi.absoluteFilePath());
  QStringList stringList;
  if (file.open(QFile::ReadOnly | QFile::Text)) {
    QTextStream textStream(&file);
    while (true) {
      QString line = textStream.readLine();
      if (line.isNull()) {
          break;
      } else {
        stringList.append(line);
      }
    }
  }
  file.close();
  return stringList;
}

QString DSRGui::findFreeResiNumber() {
  //! returns the next free residue number in the structure
  QSet<int> resiset;
  QList<int> resilist;
  int resnum = 0;
  for (int i=0; i < m_molecule->asymm.size(); i++) {
    MyAtom atom;
    atom = m_molecule->asymm.at(i);
    if (atom.resiNr >= 0) {
      resiset.insert(atom.resiNr);
    }
  }
  resilist = resiset.values();//.toList();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
  std::sort(resilist.begin(), resilist.end());
#else
  qSort(resilist);
#endif
  int count = 0;
  foreach (int num, resilist) {
    if (num != count) {
      // a gap in residue numbers is found, use this number:
      resnum = count;
      break;
    }
    count++;
  }
  // no gap found, use next number:
  resnum = count;
  // In this case we have no residue in the file:
  if (resilist.isEmpty()) {
    resnum = 1;
  }
  return QString("%1").arg(resnum);
}


bool DSRGui::getFragmentHeader(QString frag) {
  //! defines Name, residue, comment and unit cell of the fragment
  //! in DSRMol
  /*!
    <tag>
     benze
    </tag>
    <comment>
     Benzene2, Benzol, C6H6
    </comment>
    <source>
     CCDC UGEDEQ
    </source>
    <cell>
     1;;1;;1;;90;;90;;90
    </cell>
    <residue>
     ERT
    </residue>
    <dbtype>
     dsr_user_db
    </dbtype>
    <restr>
     RIGU C1 > C6;;SADI C1 C2 C3 C4
     </restr>
    <atoms>
      C1 6 1.78099 7.14907 12.00423;;C2 6 2.20089 8.30676 11.13758;;C3 6 1.26895 9.02168 10.39032;;C4 6 1.64225 10.07768 9.58845;;C5 6 2.98081 10.44432 9.51725;;C6 6 3.92045 9.74974 10.25408
    </atoms>
   */
  header->atoms.clear();
  header->cell.clear();
  header->comment.clear();
  header->dbtype.clear();
  header->residue.clear();
  header->restr.clear();
  header->tag.clear();
  outtext->clear();
  QString *rawheader = new QString;
  QStringList *headerlist = new QStringList;
  QString options = " -ah " + frag;
  dsrResulttext.clear();
  runDSR(options);
  if (dsrResulttext.isEmpty()) {
    outtext->clear();
    outtext->append(tr("Unable to run DSR."));
    editButton->setDisabled(true); // editing the empty header would crash ShelXle
    return false;
  } else {
    rawheader->append(dsrResulttext);
  }
  // in this case no fragment list returned. Hence, we have an error.
  if (!rawheader->contains(";;")) {
    outtext->clear();
    outtext->append(*rawheader);
    //editButton->setDisabled(true); // editing the empty header would crash ShelXle
    return false;
  }
  headerlist->append(rawheader->split(QRegularExpression("\n|\r\n|\r")));
  QStringList line;
  for (int i=0; i<headerlist->size(); i++) {
    if (headerlist->at(i).size() == 0){
      continue;
    }
    line.clear();
    if (headerlist->at(i).trimmed().startsWith("***")) {
      QString error;
      error = headerlist->at(i).trimmed();
      outtext->append("<b>"+error+"</b>");
    }
    if (headerlist->at(i).trimmed().startsWith("<tag>")) {
      line = headerlist->at(i+1).trimmed().split(" ");
      header->tag = line.join("");
    }
    if (headerlist->at(i).trimmed().startsWith("<comment>")) {
      line = headerlist->at(i+1).trimmed().split(" ");
      header->comment = line.join(" ");
    }
    if (headerlist->at(i).trimmed().startsWith("<source>")) {
      line = headerlist->at(i+1).trimmed().split(" ");
      header->source = line.join(" ");
    }
    if (headerlist->at(i).trimmed().startsWith("<cell>")) {
      line = headerlist->at(i+1).simplified().split(";;");
      foreach (QString item, line) {
        header->cell.append(item.toDouble());
      }
    }
    if (headerlist->at(i).trimmed().startsWith("<residue>")) {
      line = headerlist->at(i+1).trimmed().split(" ");
      header->residue = line.join("");
      resiclass = header->residue;
      resiclassEdit->setText(resiclass);
    }
    if (headerlist->at(i).trimmed().startsWith("<dbtype>")) {
      line = headerlist->at(i+1).trimmed().split(" ");
      header->dbtype = line.join("");
    }
    if (headerlist->at(i).trimmed().startsWith("<restr>")) {
      line = headerlist->at(i+1).simplified().split(";;");
      foreach (QString item, line) {
        header->restr.append(item);
      }
    }
    if (headerlist->at(i).trimmed().contains("<atoms>")) {
      line = headerlist->at(i+1).simplified().split(";;");
      foreach (QString item, line) {
        header->atoms.append(item.split(" "));
      }
    }
  }
  editButton->setEnabled(true);
  return true;
}


int DSRGui::getCharWidth(int numchars) {
  //! returns the width in pixel of numchars times the # character
  QString buchstaben;
  buchstaben.clear();
  for (int i=1; i<=numchars; i++) {
    buchstaben += "#";
  }
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
  return QFontMetrics(this->font()).horizontalAdvance(buchstaben);
#else
  return QFontMetrics(this->font()).width(buchstaben);
#endif
}


void DSRGui::activateFitButton(void) {
    fitDSRButton->setEnabled(true);
    exportFragButton->setEnabled(true);
}


void DSRGui::combineOptionstext(void) {
  //! combines all options to a single DSR command line
  //! This method gets invoked if optionTextChanged signal is emmitted
  combiDSRline.clear();
  // Displays error messages from DSR:
  if (!outtext->toPlainText().contains("***")) {
    outtext->clear();
  } //else {
    //return;
  //}
  QString split = "";
  // CF3 groups are dummy entries in the DSR database. They get calculated
  // on ideal positions at the respective carbon atom:
  if (fragmentNameTag == QString("cf6")) {
    splitModeBox->show();
  } else {
    splitModeBox->hide();
  }
  if ( (fragmentNameTag == QString("cf3")) ||
       (fragmentNameTag == QString("cf6")) ||
       (fragmentNameTag == QString("cf9")) ) {
    this->cf3 = true;
    rigidBox->setDisabled(true);
    invertFragBox->setDisabled(true);
    runExtBox->setDisabled(true);
    replaceModeBox->setDisabled(true);
    residueOptionsBox->setDisabled(true);
    if (splitModeBox->isChecked() ) {
      split = "SPLIT";
    }
  } else {
    splitModeBox->hide();
    this->cf3 = false;
    rigidBox->setDisabled(false);
    invertFragBox->setDisabled(false);
    runExtBox->setDisabled(false);
    replaceModeBox->setDisabled(false);
    residueOptionsBox->setDisabled(false);
  }
  target_atoms = getSelectedAtomsList();
  QString putreplace = QString("PUT ");
  if (replace) {
      putreplace = QString("REPLACE ");
  }
  if (!cf3) {
    if (target_atoms.split(" ").length() != 3) {
      target_atoms = "<font color=red> Please select 3 target atoms/q-peaks! </font>";
    }
    if (mygl->source_atoms.split(" ").length() != 3){
      mygl->source_atoms = "<font color=red> Please select 3 fragment atoms! </font>";
    }
  } else {
    if (target_atoms.split(" ").length() != 1) {
      target_atoms = "<font color=red> Please select only <b>a single</b> carbon atom! </font>";
    }
    mygl->source_atoms = "";
  }
  QString resistr = "RESI ";
  if (!residueOptionsBox->isChecked() || !residueOptionsBox->isEnabled()) {
    resistr = "";
    resiTextLabel->setText("");
  } else {
    resiTextLabel->setText(*resnumbertext);
    if (resiclassEdit->text() == resiclass) {
      resistr = "RESI "+resiclass;
    } else {
      resistr = "RESI "+resiclassEdit->text();
    }
  }
  QString with;
  if (cf3) {
    with = QString(" ");
  } else {
    with = QString(" WITH ");
  }
  QString outstring = QString(QString("REM DSR ")+putreplace+fragmentNameTag+" "+
                          with+mygl->source_atoms+" "+QString("ON ")+
                          target_atoms+" "+part+" "+fvarocc+" "+dfix+" "+resistr+split);
  combiDSRline = outstring.simplified().toUpper();
  outtext->append(combiDSRline);

  mygl->selchanged = true;
  //printf("combineOptionstext\n");
}


void DSRGui::setResiClass(QString rclass) {
//! defines the residue class
  if (rclass[0].isLetter()){
    if (rclass.length() > 4) {
      resiclassEdit->setText(QString(rclass.mid(0, 4)));
    }
    emit optionTextChanged();
  } else {
    outtext->append(QString(tr("Please start residue "
                            "class with a letter.")));
    resiclassEdit->clear();
  }
}

void DSRGui::setFragName(QModelIndex name) {
//! set the fragment name variable
  //outtext->clear();
  fragmentNameTag = name.sibling(name.row(), 0).data().toString();
  writeFavorites(fragmentNameTag);
  //outtext->clear();
  if (!getFragmentHeader(fragmentNameTag)) {
    // In this case, the most important thing is missing
    return;
  }
  if (header->comment.isEmpty()){
    outtext->append("You should give this fragment a name.");
  }
  if (header->atoms.isEmpty()){
    return;
  }
  if (header->tag.isEmpty()){
    return;
  }
  if (header->restr.isEmpty()){
    return;
  }
  if (header->cell.isEmpty()){
    return;
  }
  //emit optionTextChanged();
  emit fragmentSelected();
  emit currentFragmentChanged(*header);
}


void DSRGui::DFIX(bool checked) {
//! toggles the dfix option
  outtext->clear();
  if (checked)
  {
    this->dfix = QString("DFIX");
  } else
  {
    this->dfix.clear();
  }
  emit optionTextChanged();
}

void DSRGui::setFvarOcc(void) {
//! defines the FVAR and occupancy option
  outtext->clear();
  int fvar = 0;
  double occ = 0;
  double focc = 0;
  fvar = fvarspinner->value();
  occ = (occEdit->text().replace(',', '.').toDouble());
  if (fvar < 0) {
    focc = -(abs(fvar) * 10 + occ);
  } else {
    focc = fvar * 10 + occ;
  }
  fvarocc = QString("OCC ")+QString::number(focc);
  emit optionTextChanged();
  outtext->append("\nFVAR num  ->  times used");
  foreach (int fvar, m_shelxle->fvarCntr.keys()) {
    if (fvar < 2) continue;
    outtext->append(QString("FVAR %1  -> %2  ").arg(fvar, 3).arg(m_shelxle->fvarCntr.value(fvar), 3));
  }
}

void DSRGui::setPART(int partnum) {
//! defines the PART option
  outtext->clear();
  if (partnum == 0)
  {
    part.clear();
  }
  else
  {
    QString s = QString::number(partnum);
    part = QString("PART ")+s ;
  }
  emit optionTextChanged();
}

void DSRGui::fitDSRExtern(bool checked) {
//! enable write restraints to external file
  if (checked) {
    this->runext = true;
  } else {
    this->runext = false;
  }
}

void DSRGui::invertFrag(bool checked) {
//! Inverts the fragment coordinates.
//! They are also inverted in the 3D view.
  // Invert coordinates in DSR:
  if (checked){
    this->invert = true;
  } else {
    this->invert = false;
  }
  /*
  V3 v1 = V3(-1,  0,  0);
  V3 v2 = V3( 0, -1,  0);
  V3 v3 = V3( 0,  0,  1);
  //rotation matrix to rotate the selection 180deg.
  // for less disturbance of the inverted view:
  // ch: WHY??

  Matrix rmat = Matrix(v1, v2, v3);*/
  // Invert the OpenGL coordinates:
  double coord;
  int index;
  index = 0;
  foreach(QStringList line, header->atoms) {
    for (int n = 2; n<5; n++) {
      coord = line[n].toDouble();
      // rotate fragment 180 deg. if ((n == 2) || (n == 3)) { coord = coord * -1; }
      header->atoms[index][n] = QString("%1").arg(-coord);
    }
    index = index+1;
  }
  //Also invert the selection of the atoms:
  for (int n=0; n<mygl->selFragAt.size(); n++) {
    //this line is essential:    mygl->selFragAt[n].pos = mygl->selFragAt[n].pos * rmat;
    mygl->selFragAt[n].pos *= -1.0;
  }
  mygl->display_fragment(*header, false);
  combineOptionstext();
  mygl->makeInfo();
  mygl->update();
}

void DSRGui::rigid_group(bool checked)
//! toggle rigid group refinenement
{
  if (checked) {
    this->rigid = true;
  } else {
    this->rigid = false;
  }
}

bool DSRGui::exportFrag(QString dirname) {
  //! export the current fragment to a res file+png
  //! change to the current dir here, because dsr exports in current dir:
  QDir::setCurrent(dirname);
  outtext->clear();
  if (fragmentNameTag.isEmpty()) {
      outtext->append("No fragment chosen. Doing nothing!");
      return false;
  }
  //outtext->clear();
  QString options = QString(" -e ") + fragmentNameTag;
  dsrResulttext.clear();
  runDSR(options, true, dirname);
  if (dsrResulttext.isEmpty()) {
    outtext->append("Unable to start DSR.");
    return false;
  }
  return true;
}

void DSRGui::refineOrNot(bool checked) {
//! enable or disable refinement after transfer
  if (checked) {
    this->norefine = true;
  } else {
    this->norefine = false;
  }
}

void DSRGui::replaceOrNot(bool checked) {
//! enable or disable replace mode
  outtext->clear();
  if (checked) {
    this->replace = true;
  } else {
    this->replace = false;
  }
  emit optionTextChanged();
}

QString DSRGui::getSelectedAtomsList() {
  //! returns the Names of the currently selected atoms of the structure
  //! loaded in ShelXle as StringList
  QStringList atoms;
  atoms.clear();
  for (int i=0; i<m_molecule->selectedatoms.size(); i++) {
    atoms.append(QString(m_molecule->selectedatoms.at(i).Label.toLatin1()).replace(QChar(187), ">>"));
  }
  return atoms.join(" ");
}

QString DSRGui::getSelectedAtomsCoords() {
  //! returns the atoms coordinates that are selected inside shelxle as a string
  QString atoms = "";
  QString line = "";
  for (int i = 0; i < m_molecule->selectedatoms.size(); ++i) {
    line = QString(" %1 %2 %3").arg(m_molecule->selectedatoms.at(i).frac.x, 10, 'f', 5)
                               .arg(m_molecule->selectedatoms.at(i).frac.y, 10, 'f', 5)
                               .arg(m_molecule->selectedatoms.at(i).frac.z, 10, 'f', 5);
    atoms.append(line);
  }
  return atoms;
}

bool DSRGui::fitDSR() {
  /*!
   runs DSR from command line

   bool QDir::setCurrent(const QString & path)
   QString QFileInfo::completeBaseName() const : "c:/programme/dsr/p21c.res -> p21c.res
   QString QFileInfo::absolutePath() const : c:/programme/dsr/p21c.res -> c:/programme/dsr/
   QString QFileInfo::absoluteFilePath() const : c:/programme/dsr/p21c.res -> c:/programme/dsr/p21c.res
   QFileInfo fi("c:/temp/foo"); => fi.absoluteFilePath()
  */
  QString atoms = getSelectedAtomsCoords();
  if (!cf3) {
    if (m_molecule->selectedatoms.size() != 3) {
      emit optionTextChanged();
      //return false;
    }
    if (mygl->source_atoms.split(" ").length() != 3) {
      emit optionTextChanged();
      outtext->append("<font color=red> \nPlease select three "
                      "atoms of the fragment! </font>");
      return false;
    }
  }
  info->hide(); // Even if the fit does not work, I want to hide it to better see the output
  QString option;
  QString source_atoms_tmp = mygl->source_atoms;
  if ((m_molecule->selectedatoms.size() != 3) && !cf3) {
    //outtext->clear();
    outtext->append("<font color=red> Please select at least three "
                    "atoms or Q-peaks as target in your structure! </font>");
    return false;
  }
  if ((m_molecule->selectedatoms.size() != 1) && cf3) {
    outtext->clear();
    outtext->append("<font color=red> Please select one carbon"
                    "atom as target in your structure! </font>");
    return false;
  }
  target_atoms = getSelectedAtomsList();
  bool ok;
  int dsrv = dsrVersion.toInt(&ok, 10);
  if (ok && dsrv < 200) {
    // This is obsolete with DSR >= 200 since we fit the fragment to
    // the actual coordinates and not to "names":
    if ( target_atoms.contains(QString(">>"))) {
      outtext->clear();
      outtext->append(QString("<font color=red><b>Symmetrie generated atoms not allowed as target! <br><br>"
                              "Please update DSR.</b></font>"));
      return false;
    }
  }
  emit optionTextChanged();
  bool save_sucess = m_shelxle->fileSave(true, false);
  if (!save_sucess) {
    outtext->append("Could not save the instruction file!");
    return false;
  }
  QStringList *reslist = new QStringList;
  reslist->append(readResfile());
  mygl->source_atoms = source_atoms_tmp;
  int DSRposition = decideDSRInsertLine(reslist);
  if (DSRposition == 0){
    outtext->append("Could not fit fragment. No FVAR command found. \nPlease refine at least one cycle.");
    return false;
  }
  QVector<int> previousLines = findDSRLines(reslist);
  QString wrappedDSRLine = textWrap(combiDSRline);
  m_shelxle->insertDSRLine(wrappedDSRLine, DSRposition, previousLines);
  delete reslist;
  if (rigid) {
    option = "-g ";
  } else {
    option = "";
  }
  if (norefine){
    option += " -n ";
  }
  if (!runext && !invert) // the standard run without extra options
  {
    option += " -r ";
  }
  else if (runext && !invert) {
    option += " -re ";
  }
  else if (!runext && invert)
  {
    option += " -t -r ";
  }
  else if (runext && invert) {
    option += " -t -re ";
  } else {
    qDebug() << "Unhandeled option case in DSRGui occoured!!";
    return false;
  }
  if (!m_shelxlPath.isEmpty() && (dsrVersion.toInt() > 182)) {
    option = " -shx " + m_shelxlPath + " " + option;
  }
  if ((dsrVersion.toInt() >= 200)) {
    option = " -target " + atoms + " " + option;
  }
  QFileInfo resfip(m_shelxle->dirName);
  option = option + resfip.completeBaseName();
  QFileInfo check_res(resfip.completeBaseName()+".res");
  if ( resfip.completeSuffix() == "ins" && check_res.size() == 0) {
    outtext->clear();
    outtext->append("Warning! Something went wrong with your .res file.\n"
                    "You are currently working on the .ins file. Please restore "
                    "the .res file before you continue.");
    return false;
  }
  bool dsr = this->runDSR(option);
  if (!dsr) {
      return false;
  }
  m_shelxle->loadAFile();
  this->show();
  this->raise();
  this->activateWindow();
  return true;
}

void DSRGui::updateDSR(void) {
  //!
  //! Updates DSR to the current version on the web server
  //!
  QString option = " -u";
  outtext->append("Update running...");
  this->runDSR(option);
}

bool DSRGui::runDSR(QString option, bool showresults, QString workdir) {
  //! runs DSR with options and shows the results in outtext if desired.
  dsrResulttext.clear();
  outtext->clear();
  QProcess dsr;
  QFileInfo resfip;
  if (workdir.isEmpty()) {
    // workdir can be the export (fragment) directory for example.
    resfip.setFile(m_shelxle->dirName);
    if (resfip.exists()) {
      // Need to check if path is not empty, because en empty path would cause dsr.start() to fail.
      // absolutePath() truncates the last path part even though its C:\foo\bar --> C:\foo
      dsr.setWorkingDirectory(resfip.absolutePath());
    }
  } else {
    resfip.setFile(workdir);
    dsr.setWorkingDirectory(resfip.absoluteFilePath());
  }
  dsr.setProcessChannelMode(QProcess::MergedChannels);
  dsr.closeWriteChannel();
  // Do not use this with fragment export:
  if (!resfip.absolutePath().isEmpty() && workdir.isEmpty()) {
    // Need to do this, because en empty path would cause dsr.start() to fail.
    dsr.setWorkingDirectory(resfip.absolutePath());
  }
  dsr.start(dsrpath, option.split(" ", skipEmptyParts));
  if (!dsr.waitForFinished()) {
    outtext->append("Unable to start DSR.");
    outtext->append(dsrpath + " " + option);
    outtext->append(dsr.readAll());
    return false;
  } else {
    dsrResulttext.append(dsr.readAll());
    //qDebug() << dsrResulttext;
  }
  /*
  if (dsrResulttext.isEmpty()) {
    bool socket = runTCPServer();
    if (!socket) {
      outtext->append("Unable read DSR output.");
    }
  } */
  if (showresults) {
    // Display the results:
    //outtext->clear();
    outtext->append(combiDSRline);
    outtext->append(dsrResulttext);
  }
  this->show();
  this->raise();
  this->activateWindow();
  //qDebug() << dsrResulttext;
  return true;
}

void DSRGui::searchFragment(QString searchName) {
  //! Searches for fragments in the database
  if ((searchName.length() < 2) && (searchName.length() > 0)){
    return;
  }
  // If search length is zero, restore full list:
  if (searchName.length() == 0){
    if (!listDSRdbFragments("None")) {
      outtext->append("Unable to find DSR fragment database.");
      return;
    }
    return;
  }
  QString option = QString(" -x ") + searchName;
  dsrResulttext.clear();
  this->runDSR(option, false);
  QVector<QStringList> fraglist;
  fraglist.clear();
  foreach (QString line, dsrResulttext.split(QRegularExpression("\n|\r\n|\r"))) {
    if (line.isEmpty()){
      continue;
    }
    if (line.contains(";;")) {
      fraglist.append(line.split(";;"));
    }
  }
  if (fraglist.size() > 0) {
    displayFragmentsList(fraglist, fraglist.at(0).at(0).toLatin1().toUpper());
  } else {
    displayFragmentsList(fraglist, "None");
  }
}

bool DSRGui::isDSRVersionCorrect(QString version) {
  //! checks if the version of DSR found in DSR_DIR
  //! is compatible with this GUI
  bool ok;
  ok = false;
  if (version.trimmed().toInt() >= 182) {
    ok = true;
  }
  return ok;
}

bool DSRGui::listDSRdbFragments(QString fav="None") {
  //! list fragments in DSR database
  //! The -lc parameter of DSR returns a semicolon (;;) separated list
  //! tag;;fullname;;line number;;db
  if (QString("None") == fav) {
    fav = loadFavoriteFragment().toLatin1().toUpper();
  }
  fragmentsList->clear();
  fragmentNameTag.clear();
  QString options = " -lc";
  runDSR(options, true);
  QStringList frag_str_list = dsrResulttext.split(QRegularExpression("\n|\r\n|\r"));
  bool versionOk = false;
  foreach (QString line, frag_str_list) {
    if (line.contains("Duplicate database entry")) {
      outtext->clear();
      outtext->append(dsrResulttext);
      return false;
    }
  }
  // in this case no fragment list returned. Hence, we have an error.
  if (!dsrResulttext.contains(";;")) {
    //outtext->clear();
    outtext->append("Something went wrong with DSR. please tell Daniel Kratzert (dkratzert@gmx.de) about this problem.");
    outtext->append(dsrResulttext);
    return false;
  }
  foreach (QString line, frag_str_list) {
    if (line.isEmpty()){
      continue;
    }
    if ( (line.split(":").size() >= 1) && line.contains("DSR version:")) {
      dsrVersion = line.split(":").at(1).trimmed();
    }
    if (line.trimmed().contains("DSR version:")) {
      versionOk = isDSRVersionCorrect(dsrVersion);
      continue;
    }
    if (line.trimmed().startsWith("***")) {
      outtext->append(line);
      continue;
    }
    if (line.contains(";;")) {
      // collect frags to global list here:
      fragmentsList->append(line.split(";;")); // the global list of all fragments
    }
  }
  if (!versionOk) {
    outtext->clear();
    outtext->append(QString(tr("Detected an old version of DSR.")));
    outtext->append(QString(tr("Please get the most recent version from https://dkratzert.de/dsr.html")));
    return false;
  }
  displayFragmentsList(*fragmentsList, fav);
  return true;
}


void DSRGui::displayFragmentsList(QVector<QStringList> list, QString fav="None") {
  //! displays the list of fragments in a table view
  //! The first column (the tag) is hidden, only the name is displayed.
  QStandardItem *fraglabel = new QStandardItem(QString("Fragment Name"));
  fraglabel->setTextAlignment(Qt::AlignLeft);
  QStandardItemModel *FragListmodel = new QStandardItemModel(list.size(), 2, this); //x Rows and 2 Columns
  FragListmodel->setHorizontalHeaderItem(0, new QStandardItem(QString("tag")));
  FragListmodel->setHorizontalHeaderItem(1, fraglabel);
  QStringList line;
  for (int i = 0; i < list.size(); ++i) {
    line.clear();
    line = list[i];
    if ( line.size() < 3 ) {
      continue;
    }
    QString column1 = line[0];
    QString column2 = line[1];
    QStandardItem *nameItem;
    // Add a bold *user* to all fragments from the user db
    if (line[3].contains("dsr_user_db")) {
      column2.append(" *user*");
      nameItem = new QStandardItem(QString(column2));
      QFont f = nameItem->font();
      f.setBold(true);
      nameItem->setFont(f);
    } else {
      nameItem = new QStandardItem(QString(column2));
    }
    FragListmodel->setItem(i, 0, new QStandardItem(QString(column1)));
    FragListmodel->setItem(i, 1, nameItem);
    // load the last fragment:
    if (fav == line.at(0).toLatin1().toUpper()) {
      if (FragListmodel->hasIndex(i, 0)) {
        setFragName(FragListmodel->index(i, 0));
      }
    }
  }
  fragmentTableView->setModel(FragListmodel);
  fragmentTableView->verticalHeader()->hide();
  fragmentTableView->hideColumn(0);
  fragmentTableView->setColumnWidth(1, 600);
  fragmentTableView->setGridStyle(Qt::PenStyle(Qt::NoPen));
  fragmentTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

QString DSRGui::getDSRDir() {
  //! returns the value of the DSR_DIR variable
  //! in case of error, it returns an empty string
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
  QString dsrdir = qEnvironmentVariable("DSR_DIR");
#else
  QString dsrdir = qgetenv("DSR_DIR");
#endif
  if (!QFile::exists(dsrdir)){
    if (!which("dsr").isEmpty()) {
      QFileInfo fi(which("dsr").at(0));
      if (fi.exists()) {
        dsrdir = fi.absolutePath();
      }
    }
    if (QFile::exists("/Applications/DSR")) {
        dsrdir = "/Applications/DSR";
    }
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
    QString dsrdir2 = qEnvironmentVariable("DSRDIR");
#else
    QString dsrdir2 = qgetenv("DSRDIR");
#endif
    if (QFile::exists(dsrdir2)) {
      qDebug() << "You are probably using an older version of DSR."
                  "\n Please use version 1.7.7 or above.";
      // return empty string, because dsr.bat will
      // hinder dsr from starting properly:
      return QString("");
    }
  }
  return QDir::fromNativeSeparators(dsrdir);
}

QString DSRGui::getDSRdbDir() {
  //! returns the directory with the userdb -> the home directory
  QString dbdir = QDir::homePath();
  return QDir::fromNativeSeparators(dbdir);;
}


void DSRGui::setExportDirDialog() {
  //! File dialog to define the directory for the res file
  //! exported by DSR
  export_dir = "";
  export_dir = QFileDialog::getExistingDirectory(this, tr("Export Fragment to ..."), tr("Directory"));
  if (QFile::exists(export_dir)){
    emit exportDirChanged(export_dir);
  }
}