Debian Codegraph @

avogadro/qtplugins/propertytables/propertyview.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "propertyview.h"
7 #include "core/avogadrocore.h"
8
9 #include <avogadro/core/residue.h>
10 #include <avogadro/qtgui/molecule.h>
11
12 #include <QAction>
13 #include <QApplication>
14 #include <QtCore/QAbstractTableModel>
15 #include <QtCore/QDir>
16 #include <QtCore/QIODevice>
17 #include <QtCore/QSortFilterProxyModel>
18 #include <QtCore/QString>
19 #include <QtCore/QTextStream>
20 #include <QtGui/QClipboard>
21 #include <QtGui/QContextMenuEvent>
22 #include <QtGui/QKeyEvent>
23 #include <QtWidgets/QMenu>
24
25 #include <QtWidgets/QDialog>
26 #include <QtWidgets/QFileDialog>
27 #include <QtWidgets/QHeaderView>
28 #include <QtWidgets/QInputDialog>
29 #include <QtWidgets/QMessageBox>
30 #include <QtWidgets/QScrollBar>
31 #include <QtWidgets/QSizePolicy>
32 #include <QtWidgets/QVBoxLayout>
33
34 #include <QtCore/QDebug>
35
36 namespace Avogadro {
37
38 using QtGui::Molecule;
39
40 PropertyView::PropertyView(PropertyType type, QWidget* parent)
41 : QTableView(parent), m_type(type), m_molecule(nullptr), m_model(nullptr)
42 {
43 QString title;
44 switch (type) {
45 case AtomType:
46 title = tr("Atom Properties");
47 break;
48 case BondType:
49 title = tr("Bond Properties");
50 break;
51 case AngleType:
52 title = tr("Angle Properties");
53 break;
54 case TorsionType:
55 title = tr("Torsion Properties");
56 break;
57 case ConformerType:
58 title = tr("Conformer Properties");
59 break;
60 case ResidueType:
61 title = tr("Residue Properties");
62 break;
63 default:
64 title = tr("Molecule Properties");
65 break;
66 }
67 this->setWindowTitle(title);
68
69 QHeaderView* horizontal = this->horizontalHeader();
70 horizontal->setSectionResizeMode(QHeaderView::Interactive);
71 horizontal->setMinimumSectionSize(75);
72 QHeaderView* vertical = this->verticalHeader();
73 vertical->setSectionResizeMode(QHeaderView::Interactive);
74 vertical->setMinimumSectionSize(30);
75 vertical->setDefaultAlignment(Qt::AlignCenter);
76
77 setCornerButtonEnabled(true);
78 setSelectionBehavior(QAbstractItemView::SelectRows);
79 setSelectionMode(QAbstractItemView::SingleSelection);
80 // Alternating row colors
81 setAlternatingRowColors(true);
82 // Allow sorting the table
83 setSortingEnabled(true);
84 }
85
86 void PropertyView::selectionChanged(const QItemSelection& selected,
87 const QItemSelection& deselected)
88 {
89 // Guard against re-entrancy: modifying molecule selection triggers
90 // model updates which can cause recursive calls to selectionChanged
91 if (m_updatingSelection)
92 return;
93
94 bool ok = false;
95 if (m_molecule == nullptr)
96 return;
97
98 m_updatingSelection = true;
99
100 // Start by clearing the molecule selection
101 for (Index i = 0; i < m_molecule->atomCount(); ++i)
102 m_molecule->undoMolecule()->setAtomSelected(i, false);
103
104 foreach (const QModelIndex& index, selected.indexes()) {
105 if (!index.isValid()) {
106 m_updatingSelection = false;
107 return;
108 }
109
110 // Since the user can sort
111 // we need to find the original index
112 int rowNum = model()
113 ->headerData(index.row(), Qt::Vertical)
114 .toString()
115 .split(" ")
116 .last()
117 .toLong(&ok) -
118 1;
119 if (!ok) {
120 m_updatingSelection = false;
121 return;
122 }
123
124 if (m_type == PropertyType::AtomType) {
125 if (static_cast<Index>(rowNum) >= m_molecule->atomCount()) {
126 m_updatingSelection = false;
127 return;
128 }
129
130 m_molecule->setAtomSelected(rowNum, true);
131 } else if (m_type == PropertyType::BondType) {
132 if (static_cast<Index>(rowNum) >= m_molecule->bondCount()) {
133 m_updatingSelection = false;
134 return;
135 }
136
137 auto bondPair = m_molecule->bondPair(rowNum);
138 m_molecule->undoMolecule()->setAtomSelected(bondPair.first, true);
139 m_molecule->undoMolecule()->setAtomSelected(bondPair.second, true);
140 } else if (m_type == PropertyType::AngleType) {
141
142 if (m_model != nullptr) {
143 auto angle = m_model->getAngle(rowNum);
144 m_molecule->undoMolecule()->setAtomSelected(std::get<0>(angle), true);
145 m_molecule->undoMolecule()->setAtomSelected(std::get<1>(angle), true);
146 m_molecule->undoMolecule()->setAtomSelected(std::get<2>(angle), true);
147 }
148 } else if (m_type == PropertyType::TorsionType) {
149
150 if (m_model != nullptr) {
151 auto torsion = m_model->getTorsion(rowNum);
152 m_molecule->undoMolecule()->setAtomSelected(std::get<0>(torsion), true);
153 m_molecule->undoMolecule()->setAtomSelected(std::get<1>(torsion), true);
154 m_molecule->undoMolecule()->setAtomSelected(std::get<2>(torsion), true);
155 m_molecule->undoMolecule()->setAtomSelected(std::get<3>(torsion), true);
156 }
157 } else if (m_type == PropertyType::ResidueType) {
158 // select all the atoms in the residue
159 if (m_model != nullptr) {
160 const auto residue = m_molecule->residue(rowNum);
161 auto atoms = residue.residueAtoms();
162 for (Index i = 0; i < atoms.size(); ++i) {
163 const auto atom = atoms[i];
164 m_molecule->undoMolecule()->setAtomSelected(atom.index(), true);
165 }
166 }
167 } else if (m_type == PropertyType::ConformerType) {
168 // selecting a row means switching to that conformer
169 m_molecule->setCoordinate3d(rowNum);
170 }
171 } // end loop through selected
172
173 m_molecule->emitChanged(Molecule::Atoms);
174 m_updatingSelection = false;
175 QTableView::selectionChanged(selected, deselected);
176 }
177
178 void PropertyView::setMolecule(Molecule* molecule)
179 {
180 m_molecule = molecule;
181 }
182
183 void PropertyView::hideEvent(QHideEvent*)
184 {
185 if (model()) {
186 model()->deleteLater();
187 }
188
189 this->deleteLater();
190 }
191
192 void PropertyView::keyPressEvent(QKeyEvent* event)
193 {
194 // handle copy event
195 // thanks to https://www.walletfox.com/course/qtableviewcopypaste.php
196 if (!event->matches(QKeySequence::Copy)) {
197 QTableView::keyPressEvent(event);
198 return;
199 }
200
201 // get the selected rows (if any)
202 QModelIndexList selectedRows = selectionModel()->selectedRows();
203
204 // if nothing is selected, copy everything to the clipboard
205 QString text;
206 if (selectedRows.isEmpty()) {
207 // iterate through every row and column and copy the data
208 for (int i = 0; i < model()->rowCount(); ++i) {
209 QStringList rowContents;
210 for (int j = 0; j < model()->columnCount(); ++j)
211 rowContents << model()->index(i, j).data().toString();
212 text += rowContents.join("\t");
213 text += "\n";
214 }
215 } else {
216 // copy the selected rows to the clipboard
217 QItemSelectionRange range = selectionModel()->selection().first();
218 for (auto i = range.top(); i <= range.bottom(); ++i) {
219 QStringList rowContents;
220 for (auto j = range.left(); j <= range.right(); ++j)
221 rowContents << model()->index(i, j).data().toString();
222 text += rowContents.join("\t");
223 text += "\n";
224 }
225 }
226 QApplication::clipboard()->setText(text);
227 }
228
229 bool PropertyView::edit(const QModelIndex& index, EditTrigger trigger,
230 QEvent* event)
231 {
232 if (m_model != nullptr && m_model->isColorIndex(index)) {
233 if (m_inColorEdit)
234 return true;
235 m_inColorEdit = true;
236 m_model->setData(index, QVariant(), Qt::EditRole);
237 m_inColorEdit = false;
238 return true;
239 }
240
241 return QTableView::edit(index, trigger, event);
242 }
243
244 void PropertyView::copySelectedRowsToClipboard()
245 {
246 // get the selected rows (if any)
247 QModelIndexList selectedRows = selectionModel()->selectedRows();
248
249 // if nothing is selected, copy everything to the clipboard
250 QString text;
251 if (selectedRows.isEmpty()) {
252 // iterate through every row and column and copy the data
253 for (int i = 0; i < model()->rowCount(); ++i) {
254 QStringList rowContents;
255 for (int j = 0; j < model()->columnCount(); ++j)
256 rowContents << model()->index(i, j).data().toString();
257 text += rowContents.join("\t");
258 text += "\n";
259 }
260 } else {
261 // copy the selected rows to the clipboard
262 QItemSelectionRange range = selectionModel()->selection().first();
263 for (auto i = range.top(); i <= range.bottom(); ++i) {
264 QStringList rowContents;
265 for (auto j = range.left(); j <= range.right(); ++j)
266 rowContents << model()->index(i, j).data().toString();
267 text += rowContents.join("\t");
268 text += "\n";
269 }
270 }
271 QApplication::clipboard()->setText(text);
272 }
273
274 void PropertyView::constrainSelectedRows()
275 {
276 // get the selected rows (if any)
277 QModelIndexList selectedRows = selectionModel()->selectedRows();
278
279 // if nothing is selected, we're done
280 if (selectedRows.isEmpty())
281 return;
282
283 if (m_molecule == nullptr)
284 return;
285
286 // loop through the selected rows
287 for (const auto& index : selectedRows) {
288 if (!index.isValid())
289 continue;
290
291 // get the row number
292 bool ok;
293 int rowNum = model()
294 ->headerData(index.row(), Qt::Vertical)
295 .toString()
296 .split(" ")
297 .last()
298 .toLong(&ok) -
299 1;
300 if (!ok)
301 continue;
302
303 if (m_type == PropertyType::BondType) {
304 // get the start and end atoms and the distance from the table data
305 auto bond = m_molecule->bond(rowNum);
306 auto atom1 = bond.atom1();
307 auto atom2 = bond.atom2();
308 Real distance = bond.length();
309 m_molecule->addConstraint(distance, atom1.index(), atom2.index());
310 } else if (m_type == PropertyType::AngleType) {
311 if (m_model != nullptr) {
312 auto angle = m_model->getAngle(rowNum);
313 auto atom1 = m_molecule->atom(std::get<0>(angle));
314 auto atom2 = m_molecule->atom(std::get<1>(angle));
315 auto atom3 = m_molecule->atom(std::get<2>(angle));
316 Real angleValue = m_model->getAngleValue(rowNum);
317 m_molecule->addConstraint(angleValue, atom1.index(), atom2.index(),
318 atom3.index());
319 }
320 } else if (m_type == PropertyType::TorsionType) {
321 if (m_model != nullptr) {
322 auto torsion = m_model->getTorsion(rowNum);
323 auto atom1 = m_molecule->atom(std::get<0>(torsion));
324 auto atom2 = m_molecule->atom(std::get<1>(torsion));
325 auto atom3 = m_molecule->atom(std::get<2>(torsion));
326 auto atom4 = m_molecule->atom(std::get<3>(torsion));
327 Real torsionValue = m_model->getTorsionValue(rowNum);
328 m_molecule->addConstraint(torsionValue, atom1.index(), atom2.index(),
329 atom3.index(), atom4.index());
330 }
331 }
332 }
333 }
334
335 void PropertyView::unconstrainSelectedRows()
336 {
337 // get the selected rows (if any)
338 QModelIndexList selectedRows = selectionModel()->selectedRows();
339
340 // if nothing is selected, we're done
341 if (selectedRows.isEmpty())
342 return;
343
344 if (m_molecule == nullptr)
345 return;
346
347 // loop through the selected rows
348 for (const auto& index : selectedRows) {
349 if (!index.isValid())
350 continue;
351
352 // get the row number
353 bool ok;
354 int rowNum = model()
355 ->headerData(index.row(), Qt::Vertical)
356 .toString()
357 .split(" ")
358 .last()
359 .toLong(&ok) -
360 1;
361 if (!ok)
362 continue;
363
364 if (m_type == PropertyType::BondType) {
365 // get the start and end atoms and the distance from the table data
366 auto bond = m_molecule->bond(rowNum);
367 auto atom1 = bond.atom1();
368 auto atom2 = bond.atom2();
369 m_molecule->removeConstraint(atom1.index(), atom2.index());
370 } else if (m_type == PropertyType::AngleType) {
371 if (m_model != nullptr) {
372 auto angle = m_model->getAngle(rowNum);
373 auto atom1 = m_molecule->atom(std::get<0>(angle));
374 auto atom2 = m_molecule->atom(std::get<1>(angle));
375 auto atom3 = m_molecule->atom(std::get<2>(angle));
376 m_molecule->removeConstraint(atom1.index(), atom2.index(),
377 atom3.index());
378 }
379 } else if (m_type == PropertyType::TorsionType) {
380 if (m_model != nullptr) {
381 auto torsion = m_model->getTorsion(rowNum);
382 auto atom1 = m_molecule->atom(std::get<0>(torsion));
383 auto atom2 = m_molecule->atom(std::get<1>(torsion));
384 auto atom3 = m_molecule->atom(std::get<2>(torsion));
385 auto atom4 = m_molecule->atom(std::get<3>(torsion));
386 m_molecule->removeConstraint(atom1.index(), atom2.index(),
387 atom3.index(), atom4.index());
388 }
389 }
390 }
391 }
392
393 void PropertyView::freezeAtom()
394 {
395 setFrozen(true);
396 }
397
398 void PropertyView::unfreezeAtom()
399 {
400 setFrozen(false);
401 }
402
403 void PropertyView::setFrozen(bool freeze)
404 {
405 // get the selected rows (if any)
406 QModelIndexList selectedRows = selectionModel()->selectedRows();
407
408 // if nothing is selected, we're done
409 if (selectedRows.isEmpty())
410 return;
411
412 if (m_molecule == nullptr)
413 return;
414
415 // loop through the selected rows
416 for (const auto& index : selectedRows) {
417 if (!index.isValid())
418 continue;
419
420 // get the row number
421 bool ok;
422 int rowNum = model()
423 ->headerData(index.row(), Qt::Vertical)
424 .toString()
425 .split(" ")
426 .last()
427 .toLong(&ok) -
428 1;
429 if (!ok)
430 continue;
431
432 m_molecule->setFrozenAtom(rowNum, freeze);
433 }
434
435 m_molecule->emitChanged(Molecule::Atoms);
436 }
437
438 void PropertyView::freezeX()
439 {
440 freezeAxis(0);
441 }
442
443 void PropertyView::freezeY()
444 {
445 freezeAxis(1);
446 }
447
448 void PropertyView::freezeZ()
449 {
450 freezeAxis(2);
451 }
452
453 void PropertyView::freezeAxis(int axis)
454 {
455 // get the selected rows (if any)
456 QModelIndexList selectedRows = selectionModel()->selectedRows();
457
458 // if nothing is selected, we're done
459 if (selectedRows.isEmpty())
460 return;
461
462 if (m_molecule == nullptr)
463 return;
464
465 // loop through the selected rows
466 for (const auto& index : selectedRows) {
467 if (!index.isValid())
468 continue;
469
470 // get the row number
471 bool ok;
472 int rowNum = model()
473 ->headerData(index.row(), Qt::Vertical)
474 .toString()
475 .split(" ")
476 .last()
477 .toLong(&ok) -
478 1;
479 if (!ok)
480 continue;
481
482 m_molecule->setFrozenAtomAxis(rowNum, axis, true);
483 }
484
485 m_molecule->emitChanged(Molecule::Atoms);
486 }
487
488 void PropertyView::openExportDialogBox()
489 {
490 // Create a file dialog for selecting the export location and file name
491 QString filePath =
492 QFileDialog::getSaveFileName(this, tr("Export CSV"), QDir::homePath(),
493 tr("CSV Files (*.csv);;All Files (*)"));
494
495 if (filePath.isEmpty()) {
496 // User canceled the dialog or didn't provide a file name
497 return;
498 }
499
500 // Open the file for writing
501 QFile file(filePath);
502 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
503 // Handle error opening the file
504 QMessageBox::critical(this, tr("Error"),
505 tr("Could not open the file for writing."));
506 return;
507 }
508
509 // Create a QTextStream to write to the file
510 QTextStream stream(&file);
511
512 // Write the header row with column names
513 for (int col = 0; col < model()->columnCount(); ++col) {
514 stream << model()->headerData(col, Qt::Horizontal).toString();
515 if (col < model()->columnCount() - 1) {
516 stream << ",";
517 }
518 }
519 stream << "\n";
520
521 // Write the data rows
522 for (int row = 0; row < model()->rowCount(); ++row) {
523 for (int col = 0; col < model()->columnCount(); ++col) {
524 stream << model()->index(row, col).data().toString();
525 if (col < model()->columnCount() - 1) {
526 stream << ",";
527 }
528 }
529 stream << "\n";
530 }
531
532 // Close the file
533 file.close();
534
535 if (file.error() != QFile::NoError) {
536 // Handle error closing the file
537 QMessageBox::critical(this, tr("Error"), tr("Error writing to the file."));
538 }
539 }
540
541 void PropertyView::changeChargeType()
542 {
543 if (m_model == nullptr || m_molecule == nullptr)
544 return;
545
546 QStringList types = m_model->availableChargeTypes();
547 if (types.isEmpty())
548 return;
549
550 // pre-select the current type
551 QString current = m_model->chargeType();
552
553 int currentIndex = types.indexOf(current, 0, Qt::CaseInsensitive);
554 if (currentIndex < 0)
555 currentIndex = 0;
556
557 bool ok = false;
558 QString selected = QInputDialog::getItem(
559 this, tr("Partial Charge Type"), tr("Select the partial charge type:"),
560 types, currentIndex, false, &ok);
561 if (ok && !selected.isEmpty())
562 m_model->setChargeType(selected);
563 }
564
565 void PropertyView::contextMenuEvent(QContextMenuEvent* event)
566 {
567 QMenu menu(this);
568 QAction* copyAction = menu.addAction(tr("Copy"));
569 menu.addAction(copyAction);
570 connect(copyAction, &QAction::triggered, this,
571 &PropertyView::copySelectedRowsToClipboard);
572
573 QAction* exportAction = menu.addAction(tr("Export…"));
574 menu.addAction(exportAction);
575 connect(exportAction, &QAction::triggered, this,
576 &PropertyView::openExportDialogBox);
577
578 if (m_type == PropertyType::AtomType) {
579 // change partial charge type
580 QAction* chargeTypeAction = menu.addAction(tr("Change Charge Type…"));
581 connect(chargeTypeAction, &QAction::triggered, this,
582 &PropertyView::changeChargeType);
583
584 menu.addSeparator();
585
586 // freeze atom
587 QAction* freezeAtomAction = menu.addAction(tr("Freeze Atom"));
588 menu.addAction(freezeAtomAction);
589 connect(freezeAtomAction, &QAction::triggered, this,
590 &PropertyView::freezeAtom);
591 QAction* freezeX = menu.addAction(tr("Freeze X"));
592 menu.addAction(freezeX);
593 connect(freezeX, &QAction::triggered, this, &PropertyView::freezeX);
594 QAction* freezeY = menu.addAction(tr("Freeze Y"));
595 menu.addAction(freezeY);
596 connect(freezeY, &QAction::triggered, this, &PropertyView::freezeY);
597 QAction* freezeZ = menu.addAction(tr("Freeze Z"));
598 menu.addAction(freezeZ);
599 connect(freezeZ, &QAction::triggered, this, &PropertyView::freezeZ);
600 QAction* unfreezeAtomAction = menu.addAction(tr("Unfreeze Atom"));
601 menu.addAction(unfreezeAtomAction);
602 connect(unfreezeAtomAction, &QAction::triggered, this,
603 &PropertyView::unfreezeAtom);
604 } else if (m_type != PropertyType::ResidueType) {
605 // bond angle & torsion are similar
606 QString name;
607 if (m_type == PropertyType::BondType)
608 name = tr("Constrain Bond");
609 else if (m_type == PropertyType::AngleType)
610 name = tr("Constrain Angle");
611 else if (m_type == PropertyType::TorsionType)
612 name = tr("Constrain Torsion");
613
614 QAction* constrainAction = menu.addAction(name);
615 menu.addAction(constrainAction);
616 connect(constrainAction, &QAction::triggered, this,
617 &PropertyView::constrainSelectedRows);
618
619 QAction* unconstrainAction = menu.addAction(tr("Remove Constraint"));
620 menu.addAction(unconstrainAction);
621 connect(unconstrainAction, &QAction::triggered, this,
622 &PropertyView::unconstrainSelectedRows);
623 }
624
625 menu.exec(event->globalPos());
626 }
627
628 } // end namespace Avogadro