4 * ***** BEGIN GPL LICENSE BLOCK *****
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * Contributor(s): Campbell Barton
22 * ***** END GPL LICENSE BLOCK *****
25 #include "DNA_listBase.h"
26 #include "RNA_access.h"
28 #include "BLI_dynstr.h"
29 #include "MEM_guardedalloc.h"
30 #include "BKE_report.h"
33 #include "BKE_context.h"
34 bContext* __py_context = NULL;
35 bContext* BPy_GetContext(void) { return __py_context; };
36 void BPy_SetContext(bContext *C) { __py_context= C; };
39 PyObject *BPY_flag_to_list(struct BPY_flag_def *flagdef, int flag)
41 PyObject *list = PyList_New(0);
48 if (fd->flag & flag) {
49 item = PyUnicode_FromString(fd->name);
50 PyList_Append(list, item);
60 static char *bpy_flag_error_str(BPY_flag_def *flagdef)
62 BPY_flag_def *fd= flagdef;
63 DynStr *dynstr= BLI_dynstr_new();
66 BLI_dynstr_append(dynstr, "Error converting a sequence of strings into a flag.\n\tExpected only these strings...\n\t");
69 BLI_dynstr_appendf(dynstr, fd!=flagdef?", '%s'":"'%s'", fd->name);
73 cstring = BLI_dynstr_get_cstring(dynstr);
74 BLI_dynstr_free(dynstr);
78 int BPY_flag_from_seq(BPY_flag_def *flagdef, PyObject *seq, int *flag)
86 if (PySequence_Check(seq)) {
87 i= PySequence_Length(seq);
90 item = PySequence_ITEM(seq, i);
91 cstring= _PyUnicode_AsString(item);
95 if (strcmp(cstring, fd->name) == 0)
99 if (fd==NULL) { /* could not find a match */
116 char *buf = bpy_flag_error_str(flagdef);
117 PyErr_SetString(PyExc_AttributeError, buf);
119 return -1; /* error value */
126 /* Copied from pythons 3's Object.c */
129 Py_CmpToRich(int op, int cmp)
134 if (PyErr_Occurred())
159 res = ok ? Py_True : Py_False;
166 void PyObSpit(char *name, PyObject *var) {
167 fprintf(stderr, "<%s> : ", name);
169 fprintf(stderr, "<NIL>");
172 PyObject_Print(var, stderr, 0);
173 fprintf(stderr, " ref:%d ", var->ob_refcnt);
174 fprintf(stderr, " ptr:%ld", (long)var);
176 fprintf(stderr, " type:");
178 fprintf(stderr, "%s", Py_TYPE(var)->tp_name);
180 fprintf(stderr, "<NIL>");
182 fprintf(stderr, "\n");
185 void PyLineSpit(void) {
190 BPY_getFileAndNum(&filename, &lineno);
192 fprintf(stderr, "%s:%d\n", filename, lineno);
195 void BPY_getFileAndNum(char **filename, int *lineno)
197 PyObject *getframe, *frame;
198 PyObject *f_lineno= NULL, *co_filename= NULL;
200 if (filename) *filename= NULL;
201 if (lineno) *lineno = -1;
203 getframe = PySys_GetObject("_getframe"); // borrowed
204 if (getframe==NULL) {
208 frame = PyObject_CallObject(getframe, NULL);
213 co_filename= PyObject_GetAttrStringArgs(frame, 1, "f_code", "co_filename");
214 if (co_filename==NULL) {
215 PyErr_SetString(PyExc_SystemError, "Could not access sys._getframe().f_code.co_filename");
220 *filename = _PyUnicode_AsString(co_filename);
221 Py_DECREF(co_filename);
225 f_lineno= PyObject_GetAttrString(frame, "f_lineno");
226 if (f_lineno==NULL) {
227 PyErr_SetString(PyExc_SystemError, "Could not access sys._getframe().f_lineno");
232 *lineno = (int)PyLong_AsSsize_t(f_lineno);
239 /* Would be nice if python had this built in */
240 PyObject *PyObject_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...)
249 for (i=0; i<n; i++) {
250 attr = va_arg(vargs, char *);
251 item = PyObject_GetAttrString(item, attr);
255 else /* python will set the error value here */
261 Py_XINCREF(item); /* final value has is increfed, to match PyObject_GetAttrString */
265 int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_class, BPY_class_attr_check* class_attrs, PyObject **py_class_attrs)
267 PyObject *item, *fitem;
268 PyObject *py_arg_count;
272 if (!PyObject_IsSubclass(class, base_class)) {
273 PyObject *name= PyObject_GetAttrString(base_class, "__name__");
274 PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
280 for(i= 0;class_attrs->name; class_attrs++, i++) {
281 item = PyObject_GetAttrString(class, class_attrs->name);
284 py_class_attrs[i]= item;
287 if ((class_attrs->flag & BPY_CLASS_ATTR_OPTIONAL)==0) {
288 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, class_attrs->name);
295 Py_DECREF(item); /* no need to keep a ref, the class owns it */
297 if((item==Py_None) && (class_attrs->flag & BPY_CLASS_ATTR_NONE_OK)) {
298 /* dont do anything, this is ok, dont bother checking other types */
301 switch(class_attrs->type) {
303 if (PyUnicode_Check(item)==0) {
304 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a string", class_type, class_attrs->name);
309 if (PyList_Check(item)==0) {
310 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a list", class_type, class_attrs->name);
315 if (PyMethod_Check(item))
316 fitem= PyMethod_Function(item); /* py 2.x */
318 fitem= item; /* py 3.x */
320 if (PyFunction_Check(fitem)==0) {
321 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, class_attrs->name);
324 if (class_attrs->arg_count >= 0) { /* -1 if we dont care*/
325 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
326 arg_count = PyLong_AsSsize_t(py_arg_count);
327 Py_DECREF(py_arg_count);
329 if (arg_count != class_attrs->arg_count) {
330 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, class_attrs->name, class_attrs->arg_count);
344 /* returns the exception string as a new PyUnicode object, depends on external StringIO module */
345 PyObject *BPY_exception_buffer(void)
347 PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
348 PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
349 PyObject *string_io = NULL;
350 PyObject *string_io_buf = NULL;
351 PyObject *string_io_mod;
352 PyObject *string_io_getvalue;
354 PyObject *error_type, *error_value, *error_traceback;
356 if (!PyErr_Occurred())
359 PyErr_Fetch(&error_type, &error_value, &error_traceback);
363 /* import StringIO / io
364 * string_io = StringIO.StringIO()
367 #if PY_VERSION_HEX < 0x03000000
368 if(! (string_io_mod= PyImport_ImportModule("StringIO")) ) {
370 if(! (string_io_mod= PyImport_ImportModule("io")) ) {
373 } else if (! (string_io = PyObject_CallMethod(string_io_mod, "StringIO", NULL))) {
374 Py_DECREF(string_io_mod);
376 } else if (! (string_io_getvalue= PyObject_GetAttrString(string_io, "getvalue"))) {
377 Py_DECREF(string_io_mod);
378 Py_DECREF(string_io);
382 Py_INCREF(stdout_backup); // since these were borrowed we dont want them freed when replaced.
383 Py_INCREF(stderr_backup);
385 PySys_SetObject("stdout", string_io); // both of these are free'd when restoring
386 PySys_SetObject("stderr", string_io);
388 PyErr_Restore(error_type, error_value, error_traceback);
389 PyErr_Print(); /* print the error */
392 string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
394 PySys_SetObject("stdout", stdout_backup);
395 PySys_SetObject("stderr", stderr_backup);
397 Py_DECREF(stdout_backup); /* now sys owns the ref again */
398 Py_DECREF(stderr_backup);
400 Py_DECREF(string_io_mod);
401 Py_DECREF(string_io_getvalue);
402 Py_DECREF(string_io); /* free the original reference */
405 return string_io_buf;
408 char *BPy_enum_as_string(EnumPropertyItem *item)
410 DynStr *dynstr= BLI_dynstr_new();
414 for (e= item; item->identifier; item++) {
415 BLI_dynstr_appendf(dynstr, (e==item)?"'%s'":", '%s'", item->identifier);
418 cstring = BLI_dynstr_get_cstring(dynstr);
419 BLI_dynstr_free(dynstr);
423 int BPy_reports_to_error(ReportList *reports)
427 report_str= BKE_reports_string(reports, RPT_ERROR);
430 PyErr_SetString(PyExc_SystemError, report_str);
431 MEM_freeN(report_str);
434 return (report_str != NULL);
438 int BPy_errors_to_report(ReportList *reports)
443 if (!PyErr_Occurred())
446 /* less hassle if we allow NULL */
453 pystring= BPY_exception_buffer();
456 BKE_report(reports, RPT_ERROR, "unknown py-exception, could not convert");
460 cstring= _PyUnicode_AsString(pystring);
462 BKE_report(reports, RPT_ERROR, cstring);
463 fprintf(stderr, "%s\n", cstring); // not exactly needed. just for testing