Manual merge of soc-2009-kazanbas branch:
[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 /* for debugging */
126 void PyObSpit(char *name, PyObject *var) {
127         fprintf(stderr, "<%s> : ", name);
128         if (var==NULL) {
129                 fprintf(stderr, "<NIL>");
130         }
131         else {
132                 PyObject_Print(var, stderr, 0);
133                 fprintf(stderr, " ref:%d ", (int)var->ob_refcnt);
134                 fprintf(stderr, " ptr:%p", (void *)var);
135                 
136                 fprintf(stderr, " type:");
137                 if(Py_TYPE(var))
138                         fprintf(stderr, "%s", Py_TYPE(var)->tp_name);
139                 else
140                         fprintf(stderr, "<NIL>");
141         }
142         fprintf(stderr, "\n");
143 }
144
145 void PyLineSpit(void) {
146         char *filename;
147         int lineno;
148
149         PyErr_Clear();
150         BPY_getFileAndNum(&filename, &lineno);
151         
152         fprintf(stderr, "%s:%d\n", filename, lineno);
153 }
154
155 void BPY_getFileAndNum(char **filename, int *lineno)
156 {
157         PyObject *getframe, *frame;
158         PyObject *f_lineno= NULL, *co_filename= NULL;
159         
160         if (filename)   *filename= NULL;
161         if (lineno)             *lineno = -1;
162         
163         getframe = PySys_GetObject("_getframe"); // borrowed
164         if (getframe==NULL) {
165                 return;
166         }
167         
168         frame = PyObject_CallObject(getframe, NULL);
169         if (frame==NULL)
170                 return;
171         
172         if (filename) {
173                 co_filename= PyObject_GetAttrStringArgs(frame, 1, "f_code", "co_filename");
174                 if (co_filename==NULL) {
175                         PyErr_SetString(PyExc_SystemError, "Could not access sys._getframe().f_code.co_filename");
176                         Py_DECREF(frame);
177                         return;
178                 }
179                 
180                 *filename = _PyUnicode_AsString(co_filename);
181                 Py_DECREF(co_filename);
182         }
183         
184         if (lineno) {
185                 f_lineno= PyObject_GetAttrString(frame, "f_lineno");
186                 if (f_lineno==NULL) {
187                         PyErr_SetString(PyExc_SystemError, "Could not access sys._getframe().f_lineno");
188                         Py_DECREF(frame);
189                         return;
190                 }
191                 
192                 *lineno = (int)PyLong_AsSsize_t(f_lineno);
193                 Py_DECREF(f_lineno);
194         }
195
196         Py_DECREF(frame);
197 }
198
199 /* Would be nice if python had this built in */
200 PyObject *PyObject_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...)
201 {
202         Py_ssize_t i;
203         PyObject *item= o;
204         char *attr;
205         
206         va_list vargs;
207
208         va_start(vargs, n);
209         for (i=0; i<n; i++) {
210                 attr = va_arg(vargs, char *);
211                 item = PyObject_GetAttrString(item, attr);
212                 
213                 if (item) 
214                         Py_DECREF(item);
215                 else /* python will set the error value here */
216                         break;
217                 
218         }
219         va_end(vargs);
220         
221         Py_XINCREF(item); /* final value has is increfed, to match PyObject_GetAttrString */
222         return item;
223 }
224
225 int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_class, BPY_class_attr_check* class_attrs, PyObject **py_class_attrs)
226 {
227         PyObject *item, *fitem;
228         PyObject *py_arg_count;
229         int i, arg_count;
230
231         if (base_class) {
232                 if (!PyObject_IsSubclass(class, base_class)) {
233                         PyObject *name= PyObject_GetAttrString(base_class, "__name__");
234                         PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
235                         Py_XDECREF(name);
236                         return -1;
237                 }
238         }
239         
240         for(i= 0;class_attrs->name; class_attrs++, i++) {
241                 item = PyObject_GetAttrString(class, class_attrs->name);
242
243                 if (py_class_attrs)
244                         py_class_attrs[i]= item;
245                 
246                 if (item==NULL) {
247                         if ((class_attrs->flag & BPY_CLASS_ATTR_OPTIONAL)==0) {
248                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, class_attrs->name);
249                                 return -1;
250                         }
251
252                         PyErr_Clear();
253                 }
254                 else {
255                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
256
257                         if((item==Py_None) && (class_attrs->flag & BPY_CLASS_ATTR_NONE_OK)) {
258                                 /* dont do anything, this is ok, dont bother checking other types */
259                         }
260                         else {
261                                 switch(class_attrs->type) {
262                                 case 's':
263                                         if (PyUnicode_Check(item)==0) {
264                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a string", class_type, class_attrs->name);
265                                                 return -1;
266                                         }
267                                         if(class_attrs->len != -1 && class_attrs->len < PyUnicode_GetSize(item)) {
268                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute string to be shorter then %d", class_type, class_attrs->name, class_attrs->len);
269                                                 return -1;
270                                         }
271
272                                         break;
273                                 case 'l':
274                                         if (PyList_Check(item)==0) {
275                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a list", class_type, class_attrs->name);
276                                                 return -1;
277                                         }
278                                         if(class_attrs->len != -1 && class_attrs->len < PyList_GET_SIZE(item)) {
279                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute list to be shorter then %d", class_type, class_attrs->name, class_attrs->len);
280                                                 return -1;
281                                         }
282                                         break;
283                                 case 'f':
284                                         if (PyMethod_Check(item))
285                                                 fitem= PyMethod_Function(item); /* py 2.x */
286                                         else
287                                                 fitem= item; /* py 3.x */
288
289                                         if (PyFunction_Check(fitem)==0) {
290                                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, class_attrs->name);
291                                                 return -1;
292                                         }
293                                         if (class_attrs->arg_count >= 0) { /* -1 if we dont care*/
294                                                 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
295                                                 arg_count = PyLong_AsSsize_t(py_arg_count);
296                                                 Py_DECREF(py_arg_count);
297
298                                                 if (arg_count != class_attrs->arg_count) {
299                                                         PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, class_attrs->name, class_attrs->arg_count);
300                                                         return -1;
301                                                 }
302                                         }
303                                         break;
304                                 }
305                         }
306                 }
307         }
308         return 0;
309 }
310
311
312
313 /* returns the exception string as a new PyUnicode object, depends on external StringIO module */
314 PyObject *BPY_exception_buffer(void)
315 {
316         PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
317         PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
318         PyObject *string_io = NULL;
319         PyObject *string_io_buf = NULL;
320         PyObject *string_io_mod= NULL;
321         PyObject *string_io_getvalue= NULL;
322         
323         PyObject *error_type, *error_value, *error_traceback;
324         
325         if (!PyErr_Occurred())
326                 return NULL;
327         
328         PyErr_Fetch(&error_type, &error_value, &error_traceback);
329         
330         PyErr_Clear();
331         
332         /* import StringIO / io
333          * string_io = StringIO.StringIO()
334          */
335         
336         if(! (string_io_mod= PyImport_ImportModule("io")) ) {
337                 goto error_cleanup;
338         } else if (! (string_io = PyObject_CallMethod(string_io_mod, "StringIO", NULL))) {
339                 goto error_cleanup;
340         } else if (! (string_io_getvalue= PyObject_GetAttrString(string_io, "getvalue"))) {
341                 goto error_cleanup;
342         }
343         
344         Py_INCREF(stdout_backup); // since these were borrowed we dont want them freed when replaced.
345         Py_INCREF(stderr_backup);
346         
347         PySys_SetObject("stdout", string_io); // both of these are free'd when restoring
348         PySys_SetObject("stderr", string_io);
349         
350         PyErr_Restore(error_type, error_value, error_traceback);
351         PyErr_Print(); /* print the error */
352         PyErr_Clear();
353         
354         string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
355         
356         PySys_SetObject("stdout", stdout_backup);
357         PySys_SetObject("stderr", stderr_backup);
358         
359         Py_DECREF(stdout_backup); /* now sys owns the ref again */
360         Py_DECREF(stderr_backup);
361         
362         Py_DECREF(string_io_mod);
363         Py_DECREF(string_io_getvalue);
364         Py_DECREF(string_io); /* free the original reference */
365         
366         PyErr_Clear();
367         return string_io_buf;
368         
369         
370 error_cleanup:
371         /* could not import the module so print the error and close */
372         Py_XDECREF(string_io_mod);
373         Py_XDECREF(string_io);
374         
375         PyErr_Restore(error_type, error_value, error_traceback);
376         PyErr_Print(); /* print the error */
377         PyErr_Clear();
378         
379         return NULL;
380 }
381
382 char *BPy_enum_as_string(EnumPropertyItem *item)
383 {
384         DynStr *dynstr= BLI_dynstr_new();
385         EnumPropertyItem *e;
386         char *cstring;
387
388         for (e= item; item->identifier; item++) {
389                 if(item->identifier[0])
390                         BLI_dynstr_appendf(dynstr, (e==item)?"'%s'":", '%s'", item->identifier);
391         }
392
393         cstring = BLI_dynstr_get_cstring(dynstr);
394         BLI_dynstr_free(dynstr);
395         return cstring;
396 }
397
398 int BPy_reports_to_error(ReportList *reports)
399 {
400         char *report_str;
401
402         report_str= BKE_reports_string(reports, RPT_ERROR);
403
404         if(report_str) {
405                 PyErr_SetString(PyExc_SystemError, report_str);
406                 MEM_freeN(report_str);
407         }
408
409         return (report_str != NULL);
410 }
411
412
413 int BPy_errors_to_report(ReportList *reports)
414 {
415         PyObject *pystring;
416         char *cstring;
417         
418         if (!PyErr_Occurred())
419                 return 1;
420         
421         /* less hassle if we allow NULL */
422         if(reports==NULL) {
423                 PyErr_Print();
424                 PyErr_Clear();
425                 return 1;
426         }
427         
428         pystring= BPY_exception_buffer();
429         
430         if(pystring==NULL) {
431                 BKE_report(reports, RPT_ERROR, "unknown py-exception, could not convert");
432                 return 0;
433         }
434         
435         cstring= _PyUnicode_AsString(pystring);
436         
437         BKE_report(reports, RPT_ERROR, cstring);
438         fprintf(stderr, "%s\n", cstring); // not exactly needed. just for testing
439         Py_DECREF(pystring);
440         return 1;
441 }