Blender V2.61 - r43446

py_capi_utils.c

Go to the documentation of this file.
00001 /*
00002  * ***** BEGIN GPL LICENSE BLOCK *****
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License
00006  * as published by the Free Software Foundation; either version 2
00007  * of the License, or (at your option) any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  * GNU General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software Foundation,
00016  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00017  *
00018  * ***** END GPL LICENSE BLOCK *****
00019  */
00020 
00033 #include <Python.h>
00034 #include <frameobject.h>
00035 
00036 #include "py_capi_utils.h"
00037 
00038 #include "BLI_string_utf8.h" /* only for BLI_strncpy_wchar_from_utf8, should replace with py funcs but too late in release now */
00039 
00040 #ifdef _WIN32 /* BLI_setenv */
00041 #include "BLI_path_util.h"
00042 #endif
00043 
00044 /* array utility function */
00045 int PyC_AsArray(void *array, PyObject *value, const int length, const PyTypeObject *type, const short is_double, const char *error_prefix)
00046 {
00047     PyObject *value_fast;
00048     int value_len;
00049     int i;
00050 
00051     if (!(value_fast=PySequence_Fast(value, error_prefix))) {
00052         return -1;
00053     }
00054 
00055     value_len= PySequence_Fast_GET_SIZE(value_fast);
00056 
00057     if (value_len != length) {
00058         Py_DECREF(value);
00059         PyErr_Format(PyExc_TypeError,
00060                      "%.200s: invalid sequence length. expected %d, got %d",
00061                      error_prefix, length, value_len);
00062         return -1;
00063     }
00064 
00065     /* for each type */
00066     if (type == &PyFloat_Type) {
00067         if (is_double) {
00068             double *array_double= array;
00069             for (i=0; i<length; i++) {
00070                 array_double[i]= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i));
00071             }
00072         }
00073         else {
00074             float *array_float= array;
00075             for (i=0; i<length; i++) {
00076                 array_float[i]= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i));
00077             }
00078         }
00079     }
00080     else if (type == &PyLong_Type) {
00081         /* could use is_double for 'long int' but no use now */
00082         int *array_int= array;
00083         for (i=0; i<length; i++) {
00084             array_int[i]= PyLong_AsSsize_t(PySequence_Fast_GET_ITEM(value_fast, i));
00085         }
00086     }
00087     else if (type == &PyBool_Type) {
00088         int *array_bool= array;
00089         for (i=0; i<length; i++) {
00090             array_bool[i]= (PyLong_AsSsize_t(PySequence_Fast_GET_ITEM(value_fast, i)) != 0);
00091         }
00092     }
00093     else {
00094         Py_DECREF(value_fast);
00095         PyErr_Format(PyExc_TypeError,
00096                      "%s: internal error %s is invalid",
00097                      error_prefix, type->tp_name);
00098         return -1;
00099     }
00100 
00101     Py_DECREF(value_fast);
00102 
00103     if (PyErr_Occurred()) {
00104         PyErr_Format(PyExc_TypeError,
00105                      "%s: one or more items could not be used as a %s",
00106                      error_prefix, type->tp_name);
00107         return -1;
00108     }
00109 
00110     return 0;
00111 }
00112 
00113 
00114 /* for debugging */
00115 void PyC_ObSpit(const char *name, PyObject *var)
00116 {
00117     fprintf(stderr, "<%s> : ", name);
00118     if (var==NULL) {
00119         fprintf(stderr, "<NIL>");
00120     }
00121     else {
00122         PyObject_Print(var, stderr, 0);
00123         fprintf(stderr, " ref:%d ", (int)var->ob_refcnt);
00124         fprintf(stderr, " ptr:%p", (void *)var);
00125         
00126         fprintf(stderr, " type:");
00127         if (Py_TYPE(var))
00128             fprintf(stderr, "%s", Py_TYPE(var)->tp_name);
00129         else
00130             fprintf(stderr, "<NIL>");
00131     }
00132     fprintf(stderr, "\n");
00133 }
00134 
00135 void PyC_LineSpit(void)
00136 {
00137 
00138     const char *filename;
00139     int lineno;
00140 
00141     /* Note, allow calling from outside python (RNA) */
00142     if (!PYC_INTERPRETER_ACTIVE) {
00143         fprintf(stderr, "python line lookup failed, interpreter inactive\n");
00144         return;
00145     }
00146 
00147     PyErr_Clear();
00148     PyC_FileAndNum(&filename, &lineno);
00149     
00150     fprintf(stderr, "%s:%d\n", filename, lineno);
00151 }
00152 
00153 void PyC_FileAndNum(const char **filename, int *lineno)
00154 {
00155     PyFrameObject *frame;
00156     
00157     if (filename)   *filename= NULL;
00158     if (lineno)     *lineno = -1;
00159 
00160     if (!(frame= PyThreadState_GET()->frame)) {
00161         return;
00162     }
00163 
00164     /* when executing a script */
00165     if (filename) {
00166         *filename = _PyUnicode_AsString(frame->f_code->co_filename);
00167     }
00168 
00169     /* when executing a module */
00170     if (filename && *filename == NULL) {
00171         /* try an alternative method to get the filename - module based
00172          * references below are all borrowed (double checked) */
00173         PyObject *mod_name= PyDict_GetItemString(PyEval_GetGlobals(), "__name__");
00174         if (mod_name) {
00175             PyObject *mod= PyDict_GetItem(PyImport_GetModuleDict(), mod_name);
00176             if (mod) {
00177                 *filename= PyModule_GetFilename(mod);
00178             }
00179 
00180             /* unlikely, fallback */
00181             if (*filename == NULL) {
00182                 *filename= _PyUnicode_AsString(mod_name);
00183             }
00184         }
00185     }
00186 
00187     if (lineno) {
00188         *lineno = PyFrame_GetLineNumber(frame);
00189     }
00190 }
00191 
00192 void PyC_FileAndNum_Safe(const char **filename, int *lineno)
00193 {
00194     if (!PYC_INTERPRETER_ACTIVE) {
00195         return;
00196     }
00197 
00198     PyC_FileAndNum(filename, lineno);
00199 }
00200 
00201 /* Would be nice if python had this built in */
00202 PyObject *PyC_Object_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...)
00203 {
00204     Py_ssize_t i;
00205     PyObject *item= o;
00206     char *attr;
00207     
00208     va_list vargs;
00209 
00210     va_start(vargs, n);
00211     for (i=0; i<n; i++) {
00212         attr = va_arg(vargs, char *);
00213         item = PyObject_GetAttrString(item, attr);
00214         
00215         if (item) 
00216             Py_DECREF(item);
00217         else /* python will set the error value here */
00218             break;
00219         
00220     }
00221     va_end(vargs);
00222     
00223     Py_XINCREF(item); /* final value has is increfed, to match PyObject_GetAttrString */
00224     return item;
00225 }
00226 
00227 /* similar to PyErr_Format(),
00228  *
00229  * implimentation - we cant actually preprend the existing exception,
00230  * because it could have _any_ argiments given to it, so instead we get its
00231  * __str__ output and raise our own exception including it.
00232  */
00233 PyObject *PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format, ...)
00234 {
00235     PyObject *error_value_prefix;
00236     va_list args;
00237 
00238     va_start(args, format);
00239     error_value_prefix= PyUnicode_FromFormatV(format, args); /* can fail and be NULL */
00240     va_end(args);
00241 
00242     if (PyErr_Occurred()) {
00243         PyObject *error_type, *error_value, *error_traceback;
00244         PyErr_Fetch(&error_type, &error_value, &error_traceback);
00245         PyErr_Format(exception_type_prefix,
00246                      "%S, %.200s(%S)",
00247                      error_value_prefix,
00248                      Py_TYPE(error_value)->tp_name,
00249                      error_value
00250                      );
00251     }
00252     else {
00253         PyErr_SetObject(exception_type_prefix,
00254                         error_value_prefix
00255                         );
00256     }
00257 
00258     Py_XDECREF(error_value_prefix);
00259 
00260     /* dumb to always return NULL but matches PyErr_Format */
00261     return NULL;
00262 }
00263 
00264 
00265 /* returns the exception string as a new PyUnicode object, depends on external traceback module */
00266 #if 0
00267 
00268 /* this version uses traceback module but somehow fails on UI errors */
00269 
00270 PyObject *PyC_ExceptionBuffer(void)
00271 {
00272     PyObject *traceback_mod= NULL;
00273     PyObject *format_tb_func= NULL;
00274     PyObject *ret= NULL;
00275 
00276     if (! (traceback_mod= PyImport_ImportModule("traceback")) ) {
00277         goto error_cleanup;
00278     }
00279     else if (! (format_tb_func= PyObject_GetAttrString(traceback_mod, "format_exc"))) {
00280         goto error_cleanup;
00281     }
00282 
00283     ret= PyObject_CallObject(format_tb_func, NULL);
00284 
00285     if (ret == Py_None) {
00286         Py_DECREF(ret);
00287         ret= NULL;
00288     }
00289 
00290 error_cleanup:
00291     /* could not import the module so print the error and close */
00292     Py_XDECREF(traceback_mod);
00293     Py_XDECREF(format_tb_func);
00294 
00295     return ret;
00296 }
00297 #else /* verbose, non-threadsafe version */
00298 PyObject *PyC_ExceptionBuffer(void)
00299 {
00300     PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
00301     PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
00302     PyObject *string_io = NULL;
00303     PyObject *string_io_buf = NULL;
00304     PyObject *string_io_mod= NULL;
00305     PyObject *string_io_getvalue= NULL;
00306 
00307     PyObject *error_type, *error_value, *error_traceback;
00308 
00309     if (!PyErr_Occurred())
00310         return NULL;
00311 
00312     PyErr_Fetch(&error_type, &error_value, &error_traceback);
00313 
00314     PyErr_Clear();
00315 
00316     /* import io
00317      * string_io = io.StringIO()
00318      */
00319 
00320     if (! (string_io_mod= PyImport_ImportModule("io")) ) {
00321         goto error_cleanup;
00322     }
00323     else if (! (string_io = PyObject_CallMethod(string_io_mod, (char *)"StringIO", NULL))) {
00324         goto error_cleanup;
00325     }
00326     else if (! (string_io_getvalue= PyObject_GetAttrString(string_io, "getvalue"))) {
00327         goto error_cleanup;
00328     }
00329 
00330     Py_INCREF(stdout_backup); // since these were borrowed we dont want them freed when replaced.
00331     Py_INCREF(stderr_backup);
00332 
00333     PySys_SetObject("stdout", string_io); // both of these are free'd when restoring
00334     PySys_SetObject("stderr", string_io);
00335 
00336     PyErr_Restore(error_type, error_value, error_traceback);
00337     PyErr_Print(); /* print the error */
00338     PyErr_Clear();
00339 
00340     string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
00341 
00342     PySys_SetObject("stdout", stdout_backup);
00343     PySys_SetObject("stderr", stderr_backup);
00344 
00345     Py_DECREF(stdout_backup); /* now sys owns the ref again */
00346     Py_DECREF(stderr_backup);
00347 
00348     Py_DECREF(string_io_mod);
00349     Py_DECREF(string_io_getvalue);
00350     Py_DECREF(string_io); /* free the original reference */
00351 
00352     PyErr_Clear();
00353     return string_io_buf;
00354 
00355 
00356 error_cleanup:
00357     /* could not import the module so print the error and close */
00358     Py_XDECREF(string_io_mod);
00359     Py_XDECREF(string_io);
00360 
00361     PyErr_Restore(error_type, error_value, error_traceback);
00362     PyErr_Print(); /* print the error */
00363     PyErr_Clear();
00364 
00365     return NULL;
00366 }
00367 #endif
00368 
00369 
00370 /* string conversion, escape non-unicode chars, coerce must be set to NULL */
00371 const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce)
00372 {
00373     const char *result;
00374 
00375     result= _PyUnicode_AsString(py_str);
00376 
00377     if (result) {
00378         /* 99% of the time this is enough but we better support non unicode
00379          * chars since blender doesnt limit this */
00380         return result;
00381     }
00382     else {
00383         PyErr_Clear();
00384 
00385         if (PyBytes_Check(py_str)) {
00386             return PyBytes_AS_STRING(py_str);
00387         }
00388         else if ((*coerce= PyUnicode_EncodeFSDefault(py_str))) {
00389             return PyBytes_AS_STRING(*coerce);
00390         }
00391         else {
00392             /* leave error raised from EncodeFS */
00393             return NULL;
00394         }
00395     }
00396 }
00397 
00398 PyObject *PyC_UnicodeFromByteAndSize(const char *str, Py_ssize_t size)
00399 {
00400     PyObject *result= PyUnicode_FromStringAndSize(str, size);
00401     if (result) {
00402         /* 99% of the time this is enough but we better support non unicode
00403          * chars since blender doesnt limit this */
00404         return result;
00405     }
00406     else {
00407         PyErr_Clear();
00408         /* this means paths will always be accessible once converted, on all OS's */
00409         result= PyUnicode_DecodeFSDefaultAndSize(str, size);
00410         return result;
00411     }
00412 }
00413 
00414 PyObject *PyC_UnicodeFromByte(const char *str)
00415 {
00416     return PyC_UnicodeFromByteAndSize(str, strlen(str));
00417 }
00418 
00419 /*****************************************************************************
00420 * Description: This function creates a new Python dictionary object.
00421 * note: dict is owned by sys.modules["__main__"] module, reference is borrowed
00422 * note: important we use the dict from __main__, this is what python expects
00423   for 'pickle' to work as well as strings like this...
00424  >> foo = 10
00425  >> print(__import__("__main__").foo)
00426 *
00427 * note: this overwrites __main__ which gives problems with nested calles.
00428 * be sure to run PyC_MainModule_Backup & PyC_MainModule_Restore if there is
00429 * any chance that python is in the call stack.
00430 *****************************************************************************/
00431 PyObject *PyC_DefaultNameSpace(const char *filename)
00432 {
00433     PyInterpreterState *interp= PyThreadState_GET()->interp;
00434     PyObject *mod_main= PyModule_New("__main__");   
00435     PyDict_SetItemString(interp->modules, "__main__", mod_main);
00436     Py_DECREF(mod_main); /* sys.modules owns now */
00437     PyModule_AddStringConstant(mod_main, "__name__", "__main__");
00438     if (filename)
00439         PyModule_AddStringConstant(mod_main, "__file__", filename); /* __file__ only for nice UI'ness */
00440     PyModule_AddObject(mod_main, "__builtins__", interp->builtins);
00441     Py_INCREF(interp->builtins); /* AddObject steals a reference */
00442     return PyModule_GetDict(mod_main);
00443 }
00444 
00445 /* restore MUST be called after this */
00446 void PyC_MainModule_Backup(PyObject **main_mod)
00447 {
00448     PyInterpreterState *interp= PyThreadState_GET()->interp;
00449     *main_mod= PyDict_GetItemString(interp->modules, "__main__");
00450     Py_XINCREF(*main_mod); /* dont free */
00451 }
00452 
00453 void PyC_MainModule_Restore(PyObject *main_mod)
00454 {
00455     PyInterpreterState *interp= PyThreadState_GET()->interp;
00456     PyDict_SetItemString(interp->modules, "__main__", main_mod);
00457     Py_XDECREF(main_mod);
00458 }
00459 
00460 /* must be called before Py_Initialize, expects output of BLI_get_folder(BLENDER_PYTHON, NULL) */
00461 void PyC_SetHomePath(const char *py_path_bundle)
00462 {
00463     if (py_path_bundle==NULL) {
00464         /* Common enough to have bundled *nix python but complain on OSX/Win */
00465 #if defined(__APPLE__) || defined(_WIN32)
00466         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");
00467 #endif
00468         return;
00469     }
00470     /* set the environment path */
00471     printf("found bundled python: %s\n", py_path_bundle);
00472 
00473 #ifdef __APPLE__
00474     /* OSX allow file/directory names to contain : character (represented as / in the Finder)
00475      but current Python lib (release 3.1.1) doesn't handle these correctly */
00476     if (strchr(py_path_bundle, ':'))
00477         printf("Warning : Blender application is located in a path containing : or / chars\
00478                \nThis may make python import function fail\n");
00479 #endif
00480 
00481 #ifdef _WIN32
00482     /* cmake/MSVC debug build crashes without this, why only
00483        in this case is unknown.. */
00484     {
00485         BLI_setenv("PYTHONPATH", py_path_bundle);
00486     }
00487 #endif
00488 
00489     {
00490         static wchar_t py_path_bundle_wchar[1024];
00491 
00492         /* cant use this, on linux gives bug: #23018, TODO: try LANG="en_US.UTF-8" /usr/bin/blender, suggested 22008 */
00493         /* mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR); */
00494 
00495         BLI_strncpy_wchar_from_utf8(py_path_bundle_wchar, py_path_bundle, sizeof(py_path_bundle_wchar) / sizeof(wchar_t));
00496 
00497         Py_SetPythonHome(py_path_bundle_wchar);
00498         // printf("found python (wchar_t) '%ls'\n", py_path_bundle_wchar);
00499     }
00500 }
00501 
00502 /* Would be nice if python had this built in */
00503 void PyC_RunQuicky(const char *filepath, int n, ...)
00504 {
00505     FILE *fp= fopen(filepath, "r");
00506 
00507     if (fp) {
00508         PyGILState_STATE gilstate= PyGILState_Ensure();
00509 
00510         va_list vargs;  
00511 
00512         int *sizes= PyMem_MALLOC(sizeof(int) * (n / 2));
00513         int i;
00514 
00515         PyObject *py_dict = PyC_DefaultNameSpace(filepath);
00516         PyObject *values= PyList_New(n / 2); /* namespace owns this, dont free */
00517 
00518         PyObject *py_result, *ret;
00519 
00520         PyObject *struct_mod= PyImport_ImportModule("struct");
00521         PyObject *calcsize= PyObject_GetAttrString(struct_mod, "calcsize"); /* struct.calcsize */
00522         PyObject *pack= PyObject_GetAttrString(struct_mod, "pack"); /* struct.pack */
00523         PyObject *unpack= PyObject_GetAttrString(struct_mod, "unpack"); /* struct.unpack */
00524 
00525         Py_DECREF(struct_mod);
00526 
00527         va_start(vargs, n);
00528         for (i=0; i * 2<n; i++) {
00529             char *format = va_arg(vargs, char *);
00530             void *ptr = va_arg(vargs, void *);
00531 
00532             ret= PyObject_CallFunction(calcsize, (char *)"s", format);
00533 
00534             if (ret) {
00535                 sizes[i]= PyLong_AsSsize_t(ret);
00536                 Py_DECREF(ret);
00537                 ret = PyObject_CallFunction(unpack, (char *)"sy#", format, (char *)ptr, sizes[i]);
00538             }
00539 
00540             if (ret == NULL) {
00541                 printf("PyC_InlineRun error, line:%d\n", __LINE__);
00542                 PyErr_Print();
00543                 PyErr_Clear();
00544 
00545                 PyList_SET_ITEM(values, i, Py_None); /* hold user */
00546                 Py_INCREF(Py_None);
00547 
00548                 sizes[i]= 0;
00549             }
00550             else {
00551                 if (PyTuple_GET_SIZE(ret) == 1) {
00552                     /* convenience, convert single tuples into single values */
00553                     PyObject *tmp= PyTuple_GET_ITEM(ret, 0);
00554                     Py_INCREF(tmp);
00555                     Py_DECREF(ret);
00556                     ret = tmp;
00557                 }
00558 
00559                 PyList_SET_ITEM(values, i, ret); /* hold user */
00560             }
00561         }
00562         va_end(vargs);
00563         
00564         /* set the value so we can access it */
00565         PyDict_SetItemString(py_dict, "values", values);
00566 
00567         py_result = PyRun_File(fp, filepath, Py_file_input, py_dict, py_dict);
00568 
00569         fclose(fp);
00570 
00571         if (py_result) {
00572 
00573             /* we could skip this but then only slice assignment would work
00574              * better not be so strict */
00575             values= PyDict_GetItemString(py_dict, "values");
00576 
00577             if (values && PyList_Check(values)) {
00578 
00579                 /* dont use the result */
00580                 Py_DECREF(py_result);
00581                 py_result= NULL;
00582 
00583                 /* now get the values back */
00584                 va_start(vargs, n);
00585                 for (i=0; i*2 <n; i++) {
00586                     char *format = va_arg(vargs, char *);
00587                     void *ptr = va_arg(vargs, void *);
00588                     
00589                     PyObject *item;
00590                     PyObject *item_new;
00591                     /* prepend the string formatting and remake the tuple */
00592                     item= PyList_GET_ITEM(values, i);
00593                     if (PyTuple_CheckExact(item)) {
00594                         int ofs= PyTuple_GET_SIZE(item);
00595                         item_new= PyTuple_New(ofs + 1);
00596                         while (ofs--) {
00597                             PyObject *member= PyTuple_GET_ITEM(item, ofs);
00598                             PyTuple_SET_ITEM(item_new, ofs + 1, member);
00599                             Py_INCREF(member);
00600                         }
00601 
00602                         PyTuple_SET_ITEM(item_new, 0, PyUnicode_FromString(format));
00603                     }
00604                     else {
00605                         item_new= Py_BuildValue("sO", format, item);
00606                     }
00607 
00608                     ret = PyObject_Call(pack, item_new, NULL);
00609 
00610                     if (ret) {
00611                         /* copy the bytes back into memory */
00612                         memcpy(ptr, PyBytes_AS_STRING(ret), sizes[i]);
00613                         Py_DECREF(ret);
00614                     }
00615                     else {
00616                         printf("PyC_InlineRun error on arg '%d', line:%d\n", i, __LINE__);
00617                         PyC_ObSpit("failed converting:", item_new);
00618                         PyErr_Print();
00619                         PyErr_Clear();
00620                     }
00621 
00622                     Py_DECREF(item_new);
00623                 }
00624                 va_end(vargs);
00625             }
00626             else {
00627                 printf("PyC_InlineRun error, 'values' not a list, line:%d\n", __LINE__);
00628             }
00629         }
00630         else {
00631             printf("PyC_InlineRun error line:%d\n", __LINE__);
00632             PyErr_Print();
00633             PyErr_Clear();
00634         }
00635 
00636         Py_DECREF(calcsize);
00637         Py_DECREF(pack);
00638         Py_DECREF(unpack);
00639 
00640         PyMem_FREE(sizes);
00641 
00642         PyGILState_Release(gilstate);
00643     }
00644 }