Merged changes in the trunk up to revision 26439.
[blender.git] / source / blender / python / intern / bpy_interface.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * Contributor(s): Michel Selten, Willian P. Germano, Stephen Swaney,
21  * Chris Keith, Chris Want, Ken Hughes, Campbell Barton
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25  
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/stat.h>
30
31
32 /* grr, python redefines */
33 #ifdef _POSIX_C_SOURCE
34 #undef _POSIX_C_SOURCE
35 #endif
36
37 #include <Python.h>
38 #include "compile.h"            /* for the PyCodeObject */
39 #include "eval.h"               /* for PyEval_EvalCode */
40
41 #include "bpy_rna.h"
42 #include "bpy_props.h"
43 #include "bpy_operator.h"
44 #include "bpy_ui.h"
45 #include "bpy_util.h"
46
47 #ifndef WIN32
48 #include <dirent.h>
49 #else
50 #include "BLI_winstuff.h"
51 #endif
52
53 #include "DNA_space_types.h"
54 #include "DNA_text_types.h"
55
56 #include "MEM_guardedalloc.h"
57
58 #include "BLI_path_util.h"
59 #include "BLI_storage.h"
60 #include "BLI_fileops.h"
61 #include "BLI_string.h"
62
63 #include "BKE_blender.h"
64 #include "BKE_context.h"
65 #include "BKE_text.h"
66 #include "BKE_context.h"
67 #include "BKE_global.h"
68 #include "BKE_main.h"
69
70 #include "BPY_extern.h"
71
72 #include "BPy_Freestyle.h"
73
74 #include "../generic/bpy_internal_import.h" // our own imports
75 /* external util modules */
76
77 #include "../generic/Mathutils.h"
78 #include "../generic/Geometry.h"
79 #include "../generic/BGL.h"
80 #include "../generic/IDProp.h"
81
82 /* for internal use, when starting and ending python scripts */
83
84 /* incase a python script triggers another python call, stop bpy_context_clear from invalidating */
85 static int py_call_level= 0;
86
87
88 // only for tests
89 #define TIME_PY_RUN
90
91 #ifdef TIME_PY_RUN
92 #include "PIL_time.h"
93 static int              bpy_timer_count = 0;
94 static double   bpy_timer; /* time since python starts */
95 static double   bpy_timer_run; /* time for each python script run */
96 static double   bpy_timer_run_tot; /* accumulate python runs */
97 #endif
98
99 void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
100 {
101         py_call_level++;
102
103         if(gilstate)
104                 *gilstate = PyGILState_Ensure();
105
106         if(py_call_level==1) {
107
108                 if(C) { // XXX - should always be true.
109                         BPy_SetContext(C);
110                         bpy_import_main_set(CTX_data_main(C));
111                 }
112                 else {
113                         fprintf(stderr, "ERROR: Python context called with a NULL Context. this should not happen!\n");
114                 }
115
116                 BPY_update_modules(); /* can give really bad results if this isnt here */
117
118 #ifdef TIME_PY_RUN
119                 if(bpy_timer_count==0) {
120                         /* record time from the beginning */
121                         bpy_timer= PIL_check_seconds_timer();
122                         bpy_timer_run = bpy_timer_run_tot = 0.0;
123                 }
124                 bpy_timer_run= PIL_check_seconds_timer();
125
126
127                 bpy_timer_count++;
128 #endif
129         }
130 }
131
132 void bpy_context_clear(bContext *C, PyGILState_STATE *gilstate)
133 {
134         py_call_level--;
135
136         if(gilstate)
137                 PyGILState_Release(*gilstate);
138
139         if(py_call_level < 0) {
140                 fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
141         }
142         else if(py_call_level==0) {
143                 // XXX - Calling classes currently wont store the context :\, cant set NULL because of this. but this is very flakey still.
144                 //BPy_SetContext(NULL);
145                 //bpy_import_main_set(NULL);
146
147 #ifdef TIME_PY_RUN
148                 bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
149                 bpy_timer_count++;
150 #endif
151
152         }
153 }
154
155 static void bpy_import_test(char *modname)
156 {
157         PyObject *mod= PyImport_ImportModuleLevel(modname, NULL, NULL, NULL, 0);
158         if(mod) {
159                 Py_DECREF(mod);
160         }
161         else {
162                 PyErr_Print();
163                 PyErr_Clear();
164         }       
165 }
166
167 void BPY_free_compiled_text( struct Text *text )
168 {
169         if( text->compiled ) {
170                 Py_DECREF( ( PyObject * ) text->compiled );
171                 text->compiled = NULL;
172         }
173 }
174
175 /*****************************************************************************
176 * Description: Creates the bpy module and adds it to sys.modules for importing
177 *****************************************************************************/
178 static BPy_StructRNA *bpy_context_module= NULL; /* for fast access */
179 static void bpy_init_modules( void )
180 {
181         PyObject *mod;
182
183         /* Needs to be first since this dir is needed for future modules */
184         char *modpath= BLI_gethome_folder("scripts/modules", BLI_GETHOME_ALL);
185         if(modpath) {
186                 PyObject *sys_path= PySys_GetObject("path"); /* borrow */
187                 PyObject *py_modpath= PyUnicode_FromString(modpath);
188                 PyList_Insert(sys_path, 0, py_modpath); /* add first */
189                 Py_DECREF(py_modpath);
190         }
191         
192         /* stand alone utility modules not related to blender directly */
193         Geometry_Init();
194         Mathutils_Init();
195         BGL_Init();
196         IDProp_Init_Types();
197         Freestyle_Init();
198
199
200         mod = PyModule_New("_bpy");
201
202         /* add the module so we can import it */
203         PyDict_SetItemString(PySys_GetObject("modules"), "_bpy", mod);
204         Py_DECREF(mod);
205
206         /* run first, initializes rna types */
207         BPY_rna_init();
208
209         PyModule_AddObject( mod, "types", BPY_rna_types() ); /* needs to be first so bpy_types can run */
210         bpy_import_test("bpy_types");
211         PyModule_AddObject( mod, "data", BPY_rna_module() ); /* imports bpy_types by running this */
212         bpy_import_test("bpy_types");
213         /* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
214         PyModule_AddObject( mod, "props", BPY_rna_props() );
215         PyModule_AddObject( mod, "ops", BPY_operator_module() ); /* ops is now a python module that does the conversion from SOME_OT_foo -> some.foo */
216         PyModule_AddObject( mod, "ui", BPY_ui_module() ); // XXX very experimental, consider this a test, especially PyCObject is not meant to be permanent
217
218
219
220         /* bpy context */
221         {
222                 bpy_context_module= ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
223
224                 RNA_pointer_create(NULL, &RNA_Context, NULL, &bpy_context_module->ptr);
225                 bpy_context_module->freeptr= 0;
226
227                 PyModule_AddObject(mod, "context", (PyObject *)bpy_context_module);
228         }
229
230         /* blender info that wont change at runtime, add into _bpy */
231         {
232                 extern char bprogname[]; /* argv[0] from creator.c */
233
234                 PyObject *mod_dict= PyModule_GetDict(mod);
235                 char tmpstr[256];
236                 PyModule_AddStringConstant(mod, "_HOME",  BLI_gethome());
237                 PyDict_SetItemString(mod_dict, "_VERSION", Py_BuildValue("(iii)", BLENDER_VERSION/100, BLENDER_VERSION%100, BLENDER_SUBVERSION));
238                 sprintf(tmpstr, "%d.%02d (sub %d)", BLENDER_VERSION/100, BLENDER_VERSION%100, BLENDER_SUBVERSION);
239                 PyModule_AddStringConstant(mod, "_VERSION_STR",  tmpstr);
240                 PyModule_AddStringConstant(mod, "_BINPATH",  bprogname);
241                 PyModule_AddIntConstant(mod, "_DEBUG",  G.f & G_DEBUG ? 1:0);
242         }
243
244         /* add our own modules dir, this is a python package */
245         bpy_import_test("bpy");
246 }
247
248 void BPY_update_modules( void )
249 {
250 #if 0 // slow, this runs all the time poll, draw etc 100's of time a sec.
251         PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
252         PyModule_AddObject( mod, "data", BPY_rna_module() );
253         PyModule_AddObject( mod, "types", BPY_rna_types() ); // atm this does not need updating
254 #endif
255
256         /* refreshes the main struct */
257         BPY_update_rna_module();
258         bpy_context_module->ptr.data= (void *)BPy_GetContext();
259 }
260
261 /*****************************************************************************
262 * Description: This function creates a new Python dictionary object.
263 *****************************************************************************/
264 static PyObject *CreateGlobalDictionary( bContext *C, const char *filename )
265 {
266         PyObject *mod;
267         PyObject *item;
268         PyObject *dict = PyDict_New(  );
269         PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins(  ) );
270
271         item = PyUnicode_FromString( "__main__" );
272         PyDict_SetItemString( dict, "__name__", item );
273         Py_DECREF(item);
274         
275         /* __file__ only for nice UI'ness */
276         if(filename) {
277                 PyObject *item = PyUnicode_FromString( filename );
278                 PyDict_SetItemString( dict, "__file__", item );
279                 Py_DECREF(item);
280         }
281
282         /* add bpy to global namespace */
283         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
284         PyDict_SetItemString( dict, "bpy", mod );
285         Py_DECREF(mod);
286         
287         return dict;
288 }
289
290 /* must be called before Py_Initialize */
291 void BPY_start_python_path(void)
292 {
293         char *py_path_bundle= BLI_gethome_folder("python", BLI_GETHOME_ALL);
294
295         if(py_path_bundle==NULL)
296                 return;
297
298         /* set the environment path */
299         printf("found bundled python: %s\n", py_path_bundle);
300
301 #ifdef __APPLE__
302         /* OSX allow file/directory names to contain : character (represented as / in the Finder)
303          but current Python lib (release 3.1.1) doesn't handle these correctly */
304         if(strchr(py_path_bundle, ':'))
305                 printf("Warning : Blender application is located in a path containing : or / chars\
306                            \nThis may make python import function fail\n");
307 #endif
308         
309 #ifdef _WIN32
310         /* cmake/MSVC debug build crashes without this, why only
311            in this case is unknown.. */
312         {
313                 char *envpath = getenv("PYTHONPATH");
314
315                 if(envpath && envpath[0]) {
316                         char *newenvpath = BLI_sprintfN("%s;%s", py_path_bundle, envpath);
317                         BLI_setenv("PYTHONPATH", newenvpath);
318                         MEM_freeN(newenvpath);
319                 }
320                 else
321                         BLI_setenv("PYTHONPATH", py_path_bundle);       
322         }
323 #endif
324
325         {
326                 static wchar_t py_path_bundle_wchar[FILE_MAXDIR];
327
328                 mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR);
329                 Py_SetPythonHome(py_path_bundle_wchar);
330         }
331 }
332
333
334
335 void BPY_set_context(bContext *C)
336 {
337         BPy_SetContext(C);
338 }
339
340 /* call BPY_set_context first */
341 void BPY_start_python( int argc, char **argv )
342 {
343         PyThreadState *py_tstate = NULL;
344         
345         BPY_start_python_path(); /* allow to use our own included python */
346
347         Py_Initialize(  );
348         
349         // PySys_SetArgv( argc, argv); // broken in py3, not a huge deal
350         /* sigh, why do python guys not have a char** version anymore? :( */
351         {
352                 int i;
353 #if 0
354                 PyObject *py_argv= PyList_New(argc);
355                 for (i=0; i<argc; i++)
356                         PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
357
358 #else   // should fix bug #20021 - utf path name problems
359                 PyObject *py_argv= PyList_New(0);
360                 for (i=0; i<argc; i++) {
361                         PyObject *item= PyUnicode_Decode(argv[i], strlen(argv[i]), Py_FileSystemDefaultEncoding, NULL);
362                         if(item==NULL) { // should never happen
363                                 PyErr_Print();
364                                 PyErr_Clear();
365                         }
366                         else {
367                                 PyList_Append(py_argv, item);
368                                 Py_DECREF(item);
369                         }
370                 }
371 #endif
372                 PySys_SetObject("argv", py_argv);
373                 Py_DECREF(py_argv);
374         }
375         
376         /* Initialize thread support (also acquires lock) */
377         PyEval_InitThreads();
378         
379         
380         /* bpy.* and lets us import it */
381         bpy_init_modules(); 
382
383         { /* our own import and reload functions */
384                 PyObject *item;
385                 //PyObject *m = PyImport_AddModule("__builtin__");
386                 //PyObject *d = PyModule_GetDict(m);
387                 PyObject *d = PyEval_GetBuiltins(  );
388                 PyDict_SetItemString(d, "reload",               item=PyCFunction_New(bpy_reload_meth, NULL));   Py_DECREF(item);
389                 PyDict_SetItemString(d, "__import__",   item=PyCFunction_New(bpy_import_meth, NULL));   Py_DECREF(item);
390         }
391         
392         pyrna_alloc_types();
393
394         py_tstate = PyGILState_GetThisThreadState();
395         PyEval_ReleaseThread(py_tstate);
396 }
397
398 void BPY_end_python( void )
399 {
400         // fprintf(stderr, "Ending Python!\n");
401
402         PyGILState_Ensure(); /* finalizing, no need to grab the state */
403         
404         // free other python data.
405         pyrna_free_types();
406
407         /* clear all python data from structs */
408         
409         Py_Finalize(  );
410         
411 #ifdef TIME_PY_RUN
412         // measure time since py started
413         bpy_timer = PIL_check_seconds_timer() - bpy_timer;
414
415         printf("*bpy stats* - ");
416         printf("tot exec: %d,  ", bpy_timer_count);
417         printf("tot run: %.4fsec,  ", bpy_timer_run_tot);
418         if(bpy_timer_count>0)
419                 printf("average run: %.6fsec,  ", (bpy_timer_run_tot/bpy_timer_count));
420
421         if(bpy_timer>0.0)
422                 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
423
424         printf("\n");
425
426         // fprintf(stderr, "Ending Python Done!\n");
427
428 #endif
429
430 }
431
432 /* Can run a file or text block */
433 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
434 {
435         PyObject *py_dict, *py_result= NULL;
436         PyGILState_STATE gilstate;
437         
438         if (fn==NULL && text==NULL) {
439                 return 0;
440         }
441         
442         bpy_context_set(C, &gilstate);
443         
444         py_dict = CreateGlobalDictionary(C, text?text->id.name+2:fn);
445
446         if (text) {
447                 
448                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
449                         char *buf = txt_to_buf( text );
450
451                         text->compiled =
452                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
453
454                         MEM_freeN( buf );
455
456                         if( PyErr_Occurred(  ) ) {
457                                 BPY_free_compiled_text( text );
458                         }
459                 }
460                 if(text->compiled)
461                         py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
462                 
463         } else {
464                 FILE *fp= fopen(fn, "r");               
465                 if(fp) {
466 #ifdef _WIN32
467                         /* Previously we used PyRun_File to run directly the code on a FILE 
468                          * object, but as written in the Python/C API Ref Manual, chapter 2,
469                          * 'FILE structs for different C libraries can be different and 
470                          * incompatible'.
471                          * So now we load the script file data to a buffer */
472                         char *pystring;
473
474                         fclose(fp);
475
476                         pystring= malloc(strlen(fn) + 32);
477                         pystring[0]= '\0';
478                         sprintf(pystring, "exec(open(r'%s').read())", fn);
479                         py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
480                         free(pystring);
481 #else
482                         py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
483                         fclose(fp);
484 #endif
485                 }
486                 else {
487                         PyErr_Format(PyExc_SystemError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
488                         py_result= NULL;
489                 }
490         }
491         
492         if (!py_result) {
493                 BPy_errors_to_report(reports);
494         } else {
495                 Py_DECREF( py_result );
496         }
497         
498         Py_DECREF(py_dict);
499         
500         bpy_context_clear(C, &gilstate);
501
502         return py_result ? 1:0;
503 }
504
505
506 /* TODO - move into bpy_space.c ? */
507 /* GUI interface routines */
508
509 /* Copied from Draw.c */
510 static void exit_pydraw( SpaceScript * sc, short err )
511 {
512         Script *script = NULL;
513
514         if( !sc || !sc->script )
515                 return;
516
517         script = sc->script;
518
519         if( err ) {
520                 BPy_errors_to_report(NULL); // TODO, reports
521                 script->flags = 0;      /* mark script struct for deletion */
522                 SCRIPT_SET_NULL(script);
523                 script->scriptname[0] = '\0';
524                 script->scriptarg[0] = '\0';
525 // XXX 2.5              error_pyscript();
526 // XXX 2.5              scrarea_queue_redraw( sc->area );
527         }
528
529 #if 0 // XXX 2.5
530         BPy_Set_DrawButtonsList(sc->but_refs);
531         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
532 #endif
533
534         sc->but_refs = NULL;
535         
536         Py_XDECREF( ( PyObject * ) script->py_draw );
537         Py_XDECREF( ( PyObject * ) script->py_event );
538         Py_XDECREF( ( PyObject * ) script->py_button );
539
540         script->py_draw = script->py_event = script->py_button = NULL;
541 }
542
543 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
544 {
545         if (sc->script==NULL) 
546                 return 0;
547         
548         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
549                 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
550                 
551         if (sc->script->py_draw==NULL)
552                 return 0;
553         
554         return 1;
555 }
556
557 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
558 {
559         if (bpy_run_script_init( (bContext *)C, sc)) {
560                 PyGILState_STATE gilstate = PyGILState_Ensure();
561                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
562                 
563                 if (result==NULL)
564                         exit_pydraw(sc, 1);
565                         
566                 PyGILState_Release(gilstate);
567         }
568         return 1;
569 }
570
571 // XXX - not used yet, listeners dont get a context
572 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
573 {
574         if (bpy_run_script_init(C, sc)) {
575                 PyGILState_STATE gilstate = PyGILState_Ensure();
576                 
577                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
578                 
579                 if (result==NULL)
580                         exit_pydraw(sc, 1);
581                         
582                 PyGILState_Release(gilstate);
583         }
584         return 1;
585 }
586
587 void BPY_DECREF(void *pyob_ptr)
588 {
589         PyGILState_STATE gilstate = PyGILState_Ensure();
590         Py_DECREF((PyObject *)pyob_ptr);
591         PyGILState_Release(gilstate);
592 }
593
594 #if 0
595 /* called from the the scripts window, assume context is ok */
596 int BPY_run_python_script_space(const char *modulename, const char *func)
597 {
598         PyObject *py_dict, *py_result= NULL;
599         char pystring[512];
600         PyGILState_STATE gilstate;
601         
602         /* for calling the module function */
603         PyObject *py_func, 
604         
605         gilstate = PyGILState_Ensure();
606         
607         py_dict = CreateGlobalDictionary(C);
608         
609         PyObject *module = PyImport_ImportModule(scpt->script.filename);
610         if (module==NULL) {
611                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
612         }
613         else {
614                 py_func = PyObject_GetAttrString(modulename, func);
615                 if (py_func==NULL) {
616                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
617                 }
618                 else {
619                         Py_DECREF(py_func);
620                         if (!PyCallable_Check(py_func)) {
621                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
622                         }
623                         else {
624                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
625                         }
626                 }
627         }
628         
629         if (!py_result) {
630                 BPy_errors_to_report(NULL); // TODO - reports
631         } else
632                 Py_DECREF( py_result );
633         
634         Py_XDECREF(module);
635         
636         Py_DECREF(py_dict);
637         
638         PyGILState_Release(gilstate);
639         return 1;
640 }
641 #endif
642
643 // #define TIME_REGISTRATION
644
645 #ifdef TIME_REGISTRATION
646 #include "PIL_time.h"
647 #endif
648
649
650 int BPY_button_eval(bContext *C, char *expr, double *value)
651 {
652         PyGILState_STATE gilstate;
653         PyObject *dict, *mod, *retval;
654         int error_ret = 0;
655         
656         if (!value || !expr || expr[0]=='\0') return -1;
657         
658         bpy_context_set(C, &gilstate);
659         
660         dict= CreateGlobalDictionary(C, NULL);
661         
662         /* import some modules: builtins,math*/
663         PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins());
664
665         mod = PyImport_ImportModule("math");
666         if (mod) {
667                 PyDict_Merge(dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
668                 
669                 /* Only keep for backwards compat! - just import all math into root, they are standard */
670                 PyDict_SetItemString(dict, "math", mod);
671                 PyDict_SetItemString(dict, "m", mod);
672                 Py_DECREF(mod);
673         } 
674         
675         retval = PyRun_String(expr, Py_eval_input, dict, dict);
676         
677         if (retval == NULL) {
678                 error_ret= -1;
679         }
680         else {
681                 double val;
682
683                 if(PyTuple_Check(retval)) {
684                         /* Users my have typed in 10km, 2m
685                          * add up all values */
686                         int i;
687                         val= 0.0;
688
689                         for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
690                                 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
691                         }
692                 }
693                 else {
694                         val = PyFloat_AsDouble(retval);
695                 }
696                 Py_DECREF(retval);
697                 
698                 if(val==-1 && PyErr_Occurred()) {
699                         error_ret= -1;
700                 }
701                 else {
702                         *value= val;
703                 }
704         }
705         
706         if(error_ret) {
707                 BPy_errors_to_report(CTX_wm_reports(C));
708         }
709         
710         Py_DECREF(dict);
711         bpy_context_clear(C, &gilstate);
712         
713         return error_ret;
714 }
715
716 void BPY_load_user_modules(bContext *C)
717 {
718         PyGILState_STATE gilstate;
719         Main *bmain= CTX_data_main(C);
720         Text *text;
721
722         /* can happen on file load */
723         if(bmain==NULL)
724                 return;
725
726         bpy_context_set(C, &gilstate);
727
728         for(text=CTX_data_main(C)->text.first; text; text= text->id.next) {
729                 if(text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
730                         PyObject *module= bpy_text_import(text);
731
732                         if (module==NULL) {
733                                 PyErr_Print();
734                                 PyErr_Clear();
735                         }
736                         else {
737                                 Py_DECREF(module);
738                         }
739                 }
740         }
741         bpy_context_clear(C, &gilstate);
742 }
743
744 int BPY_context_get(bContext *C, const char *member, bContextDataResult *result)
745 {
746         PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
747         PyObject *item= PyDict_GetItemString(pyctx, member);
748         PointerRNA *ptr= NULL;
749         int done= 0;
750
751         if(item==NULL) {
752                 /* pass */
753         }
754         else if(item==Py_None) {
755                 /* pass */
756         }
757         else if(BPy_StructRNA_Check(item)) {
758                 ptr= &(((BPy_StructRNA *)item)->ptr);
759
760                 //result->ptr= ((BPy_StructRNA *)item)->ptr;
761                 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
762                 done= 1;
763         }
764         else if (PySequence_Check(item)) {
765                 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
766                 if (seq_fast==NULL) {
767                         PyErr_Print();
768                         PyErr_Clear();
769                 }
770                 else {
771                         int len= PySequence_Fast_GET_SIZE(seq_fast);
772                         int i;
773                         for(i = 0; i < len; i++) {
774                                 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
775
776                                 if(BPy_StructRNA_Check(list_item)) {
777                                         /*
778                                         CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
779                                         link->ptr= ((BPy_StructRNA *)item)->ptr;
780                                         BLI_addtail(&result->list, link);
781                                         */
782                                         ptr= &(((BPy_StructRNA *)list_item)->ptr);
783                                         CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
784                                 }
785                                 else {
786                                         printf("List item not a valid type\n");
787                                 }
788
789                         }
790                         Py_DECREF(seq_fast);
791
792                         done= 1;
793                 }
794         }
795
796         if(done==0) {
797                 if (item)       printf("Context '%s' not a valid type\n", member);
798                 else            printf("Context '%s' not found\n", member);
799         }
800         else if (G.f & G_DEBUG) {
801                 printf("Context '%s' found\n", member);
802         }
803
804         return done;
805 }
806