2 * ***** BEGIN GPL LICENSE BLOCK *****
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * ***** END GPL LICENSE BLOCK *****
21 /** \file blender/python/generic/py_capi_utils.c
24 * Extend upon CPython's API, filling in some gaps, these functions use PyC_
25 * prefix to distinguish them apart from CPython.
28 * This module should only depend on CPython, however it currently uses
29 * BLI_string_utf8() for unicode conversion.
34 #include <frameobject.h>
36 #include "BLI_utildefines.h" /* for bool */
38 #include "py_capi_utils.h"
40 /* only for BLI_strncpy_wchar_from_utf8, should replace with py funcs but too late in release now */
41 #include "BLI_string_utf8.h"
43 #ifdef _WIN32 /* BLI_setenv */
44 #include "BLI_path_util.h"
47 /* array utility function */
48 int PyC_AsArray(void *array, PyObject *value, const Py_ssize_t length,
49 const PyTypeObject *type, const bool is_double, const char *error_prefix)
55 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
59 value_len = PySequence_Fast_GET_SIZE(value_fast);
61 if (value_len != length) {
63 PyErr_Format(PyExc_TypeError,
64 "%.200s: invalid sequence length. expected %d, got %d",
65 error_prefix, length, value_len);
70 if (type == &PyFloat_Type) {
72 double *array_double = array;
73 for (i = 0; i < length; i++) {
74 array_double[i] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i));
78 float *array_float = array;
79 for (i = 0; i < length; i++) {
80 array_float[i] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i));
84 else if (type == &PyLong_Type) {
85 /* could use is_double for 'long int' but no use now */
86 int *array_int = array;
87 for (i = 0; i < length; i++) {
88 array_int[i] = PyLong_AsLong(PySequence_Fast_GET_ITEM(value_fast, i));
91 else if (type == &PyBool_Type) {
92 int *array_bool = array;
93 for (i = 0; i < length; i++) {
94 array_bool[i] = (PyLong_AsLong(PySequence_Fast_GET_ITEM(value_fast, i)) != 0);
98 Py_DECREF(value_fast);
99 PyErr_Format(PyExc_TypeError,
100 "%s: internal error %s is invalid",
101 error_prefix, type->tp_name);
105 Py_DECREF(value_fast);
107 if (PyErr_Occurred()) {
108 PyErr_Format(PyExc_TypeError,
109 "%s: one or more items could not be used as a %s",
110 error_prefix, type->tp_name);
117 /* array utility function */
118 PyObject *PyC_FromArray(const void *array, int length, const PyTypeObject *type,
119 const bool is_double, const char *error_prefix)
124 tuple = PyTuple_New(length);
127 if (type == &PyFloat_Type) {
129 const double *array_double = array;
130 for (i = 0; i < length; ++i) {
131 PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array_double[i]));
135 const float *array_float = array;
136 for (i = 0; i < length; ++i) {
137 PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array_float[i]));
141 else if (type == &PyLong_Type) {
142 /* could use is_double for 'long int' but no use now */
143 const int *array_int = array;
144 for (i = 0; i < length; ++i) {
145 PyTuple_SET_ITEM(tuple, i, PyLong_FromLong(array_int[i]));
148 else if (type == &PyBool_Type) {
149 const int *array_bool = array;
150 for (i = 0; i < length; ++i) {
151 PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array_bool[i]));
156 PyErr_Format(PyExc_TypeError,
157 "%s: internal error %s is invalid",
158 error_prefix, type->tp_name);
166 * Caller needs to ensure tuple is uninitialized.
167 * Handy for filling a typle with None for eg.
169 void PyC_Tuple_Fill(PyObject *tuple, PyObject *value)
171 unsigned int tot = PyTuple_GET_SIZE(tuple);
174 for (i = 0; i < tot; i++) {
175 PyTuple_SET_ITEM(tuple, i, value);
181 void PyC_ObSpit(const char *name, PyObject *var)
183 fprintf(stderr, "<%s> : ", name);
185 fprintf(stderr, "<NIL>");
188 PyObject_Print(var, stderr, 0);
189 fprintf(stderr, " ref:%d ", (int)var->ob_refcnt);
190 fprintf(stderr, " ptr:%p", (void *)var);
192 fprintf(stderr, " type:");
194 fprintf(stderr, "%s", Py_TYPE(var)->tp_name);
196 fprintf(stderr, "<NIL>");
198 fprintf(stderr, "\n");
201 void PyC_LineSpit(void)
204 const char *filename;
207 /* Note, allow calling from outside python (RNA) */
208 if (!PyC_IsInterpreterActive()) {
209 fprintf(stderr, "python line lookup failed, interpreter inactive\n");
214 PyC_FileAndNum(&filename, &lineno);
216 fprintf(stderr, "%s:%d\n", filename, lineno);
219 void PyC_StackSpit(void)
221 /* Note, allow calling from outside python (RNA) */
222 if (!PyC_IsInterpreterActive()) {
223 fprintf(stderr, "python line lookup failed, interpreter inactive\n");
228 PyGILState_STATE gilstate = PyGILState_Ensure();
229 PyRun_SimpleString("__import__('traceback').print_stack()");
230 PyGILState_Release(gilstate);
234 void PyC_FileAndNum(const char **filename, int *lineno)
236 PyFrameObject *frame;
238 if (filename) *filename = NULL;
239 if (lineno) *lineno = -1;
241 if (!(frame = PyThreadState_GET()->frame)) {
245 /* when executing a script */
247 *filename = _PyUnicode_AsString(frame->f_code->co_filename);
250 /* when executing a module */
251 if (filename && *filename == NULL) {
252 /* try an alternative method to get the filename - module based
253 * references below are all borrowed (double checked) */
254 PyObject *mod_name = PyDict_GetItemString(PyEval_GetGlobals(), "__name__");
256 PyObject *mod = PyDict_GetItem(PyImport_GetModuleDict(), mod_name);
258 *filename = PyModule_GetFilename(mod);
261 /* unlikely, fallback */
262 if (*filename == NULL) {
263 *filename = _PyUnicode_AsString(mod_name);
269 *lineno = PyFrame_GetLineNumber(frame);
273 void PyC_FileAndNum_Safe(const char **filename, int *lineno)
275 if (!PyC_IsInterpreterActive()) {
279 PyC_FileAndNum(filename, lineno);
282 /* Would be nice if python had this built in */
283 PyObject *PyC_Object_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...)
292 for (i = 0; i < n; i++) {
293 attr = va_arg(vargs, char *);
294 item = PyObject_GetAttrString(item, attr);
298 else /* python will set the error value here */
304 Py_XINCREF(item); /* final value has is increfed, to match PyObject_GetAttrString */
308 PyObject *PyC_FrozenSetFromStrings(const char **strings)
313 ret = PyFrozenSet_New(NULL);
315 for (str = strings; *str; str++) {
316 PyObject *py_str = PyUnicode_FromString(*str);
317 PySet_Add(ret, py_str);
325 /* similar to PyErr_Format(),
327 * implementation - we cant actually preprend the existing exception,
328 * because it could have _any_ arguments given to it, so instead we get its
329 * __str__ output and raise our own exception including it.
331 PyObject *PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format, ...)
333 PyObject *error_value_prefix;
336 va_start(args, format);
337 error_value_prefix = PyUnicode_FromFormatV(format, args); /* can fail and be NULL */
340 if (PyErr_Occurred()) {
341 PyObject *error_type, *error_value, *error_traceback;
342 PyErr_Fetch(&error_type, &error_value, &error_traceback);
343 PyErr_Format(exception_type_prefix,
346 Py_TYPE(error_value)->tp_name,
351 PyErr_SetObject(exception_type_prefix,
356 Py_XDECREF(error_value_prefix);
358 /* dumb to always return NULL but matches PyErr_Format */
363 /* returns the exception string as a new PyUnicode object, depends on external traceback module */
366 /* this version uses traceback module but somehow fails on UI errors */
368 PyObject *PyC_ExceptionBuffer(void)
370 PyObject *traceback_mod = NULL;
371 PyObject *format_tb_func = NULL;
372 PyObject *ret = NULL;
374 if (!(traceback_mod = PyImport_ImportModule("traceback"))) {
377 else if (!(format_tb_func = PyObject_GetAttrString(traceback_mod, "format_exc"))) {
381 ret = PyObject_CallObject(format_tb_func, NULL);
383 if (ret == Py_None) {
389 /* could not import the module so print the error and close */
390 Py_XDECREF(traceback_mod);
391 Py_XDECREF(format_tb_func);
395 #else /* verbose, non-threadsafe version */
396 PyObject *PyC_ExceptionBuffer(void)
398 PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
399 PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
400 PyObject *string_io = NULL;
401 PyObject *string_io_buf = NULL;
402 PyObject *string_io_mod = NULL;
403 PyObject *string_io_getvalue = NULL;
405 PyObject *error_type, *error_value, *error_traceback;
407 if (!PyErr_Occurred())
410 PyErr_Fetch(&error_type, &error_value, &error_traceback);
415 * string_io = io.StringIO()
418 if (!(string_io_mod = PyImport_ImportModule("io"))) {
421 else if (!(string_io = PyObject_CallMethod(string_io_mod, (char *)"StringIO", NULL))) {
424 else if (!(string_io_getvalue = PyObject_GetAttrString(string_io, "getvalue"))) {
428 Py_INCREF(stdout_backup); // since these were borrowed we don't want them freed when replaced.
429 Py_INCREF(stderr_backup);
431 PySys_SetObject("stdout", string_io); // both of these are freed when restoring
432 PySys_SetObject("stderr", string_io);
434 PyErr_Restore(error_type, error_value, error_traceback);
435 PyErr_Print(); /* print the error */
438 string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
440 PySys_SetObject("stdout", stdout_backup);
441 PySys_SetObject("stderr", stderr_backup);
443 Py_DECREF(stdout_backup); /* now sys owns the ref again */
444 Py_DECREF(stderr_backup);
446 Py_DECREF(string_io_mod);
447 Py_DECREF(string_io_getvalue);
448 Py_DECREF(string_io); /* free the original reference */
451 return string_io_buf;
455 /* could not import the module so print the error and close */
456 Py_XDECREF(string_io_mod);
457 Py_XDECREF(string_io);
459 PyErr_Restore(error_type, error_value, error_traceback);
460 PyErr_Print(); /* print the error */
468 /* string conversion, escape non-unicode chars, coerce must be set to NULL */
469 const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce)
473 result = _PyUnicode_AsString(py_str);
476 /* 99% of the time this is enough but we better support non unicode
477 * chars since blender doesnt limit this */
483 if (PyBytes_Check(py_str)) {
484 return PyBytes_AS_STRING(py_str);
487 /* bug [#31856] oddly enough, Python3.2 --> 3.3 on Windows will throw an
488 * exception here this needs to be fixed in python:
489 * see: bugs.python.org/issue15859 */
490 else if (!PyUnicode_Check(py_str)) {
495 else if ((*coerce = PyUnicode_EncodeFSDefault(py_str))) {
496 return PyBytes_AS_STRING(*coerce);
499 /* leave error raised from EncodeFS */
505 PyObject *PyC_UnicodeFromByteAndSize(const char *str, Py_ssize_t size)
507 PyObject *result = PyUnicode_FromStringAndSize(str, size);
509 /* 99% of the time this is enough but we better support non unicode
510 * chars since blender doesnt limit this */
515 /* this means paths will always be accessible once converted, on all OS's */
516 result = PyUnicode_DecodeFSDefaultAndSize(str, size);
521 PyObject *PyC_UnicodeFromByte(const char *str)
523 return PyC_UnicodeFromByteAndSize(str, strlen(str));
526 /*****************************************************************************
527 * Description: This function creates a new Python dictionary object.
528 * note: dict is owned by sys.modules["__main__"] module, reference is borrowed
529 * note: important we use the dict from __main__, this is what python expects
530 * for 'pickle' to work as well as strings like this...
532 * >> print(__import__("__main__").foo)
534 * note: this overwrites __main__ which gives problems with nested calls.
535 * be sure to run PyC_MainModule_Backup & PyC_MainModule_Restore if there is
536 * any chance that python is in the call stack.
537 ****************************************************************************/
538 PyObject *PyC_DefaultNameSpace(const char *filename)
540 PyInterpreterState *interp = PyThreadState_GET()->interp;
541 PyObject *mod_main = PyModule_New("__main__");
542 PyDict_SetItemString(interp->modules, "__main__", mod_main);
543 Py_DECREF(mod_main); /* sys.modules owns now */
544 PyModule_AddStringConstant(mod_main, "__name__", "__main__");
546 /* __file__ mainly for nice UI'ness */
547 PyModule_AddObject(mod_main, "__file__", PyUnicode_DecodeFSDefault(filename));
549 PyModule_AddObject(mod_main, "__builtins__", interp->builtins);
550 Py_INCREF(interp->builtins); /* AddObject steals a reference */
551 return PyModule_GetDict(mod_main);
554 /* restore MUST be called after this */
555 void PyC_MainModule_Backup(PyObject **main_mod)
557 PyInterpreterState *interp = PyThreadState_GET()->interp;
558 *main_mod = PyDict_GetItemString(interp->modules, "__main__");
559 Py_XINCREF(*main_mod); /* don't free */
562 void PyC_MainModule_Restore(PyObject *main_mod)
564 PyInterpreterState *interp = PyThreadState_GET()->interp;
565 PyDict_SetItemString(interp->modules, "__main__", main_mod);
566 Py_XDECREF(main_mod);
569 /* must be called before Py_Initialize, expects output of BLI_get_folder(BLENDER_PYTHON, NULL) */
570 void PyC_SetHomePath(const char *py_path_bundle)
572 if (py_path_bundle == NULL) {
573 /* Common enough to have bundled *nix python but complain on OSX/Win */
574 #if defined(__APPLE__) || defined(_WIN32)
575 fprintf(stderr, "Warning! bundled python not found and is expected on this platform. "
576 "(if you built with CMake: 'install' target may have not been built)\n");
580 /* set the environment path */
581 printf("found bundled python: %s\n", py_path_bundle);
584 /* OSX allow file/directory names to contain : character (represented as / in the Finder)
585 * but current Python lib (release 3.1.1) doesn't handle these correctly */
586 if (strchr(py_path_bundle, ':'))
587 printf("Warning : Blender application is located in a path containing : or / chars\
588 \nThis may make python import function fail\n");
592 #if 0 /* disable for now [#31506] - campbell */
594 /* cmake/MSVC debug build crashes without this, why only
595 * in this case is unknown.. */
597 /*BLI_setenv("PYTHONPATH", py_path_bundle)*/;
603 static wchar_t py_path_bundle_wchar[1024];
605 /* cant use this, on linux gives bug: #23018, TODO: try LANG="en_US.UTF-8" /usr/bin/blender, suggested 22008 */
606 /* mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR); */
608 BLI_strncpy_wchar_from_utf8(py_path_bundle_wchar, py_path_bundle,
609 sizeof(py_path_bundle_wchar) / sizeof(wchar_t));
611 Py_SetPythonHome(py_path_bundle_wchar);
612 // printf("found python (wchar_t) '%ls'\n", py_path_bundle_wchar);
616 bool PyC_IsInterpreterActive(void)
618 return (((PyThreadState *)_Py_atomic_load_relaxed(&_PyThreadState_Current)) != NULL);
621 /* Would be nice if python had this built in
622 * See: http://wiki.blender.org/index.php/Dev:Doc/Tools/Debugging/PyFromC
624 void PyC_RunQuicky(const char *filepath, int n, ...)
626 FILE *fp = fopen(filepath, "r");
629 PyGILState_STATE gilstate = PyGILState_Ensure();
633 int *sizes = PyMem_MALLOC(sizeof(int) * (n / 2));
636 PyObject *py_dict = PyC_DefaultNameSpace(filepath);
637 PyObject *values = PyList_New(n / 2); /* namespace owns this, don't free */
639 PyObject *py_result, *ret;
641 PyObject *struct_mod = PyImport_ImportModule("struct");
642 PyObject *calcsize = PyObject_GetAttrString(struct_mod, "calcsize"); /* struct.calcsize */
643 PyObject *pack = PyObject_GetAttrString(struct_mod, "pack"); /* struct.pack */
644 PyObject *unpack = PyObject_GetAttrString(struct_mod, "unpack"); /* struct.unpack */
646 Py_DECREF(struct_mod);
649 for (i = 0; i * 2 < n; i++) {
650 const char *format = va_arg(vargs, char *);
651 void *ptr = va_arg(vargs, void *);
653 ret = PyObject_CallFunction(calcsize, (char *)"s", format);
656 sizes[i] = PyLong_AsLong(ret);
658 ret = PyObject_CallFunction(unpack, (char *)"sy#", format, (char *)ptr, sizes[i]);
662 printf("PyC_InlineRun error, line:%d\n", __LINE__);
666 PyList_SET_ITEM(values, i, Py_None); /* hold user */
672 if (PyTuple_GET_SIZE(ret) == 1) {
673 /* convenience, convert single tuples into single values */
674 PyObject *tmp = PyTuple_GET_ITEM(ret, 0);
680 PyList_SET_ITEM(values, i, ret); /* hold user */
685 /* set the value so we can access it */
686 PyDict_SetItemString(py_dict, "values", values);
688 py_result = PyRun_File(fp, filepath, Py_file_input, py_dict, py_dict);
694 /* we could skip this but then only slice assignment would work
695 * better not be so strict */
696 values = PyDict_GetItemString(py_dict, "values");
698 if (values && PyList_Check(values)) {
700 /* don't use the result */
701 Py_DECREF(py_result);
704 /* now get the values back */
706 for (i = 0; i * 2 < n; i++) {
707 const char *format = va_arg(vargs, char *);
708 void *ptr = va_arg(vargs, void *);
712 /* prepend the string formatting and remake the tuple */
713 item = PyList_GET_ITEM(values, i);
714 if (PyTuple_CheckExact(item)) {
715 int ofs = PyTuple_GET_SIZE(item);
716 item_new = PyTuple_New(ofs + 1);
718 PyObject *member = PyTuple_GET_ITEM(item, ofs);
719 PyTuple_SET_ITEM(item_new, ofs + 1, member);
723 PyTuple_SET_ITEM(item_new, 0, PyUnicode_FromString(format));
726 item_new = Py_BuildValue("sO", format, item);
729 ret = PyObject_Call(pack, item_new, NULL);
732 /* copy the bytes back into memory */
733 memcpy(ptr, PyBytes_AS_STRING(ret), sizes[i]);
737 printf("PyC_InlineRun error on arg '%d', line:%d\n", i, __LINE__);
738 PyC_ObSpit("failed converting:", item_new);
748 printf("PyC_InlineRun error, 'values' not a list, line:%d\n", __LINE__);
752 printf("PyC_InlineRun error line:%d\n", __LINE__);
763 PyGILState_Release(gilstate);
767 /* generic function to avoid depending on RNA */
768 void *PyC_RNA_AsPointer(PyObject *value, const char *type_name)
770 PyObject *as_pointer;
773 if (STREQ(Py_TYPE(value)->tp_name, type_name) &&
774 (as_pointer = PyObject_GetAttrString(value, "as_pointer")) != NULL &&
775 PyCallable_Check(as_pointer))
779 /* must be a 'type_name' object */
780 pointer = PyObject_CallObject(as_pointer, NULL);
781 Py_DECREF(as_pointer);
784 PyErr_SetString(PyExc_SystemError, "value.as_pointer() failed");
787 result = PyLong_AsVoidPtr(pointer);
790 PyErr_SetString(PyExc_SystemError, "value.as_pointer() failed");
796 PyErr_Format(PyExc_TypeError,
797 "expected '%.200s' type found '%.200s' instead",
798 type_name, Py_TYPE(value)->tp_name);
804 /* PyC_FlagSet_* functions - so flags/sets can be interchanged in a generic way */
805 #include "BLI_dynstr.h"
806 #include "MEM_guardedalloc.h"
808 char *PyC_FlagSet_AsString(PyC_FlagSet *item)
810 DynStr *dynstr = BLI_dynstr_new();
814 for (e = item; item->identifier; item++) {
815 BLI_dynstr_appendf(dynstr, (e == item) ? "'%s'" : ", '%s'", item->identifier);
818 cstring = BLI_dynstr_get_cstring(dynstr);
819 BLI_dynstr_free(dynstr);
823 int PyC_FlagSet_ValueFromID_int(PyC_FlagSet *item, const char *identifier, int *value)
825 for ( ; item->identifier; item++) {
826 if (STREQ(item->identifier, identifier)) {
827 *value = item->value;
835 int PyC_FlagSet_ValueFromID(PyC_FlagSet *item, const char *identifier, int *value, const char *error_prefix)
837 if (PyC_FlagSet_ValueFromID_int(item, identifier, value) == 0) {
838 const char *enum_str = PyC_FlagSet_AsString(item);
839 PyErr_Format(PyExc_ValueError,
840 "%s: '%.200s' not found in (%s)",
841 error_prefix, identifier, enum_str);
842 MEM_freeN((void *)enum_str);
849 int PyC_FlagSet_ToBitfield(PyC_FlagSet *items, PyObject *value, int *r_value, const char *error_prefix)
851 /* set of enum items, concatenate all values with OR */
859 if (!PySet_Check(value)) {
860 PyErr_Format(PyExc_TypeError,
861 "%.200s expected a set, not %.200s",
862 error_prefix, Py_TYPE(value)->tp_name);
868 while (_PySet_NextEntry(value, &pos, &key, &hash)) {
869 const char *param = _PyUnicode_AsString(key);
872 PyErr_Format(PyExc_TypeError,
873 "%.200s set must contain strings, not %.200s",
874 error_prefix, Py_TYPE(key)->tp_name);
878 if (PyC_FlagSet_ValueFromID(items, param, &ret, error_prefix) < 0) {
889 PyObject *PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag)
891 PyObject *ret = PySet_New(NULL);
894 for ( ; items->identifier; items++) {
895 if (items->value & flag) {
896 pystr = PyUnicode_FromString(items->identifier);
897 PySet_Add(ret, pystr);
906 #if PY_VERSION_HEX < 0x03030200
908 _PyLong_AsInt(PyObject *obj)
911 long result = PyLong_AsLongAndOverflow(obj, &overflow);
912 if (overflow || result > INT_MAX || result < INT_MIN) {
913 PyErr_SetString(PyExc_OverflowError,
914 "Python int too large to convert to C int");