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