GUIScript: Add ability to call callbacks with an int parameter.
[gemrb.git] / gemrb / plugins / GUIScript / PythonHelpers.cpp
blobe7ce62741cc1659ed7ec5648388cddf5777cd517
1 /* GemRB - Infinity Engine Emulator
2 * Copyright (C) 2003 The GemRB Project
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 #include "PythonHelpers.h"
23 static bool CallPython(PyObject *Function, PyObject *args = NULL)
25 if (!Function) {
26 return false;
28 PyObject *ret = PyObject_CallObject(Function, args);
29 Py_XDECREF( args );
30 if (ret == NULL) {
31 if (PyErr_Occurred()) {
32 PyErr_Print();
34 return false;
36 Py_DECREF(ret);
37 return true;
40 static bool CallPython(PyObject *Function, int arg)
42 if (!Function) {
43 return false;
45 PyObject *args = Py_BuildValue("(i)", arg);
46 return CallPython(Function, args);
49 StringCallback::StringCallback(const char *str)
50 : Name(PyString_FromString(const_cast<char*>(str)))
54 StringCallback::StringCallback(PyObject *Name)
55 : Name(Name)
57 Py_XINCREF(Name);
60 StringCallback::~StringCallback()
62 Py_XDECREF(Name);
65 PyObject *StringCallback::GetFunction()
67 if (!Name || !Py_IsInitialized()) {
68 return NULL;
70 /* Borrowed reference */
71 PyObject *Function = PyDict_GetItem(gs->pDict, Name);
72 if (!Function || !PyCallable_Check(Function)) {
73 printMessage("GUIScript", "Missing callback function:", LIGHT_RED);
74 printf("%s\n", PyString_AsString(Name));
75 return NULL;
77 return Function;
80 bool StringCallback::call()
82 return CallPython(GetFunction());
85 bool StringCallback::call(int arg)
87 return CallPython(GetFunction(), arg);
90 PythonCallback::PythonCallback(PyObject *Function)
91 : Function(Function)
93 if (Function && PyCallable_Check(Function)) {
94 Py_INCREF(Function);
95 } else {
96 Function = NULL;
100 PythonCallback::~PythonCallback()
102 if (Py_IsInitialized()) {
103 Py_XDECREF(Function);
107 bool PythonCallback::call ()
109 if (!Function || !Py_IsInitialized()) {
110 return false;
112 return CallPython(Function);
115 bool PythonCallback::call (int arg)
117 if (!Function || !Py_IsInitialized()) {
118 return false;
120 return CallPython(Function, arg);