Debian Codegraph @

avogadro/qtplugins/commandscripts/command.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 "command.h"
7
8 #include <avogadro/qtgui/avogadropython.h>
9 #include <avogadro/qtgui/filebrowsewidget.h>
10 #include <avogadro/qtgui/fileformatdialog.h>
11 #include <avogadro/qtgui/interfacescript.h>
12 #include <avogadro/qtgui/interfacewidget.h>
13 #include <avogadro/qtgui/molecule.h>
14 #include <avogadro/qtgui/packagemanager.h>
15 #include <avogadro/qtgui/pythonscript.h>
16 #include <avogadro/qtgui/utilities.h>
17
18 #include <QAction>
19 #include <QtWidgets/QDialog>
20 #include <QtWidgets/QDialogButtonBox>
21 #include <QtWidgets/QLabel>
22 #include <QtWidgets/QMessageBox>
23 #include <QtWidgets/QProgressDialog>
24 #include <QtWidgets/QVBoxLayout>
25
26 #include <QtCore/QCoreApplication>
27 #include <QtCore/QDebug>
28 #include <QtCore/QDir>
29 #include <QtCore/QSettings>
30 #include <QtCore/QStandardPaths>
31 #include <QtCore/QStringList>
32 #include <QtCore/QtPlugin>
33
34 namespace Avogadro::QtPlugins {
35
36 using Avogadro::QtGui::InterfaceScript;
37 using Avogadro::QtGui::InterfaceWidget;
38
39 Command::Command(QObject* parent_)
40 : ExtensionPlugin(parent_), m_molecule(nullptr), m_currentDialog(nullptr),
41 m_currentInterface(nullptr), m_currentScript(nullptr), m_progress(nullptr),
42 m_outputFormat(nullptr)
43 {
44 refreshScripts();
45
46 // Connect to PackageManager for pyproject.toml-based packages
47 auto* pm = QtGui::PackageManager::instance();
48 connect(pm, &QtGui::PackageManager::featureRegistered, this,
49 &Command::registerFeature);
50 connect(pm, &QtGui::PackageManager::featureRemoved, this,
51 &Command::unregisterFeature);
52 }
53
54 Command::~Command()
55 {
56 qDeleteAll(m_dialogs.values());
57 m_dialogs.clear();
58 }
59
60 QList<QAction*> Command::actions() const
61 {
62 return m_actions;
63 }
64
65 QStringList Command::menuPath(QAction* action) const
66 {
67 // Package-based actions carry their menu path in a property
68 QVariant pkgMenuPath = action->property("packageMenuPath");
69 if (pkgMenuPath.isValid())
70 return pkgMenuPath.toStringList();
71
72 QString scriptFileName = action->data().toString();
73 QStringList path;
74
75 // if we have an empty script name, default to Extensions > Scripts
76 if (scriptFileName.isEmpty()) {
77 path << tr("&Extensions") << tr("Scripts");
78 return path;
79 }
80
81 // cache the menu paths
82 QSettings settings;
83 QFileInfo info(scriptFileName); // check if the script matches the hash
84 QString hash =
85 settings.value("scripts/" + scriptFileName + "/hash").toString();
86 if (hash == QString::number(info.size()) + info.lastModified().toString()) {
87 path = settings.value("scripts/" + scriptFileName + "/menu").toStringList();
88 if (!path.isEmpty())
89 return path;
90 }
91
92 // otherwise, we have a script name, so ask it
93 InterfaceScript gen(scriptFileName);
94 path = gen.menuPath().split('|');
95 if (gen.hasErrors()) {
96 path << tr("&Extensions") << tr("Scripts");
97 qWarning() << "Command: Unable to retrieve menu "
98 "name for: "
99 << scriptFileName << "." << gen.errorList().join("\n\n");
100 return path;
101 }
102
103 // look for {number} in the last part of the path
104 // (this is a priority integer)
105 QString lastPart = path.takeLast();
106 int priority = 0;
107 int braceIndex = lastPart.indexOf('{');
108 int endBraceIndex = lastPart.indexOf('}');
109 if (braceIndex >= 0 && endBraceIndex >= 0 && endBraceIndex > braceIndex) {
110 bool ok = false;
111 size_t len = endBraceIndex - braceIndex - 1;
112 priority = lastPart.mid(braceIndex + 1, len).toInt(&ok);
113 if (ok) {
114 lastPart = lastPart.left(braceIndex);
115 }
116 }
117 // add it back to the path
118 path << lastPart;
119
120 // cache the path
121 settings.setValue("scripts/" + scriptFileName + "/menu", path);
122
123 if (priority != 0) {
124 action->setProperty("menu priority", priority);
125 }
126
127 // try to translate each part of the path
128 // not ideal, but most menus should already be in the translation file
129 QStringList translatedPath;
130 foreach (QString part, path)
131 translatedPath << tr(part.toUtf8());
132
133 return translatedPath;
134 }
135
136 void Command::setMolecule(QtGui::Molecule* mol)
137 {
138 if (m_molecule == mol)
139 return;
140
141 m_molecule = mol;
142
143 foreach (InterfaceWidget* dlg, m_dialogs.values())
144 dlg->setMolecule(mol);
145 }
146
147 bool Command::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 Command::refreshScripts() {}
165
166 void Command::menuActivated()
167 {
168 auto* theSender = qobject_cast<QAction*>(sender());
169 if (!theSender)
170 return;
171
172 QWidget* theParent = qobject_cast<QWidget*>(parent());
173
174 if (m_currentDialog) {
175 delete m_currentDialog->layout();
176 if (m_currentInterface)
177 m_currentInterface->hide();
178 }
179
180 bool isPackage = theSender->property("packageMode").toBool();
181 QString key; // dialog cache key
182 InterfaceWidget* widget = nullptr;
183
184 if (isPackage) {
185 QString pkgDir = theSender->property("packageDir").toString();
186 QString pkgCmd = theSender->property("packageCommand").toString();
187 QString pkgId = theSender->property("packageIdentifier").toString();
188 key = QtGui::PackageManager::packageFeatureKey(pkgDir, pkgCmd, pkgId);
189
190 widget = m_dialogs.value(key, nullptr);
191 if (!widget) {
192 widget = new InterfaceWidget(QString(), theParent);
193 widget->interfaceScript().interpreter().setPackageInfo(
194 pkgDir, pkgCmd, pkgId,
195 theSender->property("packageDisplayName").toString());
196
197 // Build options from pyproject.toml metadata; never call --print-options
198 // for package-based commands (mirrors QuantumInput::menuActivated()).
199 QJsonObject opts;
200 QString inputFormat =
201 theSender->property("packageInputFormat").toString();
202 if (!inputFormat.isEmpty())
203 opts.insert(QStringLiteral("inputMoleculeFormat"), inputFormat);
204
205 // The pyproject.toml [avogadro.X] table may declare a separate
206 // user-options file (JSON or TOML), or the literal "dynamic" to run
207 // the script with --user-options. Its keys are the user-facing
208 // option definitions and must be wrapped under "userOptions" so that
209 // JsonWidget::buildOptionGui() recognises them and builds the dialog.
210 QString userOptionsRel =
211 theSender->property("packageUserOptions").toString();
212 if (!userOptionsRel.isEmpty()) {
213 QJsonObject userOpts = QtGui::PackageManager::resolveUserOptions(
214 userOptionsRel, pkgDir, pkgCmd, pkgId);
215 if (!userOpts.isEmpty())
216 opts.insert(QStringLiteral("userOptions"), userOpts);
217 }
218
219 // Pre-populate the cached options so reloadOptions() does not invoke
220 // the script with --print-options.
221 widget->interfaceScript().setOptionsJson(opts);
222 widget->reloadOptions();
223 m_dialogs.insert(key, widget);
224 }
225 } else {
226 key = theSender->data().toString();
227 widget = m_dialogs.value(key, nullptr);
228 if (!widget) {
229 widget = new InterfaceWidget(key, theParent);
230 m_dialogs.insert(key, widget);
231 }
232 }
233
234 widget->setMolecule(m_molecule);
235 m_currentInterface = widget;
236 if (widget->isEmpty()) {
237 run(); // no options, do it immediately
238 return;
239 }
240
241 m_currentDialog = new QDialog(theParent);
242 m_currentDialog->setWindowTitle(theSender->text());
243
244 auto* vbox = new QVBoxLayout();
245 widget->show();
246 vbox->addWidget(widget);
247 auto* buttonBox =
248 new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
249
250 connect(buttonBox, SIGNAL(accepted()), this, SLOT(run()));
251 connect(buttonBox, SIGNAL(rejected()), m_currentDialog, SLOT(reject()));
252 vbox->addWidget(buttonBox);
253 m_currentDialog->setLayout(vbox);
254 m_currentDialog->exec();
255 }
256
257 void Command::run()
258 {
259 if (m_currentDialog)
260 m_currentDialog->accept();
261
262 if (m_progress)
263 m_progress->deleteLater();
264
265 if (m_currentScript) {
266 disconnect(m_currentScript, SIGNAL(finished()), this,
267 SLOT(processFinished()));
268 m_currentScript->deleteLater();
269 }
270
271 if (m_currentInterface) {
272 QJsonObject collected = m_currentInterface->collectOptions();
273 const auto& iface = m_currentInterface->interfaceScript();
274
275 // Create a new InterfaceScript with the same configuration
276 m_currentScript = new InterfaceScript(parent());
277 const auto& interp = iface.interpreter();
278 QJsonObject options;
279 if (interp.isPackageMode()) {
280 m_currentScript->interpreter().setPackageInfo(
281 interp.packageDir(), interp.packageCommand(),
282 interp.packageIdentifier(), interp.packageDisplayName());
283 // Copy cached options so insertMolecule() doesn't call --print-options
284 m_currentScript->setOptionsJson(iface.options());
285 // Wrap user selections under "options" so Python receives them as
286 // avo_input["options"]["key"] (matching the package plugin convention).
287 options.insert(QStringLiteral("options"), collected);
288 } else {
289 m_currentScript->setScriptFilePath(iface.scriptFilePath());
290 options = collected;
291 }
292 connect(m_currentScript, SIGNAL(finished()), this, SLOT(processFinished()));
293
294 // no cancel button - just an indication we're waiting...
295 QString title = tr("Processing %1").arg(iface.displayName());
296 m_progress = new QProgressDialog(title, QString(), 0, 0,
297 qobject_cast<QWidget*>(parent()));
298 m_progress->setMinimumDuration(1000); // 1 second
299
300 m_currentScript->runCommand(options, m_molecule);
301 }
302 }
303
304 void Command::processFinished()
305 {
306 if (m_currentScript == nullptr)
307 return;
308
309 if (m_progress) {
310 m_progress->close();
311 m_progress->deleteLater();
312 m_progress = nullptr;
313 }
314
315 m_currentScript->processCommand(m_molecule);
316
317 // collect errors
318 if (m_currentScript->hasErrors()) {
319 qWarning() << m_currentScript->errorList();
320 }
321 }
322
323 void Command::configurePython()
324 {
325 // Create objects
326 QSettings settings;
327 QDialog dlg(qobject_cast<QWidget*>(parent()));
328 auto* label = new QLabel;
329 auto* layout = new QVBoxLayout;
330 auto* browser = new QtGui::FileBrowseWidget;
331 auto* buttonBox = new QDialogButtonBox;
332
333 // Configure objects
334 // Check for python interpreter in env var
335 QString pythonInterp =
336 QString::fromLocal8Bit(qgetenv("AVO_PYTHON_INTERPRETER"));
337 if (pythonInterp.isEmpty()) {
338 // Check settings
339 pythonInterp = settings.value("interpreters/python", QString()).toString();
340 }
341 // Use compile-time default if still not found.
342 if (pythonInterp.isEmpty())
343 pythonInterp = QString(pythonInterpreterPath);
344 browser->setMode(QtGui::FileBrowseWidget::ExecutableFile);
345 browser->setFileName(pythonInterp);
346
347 buttonBox->setStandardButtons(QDialogButtonBox::Ok |
348 QDialogButtonBox::Cancel);
349
350 dlg.setWindowTitle(tr("Set path to Python interpreter:"));
351 label->setText(
352 tr("Select the python interpreter to run external scripts.\n"
353 "Avogadro must be restarted for any changes to take effect."));
354
355 // Build layout
356 layout->addWidget(label);
357 layout->addWidget(browser);
358 layout->addWidget(buttonBox);
359 dlg.setLayout(layout);
360
361 // Connect
362 connect(buttonBox, SIGNAL(accepted()), &dlg, SLOT(accept()));
363 connect(buttonBox, SIGNAL(rejected()), &dlg, SLOT(reject()));
364
365 // Show dialog
366 auto response = static_cast<QDialog::DialogCode>(dlg.exec());
367 if (response != QDialog::Accepted)
368 return;
369
370 // Handle response
371 settings.setValue("interpreters/python", browser->fileName());
372 }
373
374 void Command::registerFeature(const QString& type, const QString& packageDir,
375 const QString& command, const QString& identifier,
376 const QVariantMap& metadata)
377 {
378 if (type != QLatin1String("menu-commands"))
379 return;
380
381 // Extract the path for the command's menu item
382 // The TOML values that specify this are the following:
383 //
384 // [[menu-commands]]
385 // menu = string | table
386 // submenu = string | table
387 // subsubmenu = string | table
388 // item = string | table
389 // menu-priorities = array[integer]
390 //
391 // The intermediate levels (submenu and subsubmenu) are optional.
392 //
393 // Each label in the cascade (menu, submenu, subsubmenu, item) is either a
394 // normal UTF-8 string or a table of localized strings.
395 // A localization table takes the form:
396 // item = { default = "...", <locale> = "...", <locale> = "...", ... }
397 // (It may of course be formatted as a separate table with a header).
398 // Examples of locale strings are "fr", "de", "de_DE", "en_GB"
399 // Localized strings *must* include a "default" key, which is the fallback
400 // value if the current locale is not found (generally US English, but this
401 // should not be relied upon).
402 //
403 // The menu-priorities array *must* contain exactly 1 fewer integer than the
404 // number of labels (though priority 0 is used as a fallback to avoid crashes)
405 // If the labels are ordered in an array [menu, (submenu), (subsubmenu), item]
406 // the integer at index i in priorities specifies the priority of the label
407 // [i + 1] within label [i], e.g. menu-priorities = [ 400, 200 ] specifies
408 // that the item should have priority 200 within the submenu and the submenu
409 // should have priority 400 within the menu.
410 // Items/submenus within a menu will be displayed in order of priority, with
411 // those with a higher priority nearer to the top. Ties are sorted
412 // alphabetically.
413 // Items with priorities within the same 100 span are grouped together (0-99
414 // in the first group, 100-199 in the next, and so on). A separator is
415 // inserted automatically between each group.
416
417 auto resolveLabel = [](const QVariant& var) -> QString {
418 if (var.typeId() == QMetaType::QVariantMap) {
419 QVariantMap m = var.toMap();
420 // TODO: use the actual locale from --lang arg
421 return m.value(QStringLiteral("default")).toString();
422 }
423 return var.toString();
424 };
425
426 QString topMenu = resolveLabel(metadata.value("menu"));
427 QString subMenu = resolveLabel(metadata.value("submenu"));
428 QString subSubMenu = resolveLabel(metadata.value("subsubmenu"));
429 QString item = resolveLabel(metadata.value("item"));
430
431 // If nothing is specified at all, just add under Extensions > Scripts with
432 // the identifier as the label
433 if (topMenu.isEmpty() && item.isEmpty()) {
434 topMenu = tr("&Extensions");
435 subMenu = tr("Scripts");
436 item = identifier;
437 }
438
439 // Build menu path list
440 QStringList menuPathList;
441 menuPathList << topMenu;
442 if (!subMenu.isEmpty()) {
443 menuPathList << subMenu;
444 }
445 if (!subSubMenu.isEmpty()) {
446 menuPathList << subSubMenu;
447 }
448
449 // Extract priorities
450 QVariantList priorities = metadata.value("menu-priorities").toList();
451 int menuPriority = priorities.size() > 0 ? priorities[0].toInt() : 0;
452 int subMenuPriority = priorities.size() > 1 ? priorities[1].toInt() : 0;
453 int subSubMenuPriority = priorities.size() > 2 ? priorities[2].toInt() : 0;
454
455 // Create the action
456 auto* action = new QAction(item, this);
457 action->setProperty("packageMode", true);
458 action->setProperty("packageDir", packageDir);
459 action->setProperty("packageCommand", command);
460 action->setProperty("packageIdentifier", identifier);
461 action->setProperty("packageDisplayName", item);
462 action->setProperty("packageMenuPath", menuPathList);
463 action->setProperty("packageUserOptions",
464 metadata.value("user-options").toString());
465 action->setProperty("packageInputFormat",
466 metadata.value("input-format").toString());
467 action->setEnabled(true);
468
469 // TODO priorities in higher level menus? Probably needs change in MenuBuilder
470 if (priorities.size() > 0)
471 action->setProperty("menu priority", priorities.last());
472
473 connect(action, SIGNAL(triggered()), SLOT(menuActivated()));
474 m_actions << action;
475 m_packageActions.insert(
476 QtGui::PackageManager::packageFeatureKey(packageDir, command, identifier),
477 action);
478 emit actionsChanged();
479 }
480
481 void Command::unregisterFeature(const QString& type, const QString& packageDir,
482 const QString& command,
483 const QString& identifier)
484 {
485 if (type != QLatin1String("menu-commands"))
486 return;
487
488 const QString featureKey =
489 QtGui::PackageManager::packageFeatureKey(packageDir, command, identifier);
490 const QList<QAction*> actions = m_packageActions.values(featureKey);
491 if (actions.isEmpty())
492 return;
493
494 m_packageActions.remove(featureKey);
495
496 InterfaceWidget* widget = m_dialogs.take(featureKey);
497 if (widget) {
498 if (widget == m_currentInterface) {
499 if (m_currentDialog) {
500 m_currentDialog->reject();
501 m_currentDialog->deleteLater();
502 m_currentDialog = nullptr;
503 }
504 m_currentInterface = nullptr;
505 }
506 delete widget;
507 }
508
509 for (QAction* action : actions) {
510 m_actions.removeAll(action);
511 action->deleteLater();
512 }
513 emit actionsChanged();
514 }
515
516 } // namespace Avogadro::QtPlugins