svn merge -r40197:40311 ^/trunk/blender
[blender.git] / source / blender / python / generic / py_capi_utils.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21 */
22
23 /** \file blender/python/generic/py_capi_utils.c
24  *  \ingroup pygen
25  */
26
27
28 #include <Python.h>
29 #include <frameobject.h>
30
31 #include "py_capi_utils.h"
32
33 #include "BKE_font.h" /* only for utf8towchar, should replace with py funcs but too late in release now */
34
35 #ifdef _WIN32 /* BLI_setenv */
36 #include "BLI_path_util.h"
37 #endif
38
39 /* array utility function */
40 int PyC_AsArray(void *array, PyObject *value, const int length, const PyTypeObject *type, const short is_double, const char *error_prefix)
41 {
42         PyObject *value_fast;
43         int value_len;
44         int i;
45
46         if(!(value_fast=PySequence_Fast(value, error_prefix))) {
47                 return -1;
48         }
49
50         value_len= PySequence_Fast_GET_SIZE(value_fast);
51
52         if(value_len != length) {
53                 Py_DECREF(value);
54                 PyErr_Format(PyExc_TypeError,
55                              "%.200s: invalid sequence length. expected %d, got %d",
56                              error_prefix, length, value_len);
57                 return -1;
58         }
59
60         /* for each type */
61         if(type == &PyFloat_Type) {
62                 if(is_double) {
63                         double *array_double= array;
64                         for(i=0; i<length; i++) {
65                                 array_double[i]= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i));
66                         }
67                 }
68                 else {
69                         float *array_float= array;
70                         for(i=0; i<length; i++) {
71                                 array_float[i]= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i));
72                         }
73                 }
74         }
75         else if(type == &PyLong_Type) {
76                 /* could use is_double for 'long int' but no use now */
77                 int *array_int= array;
78                 for(i=0; i<length; i++) {
79                         array_int[i]= PyLong_AsSsize_t(PySequence_Fast_GET_ITEM(value_fast, i));
80                 }
81         }
82         else if(type == &PyBool_Type) {
83                 int *array_bool= array;
84                 for(i=0; i<length; i++) {
85                         array_bool[i]= (PyLong_AsSsize_t(PySequence_Fast_GET_ITEM(value_fast, i)) != 0);
86                 }
87         }
88         else {
89                 Py_DECREF(value_fast);
90                 PyErr_Format(PyExc_TypeError,
91                              "%s: internal error %s is invalid",
92                              error_prefix, type->tp_name);
93                 return -1;
94         }
95
96         Py_DECREF(value_fast);
97
98         if(PyErr_Occurred()) {
99                 PyErr_Format(PyExc_TypeError,
100                              "%s: one or more items could not be used as a %s",
101                              error_prefix, type->tp_name);
102                 return -1;
103         }
104
105         return 0;
106 }
107
108
109 /* for debugging */
110 void PyC_ObSpit(const char *name, PyObject *var) {
111         fprintf(stderr, "<%s> : ", name);
112         if (var==NULL) {
113                 fprintf(stderr, "<NIL>");
114         }
115         else {
116                 PyObject_Print(var, stderr, 0);
117                 fprintf(stderr, " ref:%d ", (int)var->ob_refcnt);
118                 fprintf(stderr, " ptr:%p", (void *)var);
119                 
120                 fprintf(stderr, " type:");
121                 if(Py_TYPE(var))
122                         fprintf(stderr, "%s", Py_TYPE(var)->tp_name);
123                 else
124                         fprintf(stderr, "<NIL>");
125         }
126         fprintf(stderr, "\n");
127 }
128
129 void PyC_LineSpit(void) {
130
131         const char *filename;
132         int lineno;
133
134         /* Note, allow calling from outside python (RNA) */
135         if(!PYC_INTERPRETER_ACTIVE) {
136                 fprintf(stderr, "python line lookup failed, interpreter inactive\n");
137                 return;
138         }
139
140         PyErr_Clear();
141         PyC_FileAndNum(&filename, &lineno);
142         
143         fprintf(stderr, "%s:%d\n", filename, lineno);
144 }
145
146 void PyC_FileAndNum(const char **filename, int *lineno)
147 {
148         PyFrameObject *frame;
149         
150         if (filename)   *filename= NULL;
151         if (lineno)             *lineno = -1;
152
153         if (!(frame= PyThreadState_GET()->frame)) {
154                 return;
155         }
156
157         /* when executing a script */
158         if (filename) {
159                 *filename = _PyUnicode_AsString(frame->f_code->co_filename);
160         }
161
162         /* when executing a module */
163         if(filename && *filename == NULL) {
164                 /* try an alternative method to get the filename - module based
165                  * references below are all borrowed (double checked) */
166                 PyObject *mod_name= PyDict_GetItemString(PyEval_GetGlobals(), "__name__");
167                 if(mod_name) {
168                         PyObject *mod= PyDict_GetItem(PyImport_GetModuleDict(), mod_name);
169                         if(mod) {
170                                 *filename= PyModule_GetFilename(mod);
171                         }
172
173                         /* unlikely, fallback */
174                         if(*filename == NULL) {
175                                 *filename= _PyUnicode_AsString(mod_name);
176                         }
177                 }
178         }
179
180         if (lineno) {
181                 *lineno = PyFrame_GetLineNumber(frame);
182         }
183 }
184
185 /* Would be nice if python had this built in */
186 PyObject *PyC_Object_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...)
187 {
188         Py_ssize_t i;
189         PyObject *item= o;
190         char *attr;
191         
192         va_list vargs;
193
194         va_start(vargs, n);
195         for (i=0; i<n; i++) {
196                 attr = va_arg(vargs, char *);
197                 item = PyObject_GetAttrString(item, attr);
198                 
199                 if (item) 
200                         Py_DECREF(item);
201                 else /* python will set the error value here */
202                         break;
203                 
204         }
205         va_end(vargs);
206         
207         Py_XINCREF(item); /* final value has is increfed, to match PyObject_GetAttrString */
208         return item;
209 }
210
211 /* similar to PyErr_Format(),
212  *
213  * implimentation - we cant actually preprend the existing exception,
214  * because it could have _any_ argiments given to it, so instead we get its
215  * __str__ output and raise our own exception including it.
216  */
217 PyObject *PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format, ...)
218 {
219         PyObject *error_value_prefix;
220         va_list args;
221
222         va_start(args, format);
223         error_value_prefix= PyUnicode_FromFormatV(format, args); /* can fail and be NULL */
224         va_end(args);
225
226         if(PyErr_Occurred()) {
227                 PyObject *error_type, *error_value, *error_traceback;
228                 PyErr_Fetch(&error_type, &error_value, &error_traceback);
229                 PyErr_Format(exception_type_prefix,
230                              "%S, %.200s(%S)",
231                              error_value_prefix,
232                              Py_TYPE(error_value)->tp_name,
233                              error_value
234                              );
235         }
236         else {
237                 PyErr_SetObject(exception_type_prefix,
238                                 error_value_prefix
239                                 );
240         }
241
242         Py_XDECREF(error_value_prefix);
243
244         /* dumb to always return NULL but matches PyErr_Format */
245         return NULL;
246 }
247
248
249 /* returns the exception string as a new PyUnicode object, depends on external traceback module */
250 #if 0
251
252 /* this version uses traceback module but somehow fails on UI errors */
253
254 PyObject *PyC_ExceptionBuffer(void)
255 {
256         PyObject *traceback_mod= NULL;
257         PyObject *format_tb_func= NULL;
258         PyObject *ret= NULL;
259
260         if(! (traceback_mod= PyImport_ImportModule("traceback")) ) {
261                 goto error_cleanup;
262         }
263         else if (! (format_tb_func= PyObject_GetAttrString(traceback_mod, "format_exc"))) {
264                 goto error_cleanup;
265         }
266
267         ret= PyObject_CallObject(format_tb_func, NULL);
268
269         if(ret == Py_None) {
270                 Py_DECREF(ret);
271                 ret= NULL;
272         }
273
274 error_cleanup:
275         /* could not import the module so print the error and close */
276         Py_XDECREF(traceback_mod);
277         Py_XDECREF(format_tb_func);
278
279         return ret;
280 }
281 #else /* verbose, non-threadsafe version */
282 PyObject *PyC_ExceptionBuffer(void)
283 {
284         PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
285         PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
286         PyObject *string_io = NULL;
287         PyObject *string_io_buf = NULL;
288         PyObject *string_io_mod= NULL;
289         PyObject *string_io_getvalue= NULL;
290
291         PyObject *error_type, *error_value, *error_traceback;
292
293         if (!PyErr_Occurred())
294                 return NULL;
295
296         PyErr_Fetch(&error_type, &error_value, &error_traceback);
297
298         PyErr_Clear();
299
300         /* import io
301          * string_io = io.StringIO()
302          */
303
304         if(! (string_io_mod= PyImport_ImportModule("io")) ) {
305                 goto error_cleanup;
306         }
307         else if (! (string_io = PyObject_CallMethod(string_io_mod, (char *)"StringIO", NULL))) {
308                 goto error_cleanup;
309         }
310         else if (! (string_io_getvalue= PyObject_GetAttrString(string_io, "getvalue"))) {
311                 goto error_cleanup;
312         }
313
314         Py_INCREF(stdout_backup); // since these were borrowed we dont want them freed when replaced.
315         Py_INCREF(stderr_backup);
316
317         PySys_SetObject("stdout", string_io); // both of these are free'd when restoring
318         PySys_SetObject("stderr", string_io);
319
320         PyErr_Restore(error_type, error_value, error_traceback);
321         PyErr_Print(); /* print the error */
322         PyErr_Clear();
323
324         string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
325
326         PySys_SetObject("stdout", stdout_backup);
327         PySys_SetObject("stderr", stderr_backup);
328
329         Py_DECREF(stdout_backup); /* now sys owns the ref again */
330         Py_DECREF(stderr_backup);
331
332         Py_DECREF(string_io_mod);
333         Py_DECREF(string_io_getvalue);
334         Py_DECREF(string_io); /* free the original reference */
335
336         PyErr_Clear();
337         return string_io_buf;
338
339
340 error_cleanup:
341         /* could not import the module so print the error and close */
342         Py_XDECREF(string_io_mod);
343         Py_XDECREF(string_io);
344
345         PyErr_Restore(error_type, error_value, error_traceback);
346         PyErr_Print(); /* print the error */
347         PyErr_Clear();
348
349         return NULL;
350 }
351 #endif
352
353
354 /* string conversion, escape non-unicode chars, coerce must be set to NULL */
355 const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce)
356 {
357         char *result;
358
359         result= _PyUnicode_AsString(py_str);
360
361         if(result) {
362                 /* 99% of the time this is enough but we better support non unicode
363                  * chars since blender doesnt limit this */
364                 return result;
365         }
366         else if(PyBytes_Check(py_str)) {
367                 PyErr_Clear();
368                 return PyBytes_AS_STRING(py_str);
369         }
370         else {
371                 return PyBytes_AS_STRING((*coerce= PyUnicode_EncodeFSDefault(py_str)));
372         }
373 }
374
375 PyObject *PyC_UnicodeFromByte(const char *str)
376 {
377         PyObject *result= PyUnicode_FromString(str);
378         if(result) {
379                 /* 99% of the time this is enough but we better support non unicode
380                  * chars since blender doesnt limit this */
381                 return result;
382         }
383         else {
384                 PyErr_Clear();
385                 /* this means paths will always be accessible once converted, on all OS's */
386                 result= PyUnicode_DecodeFSDefault(str);
387                 return result;
388         }
389 }
390
391 /*****************************************************************************
392 * Description: This function creates a new Python dictionary object.
393 * note: dict is owned by sys.modules["__main__"] module, reference is borrowed
394 * note: important we use the dict from __main__, this is what python expects
395   for 'pickle' to work as well as strings like this...
396  >> foo = 10
397  >> print(__import__("__main__").foo)
398 *
399 * note: this overwrites __main__ which gives problems with nested calles.
400 * be sure to run PyC_MainModule_Backup & PyC_MainModule_Restore if there is
401 * any chance that python is in the call stack.
402 *****************************************************************************/
403 PyObject *PyC_DefaultNameSpace(const char *filename)
404 {
405         PyInterpreterState *interp= PyThreadState_GET()->interp;
406         PyObject *mod_main= PyModule_New("__main__");   
407         PyDict_SetItemString(interp->modules, "__main__", mod_main);
408         Py_DECREF(mod_main); /* sys.modules owns now */
409         PyModule_AddStringConstant(mod_main, "__name__", "__main__");
410         if(filename)
411                 PyModule_AddStringConstant(mod_main, "__file__", filename); /* __file__ only for nice UI'ness */
412         PyModule_AddObject(mod_main, "__builtins__", interp->builtins);
413         Py_INCREF(interp->builtins); /* AddObject steals a reference */
414         return PyModule_GetDict(mod_main);
415 }
416
417 /* restore MUST be called after this */
418 void PyC_MainModule_Backup(PyObject **main_mod)
419 {
420         PyInterpreterState *interp= PyThreadState_GET()->interp;
421         *main_mod= PyDict_GetItemString(interp->modules, "__main__");
422         Py_XINCREF(*main_mod); /* dont free */
423 }
424
425 void PyC_MainModule_Restore(PyObject *main_mod)
426 {
427         PyInterpreterState *interp= PyThreadState_GET()->interp;
428         PyDict_SetItemString(interp->modules, "__main__", main_mod);
429         Py_XDECREF(main_mod);
430 }
431
432 /* must be called before Py_Initialize, expects output of BLI_get_folder(BLENDER_PYTHON, NULL) */
433 void PyC_SetHomePath(const char *py_path_bundle)
434 {
435         if(py_path_bundle==NULL) {
436                 /* Common enough to have bundled *nix python but complain on OSX/Win */
437 #if defined(__APPLE__) || defined(_WIN32)
438                 fprintf(stderr, "Warning! bundled python not found and is expected on this platform. (if you built with CMake: 'install' target may have not been built)\n");
439 #endif
440                 return;
441         }
442         /* set the environment path */
443         printf("found bundled python: %s\n", py_path_bundle);
444
445 #ifdef __APPLE__
446         /* OSX allow file/directory names to contain : character (represented as / in the Finder)
447          but current Python lib (release 3.1.1) doesn't handle these correctly */
448         if(strchr(py_path_bundle, ':'))
449                 printf("Warning : Blender application is located in a path containing : or / chars\
450                            \nThis may make python import function fail\n");
451 #endif
452
453 #ifdef _WIN32
454         /* cmake/MSVC debug build crashes without this, why only
455            in this case is unknown.. */
456         {
457                 BLI_setenv("PYTHONPATH", py_path_bundle);
458         }
459 #endif
460
461         {
462                 static wchar_t py_path_bundle_wchar[1024];
463
464                 /* cant use this, on linux gives bug: #23018, TODO: try LANG="en_US.UTF-8" /usr/bin/blender, suggested 22008 */
465                 /* mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR); */
466
467                 utf8towchar(py_path_bundle_wchar, py_path_bundle);
468
469                 Py_SetPythonHome(py_path_bundle_wchar);
470                 // printf("found python (wchar_t) '%ls'\n", py_path_bundle_wchar);
471         }
472 }
473
474 /* Would be nice if python had this built in */
475 void PyC_RunQuicky(const char *filepath, int n, ...)
476 {
477         FILE *fp= fopen(filepath, "r");
478
479         if(fp) {
480                 PyGILState_STATE gilstate= PyGILState_Ensure();
481
482                 va_list vargs;  
483
484                 int *sizes= PyMem_MALLOC(sizeof(int) * (n / 2));
485                 int i;
486
487                 PyObject *py_dict = PyC_DefaultNameSpace(filepath);
488                 PyObject *values= PyList_New(n / 2); /* namespace owns this, dont free */
489
490                 PyObject *py_result, *ret;
491
492                 PyObject *struct_mod= PyImport_ImportModule("struct");
493                 PyObject *calcsize= PyObject_GetAttrString(struct_mod, "calcsize"); /* struct.calcsize */
494                 PyObject *pack= PyObject_GetAttrString(struct_mod, "pack"); /* struct.pack */
495                 PyObject *unpack= PyObject_GetAttrString(struct_mod, "unpack"); /* struct.unpack */
496
497                 Py_DECREF(struct_mod);
498
499                 va_start(vargs, n);
500                 for (i=0; i * 2<n; i++) {
501                         char *format = va_arg(vargs, char *);
502                         void *ptr = va_arg(vargs, void *);
503
504                         ret= PyObject_CallFunction(calcsize, (char *)"s", format);
505
506                         if(ret) {
507                                 sizes[i]= PyLong_AsSsize_t(ret);
508                                 Py_DECREF(ret);
509                                 ret = PyObject_CallFunction(unpack, (char *)"sy#", format, (char *)ptr, sizes[i]);
510                         }
511
512                         if(ret == NULL) {
513                                 printf("PyC_InlineRun error, line:%d\n", __LINE__);
514                                 PyErr_Print();
515                                 PyErr_Clear();
516
517                                 PyList_SET_ITEM(values, i, Py_None); /* hold user */
518                                 Py_INCREF(Py_None);
519
520                                 sizes[i]= 0;
521                         }
522                         else {
523                                 if(PyTuple_GET_SIZE(ret) == 1) {
524                                         /* convenience, convert single tuples into single values */
525                                         PyObject *tmp= PyTuple_GET_ITEM(ret, 0);
526                                         Py_INCREF(tmp);
527                                         Py_DECREF(ret);
528                                         ret = tmp;
529                                 }
530
531                                 PyList_SET_ITEM(values, i, ret); /* hold user */
532                         }
533                 }
534                 va_end(vargs);
535                 
536                 /* set the value so we can access it */
537                 PyDict_SetItemString(py_dict, "values", values);
538
539                 py_result = PyRun_File(fp, filepath, Py_file_input, py_dict, py_dict);
540
541                 fclose(fp);
542
543                 if(py_result) {
544
545                         /* we could skip this but then only slice assignment would work
546                          * better not be so strict */
547                         values= PyDict_GetItemString(py_dict, "values");
548
549                         if(values && PyList_Check(values)) {
550
551                                 /* dont use the result */
552                                 Py_DECREF(py_result);
553                                 py_result= NULL;
554
555                                 /* now get the values back */
556                                 va_start(vargs, n);
557                                 for (i=0; i*2 <n; i++) {
558                                         char *format = va_arg(vargs, char *);
559                                         void *ptr = va_arg(vargs, void *);
560                                         
561                                         PyObject *item;
562                                         PyObject *item_new;
563                                         /* prepend the string formatting and remake the tuple */
564                                         item= PyList_GET_ITEM(values, i);
565                                         if(PyTuple_CheckExact(item)) {
566                                                 int ofs= PyTuple_GET_SIZE(item);
567                                                 item_new= PyTuple_New(ofs + 1);
568                                                 while(ofs--) {
569                                                         PyObject *member= PyTuple_GET_ITEM(item, ofs);
570                                                         PyTuple_SET_ITEM(item_new, ofs + 1, member);
571                                                         Py_INCREF(member);
572                                                 }
573
574                                                 PyTuple_SET_ITEM(item_new, 0, PyUnicode_FromString(format));
575                                         }
576                                         else {
577                                                 item_new= Py_BuildValue("sO", format, item);
578                                         }
579
580                                         ret = PyObject_Call(pack, item_new, NULL);
581
582                                         if(ret) {
583                                                 /* copy the bytes back into memory */
584                                                 memcpy(ptr, PyBytes_AS_STRING(ret), sizes[i]);
585                                                 Py_DECREF(ret);
586                                         }
587                                         else {
588                                                 printf("PyC_InlineRun error on arg '%d', line:%d\n", i, __LINE__);
589                                                 PyC_ObSpit("failed converting:", item_new);
590                                                 PyErr_Print();
591                                                 PyErr_Clear();
592                                         }
593
594                                         Py_DECREF(item_new);
595                                 }
596                                 va_end(vargs);
597                         }
598                         else {
599                                 printf("PyC_InlineRun error, 'values' not a list, line:%d\n", __LINE__);
600                         }
601                 }
602                 else {
603                         printf("PyC_InlineRun error line:%d\n", __LINE__);
604                         PyErr_Print();
605                         PyErr_Clear();
606                 }
607
608                 Py_DECREF(calcsize);
609                 Py_DECREF(pack);
610                 Py_DECREF(unpack);
611
612                 PyMem_FREE(sizes);
613
614                 PyGILState_Release(gilstate);
615         }
616 }