/
pythonplugin.cpp
executable file
·355 lines (258 loc) · 10.2 KB
/
pythonplugin.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*******************************************************************************
Copyright The University of Auckland
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*******************************************************************************/
//==============================================================================
// Python plugin
//==============================================================================
// This must be the first include file
#include "Python.h"
//==============================================================================
#include "coreguiutils.h"
#include "pythonplugin.h"
//==============================================================================
#include <QCoreApplication>
#include <QSettings>
//==============================================================================
#include <clocale>
#include <iostream>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#ifdef __FreeBSD__
#include <fenv.h>
#endif
//==============================================================================
namespace OpenCOR {
namespace Python {
//==============================================================================
PLUGININFO_FUNC PythonPluginInfo()
{
Descriptions descriptions;
descriptions.insert("en", QString::fromUtf8("a plugin to provide the <a href=\"https://www.python.org/\">Python</a> language."));
descriptions.insert("fr", QString::fromUtf8("une extension ..."));
return new PluginInfo(PluginInfo::ThirdParty, false, true,
QStringList() << "zlib" << "OpenSSL",
descriptions);
}
//==============================================================================
// CLI interface
//==============================================================================
int PythonPlugin::executeCommand(const QString &pCommand,
const QStringList &pArguments)
{
// Pass the given CLI command to the Python interpreter
if (!pCommand.compare("help")) {
// Display the commands that we support
runHelpCommand();
return 0;
} else if (pCommand.isEmpty() || !pCommand.compare("shell")) {
// Run the Python interpreter
return runPythonShell(pArguments);
} else if (!pCommand.compare("pip")) {
// Run the pip package installer
return runPipInstaller(pArguments);
} else {
// Not a CLI command that we support
runHelpCommand();
return -1;
}
}
//==============================================================================
// Plugin interface
//==============================================================================
bool PythonPlugin::definesPluginInterfaces()
{
// We don't handle this interface...
return false;
}
//==============================================================================
bool PythonPlugin::pluginInterfacesOk(const QString &pFileName,
QObject *pInstance)
{
Q_UNUSED(pFileName);
Q_UNUSED(pInstance);
// We don't handle this interface...
return false;
}
//==============================================================================
void PythonPlugin::initializePlugin()
{
// We must set PYTHONHOME to where Python is 'installed' **before** calling
// any Python library code. Calling `Py_SetPythonHome()` doesn't work as
// the `Py_Initialize()` code first checks the environment and, if PYTHONHOME
// isn't set, uses the installation path compiled in at Python build time...
auto applicationDirectories = QCoreApplication::applicationDirPath().split("/");
applicationDirectories.removeLast();
auto pythonHome = QString();
#if __APPLE__
pythonHome = (applicationDirectories << "Frameworks" << "Python").join("/");
#elif _WIN32
pythonHome = (applicationDirectories << "Python").join("/");
#else
pythonHome = applicationDirectories.join("/");
#endif
qputenv("PYTHONHOME", pythonHome.toUtf8());
// Ensure the user's Python site directory (in ~/.local etc) isn't used
Py_NoUserSiteDirectory = 1;
}
//==============================================================================
void PythonPlugin::finalizePlugin()
{
// We don't handle this interface...
}
//==============================================================================
void PythonPlugin::pluginsInitialized(const Plugins &pLoadedPlugins)
{
Q_UNUSED(pLoadedPlugins);
// We don't handle this interface...
}
//==============================================================================
void PythonPlugin::loadSettings(QSettings *pSettings)
{
Q_UNUSED(pSettings);
// TODO: Retrieve our Python settings
}
//==============================================================================
void PythonPlugin::saveSettings(QSettings *pSettings) const
{
Q_UNUSED(pSettings);
// TODO: Keep track of our Python settings
}
//==============================================================================
void PythonPlugin::handleUrl(const QUrl &pUrl)
{
Q_UNUSED(pUrl);
// We don't handle this interface...
}
//==============================================================================
// Plugin specific
//==============================================================================
void PythonPlugin::runHelpCommand()
{
// Output the commands we support
std::cout << "Commands supported by the Python plugin:" << std::endl;
std::cout << " * Display the commands supported by the Python plugin:" << std::endl;
std::cout << " help" << std::endl;
std::cout << " * Run a Python interpreter:" << std::endl;
std::cout << " shell ..." << std::endl;
std::cout << " * Install Python packages from PyPi:" << std::endl;
std::cout << " pip ..." << std::endl;
}
//==============================================================================
int PythonPlugin::runPipInstaller(const QStringList &pArguments)
{
// A helper macro
#define SET_AND_CHECK_PY_OBJECT(obj, value) \
obj = (value); \
if (obj == nullptr) { \
PyErr_PrintEx(0); \
break; \
}
// In case of failure
int result = -1;
// Python objects we create and use
PyObject
*argList = nullptr,
*pipModule = nullptr,
*pipMain = nullptr,
*argTuple = nullptr,
*pipMainResult = nullptr;
// Initialise the Python interpreter
Py_Initialize();
do {
const int argc = pArguments.size();
// Create a Python list for the arguments
SET_AND_CHECK_PY_OBJECT(argList, PyList_New(argc));
// Copy arguments into the list
for (int i = 0; i < argc; i++) {
PyList_SET_ITEM(argList, i, PyUnicode_FromString(pArguments[i].toUtf8().constData()));
}
// import pip
// pip.main(argList)
SET_AND_CHECK_PY_OBJECT(argTuple, PyTuple_Pack(1, argList));
SET_AND_CHECK_PY_OBJECT(pipModule, PyImport_ImportModule("pip"))
SET_AND_CHECK_PY_OBJECT(pipMain, PyObject_GetAttrString(pipModule, "main"))
SET_AND_CHECK_PY_OBJECT(pipMainResult, PyObject_CallObject(pipMain, argTuple));
// All was well
result = 0;
} while (0);
// Decrement the reference count of our Python objects
Py_XDECREF(pipMain);
Py_XDECREF(pipModule);
Py_XDECREF(argTuple);
Py_XDECREF(argList);
// Finished with the interpreter
Py_Finalize();
return result;
}
//==============================================================================
int PythonPlugin::runPythonShell(const QStringList &pArguments)
{
// The following has been adapted from `Programs/python.c` in the Python sources.
const int argc = pArguments.size() + 1;
wchar_t **argv_copy;
/* We need a second copy, as Python might modify the first one. */
wchar_t **argv_copy2;
int i, res;
char *oldloc;
argv_copy = (wchar_t **)PyMem_RawMalloc(sizeof(wchar_t*) * (argc+1));
argv_copy2 = (wchar_t **)PyMem_RawMalloc(sizeof(wchar_t*) * (argc+1));
if (!argv_copy || !argv_copy2) {
fprintf(stderr, "out of memory\n");
return 1;
}
/* 754 requires that FP exceptions run in "no stop" mode by default,
* and until C vendors implement C99's ways to control FP exceptions,
* Python requires non-stop mode. Alas, some platforms enable FP
* exceptions by default. Here we disable them.
*/
#ifdef __FreeBSD__
fedisableexcept(FE_OVERFLOW);
#endif
oldloc = _PyMem_RawStrdup(setlocale(LC_ALL, NULL));
if (!oldloc) {
fprintf(stderr, "out of memory\n");
return 1;
}
setlocale(LC_ALL, "");
argv_copy2[0] = argv_copy[0] = Py_DecodeLocale("python", NULL);
for (i = 1; i < argc; i++) {
argv_copy[i] = Py_DecodeLocale(pArguments[i-1].toUtf8().constData(), NULL);
if (!argv_copy[i]) {
PyMem_RawFree(oldloc);
fprintf(stderr, "Fatal Python error: "
"unable to decode the command line argument #%i\n",
i + 1);
return 1;
}
argv_copy2[i] = argv_copy[i];
}
argv_copy2[argc] = argv_copy[argc] = NULL;
setlocale(LC_ALL, oldloc);
PyMem_RawFree(oldloc);
// N.B. PyMain() calls Py_Initialize() and Py_Finalize()
res = Py_Main(argc, argv_copy);
for (i = 0; i < argc; i++) {
PyMem_RawFree(argv_copy2[i]);
}
PyMem_RawFree(argv_copy);
PyMem_RawFree(argv_copy2);
return res;
}
//==============================================================================
} // namespace Python
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================