Debian Codegraph @

avogadro/molequeue/inputgenerator.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 "inputgenerator.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/pythonscript.h>
16
17 #include <QtCore/QDebug>
18 #include <QtCore/QFile>
19 #include <QtCore/QJsonArray>
20 #include <QtCore/QJsonDocument>
21
22 #include <QGuiApplication>
23 #include <QStyleHints>
24 #include <QColor>
25 #include <QPalette>
26 #include <unordered_map>
27
28 namespace Avogadro::MoleQueue {
29
30 using QtGui::GenericHighlighter;
31 using QtGui::PythonScript;
32
33 InputGenerator::InputGenerator(const QString& scriptFilePath_, QObject* parent_)
34 : QObject(parent_), m_interpreter(new PythonScript(scriptFilePath_, this)),
35 m_moleculeExtension("Unknown")
36 {
37 }
38
39 InputGenerator::InputGenerator(QObject* parent_)
40 : QObject(parent_), m_interpreter(new PythonScript(this)),
41 m_moleculeExtension("Unknown")
42 {
43 }
44
45 bool InputGenerator::debug() const
46 {
47 return m_interpreter->debug();
48 }
49
50 QJsonObject InputGenerator::options() const
51 {
52 m_errors.clear();
53 if (m_options.isEmpty()) {
54 qDeleteAll(m_highlightStyles.values());
55 m_highlightStyles.clear();
56
57 // Retrieve/set options
58 QByteArray json =
59 m_interpreter->execute(QStringList() << "--print-options");
60
61 if (m_interpreter->hasErrors()) {
62 m_errors << m_interpreter->errorList();
63 return m_options;
64 }
65
66 QJsonDocument doc;
67 if (!parseJson(json, doc))
68 return m_options;
69
70 if (!doc.isObject()) {
71 m_errors << tr("script --print-options output must be an JSON object "
72 "at top level. Received:\n%1")
73 .arg(json.constData());
74 return m_options;
75 }
76
77 m_options = doc.object();
78
79 // Check if the generator needs to read a molecule.
80 m_moleculeExtension = "None";
81 if (m_options.contains("inputMoleculeFormat") &&
82 m_options["inputMoleculeFormat"].isString()) {
83 m_moleculeExtension = m_options["inputMoleculeFormat"].toString();
84 }
85
86 if (m_options.contains("highlightStyles") &&
87 m_options.value("highlightStyles").isArray()) {
88 if (!parseHighlightStyles(m_options.value("highlightStyles").toArray())) {
89 qDebug() << "Failed to parse highlighting styles.";
90 }
91 }
92 }
93
94 return m_options;
95 }
96
97 QString InputGenerator::displayName() const
98 {
99 m_errors.clear();
100 if (m_displayName.isEmpty()) {
101 if (m_interpreter->isPackageMode()) {
102 m_displayName = m_interpreter->packageDisplayName().trimmed();
103 if (m_displayName.isEmpty())
104 m_displayName = m_interpreter->packageIdentifier().trimmed();
105 } else {
106 m_displayName =
107 QString(m_interpreter->execute(QStringList() << "--display-name"));
108 m_errors << m_interpreter->errorList();
109 m_displayName = m_displayName.trimmed();
110 }
111 }
112
113 return m_displayName;
114 }
115
116 QString InputGenerator::scriptFilePath() const
117 {
118 return m_interpreter->scriptFilePath();
119 }
120
121 void InputGenerator::setScriptFilePath(const QString& scriptFile)
122 {
123 reset();
124 m_interpreter->setScriptFilePath(scriptFile);
125 }
126
127 void InputGenerator::setOptions(const QJsonObject& options)
128 {
129 m_options = options;
130
131 m_moleculeExtension = "None";
132 if (m_options.contains("inputMoleculeFormat") &&
133 m_options["inputMoleculeFormat"].isString()) {
134 m_moleculeExtension = m_options["inputMoleculeFormat"].toString();
135 }
136
137 if (m_options.contains("highlightStyles") &&
138 m_options.value("highlightStyles").isArray()) {
139 qDeleteAll(m_highlightStyles.values());
140 m_highlightStyles.clear();
141 if (!parseHighlightStyles(m_options.value("highlightStyles").toArray()))
142 qDebug() << "Failed to parse highlighting styles.";
143 }
144 }
145
146 void InputGenerator::reset()
147 {
148 m_interpreter->setDefaultPythonInterpreter();
149 m_interpreter->setScriptFilePath(QString());
150 m_moleculeExtension = "Unknown";
151 m_displayName = QString();
152 m_options = QJsonObject();
153 m_warnings.clear();
154 m_errors.clear();
155 m_filenames.clear();
156 m_mainFileName.clear();
157 m_files.clear();
158 m_fileHighlighters.clear();
159 m_highlightStyles.clear();
160 }
161
162 bool InputGenerator::generateInput(const QJsonObject& options_,
163 const Core::Molecule& mol)
164 {
165 m_errors.clear();
166 m_warnings.clear();
167 m_filenames.clear();
168 qDeleteAll(m_fileHighlighters.values());
169 m_fileHighlighters.clear();
170 m_mainFileName.clear();
171 m_files.clear();
172
173 // Add the molecule file to the options
174 QJsonObject allOptions(options_);
175 if (!insertMolecule(allOptions, mol))
176 return false;
177
178 // Pass options on stdin to avoid command-line length limits (e.g. Windows).
179 QByteArray jsonDoc = QJsonDocument(allOptions).toJson(QJsonDocument::Compact);
180 QByteArray json = m_interpreter->execute(QStringList(), jsonDoc);
181
182 if (m_interpreter->hasErrors()) {
183 m_errors << m_interpreter->errorList();
184 return false;
185 }
186
187 QJsonDocument doc;
188 if (!parseJson(json, doc))
189 return false;
190
191 // Update cache
192 bool result = true;
193 if (doc.isObject()) {
194 QJsonObject obj = doc.object();
195
196 // Check for any warnings:
197 if (obj.contains("warnings")) {
198 if (obj["warnings"].isArray()) {
199 foreach (const QJsonValue& warning, obj["warnings"].toArray()) {
200 if (warning.isString())
201 m_warnings << warning.toString();
202 else
203 m_errors << tr("Non-string warning returned.");
204 }
205 } else {
206 m_errors << tr("'warnings' member is not an array.");
207 }
208 }
209
210 // Extract input file text:
211 if (obj.contains("files")) {
212 if (obj["files"].isArray()) {
213 foreach (const QJsonValue& file, obj["files"].toArray()) {
214 if (file.isObject()) {
215 QJsonObject fileObj = file.toObject();
216 if (fileObj["filename"].isString()) {
217 QString fileName = fileObj["filename"].toString();
218 QString contents;
219 if (fileObj["contents"].isString()) {
220 contents = fileObj["contents"].toString();
221 } else if (fileObj["filePath"].isString()) {
222 QFile refFile(fileObj["filePath"].toString());
223 if (refFile.exists() && refFile.open(QFile::ReadOnly)) {
224 contents = QString(refFile.readAll());
225 } else {
226 contents = tr("Reference file '%1' does not exist.")
227 .arg(refFile.fileName());
228 m_warnings << tr("Error populating file %1: %2")
229 .arg(fileName, contents);
230 }
231 } else {
232 m_errors << tr("File '%1' poorly formed. Missing string "
233 "'contents' or 'filePath' members.")
234 .arg(fileName);
235 contents = m_errors.back();
236 result = false;
237 }
238 replaceKeywords(contents, mol);
239 m_filenames << fileName;
240 m_files.insert(fileObj["filename"].toString(), contents);
241
242 // Concatenate the requested styles for this input file.
243 if (fileObj["highlightStyles"].isArray()) {
244 auto* highlighter(new GenericHighlighter(this));
245 foreach (const QJsonValue& styleVal,
246 fileObj["highlightStyles"].toArray()) {
247 if (styleVal.isString()) {
248 QString styleName(styleVal.toString());
249 if (m_highlightStyles.contains(styleName)) {
250 *highlighter += *m_highlightStyles[styleName];
251 } else {
252 qDebug() << "Cannot find highlight style '" << styleName
253 << "' for file '" << fileName << "'";
254 }
255 }
256 }
257 if (highlighter->ruleCount() > 0)
258 m_fileHighlighters[fileName] = highlighter;
259 else
260 highlighter->deleteLater();
261 } else if (m_highlightStyles.contains("default")) {
262 auto* highlighter(new GenericHighlighter(this));
263 *highlighter += *m_highlightStyles["default"];
264 if (highlighter->ruleCount() > 0)
265 m_fileHighlighters[fileName] = highlighter;
266 else
267 highlighter->deleteLater();
268 }
269 } else {
270 result = false;
271 m_errors << tr("Malformed file entry: filename/contents missing"
272 " or not strings:\n%1")
273 .arg(QString(QJsonDocument(fileObj).toJson()));
274 } // end if/else filename and contents are strings
275 } else {
276 result = false;
277 m_errors << tr("Malformed file entry at index %1: Not an object.")
278 .arg(m_filenames.size());
279 } // end if/else file is JSON object
280 } // end foreach file
281 } else {
282 result = false;
283 m_errors << tr("'files' member not an array.");
284 } // end if obj["files"] is JSON array
285 } else {
286 result = false;
287 m_errors << tr("'files' member missing.");
288 } // end if obj contains "files"
289
290 // Extract main input filename:
291 if (obj.contains("mainFile")) {
292 if (obj["mainFile"].isString()) {
293 QString mainFile = obj["mainFile"].toString();
294 if (m_filenames.contains(mainFile)) {
295 m_mainFileName = mainFile;
296 } else {
297 result = false;
298 m_errors << tr("'mainFile' member does not refer to an entry in "
299 "'files'.");
300 } // end if/else mainFile is known
301 } else {
302 result = false;
303 m_errors << tr("'mainFile' member must be a string.");
304 } // end if/else mainFile is string
305 } else {
306 // If no mainFile is specified and there is only one file, use it as the
307 // main file. Otherwise, don't set a main input file -- all files will
308 // be treated as supplemental input files
309 if (m_filenames.size() == 1)
310 m_mainFileName = m_filenames.first();
311 } // end if/else object contains mainFile
312 } else {
313 result = false;
314 m_errors << tr("Response must be a JSON object at top-level.");
315 }
316
317 if (!result)
318 m_errors << tr("Script output:\n%1").arg(QString(json));
319
320 return result;
321 }
322
323 int InputGenerator::numberOfInputFiles() const
324 {
325 return m_filenames.size();
326 }
327
328 QStringList InputGenerator::fileNames() const
329 {
330 return m_filenames;
331 }
332
333 QString InputGenerator::mainFileName() const
334 {
335 return m_mainFileName;
336 }
337
338 QString InputGenerator::fileContents(const QString& fileName) const
339 {
340 return m_files.value(fileName, QString());
341 }
342
343 GenericHighlighter* InputGenerator::createFileHighlighter(
344 const QString& fileName) const
345 {
346 GenericHighlighter* toClone(m_fileHighlighters.value(fileName, nullptr));
347 return toClone ? new GenericHighlighter(*toClone) : toClone;
348 }
349
350 void InputGenerator::setDebug(bool d)
351 {
352 m_interpreter->setDebug(d);
353 }
354
355 bool InputGenerator::parseJson(const QByteArray& json, QJsonDocument& doc) const
356 {
357 QJsonParseError error;
358 doc = QJsonDocument::fromJson(json, &error);
359
360 if (error.error != QJsonParseError::NoError) {
361 m_errors << tr("Parse error at offset %L1: '%2'\nRaw JSON:\n\n%3")
362 .arg(error.offset)
363 .arg(error.errorString())
364 .arg(QString(json));
365 return false;
366 }
367 return true;
368 }
369
370 bool InputGenerator::insertMolecule(QJsonObject& json,
371 const Core::Molecule& mol) const
372 {
373 // Update the cached options if the format is not set
374 if (m_moleculeExtension == "Unknown")
375 options();
376
377 if (m_moleculeExtension == "None")
378 return true;
379
380 Io::FileFormatManager& formats = Io::FileFormatManager::instance();
381 QScopedPointer<Io::FileFormat> format(
382 formats.newFormatFromFileExtension(m_moleculeExtension.toStdString()));
383
384 if (format.isNull()) {
385 m_errors << tr("Error saving molecule representation to string: "
386 "Unrecognized file format: %1")
387 .arg(m_moleculeExtension);
388 return false;
389 }
390
391 std::string str;
392 if (!format->writeString(str, mol)) {
393 m_errors << tr("Error saving molecule representation to string: %1",
394 "%1 = error message")
395 .arg(QString::fromStdString(format->error()));
396 return false;
397 }
398
399 if (m_moleculeExtension != "cjson") {
400 json.insert(m_moleculeExtension, QJsonValue(QString::fromStdString(str)));
401 } else {
402 // If cjson was requested, embed the actual JSON, rather than the string.
403 QJsonParseError error;
404 QJsonDocument doc = QJsonDocument::fromJson(str.c_str(), &error);
405 if (error.error != QJsonParseError::NoError) {
406 m_errors << tr("Error generating cjson object: Parse error at offset %1: "
407 "%2\nRaw JSON:\n\n%3")
408 .arg(error.offset)
409 .arg(error.errorString())
410 .arg(QString::fromStdString(str));
411 return false;
412 }
413
414 if (!doc.isObject()) {
415 m_errors << tr("Error generator cjson object: Parsed JSON is not an "
416 "object:\n%1")
417 .arg(QString::fromStdString(str));
418 return false;
419 }
420
421 json.insert(m_moleculeExtension, doc.object());
422 }
423
424 return true;
425 }
426
427 QString InputGenerator::generateCoordinateBlock(const QString& spec,
428 const Core::Molecule& mol) const
429 {
430 Core::CoordinateBlockGenerator gen;
431 gen.setMolecule(&mol);
432 gen.setSpecification(spec.toStdString());
433 std::string tmp(gen.generateCoordinateBlock());
434 if (!tmp.empty())
435 tmp.resize(tmp.size() - 1); // Pop off the trailing newline
436 return QString::fromStdString(tmp);
437 }
438
439 void InputGenerator::replaceKeywords(QString& str,
440 const Core::Molecule& mol) const
441 {
442 // Simple keywords:
443 str.replace("$$atomCount$$", QString::number(mol.atomCount()));
444 str.replace("$$bondCount$$", QString::number(mol.bondCount()));
445
446 // Find each coordinate block keyword in the file, then generate and replace
447 // it with the appropriate values.
448 QRegularExpression coordParser(R"(\$\$coords:([^\$]*)\$\$)");
449 QRegularExpressionMatch match;
450 int ind = 0;
451 // Not sure while this needs to be a while statement since we replace all in
452 // one go? We never iterate ind...
453 while ((match = coordParser.match(str, ind)).hasMatch()) {
454 // Extract spec and prepare the replacement
455 const QString keyword = match.captured(0);
456 const QString spec = match.captured(1);
457
458 // Replace all blocks with this signature
459 str.replace(keyword, generateCoordinateBlock(spec, mol));
460
461 } // end for coordinate block
462 }
463
464 bool InputGenerator::parseHighlightStyles(const QJsonArray& json) const
465 {
466 bool result(true);
467 foreach (QJsonValue styleVal, json) {
468 if (!styleVal.isObject()) {
469 qDebug() << "Non-object in highlightStyles array.";
470 result = false;
471 continue;
472 }
473 QJsonObject styleObj(styleVal.toObject());
474
475 if (!styleObj.contains("style")) {
476 qDebug() << "Style object missing 'style' member.";
477 result = false;
478 continue;
479 }
480 if (!styleObj.value("style").isString()) {
481 qDebug() << "Style object contains non-string 'style' member.";
482 result = false;
483 continue;
484 }
485 QString styleName(styleObj.value("style").toString());
486
487 if (m_highlightStyles.contains(styleName)) {
488 qDebug() << "Duplicate highlight style: " << styleName;
489 result = false;
490 continue;
491 }
492
493 if (!styleObj.contains("rules")) {
494 qDebug() << "Style object" << styleName << "missing 'rules' member.";
495 result = false;
496 continue;
497 }
498 if (!styleObj.value("rules").isArray()) {
499 qDebug() << "Style object" << styleName
500 << "contains non-array 'rules' member.";
501 result = false;
502 continue;
503 }
504 QJsonArray rulesArray(styleObj.value("rules").toArray());
505
506 auto* highlighter(
507 new GenericHighlighter(const_cast<InputGenerator*>(this)));
508 if (!parseRules(rulesArray, *highlighter)) {
509 qDebug() << "Error parsing style" << styleName << '\n'
510 << QString(QJsonDocument(styleObj).toJson());
511 highlighter->deleteLater();
512 result = false;
513 continue;
514 }
515 m_highlightStyles.insert(styleName, highlighter);
516 }
517
518 return result;
519 }
520
521 bool InputGenerator::parseRules(const QJsonArray& json,
522 GenericHighlighter& highligher) const
523 {
524 bool result(true);
525 foreach (QJsonValue ruleVal, json) {
526 if (!ruleVal.isObject()) {
527 qDebug() << "Rule is not an object.";
528 result = false;
529 continue;
530 }
531 QJsonObject ruleObj(ruleVal.toObject());
532
533 if (!ruleObj.contains("patterns")) {
534 qDebug() << "Rule missing 'patterns' array:" << '\n'
535 << QString(QJsonDocument(ruleObj).toJson());
536 result = false;
537 continue;
538 }
539 if (!ruleObj.value("patterns").isArray()) {
540 qDebug() << "Rule 'patterns' member is not an array:" << '\n'
541 << QString(QJsonDocument(ruleObj).toJson());
542 result = false;
543 continue;
544 }
545 QJsonArray patternsArray(ruleObj.value("patterns").toArray());
546
547 if (!ruleObj.contains("format")) {
548 qDebug() << "Rule missing 'format' object:" << '\n'
549 << QString(QJsonDocument(ruleObj).toJson());
550 result = false;
551 continue;
552 }
553 if (!ruleObj.value("format").isObject()) {
554 qDebug() << "Rule 'format' member is not an object:" << '\n'
555 << QString(QJsonDocument(ruleObj).toJson());
556 result = false;
557 continue;
558 }
559 QJsonObject formatObj(ruleObj.value("format").toObject());
560
561 GenericHighlighter::Rule& rule = highligher.addRule();
562
563 foreach (QJsonValue patternVal, patternsArray) {
564 QRegularExpression pattern;
565 if (!parsePattern(patternVal, pattern)) {
566 qDebug() << "Error while parsing pattern:" << '\n'
567 << QString(QJsonDocument(patternVal.toObject()).toJson());
568 result = false;
569 continue;
570 }
571 rule.addPattern(pattern);
572 }
573
574 QTextCharFormat format;
575 if (!parseFormat(formatObj, format)) {
576 qDebug() << "Error while parsing format:" << '\n'
577 << QString(QJsonDocument(formatObj).toJson());
578 result = false;
579 }
580 rule.setFormat(format);
581 }
582
583 return result;
584 }
585
586 // Dark-mode palette: brighter / higher-value colors for contrast on dark
587 // backgrounds.
588 static const std::map<std::string, QColor> darkModeColors = {
589 { "red", QColorConstants::Svg::crimson }, // #DC143C
590 { "orange", QColorConstants::Svg::coral }, // #FF7F50
591 { "yellow", QColorConstants::Svg::goldenrod }, // #DAA520
592 { "green", QColorConstants::Svg::springgreen }, // #00FF7F
593 { "cyan", QColorConstants::Svg::cyan }, // #00FFFF
594 { "blue", QColorConstants::Svg::dodgerblue }, // #1E90FF
595 { "purple", QColorConstants::Svg::mediumpurple }, // #9370DB
596 { "pink", QColorConstants::Svg::orchid }, // #DA70D6
597 { "white", QColorConstants::Svg::whitesmoke }, // #F5F5F5
598 { "gray", QColorConstants::Svg::darkgray }, // #A9A9A9
599 };
600
601 // Light-mode palette: deeper / more saturated colors for contrast on light
602 // backgrounds.
603 static const std::map<std::string, QColor> lightModeColors = {
604 { "red", QColorConstants::Svg::maroon }, // #800000
605 { "orange", QColorConstants::Svg::coral }, // #FF7F50
606 { "yellow", QColorConstants::Svg::goldenrod }, // #DAA520
607 { "green", QColorConstants::Svg::limegreen }, // #32CD32
608 { "cyan", QColorConstants::Svg::deepskyblue }, // #00BFFF
609 { "blue", QColorConstants::Svg::blue }, // #0000FF
610 { "purple", QColorConstants::Svg::blueviolet }, // #8A2BE2
611 { "pink", QColorConstants::Svg::fuchsia }, // #FF00FF
612 { "white", QColorConstants::Svg::black }, // #000000
613 { "gray", QColorConstants::Svg::dimgray }, // #696969
614 };
615
616 inline const QColor highlightColor(const std::string& name, bool isDarkMode)
617 {
618 return isDarkMode ? darkModeColors.at(name) : lightModeColors.at(name);
619 }
620
621 bool InputGenerator::parseFormat(const QJsonObject& json,
622 QTextCharFormat& format) const
623 {
624 // Check for presets first:
625 if (json.contains("preset")) {
626 if (!json["preset"].isString()) {
627 qDebug() << "Preset is not a string.";
628 return false;
629 }
630
631 QString preset(json["preset"].toString());
632
633 enum class HighlightPreset
634 {
635 Title,
636 Keyword,
637 Property,
638 NumLiteral,
639 StrLiteral,
640 Comment,
641 Method,
642 Basis,
643 Block,
644 };
645
646 std::unordered_map<QString, HighlightPreset> mapStringToPreset{
647 { QString("title"), HighlightPreset::Title },
648 { QString("keyword"), HighlightPreset::Keyword },
649 { QString("property"), HighlightPreset::Property },
650 { QString("num_literal"), HighlightPreset::NumLiteral },
651 { QString("str_literal"), HighlightPreset::StrLiteral },
652 { QString("comment"), HighlightPreset::Comment },
653 { QString("method"), HighlightPreset::Method },
654 { QString("basis"), HighlightPreset::Basis },
655 { QString("block"), HighlightPreset::Block },
656 };
657
658 const QPalette defaultPalette;
659 bool isDarkMode = (defaultPalette.color(QPalette::WindowText).lightness() >
660 defaultPalette.color(QPalette::Window).lightness());
661
662 if (mapStringToPreset.count(preset) == 0) {
663 qDebug() << "Invalid style preset: " << preset;
664 return false;
665 }
666
667 HighlightPreset presetType = mapStringToPreset[preset];
668
669 format.setFontFamily(QStringLiteral("mono"));
670
671 /// @todo Store presets in a singleton that can be configured in the GUI,
672 /// rather than hardcoding them.
673 switch (presetType) {
674 case HighlightPreset::Title:
675 format.setFontWeight(QFont::Bold);
676 format.setForeground(highlightColor("green", isDarkMode));
677 return true;
678 case HighlightPreset::Keyword:
679 format.setForeground(highlightColor("blue", isDarkMode));
680 return true;
681 case HighlightPreset::Property:
682 format.setForeground(highlightColor("cyan", isDarkMode));
683 return true;
684 case HighlightPreset::NumLiteral:
685 format.setForeground(highlightColor("orange", isDarkMode));
686 return true;
687 case HighlightPreset::StrLiteral:
688 format.setForeground(highlightColor("red", isDarkMode));
689 return true;
690 case HighlightPreset::Comment:
691 format.setFontItalic(true);
692 format.setForeground(highlightColor("gray", isDarkMode));
693 return true;
694 case HighlightPreset::Method:
695 format.setForeground(highlightColor("purple", isDarkMode));
696 return true;
697 case HighlightPreset::Basis:
698 format.setForeground(highlightColor("pink", isDarkMode));
699 return true;
700 case HighlightPreset::Block:
701 format.setForeground(highlightColor("yellow", isDarkMode));
702 return true;
703 }
704 }
705
706 // Extract an RGB tuple from 'array' as a QBrush:
707 struct
708 {
709 QBrush operator()(const QJsonArray& array, bool* ok)
710 {
711 *ok = false;
712 QBrush result;
713
714 if (array.size() != 3)
715 return result;
716
717 int rgb[3];
718 for (int i = 0; i < 3; ++i) {
719 if (!array.at(i).isDouble())
720 return result;
721 rgb[i] = static_cast<int>(array.at(i).toDouble());
722 if (rgb[i] < 0 || rgb[i] > 255) {
723 qDebug() << "Warning: Color component value invalid: " << rgb[i]
724 << " (Valid range is 0-255).";
725 }
726 }
727
728 result.setColor(QColor(rgb[0], rgb[1], rgb[2]));
729 result.setStyle(Qt::SolidPattern);
730 *ok = true;
731 return result;
732 }
733 } colorParser;
734
735 if (json.contains("foreground") && json.value("foreground").isArray()) {
736 QJsonArray foregroundArray(json.value("foreground").toArray());
737 bool ok;
738 format.setForeground(colorParser(foregroundArray, &ok));
739 if (!ok)
740 return false;
741 }
742
743 if (json.contains("background") && json.value("background").isArray()) {
744 QJsonArray backgroundArray(json.value("background").toArray());
745 bool ok;
746 format.setBackground(colorParser(backgroundArray, &ok));
747 if (!ok)
748 return false;
749 }
750
751 if (json.contains("attributes") && json.value("attributes").isArray()) {
752 QJsonArray attributesArray(json.value("attributes").toArray());
753 format.setFontWeight(attributesArray.contains(QLatin1String("bold"))
754 ? QFont::Bold
755 : QFont::Normal);
756 format.setFontItalic(attributesArray.contains(QLatin1String("italic")));
757 format.setFontUnderline(
758 attributesArray.contains(QLatin1String("underline")));
759 }
760
761 if (json.contains("family") && json.value("family").isString()) {
762 format.setFontFamily(json.value("family").toString());
763 }
764
765 return true;
766 }
767
768 bool InputGenerator::parsePattern(const QJsonValue& json,
769 QRegularExpression& pattern) const
770 {
771 if (!json.isObject())
772 return false;
773
774 QJsonObject patternObj(json.toObject());
775 QString regexPattern;
776 QRegularExpression::PatternOptions patternOptions =
777 QRegularExpression::NoPatternOption;
778
779 if (patternObj.contains(QStringLiteral("regexp")) &&
780 patternObj.value(QStringLiteral("regexp")).isString()) {
781 // Use the provided regular expression as-is
782 regexPattern = patternObj.value(QStringLiteral("regexp")).toString();
783 } else if (patternObj.contains(QStringLiteral("wildcard")) &&
784 patternObj.value(QStringLiteral("wildcard")).isString()) {
785 // Convert wildcard pattern (* -> .* and ? -> .)
786 QString wildcard = patternObj.value(QStringLiteral("wildcard")).toString();
787 regexPattern = QRegularExpression::escape(wildcard)
788 .replace("\\*", ".*")
789 .replace("\\?", ".");
790 } else if (patternObj.contains(QStringLiteral("string")) &&
791 patternObj.value(QStringLiteral("string")).isString()) {
792 // Escape the string so it is treated literally in the regex
793 regexPattern = QRegularExpression::escape(
794 patternObj.value(QStringLiteral("string")).toString());
795 } else {
796 return false;
797 }
798
799 // Set case sensitivity if specified
800 if (patternObj.contains(QStringLiteral("caseSensitive"))) {
801 bool caseSensitive =
802 patternObj.value(QStringLiteral("caseSensitive")).toBool(true);
803 if (!caseSensitive) {
804 patternOptions |= QRegularExpression::CaseInsensitiveOption;
805 }
806 }
807
808 // Set the final pattern with options
809 pattern = QRegularExpression(regexPattern, patternOptions);
810
811 return pattern.isValid();
812 }
813
814 } // namespace Avogadro::MoleQueue