aboutsummaryrefslogtreecommitdiffstats
path: root/src/modules/pythoncore/libkvipythoncore.cpp
blob: 11645bdcb290c09d8245aae2c42ebb483f1403b0 (about) (plain) (blame)
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
//=============================================================================
//
//   File : libkvipythoncore.cpp
//   Creation date : Fri Nov 07 00:18:31 2008 GMT by Elvio Basello
//
//   This file is part of the KVIrc IRC client distribution
//   Copyright (C) 2008 Elvio Basello (hellvis69 at netsons dot org)
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the terms of the GNU General Public License
//   as published by the Free Software Foundation; either version 2
//   of the License, or (at your option) any later version.
//
//   This program is distributed in the HOPE that it will be USEFUL,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//   See the GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program. If not, write to the Free Software Foundation,
//   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================

#include <functional>
#include <memory>
#include <unordered_map>
#include <utility>

#include "kvi_settings.h"
#include "KviModule.h"
#include "KviLocale.h"
#include "KviRegExp.h"

#ifdef COMPILE_PYTHON_SUPPORT
#include "pythoncoreinterface.h"

#include "pythonheaderwrapper.h"

KviKvsRunTimeContext * g_pCurrentKvsContext = nullptr;
bool g_bExecuteQuiet = false;
QStringList g_lWarningList;
QString g_lError;

static PyThreadState * mainThreadState = nullptr;

struct KviPythonLock
{
	KviPythonLock(PyThreadState * ts)
	{
		PyEval_RestoreThread(ts);
	}
	~KviPythonLock()
	{
		PyEval_SaveThread();
	}
};

struct KviPythonInterpreterDeleter
{
	void operator()(PyThreadState * ts) const
	{
		KviPythonLock lock{ ts };
		Py_EndInterpreter(ts);
		PyThreadState_Swap(mainThreadState);
	}
};

struct KviPythonInterpreter
{
	KviPythonInterpreter();
	bool execute(QString, QStringList &, QString &, QString &, QStringList &);
	std::unique_ptr<PyThreadState, KviPythonInterpreterDeleter> m_uptrThreadState;
};

struct KviCaseInsensitiveQStringHash
{
	std::size_t operator()(const QString & s) const
	{
		return static_cast<std::size_t>(qHash(s.toLower()));
	}
};

struct KviCaseInsensitiveQStringEqual
{
	bool operator()(const QString & s, const QString & t) const
	{
		return (s.toLower() == t.toLower());
	}
};

static std::unordered_map<QString, KviPythonInterpreter, KviCaseInsensitiveQStringHash, KviCaseInsensitiveQStringEqual> g_Interpreters;

KviPythonInterpreter::KviPythonInterpreter()
{
	KviPythonLock lock{ mainThreadState };
	m_uptrThreadState.reset(Py_NewInterpreter());

	// hook in the kvirc error handling routines
	QString szPreCode = QString(
	    "import kvirc\n"
	    "import sys\n"
	    "class kvirc_stderr_grabber:\n\tdef write(self,s):\n\t\tkvirc.error(s)\n"
	    "sys.stderr=kvirc_stderr_grabber()\n");

	PyRun_SimpleString(szPreCode.toUtf8().data());
}

bool KviPythonInterpreter::execute(QString szCode, QStringList & lArgs,
    QString & szRetVal, QString & szError, QStringList &)
{
	if(!m_uptrThreadState)
	{
		szError = __tr2qs_ctx("Internal error: Python interpreter not initialized", "python");
		return false;
	}

	g_lError.clear();

	KviPythonLock lock{ m_uptrThreadState.get() };

	QString szVarCode = "aArgs = [";

	bool bFirst = true;
	foreach(QString szArg, lArgs)
	{
		if(!bFirst)
			szVarCode += ",";
		else
			bFirst = false;

		szVarCode += QString::fromLatin1("\"%1\"").arg(szArg);
	}

	szVarCode += "]";

	PyRun_SimpleString(szVarCode.toUtf8().data());

	// clean "cr" from the python code (ticket #1028)
	szCode.replace(KviRegExp("\r\n?"), "\n");

	int retVal = PyRun_SimpleString(szCode.toUtf8().data());

	szRetVal.setNum(retVal);

	if(PyErr_Occurred() || retVal)
		szError = g_lError;

	return !retVal;
}

