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