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