Debian Codegraph @

avogadro/qtgui/interfacescript.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 "interfacescript.h"
7
8 #include <avogadro/core/coordinateblockgenerator.h>
9 #include <avogadro/core/molecule.h>
10
11 #include <avogadro/io/fileformat.h>
12 #include <avogadro/io/fileformatmanager.h>
13
14 #include <avogadro/qtgui/generichighlighter.h>
15 #include <avogadro/qtgui/molecule.h>
16 #include <avogadro/qtgui/pythonscript.h>
17 #include <avogadro/qtgui/rwmolecule.h>
18
19 #include <QtCore/QDebug>
20 #include <QtCore/QFile>
21 #include <QtCore/QJsonArray>
22 #include <QtCore/QJsonDocument>
23
24 #include <QtWidgets/QMessageBox>
25
26 namespace Avogadro::QtGui {
27
28 using QtGui::GenericHighlighter;
29 using QtGui::PythonScript;
30
31 // Strip any leading non-JSON output (e.g. deprecation warnings printed to
32 // stdout by third-party libraries). Find the first '{' or '['.
33 static void stripLeadingNonJson(QByteArray& data)
34 {
35 qsizetype jsonObj = data.indexOf('{');
36 qsizetype jsonArr = data.indexOf('[');
37 qsizetype jsonStart = (jsonObj < 0) ? jsonArr
38 : (jsonArr < 0) ? jsonObj
39 : qMin(jsonObj, jsonArr);
40 if (jsonStart > 0) {
41 if (!qgetenv("AVO_PYTHON_SCRIPT_DEBUG").isEmpty()) {
42 qDebug() << "InterfaceScript: stripping leading non-JSON output:\n"
43 << data.left(jsonStart);
44 }
45 data = data.mid(jsonStart);
46 }
47 }
48
49 InterfaceScript::InterfaceScript(const QString& scriptFilePath_,
50 QObject* parent_)
51 : QObject(parent_), m_interpreter(new PythonScript(scriptFilePath_, this)),
52 m_moleculeExtension(QStringLiteral("Unknown"))
53 {
54 }
55
56 InterfaceScript::InterfaceScript(QObject* parent_)
57 : QObject(parent_), m_interpreter(new PythonScript(this)),
58 m_moleculeExtension(QStringLiteral("Unknown"))
59 {
60 }
61
62 InterfaceScript::~InterfaceScript() {}
63
64 bool InterfaceScript::debug() const
65 {
66 return m_interpreter->debug();
67 }
68
69 QJsonObject InterfaceScript::options() const
70 {
71 m_errors.clear();
72 if (m_options.isEmpty()) {
73 qDeleteAll(m_highlightStyles.values());
74 m_highlightStyles.clear();
75
76 // Retrieve/set options
77 QByteArray json = m_interpreter->execute(
78 QStringList() << QStringLiteral("--print-options"));
79
80 if (m_interpreter->hasErrors()) {
81 m_errors << m_interpreter->errorList();
82 return m_options;
83 }
84
85 QJsonDocument doc;
86 if (!parseJson(json, doc))
87 return m_options;
88
89 if (!doc.isObject()) {
90 m_errors << tr("script --print-options output must be an JSON object "
91 "at top level. Received:\n%1")
92 .arg(json.constData());
93 return m_options;
94 }
95
96 m_options = doc.object();
97
98 if (m_options.contains(QStringLiteral("highlightStyles")) &&
99 m_options.value(QStringLiteral("highlightStyles")).isArray()) {
100 if (!parseHighlightStyles(
101 m_options.value(QStringLiteral("highlightStyles")).toArray())) {
102 qDebug() << "Failed to parse highlighting styles.";
103 }
104 }
105 }
106
107 // Check if the generator needs to read a molecule.
108 m_moleculeExtension = QLatin1String("cjson");
109 if (m_options.contains(QStringLiteral("inputMoleculeFormat")) &&
110 m_options[QStringLiteral("inputMoleculeFormat")].isString()) {
111 m_moleculeExtension =
112 m_options[QStringLiteral("inputMoleculeFormat")].toString();
113 }
114
115 return m_options;
116 }
117
118 QString InterfaceScript::displayName() const
119 {
120 m_errors.clear();
121 if (m_displayName.isEmpty()) {
122 if (m_interpreter->isPackageMode()) {
123 m_displayName = m_interpreter->packageDisplayName().trimmed();
124 if (m_displayName.isEmpty())
125 m_displayName = m_interpreter->packageIdentifier().trimmed();
126 } else {
127 m_displayName = QString(m_interpreter->execute(
128 QStringList() << QStringLiteral("--display-name")));
129 m_errors << m_interpreter->errorList();
130 m_displayName = m_displayName.trimmed();
131 }
132 }
133
134 return m_displayName;
135 }
136
137 QString InterfaceScript::menuPath() const
138 {
139 m_errors.clear();
140 if (m_menuPath.isEmpty()) {
141 m_menuPath = QString(
142 m_interpreter->execute(QStringList() << QStringLiteral("--menu-path")));
143 m_errors << m_interpreter->errorList();
144 m_menuPath = m_menuPath.trimmed();
145 }
146
147 return m_menuPath;
148 }
149
150 QString InterfaceScript::scriptFilePath() const
151 {
152 return m_interpreter->scriptFilePath();
153 }
154
155 void InterfaceScript::setScriptFilePath(const QString& scriptFile)
156 {
157 reset();
158 m_interpreter->setScriptFilePath(scriptFile);
159 }
160
161 void InterfaceScript::setOptionsJson(const QJsonObject& opts)
162 {
163 m_options = opts;
164 }
165
166 void InterfaceScript::reset()
167 {
168 m_interpreter->setDefaultPythonInterpreter();
169 m_interpreter->setScriptFilePath(QString());
170 m_moleculeExtension = QLatin1String("Unknown");
171 m_displayName = QString();
172 m_options = QJsonObject();
173 m_warnings.clear();
174 m_errors.clear();
175 m_filenames.clear();
176 m_mainFileName.clear();
177 m_files.clear();
178 m_fileHighlighters.clear();
179 m_highlightStyles.clear();
180 }
181
182 bool InterfaceScript::runCommand(const QJsonObject& options_,
183 Core::Molecule* mol)
184 {
185 m_errors.clear();
186 m_warnings.clear();
187 m_filenames.clear();
188 qDeleteAll(m_fileHighlighters.values());
189 m_fileHighlighters.clear();
190 m_mainFileName.clear();
191 m_files.clear();
192
193 // Add the molecule file to the options
194 QJsonObject allOptions(options_);
195 if (!insertMolecule(allOptions, *mol))
196 return false;
197
198 connect(m_interpreter, &PythonScript::finished, this,
199 &::Avogadro::QtGui::InterfaceScript::commandFinished);
200 // Package-mode scripts take no command-line flag; the identifier is already
201 // the positional argument and JSON arrives on stdin (mirrors
202 // InputGenerator::generateInput() which passes QStringList()).
203 QStringList runArgs;
204 if (!m_interpreter->isPackageMode())
205 runArgs << QStringLiteral("--run-command");
206 m_interpreter->asyncExecute(runArgs, QJsonDocument(allOptions).toJson());
207 return true;
208 }
209
210 void InterfaceScript::commandFinished()
211 {
212 emit finished();
213 }
214
215 bool InterfaceScript::processCommand(Core::Molecule* mol)
216 {
217 if (m_interpreter == nullptr)
218 return false;
219
220 QByteArray json(m_interpreter->asyncResponse());
221
222 if (m_interpreter->hasErrors()) {
223 m_errors << m_interpreter->errorList();
224 return false;
225 }
226
227 stripLeadingNonJson(json);
228
229 QJsonDocument doc;
230 if (!parseJson(json, doc)) {
231 return false;
232 }
233
234 // Update cache
235 bool result = true;
236 if (doc.isObject()) {
237 QJsonObject obj = doc.object();
238
239 // Check for any warnings:
240 if (obj.contains(QStringLiteral("warnings"))) {
241 if (obj[QStringLiteral("warnings")].isArray()) {
242 foreach (const QJsonValue& warning, obj["warnings"].toArray()) {
243 if (warning.isString())
244 m_warnings << warning.toString();
245 else
246 m_errors << tr("Non-string warning returned.");
247 }
248 } else {
249 m_errors << tr("'warnings' member is not an array.");
250 }
251 }
252
253 m_moleculeExtension = "cjson";
254 if (obj.contains("moleculeFormat") && obj["moleculeFormat"].isString()) {
255 m_moleculeExtension = obj["moleculeFormat"].toString();
256 }
257
258 Io::FileFormatManager& formats = Io::FileFormatManager::instance();
259 QScopedPointer<Io::FileFormat> format(
260 formats.newFormatFromFileExtension(m_moleculeExtension.toStdString()));
261
262 if (format.isNull()) {
263 m_errors << tr("Error reading molecule representation: "
264 "Unrecognized file format: %1")
265 .arg(m_moleculeExtension);
266 return false;
267 }
268
269 auto* guiMol = static_cast<QtGui::Molecule*>(mol);
270 QtGui::Molecule newMol(guiMol->parent());
271 if (m_moleculeExtension == "cjson") {
272 // convert the "cjson" field to a string
273 QJsonObject cjsonObj = obj["cjson"].toObject();
274 QJsonDocument doc2(cjsonObj);
275 QString strCJSON(doc2.toJson(QJsonDocument::Compact));
276 if (!strCJSON.isEmpty()) {
277 result = format->readString(strCJSON.toStdString(), newMol);
278 }
279 } else if (obj.contains(m_moleculeExtension) &&
280 obj[m_moleculeExtension].isString()) {
281 QString strFile = obj[m_moleculeExtension].toString();
282 result = format->readString(strFile.toStdString(), newMol);
283 }
284
285 // check if the script wants us to perceive bonds first
286 if (obj["bond"].toBool()) {
287 newMol.perceiveBondsSimple();
288 newMol.perceiveBondOrders();
289 }
290
291 // how do we handle this result?
292 if (obj["readProperties"].toBool()) {
293 guiMol->readProperties(newMol);
294 guiMol->emitChanged(Molecule::Properties | Molecule::Added);
295 } else if (obj["append"].toBool()) {
296 guiMol->undoMolecule()->appendMolecule(newMol, m_displayName);
297 } else { // replace the whole molecule
298 Molecule::MoleculeChanges changes = (Molecule::Atoms | Molecule::Bonds |
299 Molecule::Added | Molecule::Removed);
300 guiMol->undoMolecule()->modifyMolecule(newMol, changes, m_displayName);
301 }
302
303 // select some atoms
304 if (obj.contains("selectedAtoms") && obj["selectedAtoms"].isArray()) {
305 QJsonArray selectedList = obj["selectedAtoms"].toArray();
306 for (auto&& i : selectedList) {
307 if (i.isDouble()) {
308 auto index = static_cast<Index>(i.toDouble());
309 if (index < guiMol->atomCount())
310 guiMol->undoMolecule()->setAtomSelected(index, true);
311 }
312 }
313 guiMol->emitChanged(Molecule::Atoms);
314 }
315
316 // check if there are messages for the user
317 auto extractMessage = [](const QJsonValue& val) -> QString {
318 if (val.isString())
319 return val.toString();
320 if (val.isArray()) {
321 QString result;
322 const QJsonArray arr = val.toArray();
323 for (const auto& item : arr) {
324 if (item.isString())
325 result += item.toString() + '\n';
326 }
327 return result;
328 }
329 return {};
330 };
331
332 if (obj.contains("message")) {
333 QString message = extractMessage(obj["message"]);
334 if (!message.isEmpty()) {
335 QMessageBox::information(qobject_cast<QWidget*>(parent()),
336 tr("%1 Message").arg(m_displayName), message);
337 }
338 }
339 if (obj.contains("warning")) {
340 QString message = extractMessage(obj["warning"]);
341 if (!message.isEmpty()) {
342 QMessageBox::warning(qobject_cast<QWidget*>(parent()),
343 tr("%1 Warning").arg(m_displayName), message);
344 }
345 }
346 if (obj.contains("error")) {
347 QString message = extractMessage(obj["error"]);
348 if (!message.isEmpty()) {
349 QMessageBox::critical(qobject_cast<QWidget*>(parent()),
350 tr("%1 Error").arg(m_displayName), message);
351 }
352 }
353 }
354 return result;
355 }
356
357 bool InterfaceScript::generateInput(const QJsonObject& options_,
358 const Core::Molecule& mol)
359 {
360 m_errors.clear();
361 m_warnings.clear();
362 m_filenames.clear();
363 qDeleteAll(m_fileHighlighters.values());
364 m_fileHighlighters.clear();
365 m_mainFileName.clear();
366 m_files.clear();
367
368 // Add the molecule file to the options
369 QJsonObject allOptions(options_);
370 if (!insertMolecule(allOptions, mol))
371 return false;
372
373 QByteArray json(
374 m_interpreter->execute(QStringList() << QStringLiteral("--generate-input"),
375 QJsonDocument(allOptions).toJson()));
376
377 if (m_interpreter->hasErrors()) {
378 m_errors << m_interpreter->errorList();
379 return false;
380 }
381
382 QJsonDocument doc;
383 if (!parseJson(json, doc))
384 return false;
385
386 // Update cache
387 bool result = true;
388 if (doc.isObject()) {
389 QJsonObject obj = doc.object();
390
391 // Check for any warnings:
392 if (obj.contains(QStringLiteral("warnings"))) {
393 if (obj[QStringLiteral("warnings")].isArray()) {
394 foreach (const QJsonValue& warning, obj["warnings"].toArray()) {
395 if (warning.isString())
396 m_warnings << warning.toString();
397 else
398 m_errors << tr("Non-string warning returned.");
399 }
400 } else {
401 m_errors << tr("'warnings' member is not an array.");
402 }
403 }
404
405 // Extract input file text:
406 if (obj.contains(QStringLiteral("files"))) {
407 if (obj[QStringLiteral("files")].isArray()) {
408 foreach (const QJsonValue& file, obj["files"].toArray()) {
409 if (file.isObject()) {
410 QJsonObject fileObj = file.toObject();
411 if (fileObj[QStringLiteral("filename")].isString()) {
412 QString fileName = fileObj[QStringLiteral("filename")].toString();
413 QString contents;
414 if (fileObj[QStringLiteral("contents")].isString()) {
415 contents = fileObj[QStringLiteral("contents")].toString();
416 } else if (fileObj[QStringLiteral("filePath")].isString()) {
417 QFile refFile(fileObj[QStringLiteral("filePath")].toString());
418 if (refFile.exists() && refFile.open(QFile::ReadOnly)) {
419 contents = QString(refFile.readAll());
420 } else {
421 contents = tr("Reference file '%1' does not exist.")
422 .arg(refFile.fileName());
423 m_warnings << tr("Error populating file %1: %2")
424 .arg(fileName, contents);
425 }
426 } else {
427 m_errors << tr("File '%1' poorly formed. Missing string "
428 "'contents' or 'filePath' members.")
429 .arg(fileName);
430 contents = m_errors.back();
431 result = false;
432 }
433 replaceKeywords(contents, mol);
434 m_filenames << fileName;
435 m_files.insert(fileObj[QStringLiteral("filename")].toString(),
436 contents);
437
438 // Concatenate the requested styles for this input file.
439 if (fileObj[QStringLiteral("highlightStyles")].isArray()) {
440 auto* highlighter(new GenericHighlighter(this));
441 foreach (const QJsonValue& styleVal,
442 fileObj["highlightStyles"].toArray()) {
443 if (styleVal.isString()) {
444 QString styleName(styleVal.toString());
445 if (m_highlightStyles.contains(styleName)) {
446 *highlighter += *m_highlightStyles[styleName];
447 } else {
448 qDebug() << "Cannot find highlight style '" << styleName
449 << "' for file '" << fileName << "'";
450 }
451 }
452 }
453 if (highlighter->ruleCount() > 0)
454 m_fileHighlighters[fileName] = highlighter;
455 else
456 highlighter->deleteLater();
457 }
458 } else {
459 result = false;
460 m_errors << tr("Malformed file entry: filename/contents missing"
461 " or not strings:\n%1")
462 .arg(QString(QJsonDocument(fileObj).toJson()));
463 } // end if/else filename and contents are strings
464 } else {
465 result = false;
466 m_errors << tr("Malformed file entry at index %1: Not an object.")
467 .arg(m_filenames.size());
468 } // end if/else file is JSON object
469 } // end foreach file
470 } else {
471 result = false;
472 m_errors << tr("'files' member not an array.");
473 } // end if obj["files"] is JSON array
474 } else {
475 result = false;
476 m_errors << tr("'files' member missing.");
477 } // end if obj contains "files"
478
479 // Extract main input filename:
480 if (obj.contains(QStringLiteral("mainFile"))) {
481 if (obj[QStringLiteral("mainFile")].isString()) {
482 QString mainFile = obj[QStringLiteral("mainFile")].toString();
483 if (m_filenames.contains(mainFile)) {
484 m_mainFileName = mainFile;
485 } else {
486 result = false;
487 m_errors << tr("'mainFile' member does not refer to an entry in "
488 "'files'.");
489 } // end if/else mainFile is known
490 } else {
491 result = false;
492 m_errors << tr("'mainFile' member must be a string.");
493 } // end if/else mainFile is string
494 } else {
495 // If no mainFile is specified and there is only one file, use it as the
496 // main file. Otherwise, don't set a main input file -- all files will
497 // be treated as supplemental input files
498 if (m_filenames.size() == 1)
499 m_mainFileName = m_filenames.first();
500 } // end if/else object contains mainFile
501 } else {
502 result = false;
503 m_errors << tr("Response must be a JSON object at top-level.");
504 }
505
506 if (result == false)
507 m_errors << tr("Script output:\n%1").arg(QString(json));
508
509 return result;
510 }
511
512 int InterfaceScript::numberOfInputFiles() const
513 {
514 return m_filenames.size();
515 }
516
517 QStringList InterfaceScript::fileNames() const
518 {
519 return m_filenames;
520 }
521
522 QString InterfaceScript::mainFileName() const
523 {
524 return m_mainFileName;
525 }
526
527 QString InterfaceScript::fileContents(const QString& fileName) const
528 {
529 return m_files.value(fileName, QString());
530 }
531
532 GenericHighlighter* InterfaceScript::createFileHighlighter(
533 const QString& fileName) const
534 {
535 GenericHighlighter* toClone(m_fileHighlighters.value(fileName, nullptr));
536 return toClone ? new GenericHighlighter(*toClone) : toClone;
537 }
538
539 void InterfaceScript::setDebug(bool d)
540 {
541 m_interpreter->setDebug(d);
542 }
543
544 bool InterfaceScript::parseJson(const QByteArray& json,
545 QJsonDocument& doc) const
546 {
547 QJsonParseError error;
548 doc = QJsonDocument::fromJson(json, &error);
549
550 if (error.error != QJsonParseError::NoError) {
551 m_errors << tr("Parse error at offset %L1: '%2'\nRaw JSON:\n\n%3")
552 .arg(error.offset)
553 .arg(error.errorString())
554 .arg(QString(json));
555 return false;
556 }
557 return true;
558 }
559
560 bool InterfaceScript::insertMolecule(QJsonObject& json,
561 const Core::Molecule& mol) const
562 {
563 // Update the cached options if the format is not set
564 if (m_moleculeExtension == QLatin1String("Unknown"))
565 options();
566
567 if (m_moleculeExtension == QLatin1String("None"))
568 return true;
569
570 // Always insert the selected atoms
571 QJsonArray selectedList;
572 for (Index i = 0; i < mol.atomCount(); ++i) {
573 if (mol.atomSelected(i))
574 selectedList.append(static_cast<qint64>(i));
575 }
576 json.insert("selectedAtoms", selectedList);
577
578 // insert the total charge
579 json.insert("charge", mol.totalCharge());
580
581 // insert the spin multiplicity
582 json.insert("spin", mol.totalSpinMultiplicity());
583
584 Io::FileFormatManager& formats = Io::FileFormatManager::instance();
585 QScopedPointer<Io::FileFormat> format(
586 formats.newFormatFromFileExtension(m_moleculeExtension.toStdString()));
587 QScopedPointer<Io::FileFormat> cjsonFormat(
588 formats.newFormatFromFileExtension("cjson"));
589
590 // If we want something *other* than CJSON, check that we can supply that
591 // format
592 if (format.isNull()) {
593 m_errors << tr("Error writing molecule representation to string: "
594 "Unrecognized file format: %1")
595 .arg(m_moleculeExtension);
596 return false;
597 }
598
599 std::string str;
600 if (!format->writeString(str, mol)) {
601 m_errors << tr("Error writing molecule representation to string: %1")
602 .arg(QString::fromStdString(format->error()));
603 return false;
604 }
605
606 // if we need a different format, insert it
607 if (m_moleculeExtension != QLatin1String("cjson")) {
608 json.insert(m_moleculeExtension, QJsonValue(QString::fromStdString(str)));
609 }
610
611 // We will *always* write the CJSON representation
612 // Embed CJSON as actual JSON, rather than a string,
613 // .. so we'll have to re-parse it
614 cjsonFormat->writeString(str, mol);
615 QJsonParseError error;
616 QJsonDocument doc = QJsonDocument::fromJson(str.c_str(), &error);
617 if (error.error != QJsonParseError::NoError) {
618 m_errors << tr("Error generating cjson object: Parse error at offset %1: "
619 "%2\nRaw JSON:\n\n%3")
620 .arg(error.offset)
621 .arg(error.errorString())
622 .arg(QString::fromStdString(str));
623 return false;
624 }
625
626 if (!doc.isObject()) {
627 m_errors << tr("Error generator cjson object: Parsed JSON is not an "
628 "object:\n%1")
629 .arg(QString::fromStdString(str));
630 return false;
631 }
632
633 json.insert("cjson", doc.object());
634
635 return true;
636 }
637
638 QString InterfaceScript::generateCoordinateBlock(
639 const QString& spec, const Core::Molecule& mol) const
640 {
641 Core::CoordinateBlockGenerator gen;
642 gen.setMolecule(&mol);
643 gen.setSpecification(spec.toStdString());
644 std::string tmp(gen.generateCoordinateBlock());
645 if (!tmp.empty())
646 tmp.resize(tmp.size() - 1); // Pop off the trailing newline
647 return QString::fromStdString(tmp);
648 }
649
650 void InterfaceScript::replaceKeywords(QString& str,
651 const Core::Molecule& mol) const
652 {
653 // Simple keywords:
654 str.replace(QLatin1String("$$atomCount$$"), QString::number(mol.atomCount()));
655 str.replace(QLatin1String("$$bondCount$$"), QString::number(mol.bondCount()));
656
657 // Find each coordinate block keyword in the file, then generate and replace
658 // it with the appropriate values.
659 QRegularExpression coordParser(R"(\$\$coords:([^\$]*)\$\$)");
660 QRegularExpressionMatch match;
661 int ind = 0;
662 // Not sure while this needs to be a while statement since we replace all in
663 // one go? We never iterate ind...
664 while ((match = coordParser.match(str, ind)).hasMatch()) {
665 // Extract spec and prepare the replacement
666 const QString keyword = match.captured(0);
667 const QString spec = match.captured(1);
668
669 // Replace all blocks with this signature
670 str.replace(keyword, generateCoordinateBlock(spec, mol));
671
672 } // end for coordinate block
673 }
674
675 bool InterfaceScript::parseHighlightStyles(const QJsonArray& json) const
676 {
677 bool result(true);
678 foreach (QJsonValue styleVal, json) {
679 if (!styleVal.isObject()) {
680 qDebug() << "Non-object in highlightStyles array.";
681 result = false;
682 continue;
683 }
684 QJsonObject styleObj(styleVal.toObject());
685
686 if (!styleObj.contains(QStringLiteral("style"))) {
687 qDebug() << "Style object missing 'style' member.";
688 result = false;
689 continue;
690 }
691 if (!styleObj.value(QStringLiteral("style")).isString()) {
692 qDebug() << "Style object contains non-string 'style' member.";
693 result = false;
694 continue;
695 }
696 QString styleName(styleObj.value(QStringLiteral("style")).toString());
697
698 if (m_highlightStyles.contains(styleName)) {
699 qDebug() << "Duplicate highlight style: " << styleName;
700 result = false;
701 continue;
702 }
703
704 if (!styleObj.contains(QStringLiteral("rules"))) {
705 qDebug() << "Style object" << styleName << "missing 'rules' member.";
706 result = false;
707 continue;
708 }
709 if (!styleObj.value(QStringLiteral("rules")).isArray()) {
710 qDebug() << "Style object" << styleName
711 << "contains non-array 'rules' member.";
712 result = false;
713 continue;
714 }
715 QJsonArray rulesArray(styleObj.value(QStringLiteral("rules")).toArray());
716
717 auto* highlighter(
718 new GenericHighlighter(const_cast<InterfaceScript*>(this)));
719 if (!parseRules(rulesArray, *highlighter)) {
720 qDebug() << "Error parsing style" << styleName << '\n'
721 << QString(QJsonDocument(styleObj).toJson());
722 highlighter->deleteLater();
723 result = false;
724 continue;
725 }
726 m_highlightStyles.insert(styleName, highlighter);
727 }
728
729 return result;
730 }
731
732 bool InterfaceScript::parseRules(const QJsonArray& json,
733 GenericHighlighter& highlighter) const
734 {
735 bool result(true);
736 foreach (QJsonValue ruleVal, json) {
737 if (!ruleVal.isObject()) {
738 qDebug() << "Rule is not an object.";
739 result = false;
740 continue;
741 }
742 QJsonObject ruleObj(ruleVal.toObject());
743
744 if (!ruleObj.contains(QStringLiteral("patterns"))) {
745 qDebug() << "Rule missing 'patterns' array:" << '\n'
746 << QString(QJsonDocument(ruleObj).toJson());
747 result = false;
748 continue;
749 }
750 if (!ruleObj.value(QStringLiteral("patterns")).isArray()) {
751 qDebug() << "Rule 'patterns' member is not an array:" << '\n'
752 << QString(QJsonDocument(ruleObj).toJson());
753 result = false;
754 continue;
755 }
756 QJsonArray patternsArray(
757 ruleObj.value(QStringLiteral("patterns")).toArray());
758
759 if (!ruleObj.contains(QStringLiteral("format"))) {
760 qDebug() << "Rule missing 'format' object:" << '\n'
761 << QString(QJsonDocument(ruleObj).toJson());
762 result = false;
763 continue;
764 }
765 if (!ruleObj.value(QStringLiteral("format")).isObject()) {
766 qDebug() << "Rule 'format' member is not an object:" << '\n'
767 << QString(QJsonDocument(ruleObj).toJson());
768 result = false;
769 continue;
770 }
771 QJsonObject formatObj(ruleObj.value(QStringLiteral("format")).toObject());
772
773 GenericHighlighter::Rule& rule = highlighter.addRule();
774
775 foreach (QJsonValue patternVal, patternsArray) {
776 QRegularExpression pattern;
777 if (!parsePattern(patternVal, pattern)) {
778 qDebug() << "Error while parsing pattern:" << '\n'
779 << QString(QJsonDocument(patternVal.toObject()).toJson());
780 result = false;
781 continue;
782 }
783 rule.addPattern(pattern);
784 }
785
786 QTextCharFormat format;
787 if (!parseFormat(formatObj, format)) {
788 qDebug() << "Error while parsing format:" << '\n'
789 << QString(QJsonDocument(formatObj).toJson());
790 result = false;
791 }
792 rule.setFormat(format);
793 }
794
795 return result;
796 }
797
798 bool InterfaceScript::parseFormat(const QJsonObject& json,
799 QTextCharFormat& format) const
800 {
801 // Check for presets first:
802 if (json.contains(QStringLiteral("preset"))) {
803 if (!json[QStringLiteral("preset")].isString()) {
804 qDebug() << "Preset is not a string.";
805 return false;
806 }
807
808 QString preset(json[QStringLiteral("preset")].toString());
809 /// @todo Store presets in a singleton that can be configured in the GUI,
810 /// rather than hardcoding them.
811 if (preset == QLatin1String("title")) {
812 format.setFontFamily(QStringLiteral("serif"));
813 format.setForeground(Qt::darkGreen);
814 format.setFontWeight(QFont::Bold);
815 } else if (preset == QLatin1String("keyword")) {
816 format.setFontFamily(QStringLiteral("mono"));
817 format.setForeground(Qt::darkBlue);
818 } else if (preset == QLatin1String("property")) {
819 format.setFontFamily(QStringLiteral("mono"));
820 format.setForeground(Qt::darkRed);
821 } else if (preset == QLatin1String("literal")) {
822 format.setFontFamily(QStringLiteral("mono"));
823 format.setForeground(Qt::darkMagenta);
824 } else if (preset == QLatin1String("comment")) {
825 format.setFontFamily(QStringLiteral("serif"));
826 format.setForeground(Qt::darkGreen);
827 format.setFontItalic(true);
828 } else {
829 qDebug() << "Invalid style preset: " << preset;
830 return false;
831 }
832 return true;
833 }
834
835 // Extract an RGB tuple from 'array' as a QBrush:
836 struct
837 {
838 QBrush operator()(const QJsonArray& array, bool* ok)
839 {
840 *ok = false;
841 QBrush result;
842
843 if (array.size() != 3)
844 return result;
845
846 int rgb[3];
847 for (int i = 0; i < 3; ++i) {
848 if (!array.at(i).isDouble())
849 return result;
850 rgb[i] = static_cast<int>(array.at(i).toDouble());
851 if (rgb[i] < 0 || rgb[i] > 255) {
852 qDebug() << "Warning: Color component value invalid: " << rgb[i]
853 << " (Valid range is 0-255).";
854 }
855 }
856
857 result.setColor(QColor(rgb[0], rgb[1], rgb[2]));
858 result.setStyle(Qt::SolidPattern);
859 *ok = true;
860 return result;
861 }
862 } colorParser;
863
864 if (json.contains(QStringLiteral("foreground")) &&
865 json.value(QStringLiteral("foreground")).isArray()) {
866 QJsonArray foregroundArray(
867 json.value(QStringLiteral("foreground")).toArray());
868 bool ok;
869 format.setForeground(colorParser(foregroundArray, &ok));
870 if (!ok)
871 return false;
872 }
873
874 if (json.contains(QStringLiteral("background")) &&
875 json.value(QStringLiteral("background")).isArray()) {
876 QJsonArray backgroundArray(
877 json.value(QStringLiteral("background")).toArray());
878 bool ok;
879 format.setBackground(colorParser(backgroundArray, &ok));
880 if (!ok)
881 return false;
882 }
883
884 if (json.contains(QStringLiteral("attributes")) &&
885 json.value(QStringLiteral("attributes")).isArray()) {
886 QJsonArray attributesArray(
887 json.value(QStringLiteral("attributes")).toArray());
888 format.setFontWeight(attributesArray.contains(QLatin1String("bold"))
889 ? QFont::Bold
890 : QFont::Normal);
891 format.setFontItalic(attributesArray.contains(QLatin1String("italic")));
892 format.setFontUnderline(
893 attributesArray.contains(QLatin1String("underline")));
894 }
895
896 if (json.contains(QStringLiteral("family")) &&
897 json.value(QStringLiteral("family")).isString()) {
898 format.setFontFamily(json.value(QStringLiteral("family")).toString());
899 }
900
901 return true;
902 }
903
904 bool InterfaceScript::parsePattern(const QJsonValue& json,
905 QRegularExpression& pattern) const
906 {
907 if (!json.isObject())
908 return false;
909
910 QJsonObject patternObj(json.toObject());
911 QString regexPattern;
912 QRegularExpression::PatternOptions patternOptions =
913 QRegularExpression::NoPatternOption;
914
915 if (patternObj.contains(QStringLiteral("regexp")) &&
916 patternObj.value(QStringLiteral("regexp")).isString()) {
917 // Use the provided regular expression as-is
918 regexPattern = patternObj.value(QStringLiteral("regexp")).toString();
919 } else if (patternObj.contains(QStringLiteral("wildcard")) &&
920 patternObj.value(QStringLiteral("wildcard")).isString()) {
921 // Convert wildcard pattern (* -> .* and ? -> .)
922 QString wildcard = patternObj.value(QStringLiteral("wildcard")).toString();
923 regexPattern = QRegularExpression::escape(wildcard)
924 .replace("\\*", ".*")
925 .replace("\\?", ".");
926 } else if (patternObj.contains(QStringLiteral("string")) &&
927 patternObj.value(QStringLiteral("string")).isString()) {
928 // Escape the string so it is treated literally in the regex
929 regexPattern = QRegularExpression::escape(
930 patternObj.value(QStringLiteral("string")).toString());
931 } else {
932 return false;
933 }
934
935 // Set case sensitivity if specified
936 if (patternObj.contains(QStringLiteral("caseSensitive"))) {
937 bool caseSensitive =
938 patternObj.value(QStringLiteral("caseSensitive")).toBool(true);
939 if (!caseSensitive) {
940 patternOptions |= QRegularExpression::CaseInsensitiveOption;
941 }
942 }
943
944 // Set the final pattern with options
945 pattern = QRegularExpression(regexPattern, patternOptions);
946
947 return pattern.isValid();
948 }
949
950 } // namespace Avogadro::QtGui