Debian Codegraph @

avogadro/qtplugins/quantuminput/quantuminput.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 "quantuminput.h"
7
8 #include <avogadro/molequeue/client/jobobject.h>
9 #include <avogadro/molequeue/inputgenerator.h>
10 #include <avogadro/molequeue/inputgeneratordialog.h>
11 #include <avogadro/molequeue/inputgeneratorwidget.h>
12
13 #include <avogadro/qtgui/avogadropython.h>
14 #include <avogadro/qtgui/filebrowsewidget.h>
15 #include <avogadro/qtgui/fileformatdialog.h>
16 #include <avogadro/qtgui/molecule.h>
17 #include <avogadro/qtgui/packagemanager.h>
18 #include <avogadro/qtgui/pythonscript.h>
19 #include <avogadro/qtgui/tomlparse.h>
20 #include <avogadro/qtgui/utilities.h>
21
22 #include <QAction>
23 #include <QtWidgets/QDialog>
24 #include <QtWidgets/QDialogButtonBox>
25 #include <QtWidgets/QLabel>
26 #include <QtWidgets/QMessageBox>
27 #include <QtWidgets/QVBoxLayout>
28
29 #include <QtCore/QCoreApplication>
30 #include <QtCore/QDebug>
31 #include <QtCore/QDir>
32 #include <QtCore/QFile>
33 #include <QtCore/QJsonArray>
34 #include <QtCore/QJsonDocument>
35 #include <QtCore/QSettings>
36 #include <QtCore/QStandardPaths>
37 #include <QtCore/QStringList>
38 #include <QtCore/QtPlugin>
39
40 namespace Avogadro::QtPlugins {
41
42 using MoleQueue::InputGenerator;
43 using MoleQueue::InputGeneratorDialog;
44 using MoleQueue::JobObject;
45
46 QuantumInput::QuantumInput(QObject* parent_)
47 : ExtensionPlugin(parent_), m_molecule(nullptr), m_outputFormat(nullptr)
48 {
49 refreshGenerators();
50
51 // Connect to PackageManager for pyproject.toml-based packages
52 auto* pm = QtGui::PackageManager::instance();
53 connect(pm, &QtGui::PackageManager::featureRegistered, this,
54 &QuantumInput::registerFeature);
55 connect(pm, &QtGui::PackageManager::featureRemoved, this,
56 &QuantumInput::unregisterFeature);
57 }
58
59 QuantumInput::~QuantumInput()
60 {
61 qDeleteAll(m_dialogs.values());
62 m_dialogs.clear();
63 }
64
65 QList<QAction*> QuantumInput::actions() const
66 {
67 return m_packageActions.values();
68 }
69
70 QStringList QuantumInput::menuPath(QAction* action) const
71 {
72 QStringList path;
73 if (action == nullptr)
74 return path;
75
76 // Package-based actions may carry a custom menu path
77 QVariant pkgMenuPath = action->property("packageMenuPath");
78 if (pkgMenuPath.isValid())
79 return pkgMenuPath.toStringList();
80 path << tr("&Input");
81 return path;
82 }
83
84 void QuantumInput::setMolecule(QtGui::Molecule* mol)
85 {
86 if (m_molecule == mol)
87 return;
88
89 if (m_molecule)
90 disconnect(m_molecule, &QtGui::Molecule::changed, this,
91 &QuantumInput::moleculeChanged);
92
93 m_molecule = mol;
94
95 if (m_molecule)
96 connect(m_molecule, &QtGui::Molecule::changed, this,
97 &QuantumInput::moleculeChanged);
98
99 foreach (InputGeneratorDialog* dlg, m_dialogs.values())
100 dlg->setMolecule(mol);
101
102 updateActionStates();
103 }
104
105 void QuantumInput::moleculeChanged(unsigned int change)
106 {
107 if (change & QtGui::Molecule::UnitCell)
108 updateActionStates();
109 }
110
111 void QuantumInput::updateActionStates()
112 {
113 bool isPeriodic = m_molecule && m_molecule->unitCell() != nullptr;
114 for (QAction* action : m_packageActions.values()) {
115 // Default: supports molecules (true), does not support periodic (false)
116 bool supportsMolecular = action->property("supportMolecular").isValid()
117 ? action->property("supportMolecular").toBool()
118 : true;
119 bool supportsPeriodic = action->property("supportPeriodic").isValid()
120 ? action->property("supportPeriodic").toBool()
121 : false;
122
123 action->setEnabled(isPeriodic ? supportsPeriodic : supportsMolecular);
124 }
125 }
126
127 void QuantumInput::openJobOutput(const JobObject& job)
128 {
129 m_outputFormat = nullptr;
130 m_outputFileName.clear();
131
132 QString outputPath(job.value("outputDirectory").toString());
133
134 using QtGui::FileFormatDialog;
135 FileFormatDialog::FormatFilePair result = FileFormatDialog::fileToRead(
136 qobject_cast<QWidget*>(parent()), tr("Open Output File"), outputPath);
137
138 if (result.first == nullptr) // User canceled
139 return;
140
141 m_outputFormat = result.first;
142 m_outputFileName = result.second;
143
144 emit moleculeReady(1);
145 }
146
147 bool QuantumInput::readMolecule(QtGui::Molecule& mol)
148 {
149 Io::FileFormat* reader = m_outputFormat->newInstance();
150 bool success = reader->readFile(m_outputFileName.toStdString(), mol);
151 if (!success) {
152 QMessageBox::information(qobject_cast<QWidget*>(parent()), tr("Error"),
153 tr("Error reading output file '%1':\n%2")
154 .arg(m_outputFileName)
155 .arg(QString::fromStdString(reader->error())));
156 }
157
158 m_outputFormat = nullptr;
159 m_outputFileName.clear();
160
161 return success;
162 }
163
164 void QuantumInput::refreshGenerators() {}
165
166 void QuantumInput::menuActivated()
167 {
168 auto* theSender = qobject_cast<QAction*>(sender());
169 if (!theSender)
170 return;
171
172 QWidget* theParent = qobject_cast<QWidget*>(parent());
173 bool isPackage = theSender->property("packageMode").toBool();
174 QString key;
175 InputGeneratorDialog* dlg = nullptr;
176
177 if (isPackage) {
178 QString pkgDir = theSender->property("packageDir").toString();
179 QString pkgCmd = theSender->property("packageCommand").toString();
180 QString pkgId = theSender->property("packageIdentifier").toString();
181 key = QtGui::PackageManager::packageFeatureKey(pkgDir, pkgCmd, pkgId);
182
183 dlg = m_dialogs.value(key, nullptr);
184 if (!dlg) {
185 dlg = new InputGeneratorDialog(theParent);
186 dlg->widget().inputGenerator().interpreter().setPackageInfo(
187 pkgDir, pkgCmd, pkgId,
188 theSender->property("packageDisplayName").toString());
189
190 // The pyproject.toml [avogadro.X] table may declare a separate
191 // user-options file (JSON or TOML) that overrides the defaults baked
192 // into the input-generator script. Load it now so the dialog starts
193 // with the right set of options.
194 QJsonObject opts;
195 // Inject the preferred input molecule format (e.g. "cjson") so the
196 // generator knows which format to request from Avogadro.
197 QString inputFormat =
198 theSender->property("packageInputFormat").toString();
199 if (!inputFormat.isEmpty())
200 opts.insert("inputMoleculeFormat", inputFormat);
201
202 QString userOptionsRel =
203 theSender->property("packageUserOptions").toString();
204 if (!userOptionsRel.isEmpty()) {
205 QJsonObject userOpts = QtGui::PackageManager::resolveUserOptions(
206 userOptionsRel, pkgDir, pkgCmd, pkgId);
207 if (!userOpts.isEmpty())
208 opts.insert(QStringLiteral("userOptions"), userOpts);
209 }
210
211 // Optionally load syntax-highlight rules from a separate file.
212 // The file path is relative to the package directory and may be
213 // JSON or TOML. The expected JSON shape fed to the widget is:
214 // "highlightStyles": [ { "style": "<name>", "rules": [...] }, … ]
215 // This runs unconditionally so a package that only supplies highlight
216 // styles (with no other options) is not silently skipped.
217 QString highlightStylesRel =
218 theSender->property("packageHighlightStyles").toString();
219 if (!highlightStylesRel.isEmpty()) {
220 QFile stylesFile(pkgDir + '/' + highlightStylesRel);
221 if (stylesFile.open(QIODevice::ReadOnly)) {
222 QByteArray content = stylesFile.readAll();
223 if (highlightStylesRel.endsWith(QLatin1String(".toml"),
224 Qt::CaseInsensitive)) {
225 // TOML layout: each top-level key is a style name whose
226 // value has a "rules" array, e.g.:
227 // [[default.rules]]
228 // …
229 // Each entry is reshaped into {"style": key, "rules": […]}.
230 bool ok = false;
231 QJsonObject stylesObj = QtGui::parseTomlToJson(content, &ok);
232 if (!ok) {
233 qWarning() << "QuantumInput: failed to parse TOML highlight"
234 " styles file:"
235 << highlightStylesRel;
236 } else { // it was converted to JSON successfully
237 QJsonArray stylesArray;
238 for (auto it = stylesObj.constBegin(); it != stylesObj.constEnd();
239 ++it) {
240 QJsonObject styleObj;
241 styleObj[QStringLiteral("style")] = it.key();
242 styleObj[QStringLiteral("rules")] =
243 it.value()
244 .toObject()
245 .value(QStringLiteral("rules"))
246 .toArray();
247 stylesArray.append(styleObj);
248 }
249 if (!stylesArray.isEmpty())
250 opts.insert("highlightStyles", stylesArray);
251 }
252 } else {
253 // JSON: accept either a bare array or an object that wraps
254 // the array under the "highlightStyles" key.
255 QJsonDocument stylesDoc = QJsonDocument::fromJson(content);
256 if (stylesDoc.isArray()) {
257 opts.insert("highlightStyles", stylesDoc.array());
258 } else if (stylesDoc.isObject()) {
259 QJsonValue v = stylesDoc.object().value("highlightStyles");
260 if (v.isArray())
261 opts.insert("highlightStyles", v.toArray());
262 }
263 }
264 }
265 }
266 if (!opts.isEmpty())
267 dlg->widget().inputGenerator().setOptions(opts);
268 }
269
270 dlg->widget().reloadOptions();
271
272 // check the title for …
273 QString title(theSender->text());
274 if (title.endsWith("..."))
275 title.chop(3);
276 else if (title.endsWith("…"))
277 title.chop(1);
278
279 dlg->setWindowTitle(tr("%1 Input Generator").arg(title));
280 connect(&dlg->widget(), &MoleQueue::InputGeneratorWidget::openJobOutput,
281 this, &QuantumInput::openJobOutput);
282 m_dialogs.insert(key, dlg);
283 }
284
285 dlg->setMolecule(m_molecule);
286 dlg->show();
287 dlg->raise();
288 dlg->activateWindow();
289 }
290
291 void QuantumInput::registerFeature(const QString& type,
292 const QString& packageDir,
293 const QString& command,
294 const QString& identifier,
295 const QVariantMap& metadata)
296 {
297 if (type != QLatin1String("input-generators"))
298 return;
299
300 // Extract label from metadata
301 QString displayName = metadata.value("program-name").toString();
302 if (displayName.isEmpty())
303 displayName = identifier;
304 QString label = displayName;
305 if (!label.endsWith("…") && !label.endsWith("..."))
306 label.append("…");
307
308 // Create the action
309 auto* action = new QAction(label, this);
310 action->setProperty("packageMode", true);
311 action->setProperty("packageDir", packageDir);
312 action->setProperty("packageCommand", command);
313 action->setProperty("packageIdentifier", identifier);
314 action->setProperty("packageDisplayName", displayName);
315 action->setProperty("packageUserOptions",
316 metadata.value("user-options").toString());
317 action->setProperty("packageInputFormat",
318 metadata.value("input-format").toString());
319 action->setProperty("packageHighlightStyles",
320 metadata.value("highlight-styles").toString());
321 // Default to &Input menu path
322 action->setProperty("packageMenuPath", QStringList() << tr("&Input"));
323 // Molecule/periodic support: default molecular=true, periodic=false
324 // "support" is a nested QVariantMap in the metadata
325 QVariantMap supportMeta = metadata.value("support").toMap();
326 action->setProperty("supportMolecular",
327 supportMeta.value("molecular", true).toBool());
328 action->setProperty("supportPeriodic",
329 supportMeta.value("periodic", false).toBool());
330 action->setEnabled(true);
331 connect(action, SIGNAL(triggered()), SLOT(menuActivated()));
332 m_packageActions.insert(
333 QtGui::PackageManager::packageFeatureKey(packageDir, command, identifier),
334 action);
335 emit actionsChanged();
336 }
337
338 void QuantumInput::unregisterFeature(const QString& type,
339 const QString& packageDir,
340 const QString& command,
341 const QString& identifier)
342 {
343 if (type != QLatin1String("input-generators"))
344 return;
345
346 const QString featureKey =
347 QtGui::PackageManager::packageFeatureKey(packageDir, command, identifier);
348 const QList<QAction*> actions = m_packageActions.values(featureKey);
349 if (actions.isEmpty())
350 return;
351
352 m_packageActions.remove(featureKey);
353
354 InputGeneratorDialog* dlg = m_dialogs.take(featureKey);
355 if (dlg) {
356 dlg->close();
357 delete dlg;
358 }
359
360 for (QAction* action : actions)
361 action->deleteLater();
362 emit actionsChanged();
363 }
364
365 } // namespace Avogadro::QtPlugins