I made multitude of fixes based on the comments provided online:
[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 /* returns the exception string as a new PyUnicode object, depends on external traceback module */
212 #if 0
213
214 /* this version uses traceback module but somehow fails on UI errors */
215
216 PyObject *PyC_ExceptionBuffer(void)
217 {
218         PyObject *traceback_mod= NULL;
219         PyObject *format_tb_func= NULL;
220         PyObject *ret= NULL;
221
222         if(! (traceback_mod= PyImport_ImportModule("traceback")) ) {
223                 goto error_cleanup;
224         }
225         else if (! (format_tb_func= PyObject_GetAttrString(traceback_mod, "format_exc"))) {
226                 goto error_cleanup;
227         }
228
229         ret= PyObject_CallObject(format_tb_func, NULL);
230
231         if(ret == Py_None) {
232                 Py_DECREF(ret);
233                 ret= NULL;
234         }
235
236 error_cleanup:
237         /* could not import the module so print the error and close */
238         Py_XDECREF(traceback_mod);
239         Py_XDECREF(format_tb_func);
240
241         return ret;
242 }
243 #else /* verbose, non-threadsafe version */
244 PyObject *PyC_ExceptionBuffer(void)
245 {
246         PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
247         PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
248         PyObject *string_io = NULL;
249         PyObject *string_io_buf = NULL;
250         PyObject *string_io_mod= NULL;
251         PyObject *string_io_getvalue= NULL;
252
253         PyObject *error_type, *error_value, *error_traceback;
254
255         if (!PyErr_Occurred())
256                 return NULL;
257
258         PyErr_Fetch(&error_type, &error_value, &error_traceback);
259
260         PyErr_Clear();
261
262         /* import io
263          * string_io = io.StringIO()
264          */
265
266         if(! (string_io_mod= PyImport_ImportModule("io")) ) {
267                 goto error_cleanup;
268         }
269         else if (! (string_io = PyObject_CallMethod(string_io_mod, (char *)"StringIO", NULL))) {
270                 goto error_cleanup;
271         }
272         else if (! (string_io_getvalue= PyObject_GetAttrString(string_io, "getvalue"))) {
273                 goto error_cleanup;
274         }
275
276         Py_INCREF(stdout_backup); // since these were borrowed we dont want them freed when replaced.
277         Py_INCREF(stderr_backup);
278
279         PySys_SetObject("stdout", string_io); // both of these are free'd when restoring
280         PySys_SetObject("stderr", string_io);
281
282         PyErr_Restore(error_type, error_value, error_traceback);
283         PyErr_Print(); /* print the error */
284         PyErr_Clear();
285
286         string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
287
288         PySys_SetObject("stdout", stdout_backup);
289         PySys_SetObject("stderr", stderr_backup);
290
291         Py_DECREF(stdout_backup); /* now sys owns the ref again */
292         Py_DECREF(stderr_backup);
293
294         Py_DECREF(string_io_mod);
295         Py_DECREF(string_io_getvalue);
296         Py_DECREF(string_io); /* free the original reference */
297
298         PyErr_Clear();
299         return string_io_buf;
300
301
302 error_cleanup:
303         /* could not import the module so print the error and close */
304         Py_XDECREF(string_io_mod);
305         Py_XDECREF(string_io);
306
307         PyErr_Restore(error_type, error_value, error_traceback);
308         PyErr_Print(); /* print the error */
309         PyErr_Clear();
310
311         return NULL;
312 }
313 #endif
314
315
316 /* string conversion, escape non-unicode chars, coerce must be set to NULL */
317 const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce)
318 {
319         char *result;
320
321         result= _PyUnicode_AsString(py_str);
322
323         if(result) {
324                 /* 99% of the time this is enough but we better support non unicode
325                  * chars since blender doesnt limit this */
326                 return result;
327         }
328         else if(PyBytes_Check(py_str)) {
329                 PyErr_Clear();
330                 return PyBytes_AS_STRING(py_str);
331         }
332         else {
333                 return PyBytes_AS_STRING((*coerce= PyUnicode_EncodeFSDefault(py_str)));
334         }
335 }
336
337 PyObject *PyC_UnicodeFromByte(const char *str)
338 {
339         PyObject *result= PyUnicode_FromString(str);
340         if(result) {
341                 /* 99% of the time this is enough but we better support non unicode
342                  * chars since blender doesnt limit this */
343                 return result;
344         }
345         else {
346                 PyErr_Clear();
347                 /* this means paths will always be accessible once converted, on all OS's */
348                 result= PyUnicode_DecodeFSDefault(str);
349                 return result;
350         }
351 }
352
353 /*****************************************************************************
354 * Description: This function creates a new Python dictionary object.
355 * note: dict is owned by sys.modules["__main__"] module, reference is borrowed
356 * note: important we use the dict from __main__, this is what python expects
357   for 'pickle' to work as well as strings like this...
358  >> foo = 10
359  >> print(__import__("__main__").foo)
360 *
361 * note: this overwrites __main__ which gives problems with nested calles.
362 * be sure to run PyC_MainModule_Backup & PyC_MainModule_Restore if there is
363 * any chance that python is in the call stack.
364 *****************************************************************************/
365 PyObject *PyC_DefaultNameSpace(const char *filename)
366 {
367         PyInterpreterState *interp= PyThreadState_GET()->interp;
368         PyObject *mod_main= PyModule_New("__main__");   
369         PyDict_SetItemString(interp->modules, "__main__", mod_main);
370         Py_DECREF(mod_main); /* sys.modules owns now */
371         PyModule_AddStringConstant(mod_main, "__name__", "__main__");
372         if(filename)
373                 PyModule_AddStringConstant(mod_main, "__file__", filename); /* __file__ only for nice UI'ness */
374         PyModule_AddObject(mod_main, "__builtins__", interp->builtins);
375         Py_INCREF(interp->builtins); /* AddObject steals a reference */
376         return PyModule_GetDict(mod_main);
377 }
378
379 /* restore MUST be called after this */
380 void PyC_MainModule_Backup(PyObject **main_mod)
381 {
382         PyInterpreterState *interp= PyThreadState_GET()->interp;
383         *main_mod= PyDict_GetItemString(interp->modules, "__main__");
384         Py_XINCREF(*main_mod); /* dont free */
385 }
386
387 void PyC_MainModule_Restore(PyObject *main_mod)
388 {
389         PyInterpreterState *interp= PyThreadState_GET()->interp;
390         PyDict_SetItemString(interp->modules, "__main__", main_mod);
391         Py_XDECREF(main_mod);
392 }
393
394 /* must be called before Py_Initialize, expects output of BLI_get_folder(BLENDER_PYTHON, NULL) */
395 void PyC_SetHomePath(const char *py_path_bundle)
396 {
397         if(py_path_bundle==NULL) {
398                 /* Common enough to have bundled *nix python but complain on OSX/Win */
399 #if defined(__APPLE__) || defined(_WIN32)
400                 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");
401 #endif
402                 return;
403         }
404         /* set the environment path */
405         printf("found bundled python: %s\n", py_path_bundle);
406
407 #ifdef __APPLE__
408         /* OSX allow file/directory names to contain : character (represented as / in the Finder)
409          but current Python lib (release 3.1.1) doesn't handle these correctly */
410         if(strchr(py_path_bundle, ':'))
411                 printf("Warning : Blender application is located in a path containing : or / chars\
412                            \nThis may make python import function fail\n");
413 #endif
414
415 #ifdef _WIN32
416         /* cmake/MSVC debug build crashes without this, why only
417            in this case is unknown.. */
418         {
419                 BLI_setenv("PYTHONPATH", py_path_bundle);
420         }
421 #endif
422
423         {
424                 static wchar_t py_path_bundle_wchar[1024];
425
426                 /* cant use this, on linux gives bug: #23018, TODO: try LANG="en_US.UTF-8" /usr/bin/blender, suggested 22008 */
427                 /* mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR); */
428
429                 utf8towchar(py_path_bundle_wchar, py_path_bundle);
430
431                 Py_SetPythonHome(py_path_bundle_wchar);
432                 // printf("found python (wchar_t) '%ls'\n", py_path_bundle_wchar);
433         }
434 }
435
436 /* Would be nice if python had this built in */
437 void PyC_RunQuicky(const char *filepath, int n, ...)
438 {
439         FILE *fp= fopen(filepath, "r");
440
441         if(fp) {
442                 PyGILState_STATE gilstate= PyGILState_Ensure();
443
444                 va_list vargs;  
445
446                 int *sizes= PyMem_MALLOC(sizeof(int) * (n / 2));
447                 int i;
448
449                 PyObject *py_dict = PyC_DefaultNameSpace(filepath);
450                 PyObject *values= PyList_New(n / 2); /* namespace owns this, dont free */
451
452                 PyObject *py_result, *ret;
453
454                 PyObject *struct_mod= PyImport_ImportModule("struct");
455                 PyObject *calcsize= PyObject_GetAttrString(struct_mod, "calcsize"); /* struct.calcsize */
456                 PyObject *pack= PyObject_GetAttrString(struct_mod, "pack"); /* struct.pack */
457                 PyObject *unpack= PyObject_GetAttrString(struct_mod, "unpack"); /* struct.unpack */
458
459                 Py_DECREF(struct_mod);
460
461                 va_start(vargs, n);
462                 for (i=0; i * 2<n; i++) {
463                         char *format = va_arg(vargs, char *);
464                         void *ptr = va_arg(vargs, void *);
465
466                         ret= PyObject_CallFunction(calcsize, (char *)"s", format);
467
468                         if(ret) {
469                                 sizes[i]= PyLong_AsSsize_t(ret);
470                                 Py_DECREF(ret);
471                                 ret = PyObject_CallFunction(unpack, (char *)"sy#", format, (char *)ptr, sizes[i]);
472                         }
473
474                         if(ret == NULL) {
475                                 printf("PyC_InlineRun error, line:%d\n", __LINE__);
476                                 PyErr_Print();
477                                 PyErr_Clear();
478
479                                 PyList_SET_ITEM(values, i, Py_None); /* hold user */
480                                 Py_INCREF(Py_None);
481
482                                 sizes[i]= 0;
483                         }
484                         else {
485                                 if(PyTuple_GET_SIZE(ret) == 1) {
486                                         /* convenience, convert single tuples into single values */
487                                         PyObject *tmp= PyTuple_GET_ITEM(ret, 0);
488                                         Py_INCREF(tmp);
489                                         Py_DECREF(ret);
490                                         ret = tmp;
491                                 }
492
493                                 PyList_SET_ITEM(values, i, ret); /* hold user */
494                         }
495                 }
496                 va_end(vargs);
497                 
498                 /* set the value so we can access it */
499                 PyDict_SetItemString(py_dict, "values", values);
500
501                 py_result = PyRun_File(fp, filepath, Py_file_input, py_dict, py_dict);
502
503                 fclose(fp);
504
505                 if(py_result) {
506
507                         /* we could skip this but then only slice assignment would work
508                          * better not be so strict */
509                         values= PyDict_GetItemString(py_dict, "values");
510
511                         if(values && PyList_Check(values)) {
512
513                                 /* dont use the result */
514                                 Py_DECREF(py_result);
515                                 py_result= NULL;
516
517                                 /* now get the values back */
518                                 va_start(vargs, n);
519                                 for (i=0; i*2 <n; i++) {
520                                         char *format = va_arg(vargs, char *);
521                                         void *ptr = va_arg(vargs, void *);
522                                         
523                                         PyObject *item;
524                                         PyObject *item_new;
525                                         /* prepend the string formatting and remake the tuple */
526                                         item= PyList_GET_ITEM(values, i);
527                                         if(PyTuple_CheckExact(item)) {
528                                                 int ofs= PyTuple_GET_SIZE(item);
529                                                 item_new= PyTuple_New(ofs + 1);
530                                                 while(ofs--) {
531                                                         PyObject *member= PyTuple_GET_ITEM(item, ofs);
532                                                         PyTuple_SET_ITEM(item_new, ofs + 1, member);
533                                                         Py_INCREF(member);
534                                                 }
535
536                                                 PyTuple_SET_ITEM(item_new, 0, PyUnicode_FromString(format));
537                                         }
538                                         else {
539                                                 item_new= Py_BuildValue("sO", format, item);
540                                         }
541
542                                         ret = PyObject_Call(pack, item_new, NULL);
543
544                                         if(ret) {
545                                                 /* copy the bytes back into memory */
546                                                 memcpy(ptr, PyBytes_AS_STRING(ret), sizes[i]);
547                                                 Py_DECREF(ret);
548                                         }
549                                         else {
550                                                 printf("PyC_InlineRun error on arg '%d', line:%d\n", i, __LINE__);
551                                                 PyC_ObSpit("failed converting:", item_new);
552                                                 PyErr_Print();
553                                                 PyErr_Clear();
554                                         }
555
556                                         Py_DECREF(item_new);
557                                 }
558                                 va_end(vargs);
559                         }
560                         else {
561                                 printf("PyC_InlineRun error, 'values' not a list, line:%d\n", __LINE__);
562                         }
563                 }
564                 else {
565                         printf("PyC_InlineRun error line:%d\n", __LINE__);
566                         PyErr_Print();
567                         PyErr_Clear();
568                 }
569
570                 Py_DECREF(calcsize);
571                 Py_DECREF(pack);
572                 Py_DECREF(unpack);
573
574                 PyMem_FREE(sizes);
575
576                 PyGILState_Release(gilstate);
577         }
578 }