2.5: warning fixes
[blender.git] / source / blender / python / intern / bpy_util.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
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.
10  *
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.
15  *
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.
19  *
20  * Contributor(s): Campbell Barton
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 #include "DNA_listBase.h"
26 #include "RNA_access.h"
27 #include "bpy_util.h"
28 #include "BLI_dynstr.h"
29 #include "MEM_guardedalloc.h"
30 #include "BKE_report.h"
31
32
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; };
37
38
39 PyObject *BPY_flag_to_list(struct BPY_flag_def *flagdef, int flag)
40 {
41         PyObject *list = PyList_New(0);
42         
43         PyObject *item;
44         BPY_flag_def *fd;
45
46         fd= flagdef;
47         while(fd->name) {
48                 if (fd->flag & flag) {
49                         item = PyUnicode_FromString(fd->name);
50                         PyList_Append(list, item);
51                         Py_DECREF(item);
52                 }
53                 fd++;
54         }
55         
56         return list;
57
58 }
59
60 static char *bpy_flag_error_str(BPY_flag_def *flagdef)
61 {
62         BPY_flag_def *fd= flagdef;
63         DynStr *dynstr= BLI_dynstr_new();
64         char *cstring;
65
66         BLI_dynstr_append(dynstr, "Error converting a sequence of strings into a flag.\n\tExpected only these strings...\n\t");
67
68         while(fd->name) {
69                 BLI_dynstr_appendf(dynstr, fd!=flagdef?", '%s'":"'%s'", fd->name);
70                 fd++;
71         }
72         
73         cstring = BLI_dynstr_get_cstring(dynstr);
74         BLI_dynstr_free(dynstr);
75         return cstring;
76 }
77
78 int BPY_flag_from_seq(BPY_flag_def *flagdef, PyObject *seq, int *flag)
79 {
80         int i, error_val= 0;
81         char *cstring;
82         PyObject *item;
83         BPY_flag_def *fd;
84         *flag = 0;
85
86         if (PySequence_Check(seq)) {
87                 i= PySequence_Length(seq);
88
89                 while(i--) {
90                         item = PySequence_ITEM(seq, i);
91                         cstring= _PyUnicode_AsString(item);
92                         if(cstring) {
93                                 fd= flagdef;
94                                 while(fd->name) {
95                                         if (strcmp(cstring, fd->name) == 0)
96                                                 (*flag) |= fd->flag;
97                                         fd++;
98                                 }
99                                 if (fd==NULL) { /* could not find a match */
100                                         error_val= 1;
101                                 }
102                         } else {
103                                 error_val= 1;
104                         }
105                         Py_DECREF(item);
106                 }
107         }
108         else {
109                 error_val= 1;
110         }
111
112         if (*flag == 0)
113                 error_val = 1;
114
115         if (error_val) {
116                 char *buf = bpy_flag_error_str(flagdef);
117                 PyErr_SetString(PyExc_AttributeError, buf);
118                 MEM_freeN(buf);
119                 return -1; /* error value */
120         }
121
122         return 0; /* ok */
123 }
124
125
126 /* Copied from pythons 3's Object.c */
127 PyObject *
128 Py_CmpToRich(int op, int cmp)
129 {
130         PyObject *res;
131         int ok;
132
133         if (PyErr_Occurred())
134                 return NULL;
135         switch (op) {
136         case Py_LT:
137                 ok = cmp <  0;
138                 break;
139         case Py_LE:
140                 ok = cmp <= 0;
141                 break;
142         case Py_EQ:
143                 ok = cmp == 0;
144                 break;
145         case Py_NE:
146                 ok = cmp != 0;
147                 break;
148         case Py_GT:
149                 ok = cmp >  0;
150                 break;
151         case Py_GE:
152                 ok = cmp >= 0;
153                 break;
154         default:
155                 PyErr_BadArgument();
156                 return NULL;
157         }
158         res = ok ? Py_True : Py_False;
159         Py_INCREF(res);
160         return res;
161 }
162
163 /* for debugging */
164 void PyObSpit(char *name, PyObject *var) {
165         fprintf(stderr, "<%s> : ", name);
166         if (var==NULL) {
167                 fprintf(stderr, "<NIL>");
168         }
169         else {
170                 PyObject_Print(var, stderr, 0);
171                 fprintf(stderr, " ref:%d ", (int)var->ob_refcnt);
172                 fprintf(stderr, " ptr:%p", (void *)var);
173                 
174                 fprintf(stderr, " type:");
175                 if(Py_TYPE(var))
176                         fprintf(stderr, "%s", Py_TYPE(var)->tp_name);
177                 else
178                         fprintf(stderr, "<NIL>");
179         }
180         fprintf(stderr, "\n");
181 }
182
183 void PyLineSpit(void) {
184         char *filename;
185         int lineno;
186
187         PyErr_Clear();
188         BPY_getFileAndNum(&filename, &lineno);
189         
190         fprintf(stderr, "%s:%d\n", filename, lineno);
191 }
192
193 void BPY_getFileAndNum(char **filename, int *lineno)
194 {
195         PyObject *getframe, *frame;
196         PyObject *f_lineno= NULL, *co_filename= NULL;
197         
198         if (filename)   *filename= NULL;
199         if (lineno)             *lineno = -1;
200         
201         getframe = PySys_GetObject("_getframe"); // borrowed
202         if (getframe==NULL) {
203                 return;
204         }
205         
206         frame = PyObject_CallObject(getframe, NULL);
207         if (frame==NULL)
208                 return;
209         
210         if (filename) {
211                 co_filename= PyObject_GetAttrStringArgs(frame, 1, "f_code", "co_filename");
212                 if (co_filename==NULL) {
213                         PyErr_SetString(PyExc_SystemError, "Could not access sys._getframe().f_code.co_filename");
214                         Py_DECREF(frame);
215                         return;
216                 }
217                 
218                 *filename = _PyUnicode_AsString(co_filename);
219                 Py_DECREF(co_filename);
220         }
221         
222         if (lineno) {
223                 f_lineno= PyObject_GetAttrString(frame, "f_lineno");
224                 if (f_lineno==NULL) {
225                         PyErr_SetString(PyExc_SystemError, "Could not access sys._getframe().f_lineno");
226                         Py_DECREF(frame);
227                         return;
228                 }
229                 
230                 *lineno = (int)PyLong_AsSsize_t(f_lineno);
231                 Py_DECREF(f_lineno);
232         }
233
234         Py_DECREF(frame);
235 }
236
237 /* Would be nice if python had this built in */
238 PyObject *PyObject_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...)
239 {
240         Py_ssize_t i;
241         PyObject *item= o;
242         char *attr;
243         
244         va_list vargs;
245
246         va_start(vargs, n);
247         for (i=0; i<n; i++) {
248                 attr = va_arg(vargs, char *);
249                 item = PyObject_GetAttrString(item, attr);
250                 
251                 if (item) 
252                         Py_DECREF(item);
253                 else /* python will set the error value here */
254                         break;
255                 
256         }
257         va_end(vargs);
258         
259         Py_XINCREF(item); /* final value has is increfed, to match PyObject_GetAttrString */
260         return item;
261 }
262
263 int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_class, BPY_class_attr_check* class_attrs, PyObject **py_class_attrs)
264 {
265         PyObject *item, *fitem;
266         PyObject *py_arg_count;
267         int i, arg_count;
268
269         if (base_class) {
270                 if (!PyObject_IsSubclass(class, base_class)) {
271                         PyObject *name= PyObject_GetAttrString(base_class, "__name__");
272                         PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
273                         Py_XDECREF(name);
274                         return -1;
275                 }
276         }
277         
278         for(i= 0;class_attrs->name; class_attrs++, i++) {
279                 item = PyObject_GetAttrString(class, class_attrs->name);
280
281                 if (py_class_attrs)
282                         py_class_attrs[i]= item;
283                 
284                 if (item==NULL) {
285                         if ((class_attrs->flag & BPY_CLASS_ATTR_OPTIONAL)==0) {
286                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, class_attrs->name);
287                                 return -1;
288                         }
289
290                         PyErr_Clear();
291                 }
292                 else {
293                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
294
295                         if((item==Py_None) && (class_attrs->flag & BPY_CLASS_ATTR_NONE_OK)) {
296                                 /* dont do anything, this is ok, dont bother checking other types */
297                         }
298                         else {
299                                 switch(class_attrs->type) {
300                                 case 's':
301                                         if (PyUnicode_Check(item)==0) {
302                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a string", class_type, class_attrs->name);
303                                                 return -1;
304                                         }
305                                         if(class_attrs->len != -1 && class_attrs->len < PyUnicode_GetSize(item)) {
306                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute string to be shorter then %d", class_type, class_attrs->name, class_attrs->len);
307                                                 return -1;
308                                         }
309
310                                         break;
311                                 case 'l':
312                                         if (PyList_Check(item)==0) {
313                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a list", class_type, class_attrs->name);
314                                                 return -1;
315                                         }
316                                         if(class_attrs->len != -1 && class_attrs->len < PyList_GET_SIZE(item)) {
317                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute list to be shorter then %d", class_type, class_attrs->name, class_attrs->len);
318                                                 return -1;
319                                         }
320                                         break;
321                                 case 'f':
322                                         if (PyMethod_Check(item))
323                                                 fitem= PyMethod_Function(item); /* py 2.x */
324                                         else
325                                                 fitem= item; /* py 3.x */
326
327                                         if (PyFunction_Check(fitem)==0) {
328                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, class_attrs->name);
329                                                 return -1;
330                                         }
331                                         if (class_attrs->arg_count >= 0) { /* -1 if we dont care*/
332                                                 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
333                                                 arg_count = PyLong_AsSsize_t(py_arg_count);
334                                                 Py_DECREF(py_arg_count);
335
336                                                 if (arg_count != class_attrs->arg_count) {
337                                                         PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, class_attrs->name, class_attrs->arg_count);
338                                                         return -1;
339                                                 }
340                                         }
341                                         break;
342                                 }
343                         }
344                 }
345         }
346         return 0;
347 }
348
349
350
351 /* returns the exception string as a new PyUnicode object, depends on external StringIO module */
352 PyObject *BPY_exception_buffer(void)
353 {
354         PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
355         PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
356         PyObject *string_io = NULL;
357         PyObject *string_io_buf = NULL;
358         PyObject *string_io_mod= NULL;
359         PyObject *string_io_getvalue= NULL;
360         
361         PyObject *error_type, *error_value, *error_traceback;
362         
363         if (!PyErr_Occurred())
364                 return NULL;
365         
366         PyErr_Fetch(&error_type, &error_value, &error_traceback);
367         
368         PyErr_Clear();
369         
370         /* import StringIO / io
371          * string_io = StringIO.StringIO()
372          */
373         
374         if(! (string_io_mod= PyImport_ImportModule("io")) ) {
375                 goto error_cleanup;
376         } else if (! (string_io = PyObject_CallMethod(string_io_mod, "StringIO", NULL))) {
377                 goto error_cleanup;
378         } else if (! (string_io_getvalue= PyObject_GetAttrString(string_io, "getvalue"))) {
379                 goto error_cleanup;
380         }
381         
382         Py_INCREF(stdout_backup); // since these were borrowed we dont want them freed when replaced.
383         Py_INCREF(stderr_backup);
384         
385         PySys_SetObject("stdout", string_io); // both of these are free'd when restoring
386         PySys_SetObject("stderr", string_io);
387         
388         PyErr_Restore(error_type, error_value, error_traceback);
389         PyErr_Print(); /* print the error */
390         PyErr_Clear();
391         
392         string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
393         
394         PySys_SetObject("stdout", stdout_backup);
395         PySys_SetObject("stderr", stderr_backup);
396         
397         Py_DECREF(stdout_backup); /* now sys owns the ref again */
398         Py_DECREF(stderr_backup);
399         
400         Py_DECREF(string_io_mod);
401         Py_DECREF(string_io_getvalue);
402         Py_DECREF(string_io); /* free the original reference */
403         
404         PyErr_Clear();
405         return string_io_buf;
406         
407         
408 error_cleanup:
409         /* could not import the module so print the error and close */
410         Py_XDECREF(string_io_mod);
411         Py_XDECREF(string_io);
412         
413         PyErr_Restore(error_type, error_value, error_traceback);
414         PyErr_Print(); /* print the error */
415         PyErr_Clear();
416         
417         return NULL;
418 }
419
420 char *BPy_enum_as_string(EnumPropertyItem *item)
421 {
422         DynStr *dynstr= BLI_dynstr_new();
423         EnumPropertyItem *e;
424         char *cstring;
425
426         for (e= item; item->identifier; item++) {
427                 if(item->identifier[0])
428                         BLI_dynstr_appendf(dynstr, (e==item)?"'%s'":", '%s'", item->identifier);
429         }
430
431         cstring = BLI_dynstr_get_cstring(dynstr);
432         BLI_dynstr_free(dynstr);
433         return cstring;
434 }
435
436 int BPy_reports_to_error(ReportList *reports)
437 {
438         char *report_str;
439
440         report_str= BKE_reports_string(reports, RPT_ERROR);
441
442         if(report_str) {
443                 PyErr_SetString(PyExc_SystemError, report_str);
444                 MEM_freeN(report_str);
445         }
446
447         return (report_str != NULL);
448 }
449
450
451 int BPy_errors_to_report(ReportList *reports)
452 {
453         PyObject *pystring;
454         char *cstring;
455         
456         if (!PyErr_Occurred())
457                 return 1;
458         
459         /* less hassle if we allow NULL */
460         if(reports==NULL) {
461                 PyErr_Print();
462                 PyErr_Clear();
463                 return 1;
464         }
465         
466         pystring= BPY_exception_buffer();
467         
468         if(pystring==NULL) {
469                 BKE_report(reports, RPT_ERROR, "unknown py-exception, could not convert");
470                 return 0;
471         }
472         
473         cstring= _PyUnicode_AsString(pystring);
474         
475         BKE_report(reports, RPT_ERROR, cstring);
476         fprintf(stderr, "%s\n", cstring); // not exactly needed. just for testing
477         Py_DECREF(pystring);
478         return 1;
479 }