[#20892] Locking animation curves with Tab Key don't hide the curves handles
[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 "../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                 PyModule_AddIntConstant(mod, "_DEBUG",  G.f & G_DEBUG ? 1:0);
239         }
240
241         /* add our own modules dir, this is a python package */
242         bpy_import_test("bpy");
243 }
244
245 void BPY_update_modules( void )
246 {
247 #if 0 // slow, this runs all the time poll, draw etc 100's of time a sec.
248         PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
249         PyModule_AddObject( mod, "data", BPY_rna_module() );
250         PyModule_AddObject( mod, "types", BPY_rna_types() ); // atm this does not need updating
251 #endif
252
253         /* refreshes the main struct */
254         BPY_update_rna_module();
255         bpy_context_module->ptr.data= (void *)BPy_GetContext();
256 }
257
258 /*****************************************************************************
259 * Description: This function creates a new Python dictionary object.
260 *****************************************************************************/
261 static PyObject *CreateGlobalDictionary( bContext *C, const char *filename )
262 {
263         PyObject *mod;
264         PyObject *item;
265         PyObject *dict = PyDict_New(  );
266         PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins(  ) );
267
268         item = PyUnicode_FromString( "__main__" );
269         PyDict_SetItemString( dict, "__name__", item );
270         Py_DECREF(item);
271         
272         /* __file__ only for nice UI'ness */
273         if(filename) {
274                 PyObject *item = PyUnicode_FromString( filename );
275                 PyDict_SetItemString( dict, "__file__", item );
276                 Py_DECREF(item);
277         }
278
279         /* add bpy to global namespace */
280         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
281         PyDict_SetItemString( dict, "bpy", mod );
282         Py_DECREF(mod);
283         
284         return dict;
285 }
286
287 /* must be called before Py_Initialize */
288 void BPY_start_python_path(void)
289 {
290         char *py_path_bundle= BLI_gethome_folder("python", BLI_GETHOME_ALL);
291
292         if(py_path_bundle==NULL)
293                 return;
294
295         /* set the environment path */
296         printf("found bundled python: %s\n", py_path_bundle);
297
298 #ifdef __APPLE__
299         /* OSX allow file/directory names to contain : character (represented as / in the Finder)
300          but current Python lib (release 3.1.1) doesn't handle these correctly */
301         if(strchr(py_path_bundle, ':'))
302                 printf("Warning : Blender application is located in a path containing : or / chars\
303                            \nThis may make python import function fail\n");
304 #endif
305         
306 #ifdef _WIN32
307         /* cmake/MSVC debug build crashes without this, why only
308            in this case is unknown.. */
309         {
310                 char *envpath = getenv("PYTHONPATH");
311
312                 if(envpath && envpath[0]) {
313                         char *newenvpath = BLI_sprintfN("%s;%s", py_path_bundle, envpath);
314                         BLI_setenv("PYTHONPATH", newenvpath);
315                         MEM_freeN(newenvpath);
316                 }
317                 else
318                         BLI_setenv("PYTHONPATH", py_path_bundle);       
319         }
320 #endif
321
322         {
323                 static wchar_t py_path_bundle_wchar[FILE_MAXDIR];
324
325                 mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR);
326                 Py_SetPythonHome(py_path_bundle_wchar);
327         }
328 }
329
330
331
332 void BPY_set_context(bContext *C)
333 {
334         BPy_SetContext(C);
335 }
336
337 /* call BPY_set_context first */
338 void BPY_start_python( int argc, char **argv )
339 {
340         PyThreadState *py_tstate = NULL;
341         
342         BPY_start_python_path(); /* allow to use our own included python */
343
344         Py_Initialize(  );
345         
346         // PySys_SetArgv( argc, argv); // broken in py3, not a huge deal
347         /* sigh, why do python guys not have a char** version anymore? :( */
348         {
349                 int i;
350 #if 0
351                 PyObject *py_argv= PyList_New(argc);
352                 for (i=0; i<argc; i++)
353                         PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
354
355 #else   // should fix bug #20021 - utf path name problems
356                 PyObject *py_argv= PyList_New(0);
357                 for (i=0; i<argc; i++) {
358                         PyObject *item= PyUnicode_Decode(argv[i], strlen(argv[i]), Py_FileSystemDefaultEncoding, NULL);
359                         if(item==NULL) { // should never happen
360                                 PyErr_Print();
361                                 PyErr_Clear();
362                         }
363                         else {
364                                 PyList_Append(py_argv, item);
365                                 Py_DECREF(item);
366                         }
367                 }
368 #endif
369                 PySys_SetObject("argv", py_argv);
370                 Py_DECREF(py_argv);
371         }
372         
373         /* Initialize thread support (also acquires lock) */
374         PyEval_InitThreads();
375         
376         
377         /* bpy.* and lets us import it */
378         bpy_init_modules(); 
379
380         { /* our own import and reload functions */
381                 PyObject *item;
382                 //PyObject *m = PyImport_AddModule("__builtin__");
383                 //PyObject *d = PyModule_GetDict(m);
384                 PyObject *d = PyEval_GetBuiltins(  );
385                 PyDict_SetItemString(d, "reload",               item=PyCFunction_New(bpy_reload_meth, NULL));   Py_DECREF(item);
386                 PyDict_SetItemString(d, "__import__",   item=PyCFunction_New(bpy_import_meth, NULL));   Py_DECREF(item);
387         }
388         
389         pyrna_alloc_types();
390
391         py_tstate = PyGILState_GetThisThreadState();
392         PyEval_ReleaseThread(py_tstate);
393 }
394
395 void BPY_end_python( void )
396 {
397         // fprintf(stderr, "Ending Python!\n");
398
399         PyGILState_Ensure(); /* finalizing, no need to grab the state */
400         
401         // free other python data.
402         pyrna_free_types();
403
404         /* clear all python data from structs */
405         
406         Py_Finalize(  );
407         
408 #ifdef TIME_PY_RUN
409         // measure time since py started
410         bpy_timer = PIL_check_seconds_timer() - bpy_timer;
411
412         printf("*bpy stats* - ");
413         printf("tot exec: %d,  ", bpy_timer_count);
414         printf("tot run: %.4fsec,  ", bpy_timer_run_tot);
415         if(bpy_timer_count>0)
416                 printf("average run: %.6fsec,  ", (bpy_timer_run_tot/bpy_timer_count));
417
418         if(bpy_timer>0.0)
419                 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
420
421         printf("\n");
422
423         // fprintf(stderr, "Ending Python Done!\n");
424
425 #endif
426
427 }
428
429 /* Can run a file or text block */
430 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
431 {
432         PyObject *py_dict, *py_result= NULL;
433         PyGILState_STATE gilstate;
434         
435         if (fn==NULL && text==NULL) {
436                 return 0;
437         }
438         
439         bpy_context_set(C, &gilstate);
440         
441         py_dict = CreateGlobalDictionary(C, text?text->id.name+2:fn);
442
443         if (text) {
444                 
445                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
446                         char *buf = txt_to_buf( text );
447
448                         text->compiled =
449                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
450
451                         MEM_freeN( buf );
452
453                         if( PyErr_Occurred(  ) ) {
454                                 BPY_free_compiled_text( text );
455                         }
456                 }
457                 if(text->compiled)
458                         py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
459                 
460         } else {
461                 FILE *fp= fopen(fn, "r");               
462                 if(fp) {
463 #ifdef _WIN32
464                         /* Previously we used PyRun_File to run directly the code on a FILE 
465                          * object, but as written in the Python/C API Ref Manual, chapter 2,
466                          * 'FILE structs for different C libraries can be different and 
467                          * incompatible'.
468                          * So now we load the script file data to a buffer */
469                         char *pystring;
470
471                         fclose(fp);
472
473                         pystring= malloc(strlen(fn) + 32);
474                         pystring[0]= '\0';
475                         sprintf(pystring, "exec(open(r'%s').read())", fn);
476                         py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
477                         free(pystring);
478 #else
479                         py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
480                         fclose(fp);
481 #endif
482                 }
483                 else {
484                         PyErr_Format(PyExc_SystemError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
485                         py_result= NULL;
486                 }
487         }
488         
489         if (!py_result) {
490                 BPy_errors_to_report(reports);
491         } else {
492                 Py_DECREF( py_result );
493         }
494         
495         Py_DECREF(py_dict);
496         
497         bpy_context_clear(C, &gilstate);
498
499         return py_result ? 1:0;
500 }
501
502
503 /* TODO - move into bpy_space.c ? */
504 /* GUI interface routines */
505
506 /* Copied from Draw.c */
507 static void exit_pydraw( SpaceScript * sc, short err )
508 {
509         Script *script = NULL;
510
511         if( !sc || !sc->script )
512                 return;
513
514         script = sc->script;
515
516         if( err ) {
517                 BPy_errors_to_report(NULL); // TODO, reports
518                 script->flags = 0;      /* mark script struct for deletion */
519                 SCRIPT_SET_NULL(script);
520                 script->scriptname[0] = '\0';
521                 script->scriptarg[0] = '\0';
522 // XXX 2.5              error_pyscript();
523 // XXX 2.5              scrarea_queue_redraw( sc->area );
524         }
525
526 #if 0 // XXX 2.5
527         BPy_Set_DrawButtonsList(sc->but_refs);
528         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
529 #endif
530
531         sc->but_refs = NULL;
532         
533         Py_XDECREF( ( PyObject * ) script->py_draw );
534         Py_XDECREF( ( PyObject * ) script->py_event );
535         Py_XDECREF( ( PyObject * ) script->py_button );
536
537         script->py_draw = script->py_event = script->py_button = NULL;
538 }
539
540 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
541 {
542         if (sc->script==NULL) 
543                 return 0;
544         
545         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
546                 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
547                 
548         if (sc->script->py_draw==NULL)
549                 return 0;
550         
551         return 1;
552 }
553
554 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
555 {
556         if (bpy_run_script_init( (bContext *)C, sc)) {
557                 PyGILState_STATE gilstate = PyGILState_Ensure();
558                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
559                 
560                 if (result==NULL)
561                         exit_pydraw(sc, 1);
562                         
563                 PyGILState_Release(gilstate);
564         }
565         return 1;
566 }
567
568 // XXX - not used yet, listeners dont get a context
569 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
570 {
571         if (bpy_run_script_init(C, sc)) {
572                 PyGILState_STATE gilstate = PyGILState_Ensure();
573                 
574                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
575                 
576                 if (result==NULL)
577                         exit_pydraw(sc, 1);
578                         
579                 PyGILState_Release(gilstate);
580         }
581         return 1;
582 }
583
584 void BPY_DECREF(void *pyob_ptr)
585 {
586         PyGILState_STATE gilstate = PyGILState_Ensure();
587         Py_DECREF((PyObject *)pyob_ptr);
588         PyGILState_Release(gilstate);
589 }
590
591 #if 0
592 /* called from the the scripts window, assume context is ok */
593 int BPY_run_python_script_space(const char *modulename, const char *func)
594 {
595         PyObject *py_dict, *py_result= NULL;
596         char pystring[512];
597         PyGILState_STATE gilstate;
598         
599         /* for calling the module function */
600         PyObject *py_func, 
601         
602         gilstate = PyGILState_Ensure();
603         
604         py_dict = CreateGlobalDictionary(C);
605         
606         PyObject *module = PyImport_ImportModule(scpt->script.filename);
607         if (module==NULL) {
608                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
609         }
610         else {
611                 py_func = PyObject_GetAttrString(modulename, func);
612                 if (py_func==NULL) {
613                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
614                 }
615                 else {
616                         Py_DECREF(py_func);
617                         if (!PyCallable_Check(py_func)) {
618                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
619                         }
620                         else {
621                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
622                         }
623                 }
624         }
625         
626         if (!py_result) {
627                 BPy_errors_to_report(NULL); // TODO - reports
628         } else
629                 Py_DECREF( py_result );
630         
631         Py_XDECREF(module);
632         
633         Py_DECREF(py_dict);
634         
635         PyGILState_Release(gilstate);
636         return 1;
637 }
638 #endif
639
640 // #define TIME_REGISTRATION
641
642 #ifdef TIME_REGISTRATION
643 #include "PIL_time.h"
644 #endif
645
646
647 int BPY_button_eval(bContext *C, char *expr, double *value)
648 {
649         PyGILState_STATE gilstate;
650         PyObject *dict, *mod, *retval;
651         int error_ret = 0;
652         
653         if (!value || !expr || expr[0]=='\0') return -1;
654         
655         bpy_context_set(C, &gilstate);
656         
657         dict= CreateGlobalDictionary(C, NULL);
658         
659         /* import some modules: builtins,math*/
660         PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins());
661
662         mod = PyImport_ImportModule("math");
663         if (mod) {
664                 PyDict_Merge(dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
665                 
666                 /* Only keep for backwards compat! - just import all math into root, they are standard */
667                 PyDict_SetItemString(dict, "math", mod);
668                 PyDict_SetItemString(dict, "m", mod);
669                 Py_DECREF(mod);
670         } 
671         
672         retval = PyRun_String(expr, Py_eval_input, dict, dict);
673         
674         if (retval == NULL) {
675                 error_ret= -1;
676         }
677         else {
678                 double val;
679
680                 if(PyTuple_Check(retval)) {
681                         /* Users my have typed in 10km, 2m
682                          * add up all values */
683                         int i;
684                         val= 0.0;
685
686                         for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
687                                 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
688                         }
689                 }
690                 else {
691                         val = PyFloat_AsDouble(retval);
692                 }
693                 Py_DECREF(retval);
694                 
695                 if(val==-1 && PyErr_Occurred()) {
696                         error_ret= -1;
697                 }
698                 else {
699                         *value= val;
700                 }
701         }
702         
703         if(error_ret) {
704                 BPy_errors_to_report(CTX_wm_reports(C));
705         }
706         
707         Py_DECREF(dict);
708         bpy_context_clear(C, &gilstate);
709         
710         return error_ret;
711 }
712
713 void BPY_load_user_modules(bContext *C)
714 {
715         PyGILState_STATE gilstate;
716         Main *bmain= CTX_data_main(C);
717         Text *text;
718
719         /* can happen on file load */
720         if(bmain==NULL)
721                 return;
722
723         bpy_context_set(C, &gilstate);
724
725         for(text=CTX_data_main(C)->text.first; text; text= text->id.next) {
726                 if(text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
727                         PyObject *module= bpy_text_import(text);
728
729                         if (module==NULL) {
730                                 PyErr_Print();
731                                 PyErr_Clear();
732                         }
733                         else {
734                                 Py_DECREF(module);
735                         }
736                 }
737         }
738         bpy_context_clear(C, &gilstate);
739 }
740
741 int BPY_context_get(bContext *C, const char *member, bContextDataResult *result)
742 {
743         PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
744         PyObject *item= PyDict_GetItemString(pyctx, member);
745         PointerRNA *ptr= NULL;
746         int done= 0;
747
748         if(item==NULL) {
749                 /* pass */
750         }
751         else if(item==Py_None) {
752                 /* pass */
753         }
754         else if(BPy_StructRNA_Check(item)) {
755                 ptr= &(((BPy_StructRNA *)item)->ptr);
756
757                 //result->ptr= ((BPy_StructRNA *)item)->ptr;
758                 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
759                 done= 1;
760         }
761         else if (PySequence_Check(item)) {
762                 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
763                 if (seq_fast==NULL) {
764                         PyErr_Print();
765                         PyErr_Clear();
766                 }
767                 else {
768                         int len= PySequence_Fast_GET_SIZE(seq_fast);
769                         int i;
770                         for(i = 0; i < len; i++) {
771                                 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
772
773                                 if(BPy_StructRNA_Check(list_item)) {
774                                         /*
775                                         CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
776                                         link->ptr= ((BPy_StructRNA *)item)->ptr;
777                                         BLI_addtail(&result->list, link);
778                                         */
779                                         ptr= &(((BPy_StructRNA *)list_item)->ptr);
780                                         CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
781                                 }
782                                 else {
783                                         printf("List item not a valid type\n");
784                                 }
785
786                         }
787                         Py_DECREF(seq_fast);
788
789                         done= 1;
790                 }
791         }
792
793         if(done==0) {
794                 if (item)       printf("Context '%s' not a valid type\n", member);
795                 else            printf("Context '%s' not found\n", member);
796         }
797         else if (G.f & G_DEBUG) {
798                 printf("Context '%s' found\n", member);
799         }
800
801         return done;
802 }
803