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