cutter/src/common/QtResImporter.cpp

92 lines
2.0 KiB
C++
Raw Normal View History

#ifdef CUTTER_ENABLE_PYTHON
2019-01-12 15:43:51 +00:00
2019-04-08 20:07:35 +00:00
#define Py_LIMITED_API 0x03050000
2018-09-30 18:30:25 +00:00
#include <Python.h>
#include "QtResImporter.h"
#include <QFile>
#include <QDebug>
2019-04-08 20:07:35 +00:00
bool QtResExists(const char *name, QFile &file)
2018-09-30 18:30:25 +00:00
{
QString fname = QString::asprintf(":/python/%s.py", name);
file.setFileName(fname);
2019-04-08 20:07:35 +00:00
return file.exists();
2018-09-30 18:30:25 +00:00
}
PyObject *QtResGetCode(const char *name)
{
QFile moduleFile;
2019-04-08 20:07:35 +00:00
if (!QtResExists(name, moduleFile)) {
2018-09-30 18:30:25 +00:00
return nullptr;
}
moduleFile.open(QIODevice::ReadOnly);
QByteArray data = moduleFile.readAll();
moduleFile.close();
2019-04-08 20:07:35 +00:00
PyObject *codeObject = Py_CompileString(data.constData(),
moduleFile.fileName().toLocal8Bit().constData(),
Py_file_input);
2018-09-30 18:30:25 +00:00
if (!codeObject) {
2019-04-08 20:07:35 +00:00
qWarning() << "Couldn't compile " << moduleFile.fileName();
2018-09-30 18:30:25 +00:00
}
return codeObject;
}
PyObject *QtResImport(const char *name)
{
PyObject *codeObject = QtResGetCode(name);
if (!codeObject) {
2018-09-30 18:30:25 +00:00
return nullptr;
}
2018-09-30 18:30:25 +00:00
PyObject *module = PyImport_ExecCodeModule(name, codeObject);
if (!module) {
PyErr_Print();
}
2018-09-30 18:30:25 +00:00
Py_DECREF(codeObject);
return module;
}
PyObject *qtres_exists(PyObject *self, PyObject *args)
{
Q_UNUSED(self)
char *name;
QFile resFile;
if (!PyArg_ParseTuple(args, "s", &name))
return NULL;
return PyBool_FromLong(QtResExists(name, resFile));
}
PyObject *qtres_get_code(PyObject *self, PyObject *args)
{
Q_UNUSED(self)
char *name;
if (!PyArg_ParseTuple(args, "s", &name))
return NULL;
PyObject *ret = QtResGetCode(name);
if (ret)
return ret;
Py_RETURN_NONE;
}
PyMethodDef QtResMethods[] = {
{ "exists", qtres_exists, METH_VARARGS, NULL },
{ "get_code", qtres_get_code, METH_VARARGS, NULL },
{NULL, NULL, 0, NULL}
};
PyModuleDef QtResModule = {
PyModuleDef_HEAD_INIT, "_qtres", NULL, -1, QtResMethods,
NULL, NULL, NULL, NULL
};
PyObject *PyInit_qtres()
{
return PyModule_Create(&QtResModule);
}
2019-01-12 15:43:51 +00:00
#endif // CUTTER_ENABLE_PYTHON