Debian Codegraph @

dsrgui.cpp

raw symbols SCIP
1 /*
2 ----------------------------------------------------------------------------
3 "THE BEER-WARE LICENSE" (Revision 42):
4 <[email protected]> wrote this file. As long as you retain
5 this notice you can do whatever you want with this stuff. If we meet some day,
6 and you think this stuff is worth it, you can buy me a beer in return.
7 Daniel Kratzert
8 ----------------------------------------------------------------------------
9 */
10
11 //#include "bits/stdc++.h"
12 #include <QtGui>
13 #include <QDir>
14 #include <QNetworkAccessManager>
15 #include "dsrgui.h"
16 #include "window.h"
17 #include "dsrglwindow.h"
18 #include "dsreditwindow.h"
19 #include "deprecation.h"
20 #include "itsme.h"
21
22 #if defined(Q_OS_WIN) || defined(Q_WS_WIN32)
23 static const QString mysystem = "win";
24 #else
25 static const QString mysystem = "unix";
26 #endif
27
28 /*
29 Explanations
30
31 - This GUI is for DSR https://dkratzert.de/dsr.html
32 - DSR stores the information for pre-defined molecular fragments and their
33 restraints in a text database in $DSR_DB_DIR.
34 - This GUI uses that information to provide a convenient interface for DSR.
35 - DSR is controlled by a special command in the SHELXL res file starting with REM DSR ...
36 and by commandline options.
37 - A special command line option -ah tells DSR to print the information about a
38 fragment in a special format for this GUI.
39 It is a list of html-like tags <tag> data </tag> with ;; separated values containing for
40 example the unit cell information and coordinates of the fragment. The first line
41 contains the version number of DSR.
42 - The GUI first runs dsr with -lc to get a list of all fragment names in the database.
43 A mouse click on a fragment in the list invokes "dsr -ah name" to get the details of
44 the selected fragment (and stores it in struct DSRMol). This details are also used to
45 edit the fragment ("edit fragment" button).
46 - The text widget below the search field displays some status output from DSR,
47 especially the text output from DSR during the fragment transfer/fit to the target structure.
48
49 - merging: go into shelxle-kratzert and svn merge -r 165:HEAD /Users/daniel/Downloads/shelxle-trunk
50 "-r (latest own commit):HEAD" svn merge -r 165:HEAD d:\downloads\shelxle-svn\trunk
51 */
52
53
54 DSRGui::DSRGui(Molecule *mole, QString shelxlPath, Window *parent): QWidget(parent) {
55 m_shelxle = parent;
56 m_molecule = mole;
57 m_shelxlPath = shelxlPath;
58 this->setWindowFlags(Qt::Window|Qt::WindowStaysOnTopHint);
59 //printf("I am DSR and this are my flags:%d\n",windowFlags ());
60 setWindowTitle(QString(tr("DSR GUI")));
61 if (mysystem == QString("win")) {
62 dsrpath = getDSRDir()+"/dsr.bat";
63 dsr_db_path = getDSRdbDir();
64 } else if (mysystem == QString("unix")){
65 dsrpath = QDir::cleanPath(getDSRDir()+"/dsr");
66 dsr_db_path = QDir::cleanPath(getDSRdbDir());
67 }
68 this->hide();
69 dsrVersion = "";
70 replace = false;
71 norefine = false; // this has to stay here
72 runext = false;
73 invert = false;
74 rigid = false;
75 cf3 = false;
76 splitmode = false;
77 fragmentsList = new QVector<QStringList>;
78 fragmentNameTag.clear();
79 header = new DSRMol;
80 mainLayout = new QGridLayout(this);
81 editLayout = new QHBoxLayout();
82 //chooserLayout = new QGridLayout;
83 searchLayout = new QHBoxLayout();
84 //partLayout = new QHBoxLayout();
85 //fvarLayout = new QHBoxLayout();
86 //occLayout = new QHBoxLayout();
87 resclassLayout = new QHBoxLayout();
88 optionsLayout2 = new QVBoxLayout();
89 optionsLayout3 = new QVBoxLayout();
90 groupBox1 = new QGroupBox();
91 optionsLayout1 = new QGridLayout(groupBox1);
92 groupBox2 = new QGroupBox();
93 residueOptionsBox = new QGroupBox(tr("Use a Residue"));
94 buttonLayout = new QVBoxLayout();
95 optionboxes = new QHBoxLayout();
96 fitDSRButton = new QPushButton(tr("Fit Fragment!"));
97 splitButton = new QPushButton(tr("Split Atoms"));
98 fitDSRButton->setStyleSheet("QPushButton {"
99 "font-weight: bold; "
100 "color: #209920}");
101 exportFragButton = new QPushButton(tr("Export Fragment"));
102 editButton = new QPushButton(tr("Edit Fragment"));
103 editButton->setStyleSheet("QPushButton {"
104 "font-weight: bold; "
105 "color: rgb(8, 82, 182)}");
106 openLastButton = new QPushButton(tr("Restore last .res"));
107 runExtBox = new QCheckBox(tr("External Restraints"));
108 invertFragBox = new QCheckBox(tr("Invert Coordinates"));
109 dfixBox = new QCheckBox(tr("Calculate DFIX"));
110 rigidBox = new QCheckBox(tr("Rigid Group (no restraints)"));
111 replaceModeBox = new QCheckBox(tr("Replace Target"));
112 splitModeBox = new QCheckBox(tr("Split Target"));
113 searchLabel = new QLabel(tr("Search:"));
114 SearchInp = new QLineEdit;//(tr("Search a fragment here"));
115 partLabel = new QLabel(tr("PART"));
116 fvarLabel = new QPushButton(tr("Free Variable")); // Is a QPushbutton to have a clicked() signal
117 fvarLabel->setStyleSheet("QPushButton {border-style: outset; border-width: 0px; text-align:left;}"); // remove border to appear like a label
118 fvarLabel->setToolTip("Click here to invert the current free variable");
119 occLabel = new QLabel(tr("Occupancy"));
120 classLabel = new QLabel(tr("Residue Class"));
121 usermanualLabel = new QLabel(tr("<a href=\"https://github.com/dkratzert/DSR/raw/master/manuals/DSR-manual.pdf\"> DSR User Manual </a>"));
122 usermanualLabel->setOpenExternalLinks(true);
123 resnumbertext = new QString(tr("A residue number will be\nchosen automatically."));
124 resiTextLabel = new QLabel();
125 resiTextLabel->setText(*resnumbertext);
126 outtext = new QTextBrowser;
127 outtext->setOpenExternalLinks(true);
128 info = new QTextBrowser;
129 //this->move(-this->width(), -this->height());
130 info->setMinimumWidth(235);
131 info->hide();
132 //info->setMaximumWidth(235);
133 fragmentTableView = new QTableView;
134 occEdit = new QLineEdit;
135 partspinner = new QSpinBox;
136 fvarspinner = new QSpinBox;
137 resiclassEdit = new QLineEdit;
138 // layout for the interactions
139 optionboxes->addWidget(groupBox1);
140 //optionboxes->addStretch();
141 optionboxes->addWidget(groupBox2);
142 //optionboxes->addStretch();
143 optionboxes->addWidget(residueOptionsBox);
144 //optionboxes->addStretch();
145 optionboxes->addLayout(buttonLayout);
146 //buttonLayout->setSizeConstraint(QLayout::SetMaximumSize);
147 // The search field:
148
149 SearchInp->setFocus(); // searching should be the default
150 SearchInp->setMinimumWidth(getCharWidth(9));
151 fragmentNameTag.clear();
152 // The OpenGL widget with the molecule:
153 mygl = new DSRGlWindow(this, m_molecule, *header, fragmentNameTag);
154 mygl->showFit = new QCheckBox(tr("show fitted target overlay"));
155 mygl->showFit->setChecked(true);
156 mygl->showFitLabel = new QCheckBox(tr("labels on target overlay"));
157 mygl->showFitLabel->setChecked(true);
158 // Table of fragments and 3D window:
159
160 editLayout->addWidget(outtext);
161 editLayout->addWidget(info);
162 editLayout->setStretchFactor(outtext, 2);
163 editLayout->setStretchFactor(info, 1);
164 outtext->setReadOnly(true);
165 QFont font("Courier");
166 font.setStyleHint(QFont::TypeWriter);
167 outtext->setFont(font);
168 outtext->setMinimumHeight(170);
169 partspinner->setRange(-99, 99);
170 partspinner->setValue(0);
171 fvarspinner->setRange(-99, 99);
172 fvarspinner->setValue(1);
173 occEdit->setValidator(new QDoubleValidator(0, 99, 5, occEdit));
174 occEdit->setMaximumWidth(getCharWidth(5));
175 occEdit->setMinimumWidth(getCharWidth(5));
176 // box1
177 optionsLayout1->addWidget(partspinner,0,0);
178 optionsLayout1->addWidget(partLabel,0,1);
179
180 optionsLayout1->addWidget(fvarspinner,1,0);
181 optionsLayout1->addWidget(fvarLabel ,1,1);
182
183 optionsLayout1->addWidget(occEdit ,2,0);
184 optionsLayout1->addWidget(occLabel,2,1);
185
186 optionsLayout1->addWidget(replaceModeBox, 3,0,1,2 );
187 optionsLayout1->addWidget(splitModeBox, 4,0,1,2 );
188 splitModeBox->hide();
189 //optionsLayout1->addStretch();
190 groupBox1->setLayout(optionsLayout1);
191 // box2
192 optionsLayout2->addWidget(invertFragBox);
193 optionsLayout2->addWidget(runExtBox);
194 optionsLayout2->addWidget(dfixBox);
195 optionsLayout2->addWidget(rigidBox);
196 //optionsLayout2->addStretch();
197 groupBox2->setLayout(optionsLayout2);
198 // box3
199 resclassLayout->addWidget(resiclassEdit);
200 resclassLayout->addWidget(classLabel);
201 resiclassEdit->setMaximumWidth(getCharWidth(8));
202 resiclassEdit->setMinimumWidth(getCharWidth(6));
203 optionsLayout3->addLayout(resclassLayout);
204 optionsLayout3->addWidget(resiTextLabel);
205 optionsLayout3->addWidget(usermanualLabel);
206 optionsLayout3->addStretch();
207 residueOptionsBox->setLayout(optionsLayout3);
208 residueOptionsBox->setCheckable(true);
209 // buttons:
210 buttonLayout->addWidget(fitDSRButton);
211 buttonLayout->addWidget(exportFragButton);
212 exportFragButton->setEnabled(false);
213 buttonLayout->addWidget(splitButton);
214 splitButton->setDisabled(true);
215 splitButton->hide(); // there is no DSR version that can do this until now.
216 buttonLayout->addWidget(editButton);
217 buttonLayout->addWidget(openLastButton);
218 // tooltips:
219 setToolTips();
220 QPixmap pix = QPixmap(250, 50);
221 pix.fill(); // need to fill in order to see the text.
222 QPainter painter(&pix);
223 QRectF rectangle(0, 0, 250-1, 49);
224 painter.setFont(QFont("Sans-Serif", 12));
225 painter.drawRect(rectangle);
226 painter.drawText(QPoint(12, 30), "Loading fragment list...");
227 QGroupBox *glGroupBox = new QGroupBox();
228 glo = new QGridLayout(glGroupBox);
229 glo->addWidget(mygl,0,0,1,2);
230 glo->addWidget(mygl->showFit,1,0,1,1);
231 glo->addWidget(mygl->showFitLabel,1,1,1,1);
232
233 glGroupBox->setFlat(true);
234 QGroupBox *fGroupBox = new QGroupBox();
235 flo = new QGridLayout(fGroupBox);
236 mainLayout->addWidget(fGroupBox, 0, 0, 3, 2);
237 mainLayout->addWidget(glGroupBox, 0, 2, 3, 5);
238 flo->addWidget(fragmentTableView ,0,0,1,2);
239 flo->addWidget(searchLabel ,1,0,1,1);
240 flo->addWidget(SearchInp ,1,1,1,1);
241 mainLayout->setRowMinimumHeight(3,200);
242 mainLayout->addLayout(editLayout, 3,0,1,7);
243 mainLayout->addLayout(optionboxes, 6,0,1,7);
244 QSplashScreen *splash = new QSplashScreen(pix);
245 splash->show();
246 splash->showMessage("");
247 target_atoms = getSelectedAtomsList(); // must be before signals
248 // request version.txt to warn for updates:
249
250 #if !defined(Q_OS_MAC) && (QT_VERSION >= 0x050000)
251 getVersionFromServer();
252 #endif
253 // Signal slot connections:
254 connect_signals_and_slots();
255 splitDecide();
256 occEdit->setText("1");
257 checkForDSRexecutable(splash);
258 splash->finish(this);
259 // call last, because keyboard focus is reated to tab order,
260 // which is based on the order the widgets are created:
261 SearchInp->setFocus();
262 // Has to be here, otherwise fragmentTableView is not initialized:
263 QItemSelectionModel *sm = fragmentTableView->selectionModel();
264 this->show();
265 if (!(sm == nullptr)){ // prevents error about missing connection if DSR is not present
266 connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
267 this, SLOT(setFragName(QModelIndex)), Qt::UniqueConnection);
268 }
269 //int scn=QApplication::desktop()->screenNumber(m_shelxle);//find out where the main window is
270 QScreen *screen = m_shelxle->window()->windowHandle()->screen();
271 //QGuiApplication::screens().at(scn)->geometry()
272 this->move(screen->geometry().x()+
273 screen->geometry().width()-this->width()-30, 30);
274
275 //printf("test\n");
276 //this->resize(this->width()-2, this->height()-2); // a trick to redraw the gl windows
277 // this raises an 'Unable to set geometry' error
278 mygl->update();
279 //printf("test2\n");
280 if (!(dsrVersion.toLatin1() == "0")) {
281 outtext->append(QString("\nFound DSR version %1.").arg(dsrVersion));
282 if (dsrVersion.toInt() > 9999) { // To be changed later
283 splitButton->show(); // logic turned, because a non-replying web server turned this button on
284 }
285 }
286 update();
287 }
288
289
290 DSRGui::~DSRGui() {
291 delete mygl;
292 }
293
294 void DSRGui::aboutDSR() {
295 QMessageBox::about(this, QString(tr("About DSR Plugin")),//only one about dlg in macOS
296 QString(
297 tr("<p><b>DSR plugin for ShelXle</b></p>"
298 "This plugin is a graphical interface for DSR.<br>"
299 "The GUI part and the interaction with DSR was developed by <b>Daniel Kratzert</b>, "
300 "while the 3D OpenGL part was developed by <b>Christian H&uuml;bschle</b>.<br>"
301 "DSR is a refinement tool with a database of molecular fragments and corresponding restraints.<br>"
302 "Place these fragments in a molecular structure to model disorder or just quickly rename "
303 "groups of atoms.<br><br>"
304 "Please cite DSR as:<br>"
305 "<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>"
306 "<a href=https://doi.org/10.1107/S1600576718004508> doi:10.1107/S1600576718004508 </a><br><br>"
307 "If you have additional fragments for the DSR database or a bug to report, please send them to "
308 "<a href=\"[email protected]\"> [email protected] </a> <br>"
309 "Please find the most recent version of DSR at <br>"
310 "<a href=\"https://dkratzert.de/dsr.html\"> https://dkratzert.de/dsr.html </a><br><br>"
311 "All DSR related software is developed at GitHub:<br>"
312 "<a href=\"https://github.com/dkratzert/DSR\"> https://github.com/dkratzert/DSR </a><br><br>"
313 "Please refer to the <a href=\"http://www.xs3-data.uni-freiburg.de/data/DSR-manual.pdf\"> manual </a> if you have any questions."
314 )));
315 }
316
317 void DSRGui::connect_signals_and_slots() {
318 //! Handles most of the signal slot connections
319 connect(this, SIGNAL(fragmentSelected(void)),
320 this, SLOT(activateFitButton(void)));
321 connect(this, SIGNAL(fragmentSelected()),
322 this, SLOT(resetSelection()));
323 connect(fitDSRButton, SIGNAL (clicked(bool)),
324 this, SLOT (fitDSR()));
325 connect(fitDSRButton, SIGNAL (clicked(bool)),
326 this->info, SLOT(hide()));
327 connect(runExtBox, SIGNAL (clicked(bool)),
328 this, SLOT (fitDSRExtern(bool)));
329 connect(dfixBox, SIGNAL (clicked(bool)),
330 this, SLOT (DFIX(bool)));
331 connect(invertFragBox, SIGNAL (clicked(bool)),
332 this, SLOT (invertFrag(bool)));
333 connect(rigidBox, SIGNAL (clicked(bool)),
334 this, SLOT (rigid_group(bool)));
335 connect(replaceModeBox, SIGNAL(clicked(bool)),
336 this, SLOT(replaceOrNot(bool)));
337 connect(SearchInp, SIGNAL(textChanged(QString)),
338 this, SLOT(searchFragment(QString)));
339 connect(occEdit, SIGNAL(textChanged(QString)),
340 this, SLOT(setFvarOcc(void)));
341 connect(fvarspinner, SIGNAL(valueChanged(int)),
342 this, SLOT(setFvarOcc(void)));
343 connect(resiclassEdit, SIGNAL(textChanged(QString)),
344 this, SLOT(setResiClass(QString)));
345 connect(residueOptionsBox, SIGNAL(toggled(bool)),
346 this, SLOT(combineOptionstext()));
347 connect(splitModeBox, SIGNAL(toggled(bool)),
348 this, SLOT(combineOptionstext()));
349 connect(partspinner, SIGNAL(valueChanged(int)),
350 this, SLOT(setPART(int)));
351 connect(exportFragButton, SIGNAL(clicked(bool)),
352 this, SLOT(setExportDirDialog(void)));
353 connect(fragmentTableView, SIGNAL(clicked(QModelIndex)),
354 this, SLOT(setFragName(QModelIndex)));
355 connect(this, SIGNAL(optionTextChanged(void)),
356 this, SLOT(combineOptionstext(void)));
357 connect(editButton, SIGNAL(clicked(bool)),
358 this, SLOT(runEditWindow()));
359 connect(openLastButton, SIGNAL(clicked(bool)),
360 this, SLOT(open_last_fileversion()));
361 connect(this, SIGNAL(exportDirChanged(QString)),
362 this, SLOT(exportFrag(QString)));
363 // sigslot for uppdating the 3D view
364 connect(this, SIGNAL(currentFragmentChanged(DSRMol)),
365 mygl, SLOT(display_fragment(DSRMol)));
366 connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
367 mygl, SLOT(update()));
368 connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
369 this, SLOT(updateTarget()));
370 connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
371 this, SLOT(update()));
372 connect(mygl->showFitLabel, SIGNAL(stateChanged(int)),
373 mygl, SLOT(update()));
374 connect(mygl->showFitLabel, SIGNAL(stateChanged(int)),
375 mygl, SLOT(update()));
376 connect(mygl->showFit, SIGNAL(stateChanged(int)),
377 mygl, SLOT(update()));
378 connect(mygl->showFit, SIGNAL(stateChanged(int)),
379 mygl, SLOT(update()));
380 connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
381 mygl, SLOT(makeInfo()));
382 connect(mygl, SIGNAL(sourceStringChanged()),
383 this, SLOT(combineOptionstext()));
384 connect(mygl, SIGNAL(updateInfo(QString)),
385 this, SLOT(setInfo(QString)));
386 #if !defined(Q_OS_MAC) && (QT_VERSION >= 0x050000)
387 connect(net_manager, SIGNAL(finished(QNetworkReply*)),
388 this, SLOT(isDSRUpToDate(QNetworkReply*)));
389 #endif
390 connect(fvarLabel, SIGNAL(clicked(bool)),
391 this, SLOT(invertFvar()));
392 connect(m_shelxle->chgl, SIGNAL(selectionChanged()),
393 this, SLOT(splitDecide(void)));
394 connect(splitButton, SIGNAL(clicked(bool)),
395 this, SLOT(splitSelectedAtoms(void)));
396 }
397
398 QSize DSRGui::minimumSizeHint() const {
399 return QSize(700, 700);
400 }
401
402 QSize DSRGui::sizeHint() const {
403 return QSize(700, 780);
404 }
405
406 void DSRGui::getVersionFromServer() {
407 //! Writes the proposed version number of DSR into reply
408 net_manager = new QNetworkAccessManager(this);
409 QNetworkRequest request;
410 request.setUrl(QUrl("http://www.xs3-data.uni-freiburg.de/data/version.txt"));
411 request.setRawHeader("User-Agent", "DSRGui");
412 reply = net_manager->get(request);
413 }
414
415 /*
416 bool DSRGui::runTCPServer() {
417 //! Socket server to get messages from DSR. Might be used in future.
418 tcpServer = new QTcpServer(this);
419 //connect(tcpServer, SIGNAL(newConnection()), this, SLOT(ReadClientData()));
420 if (!tcpServer->listen(QHostAddress::LocalHost, 51234)) {
421 tcpServer->close();
422 return false;
423 } else {
424 if (tcpServer->waitForNewConnection()) {
425 if (tcpServer->hasPendingConnections()) {
426 ReadClientData();
427 }
428 }
429 }
430 return true;
431 }
432 */
433 /*
434 void DSRGui::ReadClientData() {
435 //! Reads DSR client data from a tcp soccet connection.
436 QByteArray data_buffer;
437 QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
438 connect(clientConnection, SIGNAL(readyRead()), clientConnection, SLOT(deleteLater()));
439 // this wait is essential to retrieve data:
440 clientConnection->waitForReadyRead();
441 while (clientConnection->bytesAvailable() > 0) {
442 data_buffer = clientConnection->readAll();
443 }
444 //close tcpServer after reading data:
445 tcpServer->deleteLater();
446 outtext->append(data_buffer);
447 //dsrResulttext.append(data_buffer);
448 }
449 */
450
451 void DSRGui::isDSRUpToDate(QNetworkReply* reply) {
452 /*
453 *! Displays a warning if the current DSR version is too old.
454 */
455 QString latestRev_str = reply->readAll();
456 bool ok;
457 bool ok2;
458 QMessageBox info;
459 info.addButton(QMessageBox::Close);
460 int dsrv = dsrVersion.toInt(&ok2, 10);
461 QPushButton *updateButton = info.addButton(tr("Update now"), QMessageBox::ActionRole);
462 if (dsrv < 193) { // This is the first version with self-update mechanism
463 updateButton->hide();
464 }
465 int latestrev_int = latestRev_str.toInt(&ok,10);
466 if ((ok&&ok2)&&(latestrev_int)>(dsrv)){
467 info.setText(QString(
468 "<h3>You should probably update DSR!</h3>"
469 "This is revision: <b>%1</b><br> "
470 "The latest version is: <b>%2</b> <br><br>"
471 "New versions can be downloaded here: <br>"
472 "<a href=\"https://dkratzert.de/dsr.html\">"
473 "https://dkratzert.de/dsr.html</a><br><br>"
474 "Please contact the author Daniel Kratzert"
475 " <a href=\"mailto:[email protected]\">[email protected]</a> "
476 "if you find any bugs.<br> Thank you!")
477 .arg(dsrVersion.toInt())
478 .arg(latestrev_int));
479 info.exec();
480 if (info.clickedButton() == updateButton) {
481 updateDSR();
482 }
483 }
484 reply->close();
485 reply->deleteLater();
486 disconnect(net_manager, SIGNAL(finished(QNetworkReply*)), NULL, NULL);
487 }
488
489 void DSRGui::updateTarget() {
490 //! updates the target atoms list
491 target_atoms = getSelectedAtomsList();
492 combineOptionstext();
493 }
494
495 void DSRGui::writeFavorites(QString name) {
496 //! Stores favorites in dsrgui.ini
497 QSettings dsr_settings( QSettings::IniFormat, QSettings::UserScope, PROGRAM_NAME, "dsrgui" );
498 dsr_settings.beginGroup("LastFragment");
499 dsr_settings.setValue("last", name);
500 dsr_settings.endGroup();
501 }
502
503 QString DSRGui::loadFavoriteFragment() {
504 //! Loads Favorites from dsrgui.ini
505 QSettings dsr_settings( QSettings::IniFormat, QSettings::UserScope, PROGRAM_NAME, "dsrgui" );
506 dsr_settings.beginGroup("LastFragment");
507 QString last = dsr_settings.value("last").toString();
508 dsr_settings.endGroup();
509 if (last == QString("cf6")) {
510 splitModeBox->show();
511 }
512 if (last == QString("")) {
513 last = QString("benzene");
514 }
515 return last;
516 }
517
518 QStringList DSRGui::which(QString programName) {
519 //! Implements a which like method
520 //! It returns all paths where programName is found in
521 //! the system path variable
522 QStringList foundInPath;
523 QStringList execlist;
524 QStringList pathList;
525 pathList.clear();
526 foundInPath.clear();
527 execlist.clear();
528 if (mysystem == "win") {
529 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
530 pathList = QString(qEnvironmentVariable("PATH")).split(";");
531 #else
532 pathList = QString(qgetenv("PATH")).split(";");
533 #endif
534 } else {
535 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
536 pathList = QString(qEnvironmentVariable("PATH")).split(":");
537 #else
538 pathList = QString(qgetenv("PATH")).split(":");
539 #endif
540 pathList.append("/usr/local/bin/");
541 }
542 execlist << ".bat" << ".exe" << "";
543 foreach (QString exec, execlist) {
544 foreach (QString path, pathList) {
545 QString fullpath = path+"/"+programName+exec;
546 QFileInfo fi(fullpath);
547 if (QFile::exists(fullpath) && (fi.isExecutable())){
548 foundInPath.append(QDir::cleanPath(fullpath));
549 }
550 }
551 }
552 return foundInPath;
553 }
554
555 void DSRGui::checkForDSRexecutable(QSplashScreen *splash) {
556 //! list fragments only if the path of dsr installation is found:
557 if (QFile::exists(dsrpath)) {
558 if (listDSRdbFragments("None")) {
559 outtext->append(tr("\n* Please pick a fragment first."));
560 outtext->append(tr("* Then select at least three atoms from "
561 "the main structure and the fragment respectively. (STRG+click)"));
562 outtext->append(tr("* Do not forget to apply a part number and free "
563 "variable in case of disorder."));
564 outtext->append(tr("* The fragment will be placed after FVAR in the SHELX file."));
565 }
566 } else {
567 outtext->clear();
568 outtext->append(QString(tr("Unable to find DSR executable."
569 "\nIs DSR_DIR environment variable set correctly?")));
570 outtext->append(QString(tr("Please find the most recent version of DSR at "
571 "<a href=\"https://dkratzert.de/dsr.html\">"
572 "https://dkratzert.de/dsr.html</a>")));
573 splash->finish(this);
574 }
575 }
576
577 void DSRGui::setToolTips() {
578 partspinner->setToolTip(tr("The PART of a fragment controls the binding of atoms.\n"
579 "For example two fragments in PART 1 and PART 2 do not\n"
580 "bind each other but to PART 0. Negative PARTs only bind themselves."));
581 replaceModeBox->setToolTip(tr("Toggle replacement of target atoms and all atoms of "
582 "PART 0 \nin 1.3A distance around the fitted fragment atoms."));
583 occEdit->setToolTip(tr("The occupancy of the fragment\n"));
584 fvarspinner->setToolTip(tr("The Free Variable for the fragment.\n"
585 "Free Variable and Occupancy will be combined occording to the SHELXL syntax.\n"
586 "For example, 21.0 means second free variable with occupancy of 1."));
587 invertFragBox->setToolTip(tr("Invert the fragment coordinates during fit."));
588 runExtBox->setToolTip(tr("Write restraints to external file."));
589 dfixBox->setToolTip(tr("Calculate DFIX/DANG/FLAT restraints "
590 "\naccording to fragment geometry. \n"
591 "Database restraints will be ignored."));
592 rigidBox->setToolTip(tr("Keep the fragment as rigid (AFIX 9) group. \n"
593 "Apply no restraints."));
594 residueOptionsBox->setToolTip(tr("Enables residues. Usually, you can leave the default.\n"
595 "It will always take the next free residue number."));
596 fitDSRButton->setToolTip("Run DSR to fit the fragment into the structure.");
597 exportFragButton->setToolTip("Export the current fragment to a .res file.");
598 editButton->setToolTip("Edit the current fragment or create a new one.");
599 openLastButton->setToolTip("Opens the .res file state before the last DSR fragment fit.");
600 }
601
602 QString DSRGui::textWrap(QString inText, QString indent) {
603 //! returns a SHELXL compatible wrapped string (string =\\n string) in case of over 77 characters
604 //! line length.
605 //! The default of subsequent_indent is "=\n "
606 int length = 70; // 70 should be save in any case
607 QStringList line_list;
608 QStringList wrapped;
609 QStringList inText_list = inText.split(" ");
610 for (int i=0; i<inText_list.length(); i++) {
611 QString word = inText_list.at(i);
612 QString testline = line_list.join(" ") + " ";
613 if (QString(word + testline + indent).length() >= length) {
614 if (i < inText_list.length()-2) {
615 line_list.append(word + " " + indent);
616 } else {
617 line_list.append(word);
618 }
619 wrapped.append(line_list.join(" "));
620 line_list.clear();
621 } else{
622 line_list.append(word);
623 }
624 }
625 if (!line_list.isEmpty()) {
626 wrapped.append(line_list.join(" "));
627 }
628 //qDebug() << wrapped.join(" ");
629 return wrapped.join(" ");
630 }
631
632 bool DSRGui::open_last_fileversion() {
633 //! Opens the last res file version before the last DSR action from the save history (./Shelxsaves/SAVEHIST)
634 QFileInfo fi(m_shelxle->dirName);
635 if (!fi.isReadable()) {
636 outtext->append("No last .res file found to load.");
637 return false;
638 }
639 QFile currentpath(fi.absolutePath());
640 QString saveHistFileName=QString("%1/%2saves/SAVEHIST").arg(currentpath.fileName()).arg(PROGRAM_NAME);
641 QFile savehist(saveHistFileName);
642 savehist.open(QIODevice::ReadOnly|QIODevice::Text);
643 if (!savehist.isReadable()) {
644 outtext->append("No last .res file found to load.");
645 return false;
646 }
647 QString savehist_content = savehist.readAll(); //Entry|@|2011-03-08T13:32:19|@|b11.res|@|
648 savehist.close();
649 QRegularExpression re = QRegularExpression("Entry\\|@\\|\\w+-\\w+-\\w+:\\w+:\\w+\\|@\\|[^@]+@\\|");
650 QStringList entries = savehist_content.split(re, skipEmptyParts);
651 QFile f(m_shelxle->dirName);
652 bool success = f.open(QIODevice::WriteOnly|QIODevice::Text);
653 if (success){
654 f.write(entries.last().toLatin1().replace(0, 1, ""));
655 f.close();
656 } else {
657 return false;
658 }
659 outtext->append("Successfully restored last file version.");
660 m_shelxle->loadFile(m_shelxle->dirName);
661 return true;
662 }
663
664 void DSRGui::invertFvar(){
665 //! Inverts the value of FVAR in the OptionsLayout1
666 int fvar;
667 fvar = fvarspinner->text().toInt();
668 fvarspinner->setValue(-fvar);
669 }
670
671 void DSRGui::resetSelection() {
672 //! reset the selection of source atoms
673 mygl->source_atoms.clear();
674 combineOptionstext();
675 info->hide();
676 }
677
678 void DSRGui::setInfo(QString s) {
679 //! shows an info table with bond distances
680 if (mygl->selFragAt.size()<1) {
681 info->hide();
682 }
683 else {
684 info->show();
685 info->setText(s);
686 }
687 }
688
689 void DSRGui::splitDecide(void) {
690 //! Enables the "split atoms" button if at least one atom is selected.
691 if (target_atoms.length() >= 1) {
692 splitButton->setEnabled(true);
693 }
694 }
695
696 void DSRGui::splitSelectedAtoms(void) {
697 //! Runs DSR to split the currebtly selected atoms along the principal axis of the ellipsoid.
698 QFileInfo resfip(m_shelxle->dirName);
699 QString option = " -splt ";
700 option = option + getSelectedAtomsList();
701 option = option + " -r " + resfip.completeBaseName();
702 this->runDSR(option);
703 }
704
705 void DSRGui::runEditWindow(void) {
706 //! Starts the edit window in order to edit a fragment
707 editwindow = new DSREditWindow(m_molecule, header, dsr_db_path,
708 fragmentNameTag, *fragmentsList, this);
709 editwindow->move(60, 50);
710 editwindow->show();
711 editwindow->setFocus();
712 editwindow->setMinimumWidth(800);
713 outtext->clear();
714 connect(editwindow, SIGNAL(updated(QString)),
715 this, SLOT(listDSRdbFragments(QString)));
716 }
717
718 void DSRGui::closeEvent(QCloseEvent *event) {
719 //! close event is emmited during DSRGui closing to reset its pointer
720 emit closed();
721 (void)event; // prevent compiler warning
722 }
723
724 int DSRGui::findFVARlines(QStringList *reslist) {
725 //! finds the line number of last FVAR or the first atom
726 //! I restrict the use of this plugin to stuctures with a valid
727 //! FVAR, because a missing FVAR makes it all too error prone.
728 int fvarline;
729 // I need lastIndexOf() here, because in case of
730 // several FVAR lines indexOf() would fail:
731 fvarline = reslist->lastIndexOf(QRegularExpression("^FVAR.*", QRegularExpression::CaseInsensitiveOption));
732 if (fvarline > 0) {
733 return fvarline;
734 } else {
735 return 0;
736 }
737 }
738
739 QVector<int> DSRGui::findDSRLines(QStringList *reslist) {
740 //! Find line with "rem DSR ..." in res file and return line number
741 //! if it exists.
742 QVector<int> lineNums;
743 int Num = 0;
744 foreach (QString line, *reslist) {
745 if (line.contains(QRegularExpression("^rem\\s{1,6}DSR\\s{1,6}.*", QRegularExpression::CaseInsensitiveOption))) {
746 lineNums.append(Num);
747 }
748 Num++;
749 }
750 return lineNums;
751 }
752
753 int DSRGui::decideDSRInsertLine(QStringList *reslist) {
754 //! decides where to instert the DSR command
755 int fvarline = findFVARlines(reslist);
756 if (fvarline > 0) {
757 return fvarline;
758 } else if (m_shelxle->firstAtomLine > 0) {
759 // in this case, no FVAR is present and we put the DSR command line
760 // before the first atom
761 combiDSRline = QString("FVAR 1\n") + combiDSRline; // dummy FVAR is added for DSR
762 return m_shelxle->firstAtomLine - 1;
763 } else {
764 return 0;
765 }
766 }
767
768 QStringList DSRGui::readResfile() {
769 //! read the entire res file into a stringlist
770 QFileInfo fi(m_shelxle->dirName);
771 QFile file(fi.absoluteFilePath());
772 QStringList stringList;
773 if (file.open(QFile::ReadOnly | QFile::Text)) {
774 QTextStream textStream(&file);
775 while (true) {
776 QString line = textStream.readLine();
777 if (line.isNull()) {
778 break;
779 } else {
780 stringList.append(line);
781 }
782 }
783 }
784 file.close();
785 return stringList;
786 }
787
788 QString DSRGui::findFreeResiNumber() {
789 //! returns the next free residue number in the structure
790 QSet<int> resiset;
791 QList<int> resilist;
792 int resnum = 0;
793 for (int i=0; i < m_molecule->asymm.size(); i++) {
794 MyAtom atom;
795 atom = m_molecule->asymm.at(i);
796 if (atom.resiNr >= 0) {
797 resiset.insert(atom.resiNr);
798 }
799 }
800 resilist = resiset.values();//.toList();
801 #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
802 std::sort(resilist.begin(), resilist.end());
803 #else
804 qSort(resilist);
805 #endif
806 int count = 0;
807 foreach (int num, resilist) {
808 if (num != count) {
809 // a gap in residue numbers is found, use this number:
810 resnum = count;
811 break;
812 }
813 count++;
814 }
815 // no gap found, use next number:
816 resnum = count;
817 // In this case we have no residue in the file:
818 if (resilist.isEmpty()) {
819 resnum = 1;
820 }
821 return QString("%1").arg(resnum);
822 }
823
824
825 bool DSRGui::getFragmentHeader(QString frag) {
826 //! defines Name, residue, comment and unit cell of the fragment
827 //! in DSRMol
828 /*!
829 <tag>
830 benze
831 </tag>
832 <comment>
833 Benzene2, Benzol, C6H6
834 </comment>
835 <source>
836 CCDC UGEDEQ
837 </source>
838 <cell>
839 1;;1;;1;;90;;90;;90
840 </cell>
841 <residue>
842 ERT
843 </residue>
844 <dbtype>
845 dsr_user_db
846 </dbtype>
847 <restr>
848 RIGU C1 > C6;;SADI C1 C2 C3 C4
849 </restr>
850 <atoms>
851 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
852 </atoms>
853 */
854 header->atoms.clear();
855 header->cell.clear();
856 header->comment.clear();
857 header->dbtype.clear();
858 header->residue.clear();
859 header->restr.clear();
860 header->tag.clear();
861 outtext->clear();
862 QString *rawheader = new QString;
863 QStringList *headerlist = new QStringList;
864 QString options = " -ah " + frag;
865 dsrResulttext.clear();
866 runDSR(options);
867 if (dsrResulttext.isEmpty()) {
868 outtext->clear();
869 outtext->append(tr("Unable to run DSR."));
870 editButton->setDisabled(true); // editing the empty header would crash ShelXle
871 return false;
872 } else {
873 rawheader->append(dsrResulttext);
874 }
875 // in this case no fragment list returned. Hence, we have an error.
876 if (!rawheader->contains(";;")) {
877 outtext->clear();
878 outtext->append(*rawheader);
879 //editButton->setDisabled(true); // editing the empty header would crash ShelXle
880 return false;
881 }
882 headerlist->append(rawheader->split(QRegularExpression("\n|\r\n|\r")));
883 QStringList line;
884 for (int i=0; i<headerlist->size(); i++) {
885 if (headerlist->at(i).size() == 0){
886 continue;
887 }
888 line.clear();
889 if (headerlist->at(i).trimmed().startsWith("***")) {
890 QString error;
891 error = headerlist->at(i).trimmed();
892 outtext->append("<b>"+error+"</b>");
893 }
894 if (headerlist->at(i).trimmed().startsWith("<tag>")) {
895 line = headerlist->at(i+1).trimmed().split(" ");
896 header->tag = line.join("");
897 }
898 if (headerlist->at(i).trimmed().startsWith("<comment>")) {
899 line = headerlist->at(i+1).trimmed().split(" ");
900 header->comment = line.join(" ");
901 }
902 if (headerlist->at(i).trimmed().startsWith("<source>")) {
903 line = headerlist->at(i+1).trimmed().split(" ");
904 header->source = line.join(" ");
905 }
906 if (headerlist->at(i).trimmed().startsWith("<cell>")) {
907 line = headerlist->at(i+1).simplified().split(";;");
908 foreach (QString item, line) {
909 header->cell.append(item.toDouble());
910 }
911 }
912 if (headerlist->at(i).trimmed().startsWith("<residue>")) {
913 line = headerlist->at(i+1).trimmed().split(" ");
914 header->residue = line.join("");
915 resiclass = header->residue;
916 resiclassEdit->setText(resiclass);
917 }
918 if (headerlist->at(i).trimmed().startsWith("<dbtype>")) {
919 line = headerlist->at(i+1).trimmed().split(" ");
920 header->dbtype = line.join("");
921 }
922 if (headerlist->at(i).trimmed().startsWith("<restr>")) {
923 line = headerlist->at(i+1).simplified().split(";;");
924 foreach (QString item, line) {
925 header->restr.append(item);
926 }
927 }
928 if (headerlist->at(i).trimmed().contains("<atoms>")) {
929 line = headerlist->at(i+1).simplified().split(";;");
930 foreach (QString item, line) {
931 header->atoms.append(item.split(" "));
932 }
933 }
934 }
935 editButton->setEnabled(true);
936 return true;
937 }
938
939
940 int DSRGui::getCharWidth(int numchars) {
941 //! returns the width in pixel of numchars times the # character
942 QString buchstaben;
943 buchstaben.clear();
944 for (int i=1; i<=numchars; i++) {
945 buchstaben += "#";
946 }
947 #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
948 return QFontMetrics(this->font()).horizontalAdvance(buchstaben);
949 #else
950 return QFontMetrics(this->font()).width(buchstaben);
951 #endif
952 }
953
954
955 void DSRGui::activateFitButton(void) {
956 fitDSRButton->setEnabled(true);
957 exportFragButton->setEnabled(true);
958 }
959
960
961 void DSRGui::combineOptionstext(void) {
962 //! combines all options to a single DSR command line
963 //! This method gets invoked if optionTextChanged signal is emmitted
964 combiDSRline.clear();
965 // Displays error messages from DSR:
966 if (!outtext->toPlainText().contains("***")) {
967 outtext->clear();
968 } //else {
969 //return;
970 //}
971 QString split = "";
972 // CF3 groups are dummy entries in the DSR database. They get calculated
973 // on ideal positions at the respective carbon atom:
974 if (fragmentNameTag == QString("cf6")) {
975 splitModeBox->show();
976 } else {
977 splitModeBox->hide();
978 }
979 if ( (fragmentNameTag == QString("cf3")) ||
980 (fragmentNameTag == QString("cf6")) ||
981 (fragmentNameTag == QString("cf9")) ) {
982 this->cf3 = true;
983 rigidBox->setDisabled(true);
984 invertFragBox->setDisabled(true);
985 runExtBox->setDisabled(true);
986 replaceModeBox->setDisabled(true);
987 residueOptionsBox->setDisabled(true);
988 if (splitModeBox->isChecked() ) {
989 split = "SPLIT";
990 }
991 } else {
992 splitModeBox->hide();
993 this->cf3 = false;
994 rigidBox->setDisabled(false);
995 invertFragBox->setDisabled(false);
996 runExtBox->setDisabled(false);
997 replaceModeBox->setDisabled(false);
998 residueOptionsBox->setDisabled(false);
999 }
1000 target_atoms = getSelectedAtomsList();
1001 QString putreplace = QString("PUT ");
1002 if (replace) {
1003 putreplace = QString("REPLACE ");
1004 }
1005 if (!cf3) {
1006 if (target_atoms.split(" ").length() != 3) {
1007 target_atoms = "<font color=red> Please select 3 target atoms/q-peaks! </font>";
1008 }
1009 if (mygl->source_atoms.split(" ").length() != 3){
1010 mygl->source_atoms = "<font color=red> Please select 3 fragment atoms! </font>";
1011 }
1012 } else {
1013 if (target_atoms.split(" ").length() != 1) {
1014 target_atoms = "<font color=red> Please select only <b>a single</b> carbon atom! </font>";
1015 }
1016 mygl->source_atoms = "";
1017 }
1018 QString resistr = "RESI ";
1019 if (!residueOptionsBox->isChecked() || !residueOptionsBox->isEnabled()) {
1020 resistr = "";
1021 resiTextLabel->setText("");
1022 } else {
1023 resiTextLabel->setText(*resnumbertext);
1024 if (resiclassEdit->text() == resiclass) {
1025 resistr = "RESI "+resiclass;
1026 } else {
1027 resistr = "RESI "+resiclassEdit->text();
1028 }
1029 }
1030 QString with;
1031 if (cf3) {
1032 with = QString(" ");
1033 } else {
1034 with = QString(" WITH ");
1035 }
1036 QString outstring = QString(QString("REM DSR ")+putreplace+fragmentNameTag+" "+
1037 with+mygl->source_atoms+" "+QString("ON ")+
1038 target_atoms+" "+part+" "+fvarocc+" "+dfix+" "+resistr+split);
1039 combiDSRline = outstring.simplified().toUpper();
1040 outtext->append(combiDSRline);
1041
1042 mygl->selchanged = true;
1043 //printf("combineOptionstext\n");
1044 }
1045
1046
1047 void DSRGui::setResiClass(QString rclass) {
1048 //! defines the residue class
1049 if (rclass[0].isLetter()){
1050 if (rclass.length() > 4) {
1051 resiclassEdit->setText(QString(rclass.mid(0, 4)));
1052 }
1053 emit optionTextChanged();
1054 } else {
1055 outtext->append(QString(tr("Please start residue "
1056 "class with a letter.")));
1057 resiclassEdit->clear();
1058 }
1059 }
1060
1061 void DSRGui::setFragName(QModelIndex name) {
1062 //! set the fragment name variable
1063 //outtext->clear();
1064 fragmentNameTag = name.sibling(name.row(), 0).data().toString();
1065 writeFavorites(fragmentNameTag);
1066 //outtext->clear();
1067 if (!getFragmentHeader(fragmentNameTag)) {
1068 // In this case, the most important thing is missing
1069 return;
1070 }
1071 if (header->comment.isEmpty()){
1072 outtext->append("You should give this fragment a name.");
1073 }
1074 if (header->atoms.isEmpty()){
1075 return;
1076 }
1077 if (header->tag.isEmpty()){
1078 return;
1079 }
1080 if (header->restr.isEmpty()){
1081 return;
1082 }
1083 if (header->cell.isEmpty()){
1084 return;
1085 }
1086 //emit optionTextChanged();
1087 emit fragmentSelected();
1088 emit currentFragmentChanged(*header);
1089 }
1090
1091
1092 void DSRGui::DFIX(bool checked) {
1093 //! toggles the dfix option
1094 outtext->clear();
1095 if (checked)
1096 {
1097 this->dfix = QString("DFIX");
1098 } else
1099 {
1100 this->dfix.clear();
1101 }
1102 emit optionTextChanged();
1103 }
1104
1105 void DSRGui::setFvarOcc(void) {
1106 //! defines the FVAR and occupancy option
1107 outtext->clear();
1108 int fvar = 0;
1109 double occ = 0;
1110 double focc = 0;
1111 fvar = fvarspinner->value();
1112 occ = (occEdit->text().replace(',', '.').toDouble());
1113 if (fvar < 0) {
1114 focc = -(abs(fvar) * 10 + occ);
1115 } else {
1116 focc = fvar * 10 + occ;
1117 }
1118 fvarocc = QString("OCC ")+QString::number(focc);
1119 emit optionTextChanged();
1120 outtext->append("\nFVAR num -> times used");
1121 foreach (int fvar, m_shelxle->fvarCntr.keys()) {
1122 if (fvar < 2) continue;
1123 outtext->append(QString("FVAR %1 -> %2 ").arg(fvar, 3).arg(m_shelxle->fvarCntr.value(fvar), 3));
1124 }
1125 }
1126
1127 void DSRGui::setPART(int partnum) {
1128 //! defines the PART option
1129 outtext->clear();
1130 if (partnum == 0)
1131 {
1132 part.clear();
1133 }
1134 else
1135 {
1136 QString s = QString::number(partnum);
1137 part = QString("PART ")+s ;
1138 }
1139 emit optionTextChanged();
1140 }
1141
1142 void DSRGui::fitDSRExtern(bool checked) {
1143 //! enable write restraints to external file
1144 if (checked) {
1145 this->runext = true;
1146 } else {
1147 this->runext = false;
1148 }
1149 }
1150
1151 void DSRGui::invertFrag(bool checked) {
1152 //! Inverts the fragment coordinates.
1153 //! They are also inverted in the 3D view.
1154 // Invert coordinates in DSR:
1155 if (checked){
1156 this->invert = true;
1157 } else {
1158 this->invert = false;
1159 }
1160 /*
1161 V3 v1 = V3(-1, 0, 0);
1162 V3 v2 = V3( 0, -1, 0);
1163 V3 v3 = V3( 0, 0, 1);
1164 //rotation matrix to rotate the selection 180deg.
1165 // for less disturbance of the inverted view:
1166 // ch: WHY??
1167
1168 Matrix rmat = Matrix(v1, v2, v3);*/
1169 // Invert the OpenGL coordinates:
1170 double coord;
1171 int index;
1172 index = 0;
1173 foreach(QStringList line, header->atoms) {
1174 for (int n = 2; n<5; n++) {
1175 coord = line[n].toDouble();
1176 // rotate fragment 180 deg. if ((n == 2) || (n == 3)) { coord = coord * -1; }
1177 header->atoms[index][n] = QString("%1").arg(-coord);
1178 }
1179 index = index+1;
1180 }
1181 //Also invert the selection of the atoms:
1182 for (int n=0; n<mygl->selFragAt.size(); n++) {
1183 //this line is essential: mygl->selFragAt[n].pos = mygl->selFragAt[n].pos * rmat;
1184 mygl->selFragAt[n].pos *= -1.0;
1185 }
1186 mygl->display_fragment(*header, false);
1187 combineOptionstext();
1188 mygl->makeInfo();
1189 mygl->update();
1190 }
1191
1192 void DSRGui::rigid_group(bool checked)
1193 //! toggle rigid group refinenement
1194 {
1195 if (checked) {
1196 this->rigid = true;
1197 } else {
1198 this->rigid = false;
1199 }
1200 }
1201
1202 bool DSRGui::exportFrag(QString dirname) {
1203 //! export the current fragment to a res file+png
1204 //! change to the current dir here, because dsr exports in current dir:
1205 QDir::setCurrent(dirname);
1206 outtext->clear();
1207 if (fragmentNameTag.isEmpty()) {
1208 outtext->append("No fragment chosen. Doing nothing!");
1209 return false;
1210 }
1211 //outtext->clear();
1212 QString options = QString(" -e ") + fragmentNameTag;
1213 dsrResulttext.clear();
1214 runDSR(options, true, dirname);
1215 if (dsrResulttext.isEmpty()) {
1216 outtext->append("Unable to start DSR.");
1217 return false;
1218 }
1219 return true;
1220 }
1221
1222 void DSRGui::refineOrNot(bool checked) {
1223 //! enable or disable refinement after transfer
1224 if (checked) {
1225 this->norefine = true;
1226 } else {
1227 this->norefine = false;
1228 }
1229 }
1230
1231 void DSRGui::replaceOrNot(bool checked) {
1232 //! enable or disable replace mode
1233 outtext->clear();
1234 if (checked) {
1235 this->replace = true;
1236 } else {
1237 this->replace = false;
1238 }
1239 emit optionTextChanged();
1240 }
1241
1242 QString DSRGui::getSelectedAtomsList() {
1243 //! returns the Names of the currently selected atoms of the structure
1244 //! loaded in ShelXle as StringList
1245 QStringList atoms;
1246 atoms.clear();
1247 for (int i=0; i<m_molecule->selectedatoms.size(); i++) {
1248 atoms.append(QString(m_molecule->selectedatoms.at(i).Label.toLatin1()).replace(QChar(187), ">>"));
1249 }
1250 return atoms.join(" ");
1251 }
1252
1253 QString DSRGui::getSelectedAtomsCoords() {
1254 //! returns the atoms coordinates that are selected inside shelxle as a string
1255 QString atoms = "";
1256 QString line = "";
1257 for (int i = 0; i < m_molecule->selectedatoms.size(); ++i) {
1258 line = QString(" %1 %2 %3").arg(m_molecule->selectedatoms.at(i).frac.x, 10, 'f', 5)
1259 .arg(m_molecule->selectedatoms.at(i).frac.y, 10, 'f', 5)
1260 .arg(m_molecule->selectedatoms.at(i).frac.z, 10, 'f', 5);
1261 atoms.append(line);
1262 }
1263 return atoms;
1264 }
1265
1266 bool DSRGui::fitDSR() {
1267 /*!
1268 runs DSR from command line
1269
1270 bool QDir::setCurrent(const QString & path)
1271 QString QFileInfo::completeBaseName() const : "c:/programme/dsr/p21c.res -> p21c.res
1272 QString QFileInfo::absolutePath() const : c:/programme/dsr/p21c.res -> c:/programme/dsr/
1273 QString QFileInfo::absoluteFilePath() const : c:/programme/dsr/p21c.res -> c:/programme/dsr/p21c.res
1274 QFileInfo fi("c:/temp/foo"); => fi.absoluteFilePath()
1275 */
1276 QString atoms = getSelectedAtomsCoords();
1277 if (!cf3) {
1278 if (m_molecule->selectedatoms.size() != 3) {
1279 emit optionTextChanged();
1280 //return false;
1281 }
1282 if (mygl->source_atoms.split(" ").length() != 3) {
1283 emit optionTextChanged();
1284 outtext->append("<font color=red> \nPlease select three "
1285 "atoms of the fragment! </font>");
1286 return false;
1287 }
1288 }
1289 info->hide(); // Even if the fit does not work, I want to hide it to better see the output
1290 QString option;
1291 QString source_atoms_tmp = mygl->source_atoms;
1292 if ((m_molecule->selectedatoms.size() != 3) && !cf3) {
1293 //outtext->clear();
1294 outtext->append("<font color=red> Please select at least three "
1295 "atoms or Q-peaks as target in your structure! </font>");
1296 return false;
1297 }
1298 if ((m_molecule->selectedatoms.size() != 1) && cf3) {
1299 outtext->clear();
1300 outtext->append("<font color=red> Please select one carbon"
1301 "atom as target in your structure! </font>");
1302 return false;
1303 }
1304 target_atoms = getSelectedAtomsList();
1305 bool ok;
1306 int dsrv = dsrVersion.toInt(&ok, 10);
1307 if (ok && dsrv < 200) {
1308 // This is obsolete with DSR >= 200 since we fit the fragment to
1309 // the actual coordinates and not to "names":
1310 if ( target_atoms.contains(QString(">>"))) {
1311 outtext->clear();
1312 outtext->append(QString("<font color=red><b>Symmetrie generated atoms not allowed as target! <br><br>"
1313 "Please update DSR.</b></font>"));
1314 return false;
1315 }
1316 }
1317 emit optionTextChanged();
1318 bool save_sucess = m_shelxle->fileSave(true, false);
1319 if (!save_sucess) {
1320 outtext->append("Could not save the instruction file!");
1321 return false;
1322 }
1323 QStringList *reslist = new QStringList;
1324 reslist->append(readResfile());
1325 mygl->source_atoms = source_atoms_tmp;
1326 int DSRposition = decideDSRInsertLine(reslist);
1327 if (DSRposition == 0){
1328 outtext->append("Could not fit fragment. No FVAR command found. \nPlease refine at least one cycle.");
1329 return false;
1330 }
1331 QVector<int> previousLines = findDSRLines(reslist);
1332 QString wrappedDSRLine = textWrap(combiDSRline);
1333 m_shelxle->insertDSRLine(wrappedDSRLine, DSRposition, previousLines);
1334 delete reslist;
1335 if (rigid) {
1336 option = "-g ";
1337 } else {
1338 option = "";
1339 }
1340 if (norefine){
1341 option += " -n ";
1342 }
1343 if (!runext && !invert) // the standard run without extra options
1344 {
1345 option += " -r ";
1346 }
1347 else if (runext && !invert) {
1348 option += " -re ";
1349 }
1350 else if (!runext && invert)
1351 {
1352 option += " -t -r ";
1353 }
1354 else if (runext && invert) {
1355 option += " -t -re ";
1356 } else {
1357 qDebug() << "Unhandeled option case in DSRGui occoured!!";
1358 return false;
1359 }
1360 if (!m_shelxlPath.isEmpty() && (dsrVersion.toInt() > 182)) {
1361 option = " -shx " + m_shelxlPath + " " + option;
1362 }
1363 if ((dsrVersion.toInt() >= 200)) {
1364 option = " -target " + atoms + " " + option;
1365 }
1366 QFileInfo resfip(m_shelxle->dirName);
1367 option = option + resfip.completeBaseName();
1368 QFileInfo check_res(resfip.completeBaseName()+".res");
1369 if ( resfip.completeSuffix() == "ins" && check_res.size() == 0) {
1370 outtext->clear();
1371 outtext->append("Warning! Something went wrong with your .res file.\n"
1372 "You are currently working on the .ins file. Please restore "
1373 "the .res file before you continue.");
1374 return false;
1375 }
1376 bool dsr = this->runDSR(option);
1377 if (!dsr) {
1378 return false;
1379 }
1380 m_shelxle->loadAFile();
1381 this->show();
1382 this->raise();
1383 this->activateWindow();
1384 return true;
1385 }
1386
1387 void DSRGui::updateDSR(void) {
1388 //!
1389 //! Updates DSR to the current version on the web server
1390 //!
1391 QString option = " -u";
1392 outtext->append("Update running...");
1393 this->runDSR(option);
1394 }
1395
1396 bool DSRGui::runDSR(QString option, bool showresults, QString workdir) {
1397 //! runs DSR with options and shows the results in outtext if desired.
1398 dsrResulttext.clear();
1399 outtext->clear();
1400 QProcess dsr;
1401 QFileInfo resfip;
1402 if (workdir.isEmpty()) {
1403 // workdir can be the export (fragment) directory for example.
1404 resfip.setFile(m_shelxle->dirName);
1405 if (resfip.exists()) {
1406 // Need to check if path is not empty, because en empty path would cause dsr.start() to fail.
1407 // absolutePath() truncates the last path part even though its C:\foo\bar --> C:\foo
1408 dsr.setWorkingDirectory(resfip.absolutePath());
1409 }
1410 } else {
1411 resfip.setFile(workdir);
1412 dsr.setWorkingDirectory(resfip.absoluteFilePath());
1413 }
1414 dsr.setProcessChannelMode(QProcess::MergedChannels);
1415 dsr.closeWriteChannel();
1416 // Do not use this with fragment export:
1417 if (!resfip.absolutePath().isEmpty() && workdir.isEmpty()) {
1418 // Need to do this, because en empty path would cause dsr.start() to fail.
1419 dsr.setWorkingDirectory(resfip.absolutePath());
1420 }
1421 dsr.start(dsrpath, option.split(" ", skipEmptyParts));
1422 if (!dsr.waitForFinished()) {
1423 outtext->append("Unable to start DSR.");
1424 outtext->append(dsrpath + " " + option);
1425 outtext->append(dsr.readAll());
1426 return false;
1427 } else {
1428 dsrResulttext.append(dsr.readAll());
1429 //qDebug() << dsrResulttext;
1430 }
1431 /*
1432 if (dsrResulttext.isEmpty()) {
1433 bool socket = runTCPServer();
1434 if (!socket) {
1435 outtext->append("Unable read DSR output.");
1436 }
1437 } */
1438 if (showresults) {
1439 // Display the results:
1440 //outtext->clear();
1441 outtext->append(combiDSRline);
1442 outtext->append(dsrResulttext);
1443 }
1444 this->show();
1445 this->raise();
1446 this->activateWindow();
1447 //qDebug() << dsrResulttext;
1448 return true;
1449 }
1450
1451 void DSRGui::searchFragment(QString searchName) {
1452 //! Searches for fragments in the database
1453 if ((searchName.length() < 2) && (searchName.length() > 0)){
1454 return;
1455 }
1456 // If search length is zero, restore full list:
1457 if (searchName.length() == 0){
1458 if (!listDSRdbFragments("None")) {
1459 outtext->append("Unable to find DSR fragment database.");
1460 return;
1461 }
1462 return;
1463 }
1464 QString option = QString(" -x ") + searchName;
1465 dsrResulttext.clear();
1466 this->runDSR(option, false);
1467 QVector<QStringList> fraglist;
1468 fraglist.clear();
1469 foreach (QString line, dsrResulttext.split(QRegularExpression("\n|\r\n|\r"))) {
1470 if (line.isEmpty()){
1471 continue;
1472 }
1473 if (line.contains(";;")) {
1474 fraglist.append(line.split(";;"));
1475 }
1476 }
1477 if (fraglist.size() > 0) {
1478 displayFragmentsList(fraglist, fraglist.at(0).at(0).toLatin1().toUpper());
1479 } else {
1480 displayFragmentsList(fraglist, "None");
1481 }
1482 }
1483
1484 bool DSRGui::isDSRVersionCorrect(QString version) {
1485 //! checks if the version of DSR found in DSR_DIR
1486 //! is compatible with this GUI
1487 bool ok;
1488 ok = false;
1489 if (version.trimmed().toInt() >= 182) {
1490 ok = true;
1491 }
1492 return ok;
1493 }
1494
1495 bool DSRGui::listDSRdbFragments(QString fav="None") {
1496 //! list fragments in DSR database
1497 //! The -lc parameter of DSR returns a semicolon (;;) separated list
1498 //! tag;;fullname;;line number;;db
1499 if (QString("None") == fav) {
1500 fav = loadFavoriteFragment().toLatin1().toUpper();
1501 }
1502 fragmentsList->clear();
1503 fragmentNameTag.clear();
1504 QString options = " -lc";
1505 runDSR(options, true);
1506 QStringList frag_str_list = dsrResulttext.split(QRegularExpression("\n|\r\n|\r"));
1507 bool versionOk = false;
1508 foreach (QString line, frag_str_list) {
1509 if (line.contains("Duplicate database entry")) {
1510 outtext->clear();
1511 outtext->append(dsrResulttext);
1512 return false;
1513 }
1514 }
1515 // in this case no fragment list returned. Hence, we have an error.
1516 if (!dsrResulttext.contains(";;")) {
1517 //outtext->clear();
1518 outtext->append("Something went wrong with DSR. please tell Daniel Kratzert ([email protected]) about this problem.");
1519 outtext->append(dsrResulttext);
1520 return false;
1521 }
1522 foreach (QString line, frag_str_list) {
1523 if (line.isEmpty()){
1524 continue;
1525 }
1526 if ( (line.split(":").size() >= 1) && line.contains("DSR version:")) {
1527 dsrVersion = line.split(":").at(1).trimmed();
1528 }
1529 if (line.trimmed().contains("DSR version:")) {
1530 versionOk = isDSRVersionCorrect(dsrVersion);
1531 continue;
1532 }
1533 if (line.trimmed().startsWith("***")) {
1534 outtext->append(line);
1535 continue;
1536 }
1537 if (line.contains(";;")) {
1538 // collect frags to global list here:
1539 fragmentsList->append(line.split(";;")); // the global list of all fragments
1540 }
1541 }
1542 if (!versionOk) {
1543 outtext->clear();
1544 outtext->append(QString(tr("Detected an old version of DSR.")));
1545 outtext->append(QString(tr("Please get the most recent version from https://dkratzert.de/dsr.html")));
1546 return false;
1547 }
1548 displayFragmentsList(*fragmentsList, fav);
1549 return true;
1550 }
1551
1552
1553 void DSRGui::displayFragmentsList(QVector<QStringList> list, QString fav="None") {
1554 //! displays the list of fragments in a table view
1555 //! The first column (the tag) is hidden, only the name is displayed.
1556 QStandardItem *fraglabel = new QStandardItem(QString("Fragment Name"));
1557 fraglabel->setTextAlignment(Qt::AlignLeft);
1558 QStandardItemModel *FragListmodel = new QStandardItemModel(list.size(), 2, this); //x Rows and 2 Columns
1559 FragListmodel->setHorizontalHeaderItem(0, new QStandardItem(QString("tag")));
1560 FragListmodel->setHorizontalHeaderItem(1, fraglabel);
1561 QStringList line;
1562 for (int i = 0; i < list.size(); ++i) {
1563 line.clear();
1564 line = list[i];
1565 if ( line.size() < 3 ) {
1566 continue;
1567 }
1568 QString column1 = line[0];
1569 QString column2 = line[1];
1570 QStandardItem *nameItem;
1571 // Add a bold *user* to all fragments from the user db
1572 if (line[3].contains("dsr_user_db")) {
1573 column2.append(" *user*");
1574 nameItem = new QStandardItem(QString(column2));
1575 QFont f = nameItem->font();
1576 f.setBold(true);
1577 nameItem->setFont(f);
1578 } else {
1579 nameItem = new QStandardItem(QString(column2));
1580 }
1581 FragListmodel->setItem(i, 0, new QStandardItem(QString(column1)));
1582 FragListmodel->setItem(i, 1, nameItem);
1583 // load the last fragment:
1584 if (fav == line.at(0).toLatin1().toUpper()) {
1585 if (FragListmodel->hasIndex(i, 0)) {
1586 setFragName(FragListmodel->index(i, 0));
1587 }
1588 }
1589 }
1590 fragmentTableView->setModel(FragListmodel);
1591 fragmentTableView->verticalHeader()->hide();
1592 fragmentTableView->hideColumn(0);
1593 fragmentTableView->setColumnWidth(1, 600);
1594 fragmentTableView->setGridStyle(Qt::PenStyle(Qt::NoPen));
1595 fragmentTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
1596 }
1597
1598 QString DSRGui::getDSRDir() {
1599 //! returns the value of the DSR_DIR variable
1600 //! in case of error, it returns an empty string
1601 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1602 QString dsrdir = qEnvironmentVariable("DSR_DIR");
1603 #else
1604 QString dsrdir = qgetenv("DSR_DIR");
1605 #endif
1606 if (!QFile::exists(dsrdir)){
1607 if (!which("dsr").isEmpty()) {
1608 QFileInfo fi(which("dsr").at(0));
1609 if (fi.exists()) {
1610 dsrdir = fi.absolutePath();
1611 }
1612 }
1613 if (QFile::exists("/Applications/DSR")) {
1614 dsrdir = "/Applications/DSR";
1615 }
1616 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1617 QString dsrdir2 = qEnvironmentVariable("DSRDIR");
1618 #else
1619 QString dsrdir2 = qgetenv("DSRDIR");
1620 #endif
1621 if (QFile::exists(dsrdir2)) {
1622 qDebug() << "You are probably using an older version of DSR."
1623 "\n Please use version 1.7.7 or above.";
1624 // return empty string, because dsr.bat will
1625 // hinder dsr from starting properly:
1626 return QString("");
1627 }
1628 }
1629 return QDir::fromNativeSeparators(dsrdir);
1630 }
1631
1632 QString DSRGui::getDSRdbDir() {
1633 //! returns the directory with the userdb -> the home directory
1634 QString dbdir = QDir::homePath();
1635 return QDir::fromNativeSeparators(dbdir);;
1636 }
1637
1638
1639 void DSRGui::setExportDirDialog() {
1640 //! File dialog to define the directory for the res file
1641 //! exported by DSR
1642 export_dir = "";
1643 export_dir = QFileDialog::getExistingDirectory(this, tr("Export Fragment to ..."), tr("Directory"));
1644 if (QFile::exists(export_dir)){
1645 emit exportDirChanged(export_dir);
1646 }
1647 }
1648
1649