| 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 "coordinateeditordialog.h" |
| 7 |
#include "coordinatetextedit.h" |
| 8 |
#include "ui_coordinateeditordialog.h" |
| 9 |
|
| 10 |
#include <avogadro/qtgui/molecule.h> |
| 11 |
#include <avogadro/qtgui/rwmolecule.h> |
| 12 |
|
| 13 |
#include <avogadro/core/avogadrocore.h> |
| 14 |
#include <avogadro/core/coordinateblockgenerator.h> |
| 15 |
#include <avogadro/core/crystaltools.h> |
| 16 |
#include <avogadro/core/elements.h> |
| 17 |
#include <avogadro/core/vector.h> |
| 18 |
|
| 19 |
#include <QtGui/QClipboard> |
| 20 |
#include <QtGui/QFont> |
| 21 |
#include <QtGui/QIcon> |
| 22 |
#include <QtGui/QRegularExpressionValidator> |
| 23 |
#include <QtGui/QTextCursor> |
| 24 |
#include <QtGui/QTextDocument> |
| 25 |
#include <QtWidgets/QApplication> |
| 26 |
#include <QtWidgets/QMessageBox> |
| 27 |
#include <QtWidgets/QToolTip> |
| 28 |
|
| 29 |
#include <QtCore/QDebug> |
| 30 |
#include <QtCore/QMimeData> |
| 31 |
#include <QtCore/QMutableListIterator> |
| 32 |
#include <QtCore/QRegularExpression> |
| 33 |
#include <QtCore/QString> |
| 34 |
#include <QtCore/QTimer> |
| 35 |
|
| 36 |
// Define this to print out details of the format detection algorithm. |
| 37 |
#undef ENABLE_FORMAT_DEBUG |
| 38 |
|
| 39 |
#ifdef ENABLE_FORMAT_DEBUG |
| 40 |
#define FORMAT_DEBUG(x) x |
| 41 |
#else // ENABLE_FORMAT_DEBUG |
| 42 |
#define FORMAT_DEBUG(x) |
| 43 |
#endif // ENABLE_FORMAT_DEBUG |
| 44 |
|
| 45 |
using Avogadro::Vector3; |
| 46 |
using Avogadro::Core::Elements; |
| 47 |
using Avogadro::QtGui::Molecule; |
| 48 |
|
| 49 |
namespace { |
| 50 |
|
| 51 |
// Ensure a cross-platform monospaced font |
| 52 |
#if defined(Q_OS_WIN) || defined(Q_OS_MACOS) |
| 53 |
static const QString EDITOR_FONT = "Courier"; |
| 54 |
#else // Linux and other OSes |
| 55 |
static const QString EDITOR_FONT = "Monospace"; |
| 56 |
#endif |
| 57 |
|
| 58 |
// Various integer constants. |
| 59 |
enum |
| 60 |
{ |
| 61 |
CustomPreset = 0 |
| 62 |
}; |
| 63 |
|
| 64 |
// Distance unit indices -- keep in sync with the .ui file. |
| 65 |
enum DistanceUnitIndex |
| 66 |
{ |
| 67 |
Angstrom = 0, |
| 68 |
Bohr |
| 69 |
}; |
| 70 |
|
| 71 |
// Types of tokens, used while parsing. |
| 72 |
enum TokenType |
| 73 |
{ |
| 74 |
Integer = 0, |
| 75 |
Double, |
| 76 |
String |
| 77 |
}; |
| 78 |
|
| 79 |
// Some frequently used regexes: |
| 80 |
static const QRegularExpression TOKEN_SEPARATOR("[\\s,;]+"); |
| 81 |
static const QRegularExpression VALID_TOKEN("[^\\s,;]+"); |
| 82 |
// These two need to be exact |
| 83 |
static const QRegularExpression INT_CHECKER( |
| 84 |
QRegularExpression::anchoredPattern("(:?[+-])?\\d+")); |
| 85 |
static const QRegularExpression DOUBLE_CHECKER( |
| 86 |
QRegularExpression::anchoredPattern( |
| 87 |
"(:?[+-])?" // Leading sign |
| 88 |
"(:?" // Must match one of the following: |
| 89 |
"\\d*\\.\\d*" // Fractional part |
| 90 |
"|" // or |
| 91 |
"\\d+[Ee](:?[+-])?\\d+" // Exponential part |
| 92 |
"|" // or |
| 93 |
"\\d*\\.\\d*" // Fractional part and |
| 94 |
"[Ee](:?[+-])?\\d+" // Exponential part |
| 95 |
")")); |
| 96 |
|
| 97 |
struct AtomStruct |
| 98 |
{ |
| 99 |
unsigned char atomicNumber; |
| 100 |
Vector3 pos; |
| 101 |
}; |
| 102 |
|
| 103 |
} // namespace |
| 104 |
|
| 105 |
namespace Avogadro::QtPlugins { |
| 106 |
|
| 107 |
// Storage class used to hold state while validating input. |
| 108 |
class CoordinateEditorDialog::ValidateStorage |
| 109 |
{ |
| 110 |
public: |
| 111 |
ValidateStorage() |
| 112 |
: isValidating(false), restartWhenFinished(false), collectAtoms(false), |
| 113 |
convertDistance(false), latticePositions(false), distanceConversion(1.f) |
| 114 |
{ |
| 115 |
} |
| 116 |
|
| 117 |
bool isValidating; |
| 118 |
bool restartWhenFinished; |
| 119 |
bool collectAtoms; |
| 120 |
bool convertDistance; |
| 121 |
bool latticePositions; |
| 122 |
float distanceConversion; |
| 123 |
|
| 124 |
// Format specification |
| 125 |
QString spec; |
| 126 |
|
| 127 |
// Text cursors |
| 128 |
QTextCursor lineCursor; |
| 129 |
QTextCursor tokenCursor; |
| 130 |
|
| 131 |
// Accumulate atom data |
| 132 |
QVector<AtomStruct> atoms; |
| 133 |
}; |
| 134 |
|
| 135 |
CoordinateEditorDialog::CoordinateEditorDialog(QWidget* parent_) |
| 136 |
: QDialog(parent_), m_ui(new Ui::CoordinateEditorDialog), m_molecule(nullptr), |
| 137 |
m_validate(new ValidateStorage), m_defaultSpec("SZxyz#N") |
| 138 |
{ |
| 139 |
m_ui->setupUi(this); |
| 140 |
|
| 141 |
// Set up text editor |
| 142 |
m_ui->text->setFont(QFont(EDITOR_FONT, qApp->font().pointSize())); |
| 143 |
connect(m_ui->text->document(), SIGNAL(modificationChanged(bool)), |
| 144 |
SLOT(textModified(bool))); |
| 145 |
|
| 146 |
// Setup spec edit |
| 147 |
QRegularExpression specRegExp("[#ZGSLNabcxyz01_]*"); |
| 148 |
auto* specValidator = new QRegularExpressionValidator(specRegExp, this); |
| 149 |
m_ui->spec->setValidator(specValidator); |
| 150 |
connect(m_ui->presets, SIGNAL(currentIndexChanged(int)), |
| 151 |
SLOT(presetChanged(int))); |
| 152 |
connect(m_ui->spec, SIGNAL(textChanged(QString)), SLOT(specChanged())); |
| 153 |
connect(m_ui->spec, SIGNAL(textEdited(QString)), SLOT(specEdited())); |
| 154 |
|
| 155 |
connect(m_ui->distanceUnit, SIGNAL(currentIndexChanged(int)), |
| 156 |
SLOT(updateText())); |
| 157 |
|
| 158 |
connect(m_ui->help, SIGNAL(clicked()), SLOT(helpClicked())); |
| 159 |
connect(m_ui->cut, SIGNAL(clicked()), SLOT(cutClicked())); |
| 160 |
connect(m_ui->copy, SIGNAL(clicked()), SLOT(copyClicked())); |
| 161 |
connect(m_ui->paste, SIGNAL(clicked()), SLOT(pasteClicked())); |
| 162 |
connect(m_ui->revert, SIGNAL(clicked()), SLOT(revertClicked())); |
| 163 |
connect(m_ui->clear, SIGNAL(clicked()), SLOT(clearClicked())); |
| 164 |
connect(m_ui->apply, SIGNAL(clicked()), SLOT(applyClicked())); |
| 165 |
|
| 166 |
m_ui->cut->setIcon(QIcon::fromTheme("edit-cut")); |
| 167 |
m_ui->copy->setIcon(QIcon::fromTheme("edit-copy")); |
| 168 |
m_ui->paste->setIcon(QIcon::fromTheme("edit-paste")); |
| 169 |
|
| 170 |
buildPresets(); |
| 171 |
listenForTextEditChanges(true); |
| 172 |
} |
| 173 |
|
| 174 |
CoordinateEditorDialog::~CoordinateEditorDialog() |
| 175 |
{ |
| 176 |
delete m_ui; |
| 177 |
} |
| 178 |
|
| 179 |
void CoordinateEditorDialog::setMolecule(QtGui::Molecule* mol) |
| 180 |
{ |
| 181 |
if (mol != m_molecule) { |
| 182 |
if (m_molecule) |
| 183 |
m_molecule->disconnect(this); |
| 184 |
m_molecule = mol; |
| 185 |
connect(m_molecule, SIGNAL(changed(uint)), SLOT(moleculeChanged(uint))); |
| 186 |
updateText(); |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
void CoordinateEditorDialog::moleculeChanged(uint change) |
| 191 |
{ |
| 192 |
if (static_cast<Molecule::MoleculeChange>(change) & Molecule::Atoms || |
| 193 |
static_cast<Molecule::MoleculeChange>(change) & Molecule::UnitCell) { |
| 194 |
updateText(); |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
void CoordinateEditorDialog::presetChanged(int ind) |
| 199 |
{ |
| 200 |
QVariant itemData(m_ui->presets->itemData(ind)); |
| 201 |
bool isCustom(itemData.type() != QVariant::String); |
| 202 |
|
| 203 |
// Changing the spec text will update the editor text. |
| 204 |
m_ui->spec->setText(isCustom ? m_defaultSpec : itemData.toString()); |
| 205 |
} |
| 206 |
|
| 207 |
void CoordinateEditorDialog::specChanged() |
| 208 |
{ |
| 209 |
// Store the spec if custom preset is selected. |
| 210 |
if (m_ui->presets->currentIndex() == CustomPreset) |
| 211 |
m_defaultSpec = m_ui->spec->text(); |
| 212 |
updateText(); |
| 213 |
} |
| 214 |
|
| 215 |
void CoordinateEditorDialog::specEdited() |
| 216 |
{ |
| 217 |
// Editing the spec switches to and updates the custom preset. |
| 218 |
if (m_ui->presets->currentIndex() != CustomPreset) { |
| 219 |
m_defaultSpec = m_ui->spec->text(); |
| 220 |
m_ui->presets->setCurrentIndex(CustomPreset); |
| 221 |
} |
| 222 |
} |
| 223 |
|
| 224 |
void CoordinateEditorDialog::updateText() |
| 225 |
{ |
| 226 |
if (m_ui->text->document()->isModified()) { |
| 227 |
int reply = QMessageBox::question( |
| 228 |
this, tr("Overwrite changes?"), |
| 229 |
tr("The text document has been modified. Would " |
| 230 |
"you like to discard your changes and revert " |
| 231 |
"to the current molecule?"), |
| 232 |
QMessageBox::Yes | QMessageBox::No, QMessageBox::No); |
| 233 |
if (reply != QMessageBox::Yes) |
| 234 |
return; |
| 235 |
} |
| 236 |
|
| 237 |
Core::CoordinateBlockGenerator gen; |
| 238 |
gen.setMolecule(m_molecule); |
| 239 |
gen.setSpecification(m_ui->spec->text().toStdString()); |
| 240 |
switch (m_ui->distanceUnit->currentIndex()) { |
| 241 |
default: |
| 242 |
case Angstrom: |
| 243 |
gen.setDistanceUnit(Core::CoordinateBlockGenerator::Angstrom); |
| 244 |
break; |
| 245 |
case Bohr: |
| 246 |
gen.setDistanceUnit(Core::CoordinateBlockGenerator::Bohr); |
| 247 |
break; |
| 248 |
} |
| 249 |
|
| 250 |
// Disable markup for the generated text. |
| 251 |
listenForTextEditChanges(false); |
| 252 |
m_ui->text->document()->setPlainText( |
| 253 |
QString::fromStdString(gen.generateCoordinateBlock())); |
| 254 |
listenForTextEditChanges(true); |
| 255 |
m_ui->text->document()->setModified(false); |
| 256 |
} |
| 257 |
|
| 258 |
void CoordinateEditorDialog::helpClicked() |
| 259 |
{ |
| 260 |
// Give the spec lineedit focus and show its tooltip. |
| 261 |
m_ui->spec->setFocus(Qt::MouseFocusReason); |
| 262 |
QPoint point(m_ui->spec->pos() + pos()); |
| 263 |
point.setY(point.y() + m_ui->spec->frameGeometry().height() + 5); |
| 264 |
QToolTip::showText(point, m_ui->spec->toolTip(), m_ui->spec); |
| 265 |
} |
| 266 |
|
| 267 |
void CoordinateEditorDialog::validateInput() |
| 268 |
{ |
| 269 |
if (m_validate->isValidating) { |
| 270 |
m_validate->restartWhenFinished = true; |
| 271 |
return; |
| 272 |
} |
| 273 |
|
| 274 |
// Reset formatting. Stop listening for changes since format changes will |
| 275 |
// retrigger validation. |
| 276 |
listenForTextEditChanges(false); |
| 277 |
m_ui->text->resetMarks(); |
| 278 |
listenForTextEditChanges(true); |
| 279 |
|
| 280 |
// No text, nothing to do! Trim the plain text - this fixes a crashing |
| 281 |
// bug if the user accidentally presses return in a blank document. |
| 282 |
if (m_ui->text->document()->toPlainText().trimmed().isEmpty()) { |
| 283 |
emit validationFinished(true); |
| 284 |
return; |
| 285 |
} |
| 286 |
|
| 287 |
// Try to detect the input format |
| 288 |
QString inputFormat(detectInputFormat()); |
| 289 |
if (inputFormat.isEmpty()) { |
| 290 |
emit validationFinished(false); |
| 291 |
return; |
| 292 |
} |
| 293 |
|
| 294 |
// Initialize |
| 295 |
m_validate->latticePositions = inputFormat.contains('a'); |
| 296 |
m_validate->isValidating = true; |
| 297 |
m_validate->spec = inputFormat; |
| 298 |
m_validate->lineCursor = QTextCursor(m_ui->text->document()); |
| 299 |
|
| 300 |
// Start the worker |
| 301 |
validateInputWorker(); |
| 302 |
} |
| 303 |
|
| 304 |
void CoordinateEditorDialog::validateInputWorker() |
| 305 |
{ |
| 306 |
if (!m_validate->isValidating) |
| 307 |
return; |
| 308 |
|
| 309 |
// Disable revalidation due to formatting changes. |
| 310 |
listenForTextEditChanges(false); |
| 311 |
|
| 312 |
// Setup some aliases to keep code concise: |
| 313 |
const QString& spec(m_validate->spec); |
| 314 |
QTextCursor& lineCursor(m_validate->lineCursor); |
| 315 |
QTextCursor& tokenCursor(m_validate->tokenCursor); |
| 316 |
|
| 317 |
QTextDocument* doc(m_ui->text->document()); |
| 318 |
QString::const_iterator begin(spec.constBegin()); |
| 319 |
QString::const_iterator end(spec.constEnd()); |
| 320 |
QString::const_iterator iter; |
| 321 |
|
| 322 |
// Only do a few lines at a time, then return control to the event loop. |
| 323 |
int lineThisIteration = 0; |
| 324 |
|
| 325 |
while (++lineThisIteration <= 10 && !lineCursor.atEnd()) { |
| 326 |
// Place the entire line in the line cursor's selection. |
| 327 |
lineCursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor); |
| 328 |
lineCursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor); |
| 329 |
|
| 330 |
// Skip empty lines - this is nice if the user accidentally left some |
| 331 |
// empty lines at the end of the input |
| 332 |
if (lineCursor.selectedText().trimmed().isEmpty()) { |
| 333 |
// So that we don't have an infinite loop... |
| 334 |
if (!lineCursor.atEnd()) { |
| 335 |
lineCursor.movePosition(QTextCursor::Down); |
| 336 |
lineCursor.movePosition(QTextCursor::StartOfLine); |
| 337 |
} |
| 338 |
continue; |
| 339 |
} |
| 340 |
|
| 341 |
// Start the token cursor at the beginning of the current line. |
| 342 |
tokenCursor.setPosition(lineCursor.anchor(), QTextCursor::MoveAnchor); |
| 343 |
|
| 344 |
// This is used when applying changes to store the atom specifications. |
| 345 |
AtomStruct atom; |
| 346 |
|
| 347 |
// Iterate through spec characters |
| 348 |
for (iter = begin; iter != end; ++iter) { |
| 349 |
// Place the next valid token in tokenCursor's selection: |
| 350 |
tokenCursor = doc->find(VALID_TOKEN, tokenCursor); |
| 351 |
|
| 352 |
// If the token cursor has moved off of the current line, mark the entire |
| 353 |
// line as invalid and move on. |
| 354 |
if (tokenCursor.isNull() || |
| 355 |
tokenCursor.position() > lineCursor.position()) { |
| 356 |
m_ui->text->markInvalid(lineCursor, tr("Too few entries on line.")); |
| 357 |
break; |
| 358 |
} |
| 359 |
|
| 360 |
switch (iter->toLatin1()) { |
| 361 |
case '?': // Nothing to validate other than that this is a valid token. |
| 362 |
break; |
| 363 |
|
| 364 |
case 'N': { |
| 365 |
// Validate name: |
| 366 |
QString cleanToken(tokenCursor.selectedText().toLower()); |
| 367 |
if (!cleanToken.isEmpty()) |
| 368 |
cleanToken.replace(0, 1, cleanToken[0].toUpper()); |
| 369 |
std::string tokenStd(cleanToken.toStdString()); |
| 370 |
atom.atomicNumber = Elements::atomicNumberFromName(tokenStd); |
| 371 |
if (atom.atomicNumber == Avogadro::InvalidElement) |
| 372 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid element name.")); |
| 373 |
else |
| 374 |
m_ui->text->markValid(tokenCursor, tr("Element name.")); |
| 375 |
break; |
| 376 |
} |
| 377 |
|
| 378 |
case 'S': { |
| 379 |
// Validate symbol: |
| 380 |
QString cleanToken(tokenCursor.selectedText().toLower()); |
| 381 |
if (!cleanToken.isEmpty()) |
| 382 |
cleanToken.replace(0, 1, cleanToken[0].toUpper()); |
| 383 |
std::string tokenStd(cleanToken.toStdString()); |
| 384 |
atom.atomicNumber = Elements::atomicNumberFromSymbol(tokenStd); |
| 385 |
if (atom.atomicNumber == Avogadro::InvalidElement) |
| 386 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid element symbol.")); |
| 387 |
else |
| 388 |
m_ui->text->markValid(tokenCursor, tr("Element symbol.")); |
| 389 |
break; |
| 390 |
} |
| 391 |
|
| 392 |
case 'L': { |
| 393 |
// Validate label (symbol + number) |
| 394 |
QString cleanToken(tokenCursor.selectedText().toLower()); |
| 395 |
if (!cleanToken.isEmpty()) |
| 396 |
cleanToken.replace(0, 1, cleanToken[0].toUpper()); |
| 397 |
|
| 398 |
// Split the label into symbol and number |
| 399 |
QRegularExpression labelSplitter("([A-Z][a-z]?)(\\d+)"); |
| 400 |
QRegularExpressionMatch match = labelSplitter.match(cleanToken); |
| 401 |
if (match.hasMatch()) { |
| 402 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid atom label.")); |
| 403 |
break; |
| 404 |
} |
| 405 |
// check the symbol |
| 406 |
std::string tokenStd(match.captured(1).toStdString()); |
| 407 |
atom.atomicNumber = Elements::atomicNumberFromSymbol(tokenStd); |
| 408 |
if (atom.atomicNumber == Avogadro::InvalidElement) |
| 409 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid element symbol.")); |
| 410 |
else |
| 411 |
m_ui->text->markValid(tokenCursor, tr("Element symbol.")); |
| 412 |
break; |
| 413 |
} |
| 414 |
|
| 415 |
case '#': { |
| 416 |
// Validate integer: |
| 417 |
bool isInt; |
| 418 |
[[maybe_unused]] int index = tokenCursor.selectedText().toInt(&isInt); |
| 419 |
if (!isInt) |
| 420 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid atomic index.")); |
| 421 |
else |
| 422 |
m_ui->text->markValid(tokenCursor, tr("Atomic index.")); |
| 423 |
break; |
| 424 |
} |
| 425 |
|
| 426 |
case 'Z': { |
| 427 |
// Validate integer: |
| 428 |
bool isInt; |
| 429 |
atom.atomicNumber = static_cast<unsigned char>( |
| 430 |
tokenCursor.selectedText().toInt(&isInt)); |
| 431 |
if (!isInt) |
| 432 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid atomic number.")); |
| 433 |
else |
| 434 |
m_ui->text->markValid(tokenCursor, tr("Atomic number.")); |
| 435 |
break; |
| 436 |
} |
| 437 |
|
| 438 |
case 'x': { |
| 439 |
// Validate real: |
| 440 |
bool isReal; |
| 441 |
atom.pos.x() = tokenCursor.selectedText().toDouble(&isReal); |
| 442 |
if (!isReal) |
| 443 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid coordinate.")); |
| 444 |
else |
| 445 |
m_ui->text->markValid(tokenCursor, tr("X coordinate.")); |
| 446 |
break; |
| 447 |
} |
| 448 |
|
| 449 |
case 'y': { |
| 450 |
// Validate real: |
| 451 |
bool isReal; |
| 452 |
atom.pos.y() = tokenCursor.selectedText().toDouble(&isReal); |
| 453 |
if (!isReal) |
| 454 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid coordinate.")); |
| 455 |
else |
| 456 |
m_ui->text->markValid(tokenCursor, tr("Y coordinate.")); |
| 457 |
break; |
| 458 |
} |
| 459 |
|
| 460 |
case 'z': { |
| 461 |
// Validate real: |
| 462 |
bool isReal; |
| 463 |
atom.pos.z() = tokenCursor.selectedText().toDouble(&isReal); |
| 464 |
if (!isReal) |
| 465 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid coordinate.")); |
| 466 |
else |
| 467 |
m_ui->text->markValid(tokenCursor, tr("Z coordinate.")); |
| 468 |
break; |
| 469 |
} |
| 470 |
|
| 471 |
case 'a': { |
| 472 |
// Validate real: |
| 473 |
bool isReal; |
| 474 |
atom.pos.x() = tokenCursor.selectedText().toDouble(&isReal); |
| 475 |
if (!isReal) |
| 476 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid coordinate.")); |
| 477 |
else |
| 478 |
m_ui->text->markValid(tokenCursor, tr("'a' lattice coordinate.")); |
| 479 |
break; |
| 480 |
} |
| 481 |
|
| 482 |
case 'b': { |
| 483 |
// Validate real: |
| 484 |
bool isReal; |
| 485 |
atom.pos.y() = tokenCursor.selectedText().toDouble(&isReal); |
| 486 |
if (!isReal) |
| 487 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid coordinate.")); |
| 488 |
else |
| 489 |
m_ui->text->markValid(tokenCursor, tr("'b' lattice coordinate.")); |
| 490 |
break; |
| 491 |
} |
| 492 |
|
| 493 |
case 'c': { |
| 494 |
// Validate real: |
| 495 |
bool isReal; |
| 496 |
atom.pos.z() = tokenCursor.selectedText().toDouble(&isReal); |
| 497 |
if (!isReal) |
| 498 |
m_ui->text->markInvalid(tokenCursor, tr("Invalid coordinate.")); |
| 499 |
else |
| 500 |
m_ui->text->markValid(tokenCursor, tr("'c' lattice coordinate.")); |
| 501 |
break; |
| 502 |
} |
| 503 |
|
| 504 |
default: |
| 505 |
qWarning() << "Unhandled character in detected spec: " << *iter; |
| 506 |
break; |
| 507 |
} |
| 508 |
} |
| 509 |
|
| 510 |
// Store this atom info if collecting. |
| 511 |
if (m_validate->collectAtoms) { |
| 512 |
if (m_validate->convertDistance && !m_validate->latticePositions) |
| 513 |
atom.pos *= m_validate->distanceConversion; |
| 514 |
m_validate->atoms << atom; |
| 515 |
} |
| 516 |
|
| 517 |
// Move down to the next line if we are not at the end. Moving to the |
| 518 |
// start of the line after moving down is necessary in case moving down |
| 519 |
// puts us at the end of the document. |
| 520 |
if (!lineCursor.atEnd()) { |
| 521 |
lineCursor.movePosition(QTextCursor::Down); |
| 522 |
lineCursor.movePosition(QTextCursor::StartOfLine); |
| 523 |
} |
| 524 |
} |
| 525 |
|
| 526 |
// Reenable validation. |
| 527 |
listenForTextEditChanges(true); |
| 528 |
|
| 529 |
// If we're not at the end, post this method back into the event loop. |
| 530 |
if (!lineCursor.atEnd()) { |
| 531 |
QTimer::singleShot(0, this, SLOT(validateInputWorker())); |
| 532 |
} else { |
| 533 |
// Otherwise emit the finished signal. |
| 534 |
emit validationFinished(!m_ui->text->hasInvalidMarks()); |
| 535 |
m_validate->isValidating = false; |
| 536 |
|
| 537 |
// If a validation request came in while already validating, revalidate. |
| 538 |
if (m_validate->restartWhenFinished) { |
| 539 |
m_validate->restartWhenFinished = false; |
| 540 |
validateInput(); |
| 541 |
} |
| 542 |
} |
| 543 |
} |
| 544 |
|
| 545 |
void CoordinateEditorDialog::applyClicked() |
| 546 |
{ |
| 547 |
if (!m_molecule) |
| 548 |
return; |
| 549 |
|
| 550 |
// If we're in the middle of a validation, abort it |
| 551 |
if (m_validate->isValidating) { |
| 552 |
m_validate->isValidating = false; |
| 553 |
qApp->processEvents(); |
| 554 |
} |
| 555 |
|
| 556 |
m_validate->collectAtoms = true; |
| 557 |
m_validate->atoms.clear(); |
| 558 |
|
| 559 |
switch (m_ui->distanceUnit->currentIndex()) { |
| 560 |
case Bohr: |
| 561 |
m_validate->convertDistance = true; |
| 562 |
m_validate->distanceConversion = BOHR_TO_ANGSTROM_F; |
| 563 |
break; |
| 564 |
default: |
| 565 |
m_validate->convertDistance = false; |
| 566 |
m_validate->distanceConversion = 1.f; |
| 567 |
break; |
| 568 |
} |
| 569 |
|
| 570 |
connect(this, SIGNAL(validationFinished(bool)), SLOT(applyFinish(bool))); |
| 571 |
validateInput(); |
| 572 |
} |
| 573 |
|
| 574 |
void CoordinateEditorDialog::applyFinish(bool valid) |
| 575 |
{ |
| 576 |
// Clean up |
| 577 |
m_validate->collectAtoms = false; |
| 578 |
QVector<AtomStruct> atoms(m_validate->atoms); |
| 579 |
m_validate->atoms.clear(); |
| 580 |
disconnect(this, SIGNAL(validationFinished(bool)), this, |
| 581 |
SLOT(applyFinish(bool))); |
| 582 |
|
| 583 |
if (!valid) { |
| 584 |
QMessageBox::critical(this, tr("Error applying geometry"), |
| 585 |
tr("Could not parse geometry specification. Fix the " |
| 586 |
"highlighted errors and try again.\n\n" |
| 587 |
"(Hint: Hold the mouse over red text for a " |
| 588 |
"description of the error.)")); |
| 589 |
return; |
| 590 |
} |
| 591 |
|
| 592 |
bool hadAtoms(m_molecule->atomCount() > 0); |
| 593 |
bool hadBonds(m_molecule->bondCount() > 0); |
| 594 |
|
| 595 |
// Create a new molecule so we can eventually store both in the undo command |
| 596 |
Molecule newMolecule = *m_molecule; |
| 597 |
newMolecule.clearAtoms(); |
| 598 |
foreach (const AtomStruct& atom, atoms) |
| 599 |
newMolecule.addAtom(atom.atomicNumber).setPosition3d(atom.pos); |
| 600 |
if (m_validate->latticePositions) { |
| 601 |
Core::CrystalTools::setFractionalCoordinates(newMolecule, |
| 602 |
newMolecule.atomPositions3d()); |
| 603 |
} else { |
| 604 |
newMolecule.perceiveBondsSimple(); |
| 605 |
newMolecule.perceiveBondOrders(); |
| 606 |
} |
| 607 |
|
| 608 |
m_ui->text->document()->setModified(false); |
| 609 |
|
| 610 |
Molecule::MoleculeChanges change = Molecule::NoChange; |
| 611 |
if (hadAtoms) |
| 612 |
change |= Molecule::Atoms | Molecule::Removed; |
| 613 |
if (hadBonds) |
| 614 |
change |= Molecule::Bonds | Molecule::Removed; |
| 615 |
if (newMolecule.atomCount() > 0) |
| 616 |
change |= Molecule::Atoms | Molecule::Added; |
| 617 |
if (newMolecule.bondCount() > 0) |
| 618 |
change |= Molecule::Bonds | Molecule::Added; |
| 619 |
|
| 620 |
QString undoText = tr("Edit Atomic Coordinates"); |
| 621 |
m_molecule->undoMolecule()->modifyMolecule(newMolecule, change, undoText); |
| 622 |
|
| 623 |
// We went from no atoms to something, don't edit by default |
| 624 |
// PR#394 |
| 625 |
if (!hadAtoms) |
| 626 |
emit pastedMolecule(); |
| 627 |
} |
| 628 |
|
| 629 |
void CoordinateEditorDialog::textModified(bool modified) |
| 630 |
{ |
| 631 |
m_ui->apply->setEnabled(modified); |
| 632 |
m_ui->revert->setEnabled(modified); |
| 633 |
} |
| 634 |
|
| 635 |
void CoordinateEditorDialog::buildPresets() |
| 636 |
{ |
| 637 |
// Custom must be first: |
| 638 |
m_ui->presets->addItem(tr("Custom"), QVariant()); |
| 639 |
m_ui->presets->addItem(tr("XYZ format (symbols)"), QVariant("Sxyz")); |
| 640 |
m_ui->presets->addItem(tr("XYZ format (names)"), QVariant("Nxyz")); |
| 641 |
m_ui->presets->addItem(tr("XYZ format (atomic numbers)"), QVariant("Zxyz")); |
| 642 |
m_ui->presets->addItem(tr("Lattice coordinates (symbols)"), QVariant("Sabc")); |
| 643 |
m_ui->presets->addItem(tr("Lattice coordinates (names)"), QVariant("Nabc")); |
| 644 |
m_ui->presets->addItem(tr("Lattice coordinates (atomic numbers)"), |
| 645 |
QVariant("Zabc")); |
| 646 |
m_ui->presets->addItem(tr("GAMESS format (symbols)"), QVariant("SGxyz")); |
| 647 |
m_ui->presets->addItem(tr("GAMESS format (names)"), QVariant("NGxyz")); |
| 648 |
m_ui->presets->addItem(tr("Turbomole format"), QVariant("xyzS")); |
| 649 |
|
| 650 |
// show Sxyz initially |
| 651 |
m_ui->presets->setCurrentIndex(1); |
| 652 |
} |
| 653 |
|
| 654 |
void CoordinateEditorDialog::listenForTextEditChanges(bool enable) |
| 655 |
{ |
| 656 |
if (enable) |
| 657 |
connect(m_ui->text, SIGNAL(textChanged()), this, SLOT(validateInput())); |
| 658 |
else |
| 659 |
disconnect(m_ui->text, SIGNAL(textChanged()), this, SLOT(validateInput())); |
| 660 |
} |
| 661 |
|
| 662 |
QString CoordinateEditorDialog::detectInputFormat() const |
| 663 |
{ |
| 664 |
if (m_ui->text->document()->isEmpty()) |
| 665 |
return QString(); |
| 666 |
|
| 667 |
if (!m_ui->spec->text().isEmpty()) |
| 668 |
return m_ui->spec->text(); |
| 669 |
|
| 670 |
// Extract the first non-empty line of text from the document. |
| 671 |
QTextCursor cur(m_ui->text->document()); |
| 672 |
QString sample; |
| 673 |
while (sample.isEmpty()) { |
| 674 |
cur.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor); |
| 675 |
cur.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor); |
| 676 |
sample = cur.selectedText(); |
| 677 |
cur.movePosition(QTextCursor::Down); |
| 678 |
} |
| 679 |
|
| 680 |
FORMAT_DEBUG(qDebug() << "\n\nExamining sample:" << sample;) |
| 681 |
|
| 682 |
// Split the string into tokens, and identify the type of each. |
| 683 |
QList<QString> tokens(sample.split(TOKEN_SEPARATOR, Qt::SkipEmptyParts)); |
| 684 |
QList<TokenType> tokenTypes; |
| 685 |
tokenTypes.reserve(tokens.size()); |
| 686 |
size_t tokenTypeCounts[3] = { 0, 0, 0 }; |
| 687 |
|
| 688 |
foreach (const QString& token, tokens) { |
| 689 |
TokenType tokenType = String; |
| 690 |
if (INT_CHECKER.match(token).hasMatch()) |
| 691 |
tokenType = Integer; |
| 692 |
else if (DOUBLE_CHECKER.match(token).hasMatch()) |
| 693 |
tokenType = Double; |
| 694 |
++tokenTypeCounts[tokenType]; |
| 695 |
tokenTypes << tokenType; |
| 696 |
} |
| 697 |
|
| 698 |
FORMAT_DEBUG(qDebug() << "\nDetected types:"; qDebug() << tokens; |
| 699 |
qDebug() << tokenTypes;); |
| 700 |
|
| 701 |
// If less than three doubles are present, promote some integers to doubles. |
| 702 |
if (tokenTypeCounts[Double] < 3 && |
| 703 |
tokenTypeCounts[Double] + tokenTypeCounts[Integer] >= 3) { |
| 704 |
|
| 705 |
// If numInts + numDoubles is greater than 3, leave the first integer as is, |
| 706 |
// we'll assume it's the atomic number. |
| 707 |
bool skipNextInt(tokenTypeCounts[Integer] + tokenTypeCounts[Double] > 3); |
| 708 |
|
| 709 |
size_t intsToPromote = 3 - tokenTypeCounts[Double]; |
| 710 |
QMutableListIterator<TokenType> tokenTypeIter(tokenTypes); |
| 711 |
while (intsToPromote > 0 && tokenTypeIter.hasNext()) { |
| 712 |
if (tokenTypeIter.next() == Integer) { |
| 713 |
if (!skipNextInt) { |
| 714 |
tokenTypeIter.setValue(Double); |
| 715 |
--intsToPromote; |
| 716 |
--tokenTypeCounts[Integer]; |
| 717 |
++tokenTypeCounts[Double]; |
| 718 |
} else { |
| 719 |
skipNextInt = false; |
| 720 |
} |
| 721 |
} |
| 722 |
} |
| 723 |
} |
| 724 |
|
| 725 |
FORMAT_DEBUG(qDebug() << "\nAfter promotion:"; qDebug() << tokens; |
| 726 |
qDebug() << tokenTypes;) |
| 727 |
|
| 728 |
// If there are no strings or integers, bail out -- we can't determine the |
| 729 |
// atom types. Likewise if there are less than 3 doubles, the coordinates |
| 730 |
// are incomplete. |
| 731 |
if ((tokenTypeCounts[Integer] == 0 && tokenTypeCounts[String] == 0) || |
| 732 |
tokenTypeCounts[Double] < 3) { |
| 733 |
return ""; |
| 734 |
} |
| 735 |
|
| 736 |
// Start assigning meaning to the values: |
| 737 |
QString resultSpec; |
| 738 |
bool atomTypeSet(false); |
| 739 |
int numCoordsSet(0); |
| 740 |
const int numberOfElements(static_cast<int>(Core::Elements::elementCount())); |
| 741 |
|
| 742 |
for (int i = 0; i < tokens.size() && (!atomTypeSet || numCoordsSet < 3); |
| 743 |
++i) { |
| 744 |
QChar current = '?'; |
| 745 |
|
| 746 |
switch (tokenTypes[i]) { |
| 747 |
case Integer: |
| 748 |
if (!atomTypeSet) { |
| 749 |
int tokenAsInt = tokens[i].toInt(); |
| 750 |
if (tokenAsInt >= 0 && tokenAsInt <= numberOfElements) { |
| 751 |
current = 'Z'; |
| 752 |
atomTypeSet = true; |
| 753 |
} |
| 754 |
} |
| 755 |
break; |
| 756 |
|
| 757 |
case Double: |
| 758 |
switch (numCoordsSet) { |
| 759 |
case 0: |
| 760 |
current = 'x'; |
| 761 |
++numCoordsSet; |
| 762 |
break; |
| 763 |
case 1: |
| 764 |
current = 'y'; |
| 765 |
++numCoordsSet; |
| 766 |
break; |
| 767 |
case 2: |
| 768 |
current = 'z'; |
| 769 |
++numCoordsSet; |
| 770 |
break; |
| 771 |
default: |
| 772 |
break; |
| 773 |
} |
| 774 |
break; |
| 775 |
|
| 776 |
case String: |
| 777 |
if (!atomTypeSet) { |
| 778 |
QString cleanToken(tokens[i].toLower()); |
| 779 |
if (!cleanToken.isEmpty()) |
| 780 |
cleanToken.replace(0, 1, cleanToken[0].toUpper()); |
| 781 |
|
| 782 |
if (cleanToken.size() <= 3) { |
| 783 |
if (Elements::atomicNumberFromSymbol(cleanToken.toStdString()) != |
| 784 |
Avogadro::InvalidElement) { |
| 785 |
current = 'S'; |
| 786 |
atomTypeSet = true; |
| 787 |
} |
| 788 |
} else { |
| 789 |
if (Elements::atomicNumberFromName(cleanToken.toStdString()) != |
| 790 |
Avogadro::InvalidElement) { |
| 791 |
current = 'N'; |
| 792 |
atomTypeSet = true; |
| 793 |
} |
| 794 |
} |
| 795 |
} |
| 796 |
break; |
| 797 |
} |
| 798 |
|
| 799 |
FORMAT_DEBUG(qDebug() << current << tokens[i];) |
| 800 |
resultSpec += current; |
| 801 |
} |
| 802 |
|
| 803 |
// Check the current specification -- if a|b|c appears before x|y|z, assume |
| 804 |
// that the specified coordinates are lattice coords |
| 805 |
static QRegularExpression cartesianSniffer("x|y|z"); |
| 806 |
static QRegularExpression fractionalSniffer("a|b|c"); |
| 807 |
const QString currentSpec(m_ui->spec->text()); |
| 808 |
int cartesianIndex = currentSpec.indexOf(cartesianSniffer); |
| 809 |
int fractionalIndex = currentSpec.indexOf(fractionalSniffer); |
| 810 |
if (fractionalIndex != -1 && |
| 811 |
(cartesianIndex == -1 || fractionalIndex < cartesianIndex)) { |
| 812 |
resultSpec.replace('x', 'a'); |
| 813 |
resultSpec.replace('y', 'b'); |
| 814 |
resultSpec.replace('z', 'c'); |
| 815 |
FORMAT_DEBUG(qDebug() << "Interpreting positions as lattice coordinates.";) |
| 816 |
} |
| 817 |
|
| 818 |
FORMAT_DEBUG(qDebug() << "Detected format:" << resultSpec); |
| 819 |
|
| 820 |
return (!atomTypeSet || numCoordsSet < 3) ? QString() : resultSpec; |
| 821 |
} |
| 822 |
|
| 823 |
void CoordinateEditorDialog::cutClicked() |
| 824 |
{ |
| 825 |
copyClicked(); |
| 826 |
clearClicked(); |
| 827 |
} |
| 828 |
|
| 829 |
void CoordinateEditorDialog::copyClicked() |
| 830 |
{ |
| 831 |
qApp->clipboard()->setText(m_ui->text->document()->toPlainText()); |
| 832 |
} |
| 833 |
|
| 834 |
void CoordinateEditorDialog::pasteClicked() |
| 835 |
{ |
| 836 |
const QMimeData* mimeData = qApp->clipboard()->mimeData(); |
| 837 |
m_ui->text->document()->setPlainText( |
| 838 |
(mimeData && mimeData->hasText()) ? mimeData->text() : ""); |
| 839 |
} |
| 840 |
|
| 841 |
void CoordinateEditorDialog::revertClicked() |
| 842 |
{ |
| 843 |
updateText(); |
| 844 |
} |
| 845 |
|
| 846 |
void CoordinateEditorDialog::clearClicked() |
| 847 |
{ |
| 848 |
m_ui->text->document()->clear(); |
| 849 |
} |
| 850 |
|
| 851 |
} // namespace Avogadro::QtPlugins |