Debian Codegraph @

avogadro/qtgui/pythonscript.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 "pythonscript.h"
7
8 #include "avogadropython.h"
9 #include "utilities.h"
10
11 #include <QtCore/QDebug>
12 #include <QtCore/QDir>
13 #include <QtCore/QFileInfo>
14 #include <QtCore/QLocale>
15 #include <QtCore/QProcess>
16 #include <QtCore/QSettings>
17 #include <QtCore/QStandardPaths>
18
19 namespace Avogadro::QtGui {
20
21 // Check whether the plugin directory has a usable pixi-managed python
22 static bool hasDefaultPixiManifest(const QString& pluginDir)
23 {
24 if (!QDir(pluginDir + "/.pixi").exists())
25 return false;
26
27 QString pythonPath = "/.pixi/envs/default/bin/";
28 #ifdef Q_OS_WIN
29 pythonPath += "python.exe";
30 #else
31 pythonPath += "python";
32 #endif
33 QFileInfo python(pluginDir + pythonPath);
34 return python.exists() && python.isExecutable();
35 }
36
37 PythonScript::PythonScript(const QString& scriptFilePath_, QObject* parent_)
38 : QObject(parent_), m_debug(!qgetenv("AVO_PYTHON_SCRIPT_DEBUG").isEmpty()),
39 m_scriptFilePath(scriptFilePath_), m_process(nullptr)
40 {
41 setDefaultPythonInterpreter();
42 }
43
44 PythonScript::PythonScript(QObject* parent_)
45 : QObject(parent_), m_debug(!qgetenv("AVO_PYTHON_SCRIPT_DEBUG").isEmpty()),
46 m_process(nullptr)
47 {
48 setDefaultPythonInterpreter();
49 }
50
51 PythonScript::~PythonScript() {}
52
53 void PythonScript::setScriptFilePath(const QString& scriptFile)
54 {
55 m_scriptFilePath = scriptFile;
56 m_packageMode = false;
57 m_packageDir.clear();
58 m_packageCommand.clear();
59 m_packageIdentifier.clear();
60 m_packageDisplayName.clear();
61 }
62
63 void PythonScript::setPackageInfo(const QString& packageDir,
64 const QString& command,
65 const QString& identifier,
66 const QString& displayName)
67 {
68 m_packageDir = packageDir;
69 m_packageCommand = command;
70 m_packageIdentifier = identifier;
71 m_packageDisplayName = displayName;
72 m_packageMode = true;
73 m_scriptFilePath.clear();
74 }
75
76 void PythonScript::setDefaultPythonInterpreter()
77 {
78 if (m_pythonInterpreter.isEmpty()) {
79 m_pythonInterpreter =
80 QSettings().value(QStringLiteral("interpreters/python")).toString();
81 }
82 if (m_pythonInterpreter.isEmpty())
83 // compiled-in default
84 m_pythonInterpreter = pythonInterpreterPath;
85
86 // check to see if the interpreter exists and is executable
87 QFileInfo info(m_pythonInterpreter);
88 if (!info.isExecutable()) {
89 #ifndef NDEBUG
90 qWarning() << "Python interpreter" << m_pythonInterpreter
91 << "does not exist trying \"python\" in your path."
92 << "Please set a path to the python interpreter.";
93 #endif
94
95 // let's try to find a python
96 #ifdef Q_OS_WIN
97 QString python("python.exe");
98 #else
99 QString python("python3");
100 #endif
101
102 QString path = Utilities::findExecutablePath(python);
103 if (path.isEmpty()) {
104 qWarning() << "Can't find python in your path";
105 } else {
106 // add a "/" to the end
107 path.append('/');
108 }
109 m_pythonInterpreter = path + python;
110 }
111
112 // check if we have pixi
113 #ifdef Q_OS_WIN
114 QString pixi("pixi.exe");
115 #else
116 QString pixi("pixi");
117 #endif
118
119 m_pixi = Utilities::findExecutablePath(pixi);
120 #ifndef NDEBUG
121 if (m_pixi.isEmpty()) {
122 qWarning() << "Can't find pixi in your path";
123 }
124 #endif
125 }
126
127 QString PythonScript::resolveCommand(QStringList& realArgs, QProcess& proc)
128 {
129 // --- Package mode: pixi run <command> <identifier> [args] ---
130 if (m_packageMode) {
131 if (m_pixi.isEmpty()) {
132 m_errors << tr("Package mode requires pixi but it was not found.");
133 return QString();
134 }
135
136 realArgs.prepend(m_packageIdentifier);
137 realArgs.prepend(m_packageCommand);
138 realArgs.prepend("--as-is");
139 realArgs.prepend("run");
140
141 proc.setWorkingDirectory(m_packageDir);
142
143 #ifdef Q_OS_WIN
144 return m_pixi + "/pixi.exe";
145 #else
146 return m_pixi + "/pixi";
147 #endif
148 }
149
150 // --- Script file mode ---
151 realArgs.prepend(m_scriptFilePath);
152
153 // Check if the user installed the default pixi manifest
154 QString pluginDir =
155 QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
156 bool defaultManifest = hasDefaultPixiManifest(pluginDir);
157
158 if (!defaultManifest || m_pixi.isEmpty()) {
159 // Plain python — no pixi available
160 return m_pythonInterpreter;
161 }
162
163 // Prepend "python" for .py scripts so pixi knows the interpreter
164 if (m_scriptFilePath.endsWith(".py"))
165 realArgs.prepend("python");
166
167 realArgs.prepend("--as-is");
168
169 // Check if the script directory (or its parent) has a .pixi directory
170 QString scriptDirPath(QFileInfo(m_scriptFilePath).absolutePath());
171 bool hasPixiDir = QDir(scriptDirPath + "/.pixi").exists() ||
172 QDir(scriptDirPath + "/../.pixi").exists();
173
174 // Use the default manifest if the script doesn't have its own .pixi
175 // directory and isn't in the user plugin directory (i.e., we bundled it)
176 if (!pluginDir.isEmpty() && !hasPixiDir &&
177 !m_scriptFilePath.startsWith(pluginDir)) {
178 #ifndef NDEBUG
179 qDebug() << "Using manifest in" << pluginDir;
180 #endif
181 realArgs.prepend(pluginDir);
182 realArgs.prepend("--manifest-path");
183 } else if (hasPixiDir || m_scriptFilePath.startsWith(pluginDir)) {
184 proc.setWorkingDirectory(scriptDirPath);
185 } else {
186 if (m_debug) {
187 qDebug() << "No valid pixi manifest configuration found for"
188 << m_scriptFilePath;
189 }
190 return QString();
191 }
192
193 realArgs.prepend("run");
194
195 #ifdef Q_OS_WIN
196 return m_pixi + "/pixi.exe";
197 #else
198 return m_pixi + "/pixi";
199 #endif
200 }
201
202 QByteArray PythonScript::execute(const QStringList& args,
203 const QByteArray& scriptStdin)
204 {
205 clearErrors();
206 QProcess proc;
207 proc.setProcessChannelMode(QProcess::SeparateChannels);
208
209 QStringList realArgs(args);
210 if (m_debug)
211 realArgs.prepend(QStringLiteral("--debug"));
212 realArgs.append("--lang");
213 realArgs.append(QLocale().name());
214
215 QString program = resolveCommand(realArgs, proc);
216 if (program.isEmpty())
217 return QByteArray();
218
219 if (m_debug) {
220 qDebug() << "Executing" << program << realArgs.join(QStringLiteral(" "))
221 << "<" << scriptStdin;
222 if (!proc.workingDirectory().isEmpty())
223 qDebug() << "Working directory is" << proc.workingDirectory();
224 }
225 proc.start(program, realArgs);
226
227 // Write scriptStdin to the process's stdin
228 if (!scriptStdin.isNull()) {
229 if (!proc.waitForStarted(10000)) {
230 m_errors << tr("Error running script '%1 %2': Timed out waiting for "
231 "start (%3).")
232 .arg(program, realArgs.join(QStringLiteral(" ")),
233 processErrorString(proc));
234 return QByteArray();
235 }
236
237 qint64 len = proc.write(scriptStdin);
238 if (len != static_cast<qint64>(scriptStdin.size()) && m_debug) {
239 m_errors << tr("Error running script '%1 %2': failed to write to stdin "
240 "(len=%3, wrote %4 bytes, QProcess error: %5).")
241 .arg(program)
242 .arg(realArgs.join(QStringLiteral(" ")))
243 .arg(scriptStdin.size())
244 .arg(len)
245 .arg(processErrorString(proc));
246 return QByteArray();
247 }
248 proc.closeWriteChannel();
249 }
250
251 if (!proc.waitForFinished(10000)) {
252 if (m_debug)
253 m_errors << tr("Error running script '%1 %2': Timed out waiting for "
254 "finish (%3).")
255 .arg(program, realArgs.join(QStringLiteral(" ")),
256 processErrorString(proc));
257 proc.kill();
258 return QByteArray();
259 }
260
261 if (proc.exitStatus() != QProcess::NormalExit || proc.exitCode() != 0) {
262 if (m_debug)
263 m_errors << tr("Error running script '%1 %2': Abnormal exit status %3 "
264 "(%4: %5)\n\nOutput:\n%6")
265 .arg(program)
266 .arg(realArgs.join(QStringLiteral(" ")))
267 .arg(proc.exitCode())
268 .arg(processErrorString(proc))
269 .arg(proc.errorString())
270 .arg(QString(proc.readAllStandardOutput()) +
271 QString(proc.readAllStandardError()));
272 else
273 m_errors << tr("Warning '%1'").arg(proc.errorString());
274 return QByteArray();
275 }
276
277 QByteArray result(proc.readAllStandardOutput());
278 QByteArray stderrOutput(proc.readAllStandardError());
279
280 if (m_debug) {
281 if (!stderrOutput.isEmpty())
282 qDebug() << "Script stderr:" << stderrOutput;
283
284 qDebug() << "Output:" << result;
285 qDebug() << " Errors: " << m_errors;
286 }
287
288 return result;
289 }
290
291 void PythonScript::asyncExecute(const QStringList& args,
292 const QByteArray& scriptStdin,
293 bool mergedChannels, bool closeWriteChannel)
294 {
295 clearErrors();
296 if (m_process != nullptr) {
297 m_process->terminate();
298 disconnect(m_process, SIGNAL(finished()), this, SLOT(processsFinished()));
299 m_process->deleteLater();
300 }
301 m_process = new QProcess(parent());
302
303 if (mergedChannels)
304 m_process->setProcessChannelMode(QProcess::MergedChannels);
305
306 QStringList realArgs(args);
307 if (m_debug)
308 realArgs.prepend(QStringLiteral("--debug"));
309 realArgs.append("--lang");
310 realArgs.append(QLocale().name());
311
312 QString program = resolveCommand(realArgs, *m_process);
313 if (program.isEmpty())
314 return;
315
316 if (m_debug) {
317 qDebug() << "Executing" << program << realArgs.join(QStringLiteral(" "))
318 << "<" << scriptStdin;
319 if (!m_process->workingDirectory().isEmpty())
320 qDebug() << "Working directory is" << m_process->workingDirectory();
321 }
322 m_process->start(program, realArgs);
323
324 // Write scriptStdin to the process's stdin
325 if (!scriptStdin.isNull()) {
326 if (!m_process->waitForStarted(5000)) {
327 m_errors << tr("Error running script '%1 %2': Timed out waiting for "
328 "start (%3).")
329 .arg(program, realArgs.join(QStringLiteral(" ")),
330 processErrorString(*m_process));
331 return;
332 }
333
334 qint64 len = m_process->write(scriptStdin);
335 if (len != static_cast<qint64>(scriptStdin.size())) {
336 m_errors << tr("Error running script '%1 %2': failed to write to stdin "
337 "(len=%3, wrote %4 bytes, QProcess error: %5).")
338 .arg(program)
339 .arg(realArgs.join(QStringLiteral(" ")))
340 .arg(scriptStdin.size())
341 .arg(len)
342 .arg(processErrorString(*m_process));
343 return;
344 }
345 if (closeWriteChannel)
346 m_process->closeWriteChannel();
347 }
348
349 // let the script run
350 connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this,
351 SLOT(processFinished(int, QProcess::ExitStatus)));
352 }
353
354 void PythonScript::processFinished(int, QProcess::ExitStatus)
355 {
356 emit finished();
357 }
358
359 void PythonScript::asyncTerminate()
360 {
361 if (m_process != nullptr) {
362 disconnect(m_process, nullptr, nullptr, nullptr);
363 m_process->kill();
364 m_process->deleteLater();
365 m_process = nullptr;
366 }
367 }
368
369 QByteArray PythonScript::asyncWriteAndResponse(QByteArray input)
370 {
371 if (m_process == nullptr)
372 return QByteArray();
373
374 m_process->write(input);
375 QByteArray buffer;
376 if (m_process->waitForReadyRead()) {
377 while (m_process->canReadLine())
378 buffer += m_process->readLine();
379 }
380 return buffer;
381 }
382
383 QByteArray PythonScript::asyncWriteAndResponseRaw(const QByteArray& input,
384 int timeoutMs)
385 {
386 if (m_process == nullptr) {
387 return QByteArray(); // wait
388 }
389
390 if (!input.isEmpty()) {
391 const qint64 len = m_process->write(input);
392 if (len != static_cast<qint64>(input.size())) {
393 m_errors << tr("Error writing raw request to script stdin (len=%1, wrote "
394 "%2 bytes, QProcess error: %3).")
395 .arg(input.size())
396 .arg(len)
397 .arg(processErrorString(*m_process));
398 return QByteArray();
399 }
400 }
401
402 QByteArray buffer;
403 if (!m_process->waitForReadyRead(timeoutMs)) {
404 return buffer;
405 }
406
407 buffer += m_process->readAll();
408 // Keep draining while data arrives immediately (no artificial delay).
409 while (m_process->waitForReadyRead(0)) {
410 buffer += m_process->readAll();
411 }
412 return buffer;
413 }
414
415 QByteArray PythonScript::asyncResponse()
416 {
417 if (m_process == nullptr || m_process->state() == QProcess::Running)
418 return QByteArray();
419
420 return m_process->readAll();
421 }
422
423 QString PythonScript::processErrorString(const QProcess& proc) const
424 {
425 QString result;
426 switch (proc.error()) {
427 case QProcess::FailedToStart:
428 result = tr("Script failed to start.");
429 break;
430 case QProcess::Crashed:
431 result = tr("Script crashed.");
432 break;
433 case QProcess::Timedout:
434 result = tr("Script timed out.");
435 break;
436 case QProcess::ReadError:
437 result = tr("Read error.");
438 break;
439 case QProcess::WriteError:
440 result = tr("Write error.");
441 break;
442 default:
443 case QProcess::UnknownError:
444 result = tr("Unknown error.");
445 break;
446 }
447 return result;
448 }
449
450 } // namespace Avogadro::QtGui