static void pythoncore_destroy_interpreter(const QString & szContextName)
{
	const auto i = g_Interpreters.find(szContextName);

	if(i != g_Interpreters.end())
		g_Interpreters.erase(i);
}

#endif // COMPILE_PYTHON_SUPPORT

template <typename T>
T * castFromModParam(void * p)
{
	T * ex = static_cast<T *>(p);

	if(ex->uSize != sizeof(T))
		return nullptr;

	return ex;
}

static bool pythoncore_module_ctrl(KviModule *, const char * cmd, void * param)
{
#ifdef COMPILE_PYTHON_SUPPORT
	if(!strcmp(cmd, KVI_PYTHONCORECTRLCOMMAND_EXECUTE))
	{
		auto * pex = castFromModParam<KviPythonCoreCtrlCommand_execute>(param);

		if(!pex)
			return false;

		auto & ex = *pex;

		g_pCurrentKvsContext = ex.pKvsContext;
		g_bExecuteQuiet = ex.bQuiet;
		if(ex.szContext.isEmpty())
		{
			KviPythonInterpreter m;
			ex.bExitOk = m.execute(ex.szCode, ex.lArgs, ex.szRetVal, ex.szError, ex.lWarnings);
		}
		else
		{
			KviPythonInterpreter & m = g_Interpreters[ex.szContext];
			ex.bExitOk = m.execute(ex.szCode, ex.lArgs, ex.szRetVal, ex.szError, ex.lWarnings);
		}
		return true;
	}
	if(!strcmp(cmd, KVI_PYTHONCORECTRLCOMMAND_DESTROY))
	{
		auto * pde = castFromModParam<KviPythonCoreCtrlCommand_destroy>(param);

		if(!pde)
			return false;

		pythoncore_destroy_interpreter(pde->szContext);
		return true;
	}
#endif // COMPILE_PYTHON_SUPPORT
	return false;
}

static bool pythoncore_module_init(KviModule *)
{
#ifdef COMPILE_PYTHON_SUPPORT
	Py_Initialize();
#if PY_VERSION_HEX < 0x03070000
	PyEval_InitThreads();
#endif

	mainThreadState = PyEval_SaveThread();

	if(!g_Interpreters.empty())
		qDebug("libkvipythoncore: init(): Called init twice??");

	return true;
#endif // COMPILE_PYTHON_SUPPORT
	return false;
}

static bool pythoncore_module_cleanup(KviModule *)
{
#ifdef COMPILE_PYTHON_SUPPORT
	g_Interpreters.clear();
	PyEval_RestoreThread(mainThreadState);
	Py_Finalize();
#endif // COMPILE_PYTHON_SUPPORT
	return true;
}

static bool pythoncore_module_can_unload(KviModule *)
{
#ifdef COMPILE_PYTHON_SUPPORT
	return g_Interpreters.empty();
#endif // COMPILE_PYTHON_SUPPORT
	return true;
}

KVIRC_MODULE(
    "PythonCore", // module name
    "4.0.0",      // module version
    "Copyright (C) 2008 Elvio Basello (hellvis69 at netsons dot org)\n"
    "Copyright (C) 2009 Fabio Bas (ctrlaltca at libero dot it)\n"
    "Copyright (C) 2016 Matt Ullman (staticfox at staticfox dot net)",
    "Python Scripting Engine Core",
    pythoncore_module_init,
    pythoncore_module_can_unload,
    pythoncore_module_ctrl,
    pythoncore_module_cleanup,
    "python")