Debian Codegraph @

avogadro/qtgui/interfacescript.h

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 #ifndef AVOGADRO_QTGUI_INTERFACESCRIPT_H
7 #define AVOGADRO_QTGUI_INTERFACESCRIPT_H
8
9 #include <QtCore/QObject>
10
11 #include "avogadroqtguiexport.h"
12
13 #include <avogadro/core/avogadrocore.h>
14
15 #include <QRegularExpression>
16 #include <QtCore/QJsonObject>
17 #include <QtCore/QMap>
18 #include <QtCore/QStringList>
19
20 class QJsonDocument;
21 class QProcess;
22 class QTextCharFormat;
23
24 namespace Avogadro {
25
26 namespace Core {
27 class Molecule;
28 }
29
30 namespace QtGui {
31 class GenericHighlighter;
32 class PythonScript;
33
34 /**
35 * @class InterfaceScript interfacescript.h
36 <avogadro/molequeue/interfacescript.h>
37 * @brief The Interface class provides an interface to external scripts
38 * @sa InterfaceWidget
39 *
40 * The QuantumInput extension provides a scriptable method for users to add
41 * custom input generators to Avogadro. By writing an executable that implements
42 * the interface defined below, new input generators can be created faster and
43 * easier than writing full Avogadro extensions.
44 *
45 * Script Entry Points
46 * ===================
47 *
48 * The script must handle the following command-line arguments:
49 * - `--debug` Enable extra debugging output. Used with other commands.
50 * It is not required that the script support extra debugging, but it should
51 * not crash when this option is passed.
52 * - `--print-options` Print the available options supported by the
53 * script, e.g. simulation parameters, etc. See below for more details.
54 * - `--generate-input` Read an option block from stdin and print
55 * input files to stdout. See below for more details.
56 * - `--display-name` Print a user-friendly name for the input generator.
57 * This is used in the GUI for menu entries, window titles, etc.
58 *
59 * Specifying parameters with `--print-options`
60 * ============================================
61 *
62 * The format of the `--print-options` output must be a JSON object of
63 * the following form:
64 ~~~{.js}
65 {
66 "userOptions": {
67 ...
68 },
69 "highlightStyles": [
70 {
71 "style": "Descriptive name",
72 "rules": [
73 {
74 "patterns": [ ... ],
75 "format": { ... }
76 },
77 ...
78 ],
79 },
80 ...
81 ],
82 "inputMoleculeFormat": "cjson"
83 }
84 ~~~
85 * The `userOptions` block contains a JSON object keyed with option names
86 * (e.g. "First option name"), which are used in the GUI to label simulation
87 * parameter settings. Various parameter types are supported:
88 *
89 * Fixed Mutually-Exclusive Parameter Lists
90 * ----------------------------------------
91 *
92 * Parameters that have a fixed number of mutually-exclusive string values will
93 * be presented using a QComboBox. Such a parameter can be specified in the
94 * `userOptions` block as:
95 ~~~{.js}
96 {
97 "userOptions": {
98 "Parameter Name": {
99 "type": "stringList",
100 "values": ["Option 1", "Option 2", "Option 3"],
101 "default": 0
102 }
103 }
104 }
105 ~~~
106 * Here, `Parameter Name` is the label that will be displayed in the GUI as a
107 * label next to the combo box.
108 * The array of strings in `values` will be used as the available entries in
109 * the combo box in the order they are written.
110 * `default` is a zero-based index into the `values` array and indicates
111 * which value should be initially selected by default.
112 *
113 * Short Free-Form Text Parameters
114 * -------------------------------
115 *
116 * A short text string can be requested (e.g. for the "title" of an
117 * optimization) via:
118 ~~~{.js}
119 {
120 "userOptions": {
121 "Parameter Name": {
122 "type": "string",
123 "default": "blah blah blah"
124 }
125 }
126 }
127 ~~~
128 * This will add a QLineEdit to the GUI, initialized with the text specified by
129 * `default`.
130 *
131 * Existing files
132 * --------------
133 *
134 * An input generator can ask for the absolute path to an existing file using
135 * the following option block:
136 ~~~{.js}
137 {
138 "userOptions": {
139 "Parameter Name": {
140 "type": "filePath",
141 "default": "/path/to/some/file"
142 }
143 }
144 }
145 ~~~
146 * This will add an Avogadro::QtGui::FileBrowseWidget to the GUI, initialized to
147 * the file pointed to by default.
148 *
149 * Clamped Integer Values
150 * ----------------------
151 *
152 * Scripts may request integer values from a specified range by adding a
153 * user-option of the following form:
154 ~~~{.js}
155 {
156 "userOptions": {
157 "Parameter Name": {
158 "type": "integer",
159 "minimum": -5,
160 "maximum": 5,
161 "default": 0,
162 "prefix": "some text ",
163 "suffix": " units"
164 }
165 }
166 }
167 ~~~
168 * This block will result in a QSpinBox, configured as follows:
169 * - `minimum` and `maximum` indicate the valid range of integers for the
170 * parameter.
171 * - `default` is the integer value that will be shown initially.
172 * - (optional) `prefix` and `suffix` are used to insert text before or
173 * after the integer value in the spin box.
174 * This is handy for specifying units.
175 * Note that any prefix or suffix will be stripped out of the corresponding
176 * entry in the call to `--generate-input`, and just the raw integer value
177 * will be sent.
178 *
179 * Boolean Parameters
180 * ------------------
181 *
182 * If a simple on/off value is needed, a boolean type option can be requested:
183 ~~~{.js}
184 {
185 "userOptions": {
186 "Parameter Name": {
187 "type": "boolean",
188 "default": true,
189 }
190 }
191 }
192 ~~~
193 * This will result in a QCheckBox in the dynamically generated GUI, with
194 * the initial check state shown in `default`.
195 *
196 * Special Parameters
197 * ------------------
198 *
199 * Some parameters are common to most calculation codes.
200 * If the following parameter names are found, they will be handled specially
201 * while creating the GUI.
202 * It is recommended to use the names below for these options to provide a
203 * consistent interface and ensure that MoleQueue job staging uses correct
204 * values where appropriate.
205 *
206 * | Option name | type | description |
207 * | :----------------: | :--------: |
208 :------------------------------------------------------------------ |
209 * | "Title" | string | Input file title comment, MoleQueue job
210 description. |
211 * | "Filename Base" | string | Input file base name, e.g. "job" in
212 "job.inp". |
213 * | "Processor Cores" | integer | Number of cores to use. Will be passed to
214 MoleQueue. |
215 * | "Calculation Type" | stringList | Type of calculation, e.g. "Single Point"
216 or "Equilibrium Geometry". |
217 * | "Theory" | stringList | Levels of QM theory, e.g. "RHF", "B3LYP",
218 "MP2", "CCSD", etc. |
219 * | "Basis" | stringList | Available basis sets, e.g. "STO-3G",
220 "6-31G**", etc. |
221 * | "Charge" | integer | Charge on the system. |
222 * | "Multiplicity" | integer | Spin multiplicity of the system. |
223 *
224 * Syntax Highlighting
225 * -------------------
226 *
227 * Rules for syntax highlighting can be specified as a collection of regular
228 * expressions or wildcard patterns and text format specifications in the
229 * "highlightRules" array. The `highlightRules` format is:
230 ~~~{.js}
231 "highlightStyles": [
232 {
233 "style": "Style 1",
234 "rules": [ (list of highlight rules, see below) ],
235 },
236 {
237 "style": "Style 2",
238 "rules": [ (list of highlight rules, see below) ],
239 },
240 ...
241 ],
242 ~~~
243 * The `style` name is unique to the style object, and used to associate a
244 * set of highlighting rules with particular output files. See the
245 * `--generate-input` documentation for more details.
246 *
247 * The general form of a highlight rule is:
248 ~~~{.js}
249 {
250 "patterns": [
251 { "regexp": "^Some regexp?$" },
252 { "wildcard": "A * wildcard expression" },
253 { "string": "An exact string to match.",
254 "caseSensitive": false
255 },
256 ...
257 ],
258 "format": {
259 "preset": "<preset name>"
260 }
261 }
262 ~~~
263 *
264 * or,
265 *
266 ~~~{.js}
267 {
268 "patterns": [
269 ...
270 ],
271 "format": {
272 "foreground": [ 255, 128, 64 ],
273 "background": [ 0, 128, 128 ],
274 "attributes": ["bold", "italic", "underline"],
275 "family": "serif"
276 }
277 }
278 ~~~
279 *
280 * The `patterns` array contains a collection of fixed strings, wildcard
281 * expressions, and regular expressions (using the QRegularExpression syntax
282 * flavor, see the QRegularExpression documentation) that are used to identify
283 * strings that should be formatted.
284 * There must be one of the following members present in each pattern object:
285 * - `regexp` A QRegularExpression-style regular expression. If no capture
286 * groups ("(...)") are defined, the entire match is formatted. If one or more
287 * capture groups, only the captured texts will be marked.
288 * - `wildcard` A wildcard expression
289 * - `string` An exact string to match.
290 *
291 * Any pattern object may also set a boolean `caseSensitive` member to indicate
292 * whether the match should consider character case. If omitted, a
293 * case-sensitive match is assumed.
294 *
295 * The preferred form of the `format` member is simply a specification of a
296 * preset format.
297 * This allows for consistent color schemes across input generators.
298 * The recognized presets are:
299 * - `"title"`: A human readable title string.
300 * - `"keyword"`: directives defined by the target input format specification
301 * to have special meaning, such as tags indicating where coordinates are
302 * to be found.
303 * - `"property"`: A property of the simulation, such as level of theory, basis
304 * set, minimization method, etc.
305 * - `"literal"`: A numeric literal (i.e. a raw number, such as a coordinate).
306 * - `"comment"`: Sections of the input that are ignored by the simulation code.
307 *
308 * If advanced formatting is desired, the second form of the `format` member
309 * allows fine-tuning of the font properties:
310 * - `foreground` color as an RGB tuple, ranged 0-255
311 * - `background` color as an RGB tuple, ranged 0-255
312 * - `attributes` array of font attributes, valid strings are `"bold"`,
313 * `"italic"`, or `"underline"`
314 * - `family` of font. Valid values are `"serif"`, `"sans"`, or `"mono"`
315 *
316 * Any of the font property members may be omitted and default QTextCharFormat
317 * settings will be substituted.
318 *
319 * The input generator extension will apply the entries in the `highlightRules`
320 * object to the text in the order they appear. Thus, later rules will
321 * override the formatting of earlier rules should a conflict arise.
322 *
323 * Requesting Full Structure of Current Molecule
324 * ---------------------------------------------
325 *
326 * The `inputMoleculeFormat` is optional, and can be used to request a
327 * representation of the current molecule's geometry when
328 * `--generate-input` is called. The corresponding value
329 * indicates the format of the molecule that the script expects. If this value
330 * is omitted, no representation of the structure will be provided.
331 *
332 * @note Currently valid options for inputMoleculeFormat are "cjson" for
333 * Chemical JSON or "cml" for Chemical Markup Language.
334 *
335 * Handling User Selections: `--generate-input`
336 * ============================================
337 *
338 * When `--generate-input` is passed, the information needed to generate
339 * the input file will be written to the script's standard input
340 * channel as JSON string of the following form:
341 ~~~{.js}
342 {
343 "cjson": {...},
344 "options": {
345 "First option name": "Value 2",
346 "Second option name": "Value 1",
347 ...
348 }
349 }
350 ~~~
351 * The `cjson` entry will contain a Chemical JSON representation
352 * of the molecule if `inputMoleculeFormat` is set to "cjson" in the
353 * `--print-options` output.
354 * Similarly, a `cml` entry and CML string will exist if a Chemical Markup
355 * Language representation was requested.
356 * It will be omitted entirely if `inputMoleculeFormat` is not set.
357 * The `options` block contains key/value
358 * pairs for each of the options specified in the `userOptions` block of the
359 * `--print-options` output.
360 *
361 * If the script is called with `--generate-input`, it must write a JSON
362 * string to standard output with the following format:
363 ~~~{.js}
364 {
365 "files": [
366 {
367 "filename": "file1.ext",
368 "contents": "...",
369 "highlightStyles": [ ... ]
370 },
371 {
372 "filename": "file2.ext",
373 "filePath": "/path/to/file/on/local/filesystem"
374 },
375 ...
376 ],
377 "warnings": ["First warning.", "Second warning.", ... ],
378 "mainFile": "file2.ext"
379 }
380 ~~~
381 * The `files` block is an array of objects, which define the actual input
382 * files. The `filename` member provides the name of the file, and
383 * either `contents` or `filePath` provide the text that goes into the file.
384 * The `contents` string will be used as the file contents, and `filePath`
385 * should contain an absolute path to a file on the filesystem to read and use
386 * as the input file contents.
387 * The optional `highlightStyles` member is an array of strings describing any
388 * highlight styles to apply to the file (see `--print-options` documentation).
389 * Each string in this array must match a `style` description in a highlighting
390 * rule in the `--print-options` output.
391 * Zero or more highlighting styles may be applied to any file.
392 * The order of the files in the
393 * GUI will match the order of the files in the array, and the first file will
394 * be displayed first.
395 *
396 * The `warnings` member provides an array of strings that describe non-fatal
397 * warnings to be shown to the users. This is useful for describing
398 * the resolution of conflicting options, e.g. "Ignoring basis set for
399 * semi-empirical calculation.". This member is optional and should be omitted
400 * if no warnings are present.
401 *
402 * The `mainFile` member points to the primary input file for a calculation.
403 * This is the file that will be used as a command line argument when executing
404 * the simulation code (if applicable), and used by MoleQueue to set the
405 * `$$inputFileName$$` and `$$inputFileBaseName$$` input template keywords.
406 * This is optional; if present, the filename must exist in the `files` array.
407 * If absent and only one file is specified in `files`, the single input file
408 * will be used. Otherwise, the main file will be left unspecified.
409 *
410 * Automatic Generation of Geometry
411 * ================================
412 *
413 * The generation of molecular geometry descriptions may be skipped in the
414 * script and deferred to the InterfaceScript class by use of a special keyword.
415 * The "contents" string may contain a keyword of the form
416 ~~~
417 $$coords:[coordSpec]$$
418 ~~~
419 * where `[coordSpec]` is a sequence of characters.
420 * The characters in `[coordSpec]` indicate the information needed about each
421 * atom in the coordinate block.
422 * See the CoordinateBlockGenerator documentation for a list of recognized
423 * characters.
424 *
425 * Other keywords that can be used in the input files are:
426 * - `$$atomCount$$`: Number of atoms in the molecule.
427 * - `$$bondCount$$`: Number of bonds in the molecule.
428 *
429 * Error Handling
430 * ==============
431 *
432 * In general, these scripts should be written robustly so that they will not
433 * fail under normal circumstances. However, if for some reason an error
434 * occurs that must be reported to the user, simply write the error message to
435 * standard output as plain text (i.e. not JSON), and it will be shown to the
436 * user.
437 *
438 * Debugging
439 * =========
440 *
441 * Debugging may be enabled by defining AVO_QM_INPUT_DEBUG in the process's
442 * environment. This will cause the <tt>--debug</tt> option to be passed in
443 * all calls to generator scripts, and will print extra information to the
444 * qDebug() stream from within avogadro. The script is free to handle the
445 * debug flag as the author wishes.
446 */
447 class AVOGADROQTGUI_EXPORT InterfaceScript : public QObject
448 {
449 Q_OBJECT
450 public:
451 /**
452 * Constructor
453 * @param scriptFilePath_ Absolute path to generator script.
454 */
455 explicit InterfaceScript(const QString& scriptFilePath_,
456 QObject* parent_ = nullptr);
457 explicit InterfaceScript(QObject* parent_ = nullptr);
458 ~InterfaceScript() override;
459
460 /**
461 * @return True if debugging is enabled.
462 */
463 bool debug() const;
464
465 /**
466 * @return True if the generator is configured with a valid script.
467 */
468 bool isValid() const;
469
470 /**
471 * Query the script for the available options (<tt>--generate-options</tt>)
472 * and return the output as a JSON object.
473 * @note The results will be cached the first time this function is called
474 * and reused in subsequent calls.
475 * @note If an error occurs, the error string will be set. Call hasErrors()
476 * to check for success, and errorString() or errorList() to get a
477 * user-friendly description of the error.
478 */
479 QJsonObject options() const;
480
481 /**
482 * Return a user-friendly name for the script.
483 * @note In package mode this is taken from package metadata. For legacy
484 * script mode, the value is queried from <tt>--display-name</tt>.
485 * @note The results will be cached the first time this function is called
486 * and reused in subsequent calls.
487 * @note If an error occurs, the error string will be set. Call hasErrors()
488 * to check for success, and errorString() or errorList() to get a
489 * user-friendly description of the error.
490 */
491 QString displayName() const;
492
493 /**
494 * Query the script for the menu path (<tt>--menu-path</tt>).
495 * @note The results will be cached the first time this function is called
496 * and reused in subsequent calls.
497 * @note If an error occurs, the error string will be set. Call hasErrors()
498 * to check for success, and errorString() or errorList() to get a
499 * user-friendly description of the error.
500 */
501 QString menuPath() const;
502
503 /**
504 * @return The path to the generator file.
505 */
506 QString scriptFilePath() const;
507
508 /**
509 * Set the path to the input generator script file. This will reset any
510 * cached data held by this class.
511 */
512 void setScriptFilePath(const QString& scriptFile);
513
514 /**
515 * Access to the underlying PythonScript interpreter for direct
516 * configuration (e.g. setting package mode via setPackageInfo()).
517 * @{
518 */
519 PythonScript& interpreter() { return *m_interpreter; }
520 const PythonScript& interpreter() const { return *m_interpreter; }
521 /** @} */
522
523 /**
524 * Clear any cached data and return to an uninitialized state.
525 */
526 void reset();
527
528 /**
529 * Set the user options directly from a JSON object, bypassing the
530 * --print-options script call. Use this for package-based plugins whose
531 * options are stored in a file referenced by the pyproject.toml metadata.
532 * Insert "inputMoleculeFormat" into @p opts before calling if you need a
533 * specific molecule format (mirrors the InputGenerator::setOptions()
534 * pattern). After calling this, reloadOptions() on the widget will use the
535 * cached options without invoking the script.
536 */
537 void setOptionsJson(const QJsonObject& opts);
538
539 /**
540 * Asynchronously run a command script using the supplied options object and
541 * molecule. See the class documentation for details on the @p options_
542 * object format.
543 *
544 * @return true on success and false on failure.
545 * @note If an error occurs, the error string will be set. Call hasErrors()
546 * to check for success, and errorString() or errorList() to get a
547 * user-friendly description of the error.
548 */
549 bool runCommand(const QJsonObject& options_, Core::Molecule* mol);
550
551 /**
552 * Finish processing an aynchronous command script
553 */
554 bool processCommand(Core::Molecule* mol);
555
556 /**
557 * Request input files from the script using the supplied options object and
558 * molecule. See the class documentation for details on the @p options_
559 * object format.
560 *
561 * If the files are generated successfully, use the functions
562 * numberOfInputFiles(), fileNames(), and fileContents() to retrieve them.
563 *
564 * @return true on success and false on failure.
565 * @note If an error occurs, the error string will be set. Call hasErrors()
566 * to check for success, and errorString() or errorList() to get a
567 * user-friendly description of the error.
568 */
569 bool generateInput(const QJsonObject& options_, const Core::Molecule& mol);
570
571 /**
572 * @return The number of input files stored by generateInput().
573 * @note This function is only valid after a successful call to
574 * generateInput().
575 */
576 int numberOfInputFiles() const;
577
578 /**
579 * @return A list of filenames created by generateInput().
580 * @note This function is only valid after a successful call to
581 * generateInput().
582 */
583 QStringList fileNames() const;
584
585 /**
586 * @return The "main" input file of the collection. This is the input file
587 * used by MoleQueue to determine the $$inputFileName$$ and
588 * $$inputFileBaseName$$ keywords.
589 * @note This function is only valid after a successful call to
590 * generateInput().
591 */
592 QString mainFileName() const;
593
594 /**
595 * @return A file contents corresponding to @p fileName. Must call
596 * generateInput() first.
597 * @sa fileNames
598 */
599 QString fileContents(const QString& fileName) const;
600
601 /**
602 * @return A syntax highlighter for the file @a fileName. Must call
603 * generateInput() first. The caller takes ownership of the returned object.
604 * If no syntax highlighter is defined, this function returns nullptr.
605 * @sa fileNames
606 */
607 QtGui::GenericHighlighter* createFileHighlighter(
608 const QString& fileName) const;
609
610 /**
611 * @return True if an error is set.
612 */
613 bool hasErrors() const { return !m_errors.isEmpty(); }
614
615 /**
616 * Reset the error counter.
617 */
618 void clearErrors() { m_errors.clear(); }
619
620 /**
621 * @return A QStringList containing all errors that occurred in the last call
622 * to the input generator script.
623 */
624 QStringList errorList() const { return m_errors; }
625
626 /**
627 * @return A QStringList containing all warnings returned by the input
628 * generator script in the last call to generateInput. These are
629 * script-specific warnings.
630 */
631 QStringList warningList() const { return m_warnings; }
632
633 signals:
634 void finished();
635
636 public slots:
637 /**
638 * Enable/disable debugging.
639 */
640 void setDebug(bool d);
641
642 /**
643 * Receives a signal when asynchronous command scripts are finished
644 */
645 void commandFinished();
646
647 protected:
648 bool parseJson(const QByteArray& json, QJsonDocument& doc) const;
649 QString generateCoordinateBlock(const QString& spec,
650 const Core::Molecule& mol) const;
651 void replaceKeywords(QString& str, const Core::Molecule& mol) const;
652 bool parseHighlightStyles(const QJsonArray& json) const;
653 bool parseRules(const QJsonArray& json,
654 QtGui::GenericHighlighter& highligher) const;
655 bool parseFormat(const QJsonObject& json, QTextCharFormat& format) const;
656 bool parsePattern(const QJsonValue& json, QRegularExpression& pattern) const;
657
658 private:
659 QtGui::PythonScript* m_interpreter;
660
661 void setDefaultPythonInterpreter();
662 QByteArray execute(const QStringList& args,
663 const QByteArray& scriptStdin = QByteArray()) const;
664 QString processErrorString(const QProcess& proc) const;
665 bool insertMolecule(QJsonObject& json, const Core::Molecule& mol) const;
666
667 // File extension of requested molecule format
668 mutable QString m_moleculeExtension;
669 mutable QString m_displayName;
670 mutable QString m_menuPath;
671 mutable QJsonObject m_options;
672 mutable QStringList m_warnings;
673 mutable QStringList m_errors;
674
675 QStringList m_filenames;
676 QString m_mainFileName;
677 QMap<QString, QString> m_files;
678 QMap<QString, QtGui::GenericHighlighter*> m_fileHighlighters;
679
680 mutable QMap<QString, QtGui::GenericHighlighter*> m_highlightStyles;
681 };
682
683 inline bool InterfaceScript::isValid() const
684 {
685 displayName();
686 return !hasErrors();
687 }
688
689 } // namespace QtGui
690 } // namespace Avogadro
691
692 #endif // AVOGADRO_MOLEQUEUE_INTERFACESCRIPT_H