2021-01-11 21:49:54 +00:00
|
|
|
#include "PythonAPI.h"
|
2018-09-30 18:30:25 +00:00
|
|
|
#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);
|
2019-02-27 13:54:47 +00:00
|
|
|
if (!codeObject) {
|
2018-09-30 18:30:25 +00:00
|
|
|
return nullptr;
|
2019-02-27 13:54:47 +00:00
|
|
|
}
|
2018-09-30 18:30:25 +00:00
|
|
|
PyObject *module = PyImport_ExecCodeModule(name, codeObject);
|
2019-02-27 13:54:47 +00:00
|
|
|
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);
|
|
|
|
}
|