== PyNodes ==
[blender-staging.git] / source / blender / python / 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  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * This is a new part of Blender.
24  *
25  * Contributor(s): Michel Selten, Willian P. Germano, Stephen Swaney,
26  * Chris Keith, Chris Want, Ken Hughes
27  *
28  * ***** END GPL LICENSE BLOCK *****
29 */
30
31 #include <Python.h>
32
33 #include "compile.h"            /* for the PyCodeObject */
34 #include "eval.h"               /* for PyEval_EvalCode */
35 #include "BLI_blenlib.h"        /* for BLI_last_slash() */
36 #include "BIF_interface.h"      /* for pupmenu() */
37 #include "BIF_space.h"
38 #include "BIF_screen.h"
39 #include "BIF_toolbox.h"
40 #include "BKE_action.h"         /* for get_pose_channel() */
41 #include "BKE_library.h"
42 #include "BKE_object.h"         /* during_scriptlink() */
43 #include "BKE_text.h"
44 #include "BKE_constraint.h" /* for bConstraintOb */
45 #include "BKE_idprop.h"
46
47 #include "DNA_curve_types.h" /* for struct IpoDriver */
48 #include "DNA_ID.h" /* ipo driver */
49 #include "DNA_object_types.h" /* ipo driver */
50 #include "DNA_constraint_types.h" /* for pyconstraint */
51
52 #include "DNA_screen_types.h"
53 #include "DNA_userdef_types.h"  /* for U.pythondir */
54 #include "MEM_guardedalloc.h"
55 #include "BPY_extern.h"
56 #include "BPY_menus.h"
57 #include "DNA_space_types.h"
58 #include "BKE_global.h"
59 #include "BKE_main.h"
60 #include "BKE_armature.h"
61 #include "BKE_depsgraph.h"
62 #include "api2_2x/EXPP_interface.h"
63 #include "api2_2x/constant.h"
64 #include "api2_2x/gen_utils.h"
65 #include "api2_2x/gen_library.h" /* GetPyObjectFromID */
66 #include "api2_2x/BGL.h" 
67 #include "api2_2x/Blender.h"
68 #include "api2_2x/Camera.h"
69 #include "api2_2x/Draw.h"
70 #include "api2_2x/Object.h"
71 #include "api2_2x/Registry.h"
72 #include "api2_2x/Pose.h"
73 #include "api2_2x/bpy.h" /* for the new "bpy" module */
74
75 /*these next two are for pyconstraints*/
76 #include "api2_2x/IDProp.h"
77 #include "api2_2x/matrix.h"
78
79 /* for scriptlinks */
80 #include "DNA_lamp_types.h"
81 #include "DNA_camera_types.h"
82 #include "DNA_world_types.h"
83 #include "DNA_scene_types.h"
84 #include "DNA_material_types.h"
85
86 /* bpy_registryDict is declared in api2_2x/Registry.h and defined
87  * in api2_2x/Registry.c
88  * This Python dictionary will be used to store data that scripts
89  * choose to preserve after they are executed, so user changes can be
90  * restored next time the script is used.  Check the Blender.Registry module. 
91  */
92 /*#include "api2_2x/Registry.h" */
93
94 /* for pydrivers (ipo drivers defined by one-line Python expressions) */
95 PyObject *bpy_pydriver_Dict = NULL;
96 PyObject *bpy_orig_syspath_List = NULL;
97
98 /*
99  * set up a weakref list for Armatures
100  *    creates list in __main__ module dict 
101  */
102   
103 int setup_armature_weakrefs()
104 {
105         PyObject *maindict;
106         PyObject *main_module;
107         char *list_name = ARM_WEAKREF_LIST_NAME;
108
109         main_module = PyImport_AddModule( "__main__");
110         if(main_module){
111                 PyObject *weakreflink;
112                 maindict= PyModule_GetDict(main_module);
113
114                 /* check if there is already a dict entry for the armature weakrefs,
115                  * and delete if so before making another one */
116
117                 weakreflink= PyDict_GetItemString(maindict,list_name);
118                 if( weakreflink != NULL ) {
119                         PyDict_DelItemString(maindict,list_name);
120                         Py_XDECREF( weakreflink );
121                 }
122
123                 if (PyDict_SetItemString(maindict, 
124                                                                  list_name, 
125                                                                  PyList_New(0)) == -1){
126                         printf("Oops - setup_armature_weakrefs()\n");
127                         
128                         return 0;
129                 }
130         }
131         return 1;
132 }
133
134 /* Declares the modules and their initialization functions
135  * These are TOP-LEVEL modules e.g. import `module` - there is no
136  * support for packages here e.g. import `package.module` */
137
138 static struct _inittab BPy_Inittab_Modules[] = {
139         {"Blender", M_Blender_Init},
140         {"bpy", m_bpy_init},
141         {NULL, NULL}
142 };
143
144 /*************************************************************************
145 * Structure definitions 
146 **************************************************************************/
147 #define FILENAME_LENGTH 24
148
149 typedef struct _ScriptError {
150         char filename[FILENAME_LENGTH];
151         int lineno;
152 } ScriptError;
153
154 /****************************************************************************
155 * Global variables 
156 ****************************************************************************/
157 ScriptError g_script_error;
158
159 /***************************************************************************
160 * Function prototypes 
161 ***************************************************************************/
162 PyObject *RunPython( Text * text, PyObject * globaldict );
163 char *GetName( Text * text );
164 PyObject *CreateGlobalDictionary( void );
165 void ReleaseGlobalDictionary( PyObject * dict );
166 void DoAllScriptsFromList( ListBase * list, short event );
167 PyObject *importText( char *name );
168 void init_ourImport( void );
169 void init_ourReload( void );
170 PyObject *blender_import( PyObject * self, PyObject * args );
171 PyObject *RunPython2( Text * text, PyObject * globaldict, PyObject *localdict );
172
173
174 void BPY_Err_Handle( char *script_name );
175 PyObject *traceback_getFilename( PyObject * tb );
176
177 /****************************************************************************
178 * Description: This function will start the interpreter and load all modules
179 * as well as search for a python installation.
180 ****************************************************************************/
181 void BPY_start_python( int argc, char **argv )
182 {
183         PyThreadState *py_tstate = NULL;
184         static int argc_copy = 0;
185         static char **argv_copy = NULL;
186         int first_time = argc;
187
188         /* we keep a copy of the values of argc and argv so that the game engine
189          * can call BPY_start_python(0, NULL) whenever a game ends, without having
190          * to know argc and argv there (in source/blender/src/space.c) */
191         if( first_time ) {
192                 argc_copy = argc;
193                 argv_copy = argv;
194         }
195
196         //stuff for Registry module
197         bpy_registryDict = PyDict_New(  );/* check comment at start of this file */
198         if( !bpy_registryDict )
199                 printf( "Error: Couldn't create the Registry Python Dictionary!" );
200         Py_SetProgramName( "blender" );
201
202         /* Py_Initialize() will attempt to import the site module and
203          * print an error if not found.  See init_syspath() for the
204          * rest of our init msgs.
205          */
206
207         /* print Python version
208          * Py_GetVersion() returns a ptr to a static string "9.9.9 (aaaa..." 
209          */
210         {
211                 int count = 3;  /* a nice default for major.minor.  example 2.5 */
212                 const char *version = Py_GetVersion();
213                 /* we know a blank is there somewhere! */
214                 char *blank_ptr = strchr( version, ' '); 
215                 if(blank_ptr)
216                         count = blank_ptr - version;
217                 
218                 printf( "Compiled with Python version %.*s.\n", count, version );
219         }
220
221
222         //Initialize the TOP-LEVEL modules
223         PyImport_ExtendInittab(BPy_Inittab_Modules);
224         
225         //Start the interpreter
226         Py_Initialize(  );
227         PySys_SetArgv( argc_copy, argv_copy );
228
229         /* Initialize thread support (also acquires lock) */
230         PyEval_InitThreads();
231
232         //Overrides __import__
233         init_ourImport(  );
234         init_ourReload(  );
235
236         //init a global dictionary
237         g_blenderdict = NULL;
238
239         //Look for a python installation
240         init_syspath( first_time ); /* not first_time: some msgs are suppressed */
241
242         py_tstate = PyGILState_GetThisThreadState();
243         PyEval_ReleaseThread(py_tstate);
244
245         return;
246 }
247
248 /*****************************************************************************/
249 /* Description: This function will terminate the Python interpreter          */
250 /*****************************************************************************/
251 void BPY_end_python( void )
252 {
253         Script *script = NULL;
254         Script *next_script = NULL;
255
256         PyGILState_Ensure(); /* finalizing, no need to grab the state */
257
258         if( bpy_registryDict ) {
259                 Py_DECREF( bpy_registryDict );
260                 bpy_registryDict = NULL;
261         }
262
263         if( bpy_pydriver_Dict ) {
264                 Py_DECREF( bpy_pydriver_Dict );
265                 bpy_pydriver_Dict = NULL;
266         }
267         
268         if( bpy_orig_syspath_List ) {
269                 Py_DECREF( bpy_orig_syspath_List );
270                 bpy_orig_syspath_List = NULL;
271         }
272
273         /* Freeing all scripts here prevents problems with the order in which
274          * Python is finalized and G.main is freed in exit_usiblender() */
275         for (script = G.main->script.first; script; script = next_script) {
276                 next_script = script->id.next;
277                 free_libblock( &G.main->script, script );
278         }
279
280         Py_Finalize(  );
281
282         BPyMenu_RemoveAllEntries(  );   /* freeing bpymenu mem */
283
284         /* a script might've opened a .blend file but didn't close it, so: */
285         EXPP_Library_Close(  );
286
287         return;
288 }
289
290 void syspath_append( char *dirname )
291 {
292         PyObject *mod_sys= NULL, *dict= NULL, *path= NULL, *dir= NULL;
293         short ok=1;
294         PyErr_Clear(  );
295
296         dir = Py_BuildValue( "s", dirname );
297
298         mod_sys = PyImport_ImportModule( "sys" );       /* new ref */
299         
300         if (mod_sys) {
301                 dict = PyModule_GetDict( mod_sys );     /* borrowed ref */
302                 path = PyDict_GetItemString( dict, "path" );    /* borrowed ref */
303                 if ( !PyList_Check( path ) ) {
304                         ok = 0;
305                 }
306         } else {
307                 /* cant get the sys module */
308                 ok = 0;
309         }
310         
311         if (PySequence_Contains(path, dir)==0) { /* Only add if we need to */
312                 if (ok && PyList_Append( path, dir ) != 0)
313                         ok = 0; /* append failed */
314         
315                 if( (ok==0) || PyErr_Occurred(  ) )
316                         Py_FatalError( "could import or build sys.path, can't continue" );
317         }
318         Py_XDECREF( mod_sys );
319 }
320
321 void init_syspath( int first_time )
322 {
323         PyObject *path;
324         PyObject *mod, *d;
325         char *progname;
326         char execdir[FILE_MAXDIR];      /*defines from DNA_space_types.h */
327
328         int n;
329         
330         
331         path = Py_BuildValue( "s", bprogname );
332
333         mod = PyImport_ImportModule( "Blender.sys" );
334
335         if( mod ) {
336                 d = PyModule_GetDict( mod );
337                 EXPP_dict_set_item_str( d, "progname", path );
338                 Py_DECREF( mod );
339         } else
340                 printf( "Warning: could not set Blender.sys.progname\n" );
341
342         progname = BLI_last_slash( bprogname ); /* looks for the last dir separator */
343
344         n = progname - bprogname;
345         if( n > 0 ) {
346                 strncpy( execdir, bprogname, n );
347                 if( execdir[n - 1] == '.' )
348                         n--;    /*fix for when run as ./blender */
349                 execdir[n] = '\0';
350
351                 syspath_append( execdir );      /* append to module search path */
352         } else {
353                 printf( "Warning: could not determine argv[0] path\n" );
354         }
355         
356         /* 
357            attempt to import 'site' module as a check for valid
358            python install found.
359         */
360
361         printf("Checking for installed Python... "); /* appears after msg "Compiled with Python 2.x"  */
362         mod = PyImport_ImportModule( "site" );  /* new ref */
363
364         if( mod ) {
365                 printf("got it!\n");  
366                 Py_DECREF( mod );
367         } else {                /* import 'site' failed */
368                 PyErr_Clear(  );
369                 if( first_time ) {
370                         printf( "No installed Python found.\n" );
371                         printf( "Only built-in modules are available.  Some scripts may not run.\n" );
372                         printf( "Continuing happily.\n" );
373                 }
374         }
375
376
377         /* 
378          * initialize the sys module
379          * set sys.executable to the Blender exe 
380          */
381
382         mod = PyImport_ImportModule( "sys" );   /* new ref */
383
384         if( mod ) {
385                 d = PyModule_GetDict( mod );    /* borrowed ref */
386                 EXPP_dict_set_item_str( d, "executable", Py_BuildValue( "s", bprogname ) );
387                 
388                 if (bpy_orig_syspath_List == NULL) {
389                         /* backup the original sys.path to rebuild later */     
390                         PyObject *syspath = PyDict_GetItemString( d, "path" );  /* borrowed ref */
391                         if (bpy_orig_syspath_List) { /* This should never happen but just incase, be nice */
392                                 Py_DECREF(bpy_orig_syspath_List);
393                         }
394                         bpy_orig_syspath_List = PyList_GetSlice(syspath, 0, PyList_Size(syspath));
395                 }
396                 
397                 Py_DECREF( mod );
398         } else{
399                 printf("import of sys module failed\n");
400         }
401 }
402
403 void BPY_rebuild_syspath( void )
404 {
405         PyObject *mod, *dict, *syspath;
406         char dirpath[FILE_MAX];
407         char *sdir = NULL;
408         PyGILState_STATE gilstate = PyGILState_Ensure();
409
410         mod = PyImport_ImportModule( "sys" );   
411         if (!mod) {
412                 printf("error: could not import python sys module. some modules may not import.\n");
413                 PyGILState_Release(gilstate);
414                 return;
415         }
416         
417         if (!bpy_orig_syspath_List) { /* should never happen */
418                 printf("error refershing python path\n");
419                 Py_DECREF(mod);
420                 PyGILState_Release(gilstate);
421                 return;
422         }
423         
424         dict = PyModule_GetDict( mod ); /* borrowed ref */
425         
426         /* Reset sys.path */    
427         syspath = PyDict_GetItemString( dict, "path" ); /* borrowed ref */
428         PyList_SetSlice(syspath, 0, PyList_Size(syspath), bpy_orig_syspath_List);
429         
430         if(U.pythondir[0] != '\0' ) {
431                 char modpath[FILE_MAX];
432                 int upyslen = strlen(U.pythondir);
433                 BLI_strncpy(dirpath, U.pythondir, FILE_MAX);
434                 
435                 /* check if user pydir ends with a slash and, if so, remove the slash
436                  * (for eventual implementations of c library's stat function that might
437                  * not like it) */
438 #ifdef WIN32
439                 if (upyslen > 3) {
440 #else
441                 if (upyslen > 1) {
442 #endif
443                         if (dirpath[upyslen-1] == '\\' || dirpath[upyslen-1] == '/') {
444                                 dirpath[upyslen-1] = '\0';
445                         }
446                 }
447
448                 BLI_convertstringcode(dirpath, G.sce);
449                 syspath_append(dirpath);        /* append to module search path */
450                 BLI_join_dirfile( modpath, dirpath, "bpymodules" );
451                 if (BLI_exists(modpath)) syspath_append(modpath);
452         }
453         
454         sdir = bpy_gethome(1);
455         if (sdir) {
456                 syspath_append(sdir);
457                 BLI_make_file_string("/", dirpath, sdir, "bpymodules");
458                 if (BLI_exists(dirpath)) syspath_append(dirpath);
459         }
460         
461         Py_DECREF(mod);
462         PyGILState_Release(gilstate);
463 }
464
465 int BPY_path_update( void )
466 {
467         BPyMenu_RemoveAllEntries(); /* free old data */
468         BPY_rebuild_syspath();
469         if (BPyMenu_Init(1) == -1) { /* re-eval scripts registration in menus */
470                 return 0;
471         }
472         return 1;
473 }
474
475 /****************************************************************************
476 * Description: This function finishes Python initialization in Blender.  
477
478 Because U.pythondir (user defined dir for scripts) isn't         
479 initialized when BPY_start_Python needs to be executed, we       
480 postpone adding U.pythondir to sys.path and also BPyMenus         
481 (mechanism to register scripts in Blender menus) for when  
482 that dir info is available.   
483 ****************************************************************************/
484 void BPY_post_start_python( void )
485 {
486         PyGILState_STATE gilstate = PyGILState_Ensure();
487
488         BPY_rebuild_syspath();
489         BPyMenu_Init( 0 );      /* get dynamic menus (registered scripts) data */
490
491         PyGILState_Release(gilstate);
492 }
493
494 /****************************************************************************
495 * Description: This function will return the linenumber on which an error  
496 *               has occurred in the Python script.                      
497 ****************************************************************************/
498 int BPY_Err_getLinenumber( void )
499 {
500         return g_script_error.lineno;
501 }
502
503 /*****************************************************************************/
504 /* Description: This function will return the filename of the python script. */
505 /*****************************************************************************/
506 const char *BPY_Err_getFilename( void )
507 {
508         return g_script_error.filename;
509 }
510
511 /*****************************************************************************/
512 /* Description: Return PyString filename from a traceback object            */
513 /*****************************************************************************/
514 PyObject *traceback_getFilename( PyObject * tb )
515 {
516         PyObject *v = NULL;
517
518 /* co_filename is in f_code, which is in tb_frame, which is in tb */
519
520         v = PyObject_GetAttrString( tb, "tb_frame" );
521         if (v) {
522                 Py_DECREF( v );
523                 v = PyObject_GetAttrString( v, "f_code" );
524                 if (v) {
525                         Py_DECREF( v );
526                         v = PyObject_GetAttrString( v, "co_filename" );
527                 }
528         }
529
530         if (v) return v;
531         else return PyString_FromString("unknown");
532 }
533
534 /****************************************************************************
535 * Description: Blender Python error handler. This catches the error and 
536 * stores filename and line number in a global  
537 *****************************************************************************/
538 void BPY_Err_Handle( char *script_name )
539 {
540         PyObject *exception, *err, *tb, *v;
541
542         if( !script_name ) {
543                 printf( "Error: script has NULL name\n" );
544                 return;
545         }
546
547         PyErr_Fetch( &exception, &err, &tb );
548
549         if (!script_name) script_name = "untitled";
550         //if( !exception && !tb ) {
551         //      printf( "FATAL: spurious exception\n" );
552         //      return;
553         //}
554
555         strcpy( g_script_error.filename, script_name );
556
557         if( exception
558             && PyErr_GivenExceptionMatches( exception, PyExc_SyntaxError ) ) {
559                 /* no traceback available when SyntaxError */
560                 PyErr_Restore( exception, err, tb );    /* takes away reference! */
561                 PyErr_Print(  );
562                 v = PyObject_GetAttrString( err, "lineno" );
563                 if( v ) {
564                         g_script_error.lineno = PyInt_AsLong( v );
565                         Py_DECREF( v );
566                 } else {
567                         g_script_error.lineno = -1;
568                 }
569                 /* this avoids an abort in Python 2.3's garbage collecting: */
570                 PyErr_Clear(  );
571                 return;
572         } else {
573                 PyErr_NormalizeException( &exception, &err, &tb );
574                 PyErr_Restore( exception, err, tb );    /* takes away reference! */
575                 PyErr_Print(  );
576                 tb = PySys_GetObject( "last_traceback" );
577
578                 if( !tb ) {
579                         printf( "\nCan't get traceback\n" );
580                         return;
581                 }
582
583                 Py_INCREF( tb );
584
585 /* From old bpython BPY_main.c:
586  * 'check traceback objects and look for last traceback in the
587  *      same text file. This is used to jump to the line of where the
588  *      error occured. "If the error occured in another text file or module,
589  *      the last frame in the current file is adressed."' 
590  */
591
592                 for(;;) {
593                         v = PyObject_GetAttrString( tb, "tb_next" );
594
595                         if( !v || v == Py_None ||
596                                 strcmp(PyString_AsString(traceback_getFilename(v)), script_name)) {
597                                 break;
598                         }
599
600                         Py_DECREF( tb );
601                         tb = v;
602                 }
603
604                 v = PyObject_GetAttrString( tb, "tb_lineno" );
605                 if (v) {
606                         g_script_error.lineno = PyInt_AsLong(v);
607                         Py_DECREF(v);
608                 }
609                 v = traceback_getFilename( tb );
610                 if (v) {
611                         strncpy( g_script_error.filename, PyString_AsString( v ),
612                                 FILENAME_LENGTH );
613                         Py_DECREF(v);
614                 }
615                 Py_DECREF( tb );
616         }
617
618         return;
619 }
620
621 /****************************************************************************
622 * Description: This function executes the script passed by st.          
623 * Notes:        It is called by blender/src/drawtext.c when a Blender user  
624 *               presses ALT+PKEY in the script's text window. 
625 *****************************************************************************/
626 int BPY_txt_do_python_Text( struct Text *text )
627 {
628         PyObject *py_dict, *py_result;
629         BPy_constant *info;
630         char textname[24];
631         Script *script = G.main->script.first;
632         PyGILState_STATE gilstate;
633
634         if( !text )
635                 return 0;
636
637         /* check if this text is already running */
638         while( script ) {
639                 if( !strcmp( script->id.name + 2, text->id.name + 2 ) ) {
640                         /* if this text is already a running script, 
641                          * just move to it: */
642                         if (!G.background) {
643                                 SpaceScript *sc;
644                                 newspace( curarea, SPACE_SCRIPT );
645                                 sc = curarea->spacedata.first;
646                                 sc->script = script;
647                                 return 1;
648                         }
649                 }
650                 script = script->id.next;
651         }
652
653         /* Create a new script structure and initialize it: */
654         script = alloc_libblock( &G.main->script, ID_SCRIPT, GetName( text ) );
655
656         if( !script ) {
657                 printf( "couldn't allocate memory for Script struct!" );
658                 return 0;
659         }
660
661         /* if in the script Blender.Load(blendfile) is not the last command,
662          * an error after it will call BPY_Err_Handle below, but the text struct
663          * will have been deallocated already, so we need to copy its name here.
664          */
665         BLI_strncpy( textname, GetName( text ),
666                      strlen( GetName( text ) ) + 1 );
667
668         script->id.us = 1;
669         script->flags = SCRIPT_RUNNING;
670         script->py_draw = NULL;
671         script->py_event = NULL;
672         script->py_button = NULL;
673         script->py_browsercallback = NULL;
674         strncpy(script->scriptname, text->id.name+2, sizeof(script->scriptname));
675         gilstate = PyGILState_Ensure();
676
677         py_dict = CreateGlobalDictionary(  );
678
679         if( !setup_armature_weakrefs()){
680                 printf("Oops - weakref dict\n");
681                 PyGILState_Release(gilstate);
682                 return 0;
683         }
684
685         script->py_globaldict = py_dict;
686
687         info = ( BPy_constant * ) PyConstant_New(  );
688         if( info ) {
689                 PyConstant_Insert( info, "name",
690                                  PyString_FromString( script->id.name + 2 ) );
691                 Py_INCREF( Py_None );
692                 PyConstant_Insert( info, "arg", Py_None );
693                 EXPP_dict_set_item_str( py_dict, "__script__",
694                                       ( PyObject * ) info );
695         }
696
697         py_result = RunPython( text, py_dict ); /* Run the script */
698
699         if( !py_result ) {      /* Failed execution of the script */
700
701                 BPY_Err_Handle( textname );
702                 ReleaseGlobalDictionary( py_dict );
703                 script->py_globaldict = NULL;
704                 free_libblock( &G.main->script, script );
705                 PyGILState_Release(gilstate);
706                 return 0;
707         } else {
708                 Py_DECREF( py_result );
709                 script->flags &= ~SCRIPT_RUNNING;
710                 if( !script->flags ) {
711                         ReleaseGlobalDictionary( py_dict );
712                         script->py_globaldict = NULL;
713                         free_libblock( &G.main->script, script );
714                 }
715         }
716
717         PyGILState_Release(gilstate);
718
719         return 1;               /* normal return */
720 }
721
722 /****************************************************************************
723 * Description: Called from command line to run a Python script
724 * automatically. The script can be a file or a Blender Text in the current 
725 * .blend.
726 ****************************************************************************/
727 void BPY_run_python_script( char *fn )
728 {
729         Text *text = NULL;
730         int is_blender_text = 0;
731
732         if (!BLI_exists(fn)) {  /* if there's no such filename ... */
733                 text = G.main->text.first;      /* try an already existing Blender Text */
734
735                 while (text) {
736                         if (!strcmp(fn, text->id.name + 2)) break;
737                         text = text->id.next;
738                 }
739
740                 if (text == NULL) {
741                         printf("\nError: no such file or Blender text -- %s.\n", fn);
742                         return;
743                 }
744                 else is_blender_text = 1;       /* fn is already a Blender Text */
745         }
746
747         else {
748                 text = add_text(fn);
749
750                 if (text == NULL) {
751                         printf("\nError in BPY_run_python_script:\n"
752                                 "couldn't create Blender text from %s\n", fn);
753                 /* Chris: On Windows if I continue I just get a segmentation
754                  * violation.  To get a baseline file I exit here. */
755                 exit(2);
756                 /* return; */
757                 }
758         }
759
760         if (BPY_txt_do_python_Text(text) != 1) {
761                 printf("\nError executing Python script from command-line:\n"
762                         "%s (at line %d).\n", fn, BPY_Err_getLinenumber());
763         }
764
765         if (!is_blender_text) {
766                 /* We can't simply free the text, since the script might have called
767                  * Blender.Load() to load a new .blend, freeing previous data.
768                  * So we check if the pointer is still valid. */
769                 Text *txtptr = G.main->text.first;
770                 while (txtptr) {
771                         if (txtptr == text) {
772                                 free_libblock(&G.main->text, text);
773                                 break;
774                         }
775                         txtptr = txtptr->id.next;
776                 }
777         }
778 }
779
780 int BPY_run_script(Script *script)
781 {
782         PyObject *py_dict, *py_res, *pyarg;
783         Text *text = NULL;
784         BPy_constant *info;
785         int len;
786         
787         FILE *fp = NULL;
788         
789         PyGILState_STATE gilstate = PyGILState_Ensure();
790         
791         if (!BLI_exists(script->scriptname)) {
792                 /* The file dosnt exist, maybe this blend file was made on some other persons computer? */
793                 char fname[FILE_MAX];
794                 char fpath[FILE_MAX];
795                 char ftmp[FILE_MAX];
796                 char *bpyhome = bpy_gethome(1);
797                 
798                 if (bpyhome) {
799                         BLI_strncpy(ftmp, script->scriptname, sizeof(ftmp));
800                         BLI_split_dirfile_basic(ftmp, NULL, fname); /* get the filename only - fname */
801                         BLI_strncpy(fpath, bpy_gethome(1), sizeof(fpath));
802                         BLI_add_slash(fpath);
803                         strcat(fpath, fname);
804                 
805                         if (BLI_exists(fpath)) {
806                                 strncpy(script->scriptname, fpath, sizeof(script->scriptname));
807                         } else {
808                                 bpyhome = NULL; /* a bit dodgy, this is so the line below runs */
809                         }
810                 }
811                 
812                 if (bpyhome == NULL && U.pythondir[0]) {
813                         BLI_make_file_string("/", fpath, U.pythondir, fname);
814                         if (BLI_exists(fpath)) {
815                                 strncpy(script->scriptname, fpath, sizeof(script->scriptname));
816                         }
817                 }
818                 
819                 /* cant find the file?, fallback to text block */
820                 if (!BLI_exists(script->scriptname)) {
821                         for (text=G.main->text.first; text; text=text->id.next) {
822                                 if (strcmp(script->scriptname, text->id.name+2)==0) {
823                                         break;
824                                 }
825                         }
826                 }
827         }
828         if (text) {
829                 Py_INCREF( Py_None );
830                 pyarg = Py_None;
831         } else {
832                 if (BLI_exists(script->scriptname)) {
833                         fp = fopen( script->scriptname, "rb" );
834                 }
835                 
836                 if( !fp ) {
837                         printf( "Error loading script: couldn't open file %s\n", script->scriptname );
838                         free_libblock( &G.main->script, script );
839                         PyGILState_Release(gilstate);
840                         return 0;
841                 }
842                 
843                 if( script->scriptarg[0] == '\0' ) { /* no submenus */
844                         Py_INCREF( Py_None );
845                         pyarg = Py_None;
846                 } else {
847                         pyarg = PyString_FromString( script->scriptarg );
848                 }
849         }
850         
851         script->id.us = 1;
852         script->flags = SCRIPT_RUNNING;
853         script->py_draw = NULL;
854         script->py_event = NULL;
855         script->py_button = NULL;
856         script->py_browsercallback = NULL;
857         
858         py_dict = CreateGlobalDictionary(  );
859
860         script->py_globaldict = py_dict;
861
862         if( !setup_armature_weakrefs()){
863                 printf("Oops - weakref dict\n");
864                 free_libblock( &G.main->script, script );
865                 ReleaseGlobalDictionary( py_dict );
866                 PyGILState_Release(gilstate);
867                 return 0;
868         }
869         
870         info = ( BPy_constant * ) PyConstant_New(  );
871         if( info ) {
872                 PyConstant_Insert( info, "name",
873                                  PyString_FromString( script->id.name + 2 ) );
874                 PyConstant_Insert( info, "arg", pyarg );
875                 EXPP_dict_set_item_str( py_dict, "__script__",
876                                       ( PyObject * ) info );
877         }
878         
879         if (text) {
880                 py_res = RunPython( text, py_dict );
881         } else {
882                 /* Previously we used PyRun_File to run directly the code on a FILE 
883                 * object, but as written in the Python/C API Ref Manual, chapter 2,
884                 * 'FILE structs for different C libraries can be different and 
885                 * incompatible'.
886                 * So now we load the script file data to a buffer */
887                 char *buffer=NULL, *buffer_ofs=NULL, *b_to, *b_from;
888                 
889                 fseek( fp, 0L, SEEK_END );
890                 len = ftell( fp );
891                 fseek( fp, 0L, SEEK_SET );
892         
893                 buffer = buffer_ofs = MEM_mallocN( len + 2, "pyfilebuf" );      /* len+2 to add '\n\0' */
894                 len = fread( buffer, 1, len, fp );
895         
896                 buffer[len] = '\n';     /* fix syntax error in files w/o eol */
897                 buffer[len + 1] = '\0';
898                 
899                 
900                 /* fast clean-up of dos cr/lf line endings, remove convert '\r\n's to '\n' */
901                 if (*buffer_ofs == '\r' && *(buffer_ofs+1) == '\n') {
902                         buffer_ofs++;
903                 }
904                 b_from = b_to = buffer_ofs;
905                 
906                 while(*b_from != '\0') {
907                         if (*b_from == '\r' && *( b_from+1 ) == '\n') {
908                                 b_from++;
909                         }
910                         if (b_from != b_to) {
911                                 *b_to = *b_from;
912                         }
913                         b_to++;
914                         b_from++;
915                 }
916                 *b_to = '\0';
917                 /* done cleaning the string */
918                 
919                 fclose( fp );
920                 
921                 py_res = PyRun_String( buffer_ofs, Py_file_input, py_dict, py_dict );
922                 MEM_freeN( buffer );
923         }
924
925         if( !py_res ) {         /* Failed execution of the script */
926
927                 BPY_Err_Handle( script->id.name + 2 );
928                 ReleaseGlobalDictionary( py_dict );
929                 script->py_globaldict = NULL;
930                 free_libblock( &G.main->script, script );
931                 error_pyscript(  );
932
933                 PyGILState_Release(gilstate);
934                 return 0;
935         } else {
936                 Py_DECREF( py_res );
937                 script->flags &= ~SCRIPT_RUNNING;
938
939                 if( !script->flags ) {
940                         ReleaseGlobalDictionary( py_dict );
941                         script->py_globaldict = NULL;
942                         free_libblock( &G.main->script, script );
943
944                         /* special case: called from the menu in the Scripts window
945                          * we have to change sc->script pointer, since it'll be freed here.*/
946                         if (!G.background) {
947                                 if( curarea->spacetype == SPACE_SCRIPT ) {
948                                         SpaceScript *sc = curarea->spacedata.first;
949                                         sc->script = G.main->script.first;      /* can be null, which is ok ... */
950                                         /* ... meaning no other script is running right now. */
951                                 }
952                         }
953
954                 }
955         }
956         
957         PyGILState_Release(gilstate);
958         return 1;
959 }
960         
961 /****************************************************************************
962 * Description: This function executes the script chosen from a menu.
963 * Notes:        It is called by the ui code in src/header_???.c when a user  
964 *               clicks on a menu entry that refers to a script.
965 *               Scripts are searched in the BPyMenuTable, using the given
966 *               menutype and event values to know which one was chosen. 
967 *****************************************************************************/
968 int BPY_menu_do_python( short menutype, int event )
969 {
970         char *argstr = NULL;
971         BPyMenu *pym;
972         BPySubMenu *pysm;
973         char scriptname[21];
974         Script *script = NULL;
975         int ret, len;
976         PyGILState_STATE gilstate;
977         char filestr[FILE_MAX];
978
979         pym = BPyMenu_GetEntry( menutype, ( short ) event );
980
981         if( !pym )
982                 return 0;
983
984         gilstate = PyGILState_Ensure();
985
986         if( pym->version > G.version )
987                 notice( "Version mismatch: script was written for Blender %d. "
988                         "It may fail with yours: %d.", pym->version,
989                         G.version );
990
991 /* if there are submenus, let the user choose one from a pupmenu that we
992  * create here.*/
993         pysm = pym->submenus;
994         if( pysm ) {
995                 char *pupstr;
996                 int arg;
997
998                 pupstr = BPyMenu_CreatePupmenuStr( pym, menutype );
999
1000                 if( pupstr ) {
1001                         arg = pupmenu( pupstr );
1002                         MEM_freeN( pupstr );
1003
1004                         if( arg >= 0 ) {
1005                                 while( arg-- )
1006                                         pysm = pysm->next;
1007                                 argstr = pysm->arg;
1008                         } else {
1009                                 PyGILState_Release(gilstate);
1010                                 return 0;
1011                         }
1012                 }
1013         }
1014
1015         if( pym->dir ) { /* script is in U.pythondir */
1016                 char upythondir[FILE_MAX];
1017
1018                 /* dirs in Blender can be "//", which has a special meaning */
1019                 BLI_strncpy(upythondir, U.pythondir, FILE_MAX);
1020                 BLI_convertstringcode(upythondir, G.sce); /* if so, this expands it */
1021                 BLI_make_file_string( "/", filestr, upythondir, pym->filename );
1022         }
1023         else { /* script is in default scripts dir */
1024                 char *scriptsdir = bpy_gethome(1);
1025
1026                 if (!scriptsdir) {
1027                         printf("Error loading script: can't find default scripts dir!");
1028                         PyGILState_Release(gilstate);
1029                         return 0;
1030                 }
1031
1032                 BLI_make_file_string( "/", filestr, scriptsdir, pym->filename );
1033         }
1034
1035         BLI_strncpy(scriptname, pym->name, 21);
1036         len = strlen(scriptname) - 1;
1037         /* by convention, scripts that open the file browser or have submenus
1038          * display '...'.  Here we remove them from the datablock name */
1039         while ((len > 0) && scriptname[len] == '.') {
1040                 scriptname[len] = '\0';
1041                 len--;
1042         }
1043         
1044         /* Create a new script structure and initialize it: */
1045         script = alloc_libblock( &G.main->script, ID_SCRIPT, scriptname );
1046
1047         if( !script ) {
1048                 printf( "couldn't allocate memory for Script struct!" );
1049                 PyGILState_Release(gilstate);
1050                 return 0;
1051         }
1052
1053         /* let's find a proper area for an eventual script gui:
1054          * (still experimenting here, need definition on which win
1055          * each group will be put to code this properly) */
1056         switch ( menutype ) {
1057
1058         case PYMENU_IMPORT:     /* first 4 were handled in header_info.c */
1059         case PYMENU_EXPORT:
1060         case PYMENU_HELP:
1061         case PYMENU_RENDER:
1062         case PYMENU_WIZARDS:
1063         case PYMENU_SCRIPTTEMPLATE:
1064         case PYMENU_MESHFACEKEY:
1065                 break;
1066
1067         default:
1068                 if( curarea->spacetype != SPACE_SCRIPT ) {
1069                         ScrArea *sa = NULL;
1070
1071                         sa = find_biggest_area_of_type( SPACE_BUTS );
1072                         if( sa ) {
1073                                 if( ( 1.5 * sa->winx ) < sa->winy )
1074                                         sa = NULL;      /* too narrow? */
1075                         }
1076
1077                         if( !sa )
1078                                 sa = find_biggest_area_of_type( SPACE_SCRIPT );
1079                         if( !sa )
1080                                 sa = find_biggest_area_of_type( SPACE_TEXT );
1081                         if( !sa )
1082                                 sa = find_biggest_area_of_type( SPACE_IMAGE );  /* group UV */
1083                         if( !sa )
1084                                 sa = find_biggest_area_of_type( SPACE_VIEW3D );
1085
1086                         if( !sa )
1087                                 sa = find_biggest_area(  );
1088
1089                         areawinset( sa->win );
1090                 }
1091                 break;
1092         }
1093         
1094         strncpy(script->scriptname, filestr, sizeof(script->scriptname));
1095         if (argstr!=NULL && argstr[0] != '\0')
1096                 strncpy(script->scriptarg, argstr, sizeof(script->scriptarg));
1097         
1098         ret = BPY_run_script(script);
1099
1100         return 1;               /* normal return */
1101 }
1102
1103 /*****************************************************************************
1104 * Description:  
1105 * Notes:
1106 *****************************************************************************/
1107 void BPY_free_compiled_text( struct Text *text )
1108 {
1109         if( !text->compiled )
1110                 return;
1111         Py_DECREF( ( PyObject * ) text->compiled );
1112         text->compiled = NULL;
1113
1114         return;
1115 }
1116
1117 /*****************************************************************************
1118 * Description: This function frees a finished (flags == 0) script.
1119 *****************************************************************************/
1120 void BPY_free_finished_script( Script * script )
1121 {
1122         PyGILState_STATE gilstate;
1123
1124         if( !script )
1125                 return;
1126
1127         gilstate = PyGILState_Ensure();
1128
1129         if( PyErr_Occurred(  ) ) {      /* if script ended after filesel */
1130                 PyErr_Print(  );        /* eventual errors are handled now */
1131                 error_pyscript(  );
1132         }
1133
1134         PyGILState_Release(gilstate);
1135
1136         free_libblock( &G.main->script, script );
1137         return;
1138 }
1139
1140 static void unlink_script( Script * script )
1141 {       /* copied from unlink_text in drawtext.c */
1142         bScreen *scr;
1143         ScrArea *area;
1144         SpaceLink *sl;
1145
1146         for( scr = G.main->screen.first; scr; scr = scr->id.next ) {
1147                 for( area = scr->areabase.first; area; area = area->next ) {
1148                         for( sl = area->spacedata.first; sl; sl = sl->next ) {
1149                                 if( sl->spacetype == SPACE_SCRIPT ) {
1150                                         SpaceScript *sc = ( SpaceScript * ) sl;
1151
1152                                         if( sc->script == script ) {                                    
1153                                                 sc->script = NULL;
1154
1155                                                 if( sc == area->spacedata.first ) {
1156                                                         scrarea_queue_redraw( area );
1157                                                 }
1158                                                 
1159                                                 if (sc->but_refs) {
1160                                                         BPy_Set_DrawButtonsList(sc->but_refs);
1161                                                         BPy_Free_DrawButtonsList();
1162                                                         sc->but_refs = NULL;
1163                                                 }
1164                                         }
1165                                 }
1166                         }
1167                 }
1168         }
1169 }
1170
1171 /* This is called from free_libblock( &G.main->script, script ); */
1172 void BPY_clear_script( Script * script )
1173 {
1174         PyObject *dict;
1175         PyGILState_STATE gilstate;
1176
1177         if( !script )
1178                 return;
1179
1180         gilstate = PyGILState_Ensure();
1181
1182         if (!Py_IsInitialized()) {
1183                 printf("\nError: trying to free script data after finalizing Python!");
1184                 printf("\nScript name: %s\n", script->id.name+2);
1185                 PyGILState_Release(gilstate);
1186                 return;
1187         }
1188
1189         Py_XDECREF( ( PyObject * ) script->py_draw );
1190         Py_XDECREF( ( PyObject * ) script->py_event );
1191         Py_XDECREF( ( PyObject * ) script->py_button );
1192         Py_XDECREF( ( PyObject * ) script->py_browsercallback );
1193         script->py_draw = NULL;
1194         script->py_event = NULL;
1195         script->py_button = NULL;
1196         script->py_browsercallback = NULL;
1197         script->scriptname[0] = '\0';
1198         script->scriptarg[0] = '\0';
1199         
1200         dict = script->py_globaldict;
1201
1202         if( dict ) {
1203                 PyDict_Clear( dict );
1204                 Py_DECREF( dict );      /* Release dictionary. */
1205                 script->py_globaldict = NULL;
1206         }
1207
1208         PyGILState_Release(gilstate);
1209
1210         unlink_script( script );
1211 }
1212
1213 /* PyDrivers */
1214
1215 /* PyDrivers are Ipo Drivers governed by expressions written in Python.
1216  * Expressions here are one-liners that evaluate to a float value. */
1217
1218 /* For faster execution we keep a special dictionary for pydrivers, with
1219  * the needed modules and aliases. */
1220 static int bpy_pydriver_create_dict(void)
1221 {
1222         PyObject *d, *mod;
1223
1224         if (bpy_pydriver_Dict) return -1;
1225
1226         d = PyDict_New();
1227         if (!d) return -1;
1228
1229         bpy_pydriver_Dict = d;
1230
1231         /* import some modules: builtins, Blender, math, Blender.noise */
1232
1233         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
1234
1235         mod = PyImport_ImportModule("Blender");
1236         if (mod) {
1237                 PyDict_SetItemString(d, "Blender", mod);
1238                 PyDict_SetItemString(d, "b", mod);
1239                 Py_DECREF(mod);
1240         }
1241
1242         mod = PyImport_ImportModule("math");
1243         if (mod) {
1244                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
1245                 
1246                 /* Only keep for backwards compat! - just import all math into root, they are standard */
1247                 PyDict_SetItemString(d, "math", mod);
1248                 PyDict_SetItemString(d, "m", mod);
1249                 Py_DECREF(mod);
1250         } 
1251
1252         mod = PyImport_ImportModule("Blender.Noise");
1253         if (mod) {
1254                 PyDict_SetItemString(d, "noise", mod);
1255                 PyDict_SetItemString(d, "n", mod);
1256                 Py_DECREF(mod);
1257         }
1258
1259         /* If there's a Blender text called pydrivers.py, import it.
1260          * Users can add their own functions to this module. */
1261         if (G.f&G_DOSCRIPTLINKS) {
1262                 mod = importText("pydrivers"); /* can also use PyImport_Import() */
1263                 if (mod) {
1264                         PyDict_SetItemString(d, "pydrivers", mod);
1265                         PyDict_SetItemString(d, "p", mod);
1266                         Py_DECREF(mod);
1267                 } else {
1268                         PyErr_Clear();
1269                 }
1270         }
1271         /* short aliases for some Get() functions: */
1272
1273         /* ob(obname) == Blender.Object.Get(obname) */
1274         mod = PyImport_ImportModule("Blender.Object");
1275         if (mod) {
1276                 PyObject *fcn = PyObject_GetAttrString(mod, "Get");
1277                 Py_DECREF(mod);
1278                 if (fcn) {
1279                         PyDict_SetItemString(d, "ob", fcn);
1280                         Py_DECREF(fcn);
1281                 }
1282         }
1283         
1284         /* TODO - change these */
1285         /* me(meshname) == Blender.Mesh.Get(meshname) */
1286         mod = PyImport_ImportModule("Blender.Mesh");
1287         if (mod) {
1288                 PyObject *fcn = PyObject_GetAttrString(mod, "Get");
1289                 Py_DECREF(mod);
1290                 if (fcn) {
1291                         PyDict_SetItemString(d, "me", fcn);
1292                         Py_DECREF(fcn);
1293                 }
1294         }
1295
1296         /* ma(matname) == Blender.Material.Get(matname) */
1297         mod = PyImport_ImportModule("Blender.Material");
1298         if (mod) {
1299                 PyObject *fcn = PyObject_GetAttrString(mod, "Get");
1300                 Py_DECREF(mod);
1301                 if (fcn) {
1302                         PyDict_SetItemString(d, "ma", fcn);
1303                         Py_DECREF(fcn);
1304                 }
1305         }
1306
1307         return 0;
1308 }
1309
1310 /* error return function for BPY_eval_pydriver */
1311 static float pydriver_error(IpoDriver *driver) {
1312
1313         if (bpy_pydriver_oblist)
1314                 bpy_pydriver_freeList();
1315
1316         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
1317                 PyDict_Clear(bpy_pydriver_Dict);
1318                 Py_DECREF(bpy_pydriver_Dict);
1319                 bpy_pydriver_Dict = NULL;
1320         }
1321
1322         driver->flag |= IPO_DRIVER_FLAG_INVALID; /* py expression failed */
1323         
1324         if (driver->ob)
1325                 fprintf(stderr, "\nError in Ipo Driver: Object %s\nThis is the failed Python expression:\n'%s'\n\n", driver->ob->id.name+2, driver->name);
1326         else
1327                 fprintf(stderr, "\nError in Ipo Driver: No Object\nThis is the failed Python expression:\n'%s'\n\n", driver->name);
1328         
1329         PyErr_Print();
1330
1331         return 0.0f;
1332 }
1333
1334
1335 /********PyConstraints*********/
1336
1337 /* This function checks whether a text-buffer is a PyConstraint candidate.
1338  * It uses simple text parsing that could be easily confused!
1339  */
1340 int BPY_is_pyconstraint(Text *text)
1341 {
1342         TextLine *tline = text->lines.first;
1343
1344         if (tline && (tline->len > 10)) {
1345                 char *line = tline->line;
1346                 
1347                 /* Expected format: #BPYCONSTRAINT
1348                  * The actual checks are forgiving, so slight variations also work. */
1349                 if (line && line[0] == '#' && strstr(line, "BPYCONSTRAINT")) return 1;
1350         }
1351         return 0;
1352 }
1353
1354 /* This function frees links from pyconstraints to a given text-buffer.
1355  * Used when a text-buffer is unlinked!
1356  */
1357 void BPY_free_pyconstraint_links(Text *text)
1358 {
1359         Object *ob;
1360         bConstraint *con;
1361         short update;
1362         
1363         /*check all pyconstraints*/
1364         for (ob=G.main->object.first; ob; ob=ob->id.next) {
1365                 update = 0;
1366                 if(ob->type==OB_ARMATURE && ob->pose) {
1367                         bPoseChannel *pchan;
1368                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1369                                 for (con = pchan->constraints.first; con; con=con->next) {
1370                                         if (con->type==CONSTRAINT_TYPE_PYTHON) {
1371                                                 bPythonConstraint *data = con->data;
1372                                                 if (data->text==text) data->text = NULL;
1373                                                 update = 1;
1374                                                 
1375                                         }
1376                                 }
1377                         }
1378                 }
1379                 for (con = ob->constraints.first; con; con=con->next) {
1380                         if (con->type==CONSTRAINT_TYPE_PYTHON) {
1381                                 bPythonConstraint *data = con->data;
1382                                 if (data->text==text) data->text = NULL;
1383                                 update = 1;
1384                         }
1385                 }
1386                 
1387                 if (update) {
1388                         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
1389                 }
1390         }
1391 }
1392
1393 /* This function is called to update PyConstraint data so that it is compatible with the script. 
1394  * Some of the allocating/freeing of memory for constraint targets occurs here, espcially
1395  * if the number of targets changes.
1396  */
1397 void BPY_pyconstraint_update(Object *owner, bConstraint *con)
1398 {
1399         bPythonConstraint *data= con->data;
1400         
1401         if (data->text) {       
1402                 /* script does exist. it is assumed that this is a valid pyconstraint script */
1403                 PyObject *globals;
1404                 PyObject *retval, *gval;
1405                 PyGILState_STATE gilstate;
1406                 int num, i;
1407                 
1408                 /* clear the relevant flags first */
1409                 data->flag = 0;
1410
1411                 gilstate = PyGILState_Ensure();
1412
1413                 /* populate globals dictionary */
1414                 globals = CreateGlobalDictionary();
1415                 retval = RunPython(data->text, globals);
1416                 
1417                 if (retval == NULL) {
1418                         BPY_Err_Handle(data->text->id.name);
1419                         ReleaseGlobalDictionary(globals);
1420                         data->flag |= PYCON_SCRIPTERROR;
1421                         PyGILState_Release(gilstate);
1422                         return;
1423                 }
1424                 
1425                 Py_XDECREF(retval);
1426                 retval = NULL;
1427                 
1428                 /* try to find NUM_TARGETS */
1429                 gval = PyDict_GetItemString(globals, "NUM_TARGETS");
1430                 if ( (gval) && (num= PyInt_AsLong(gval)) ) {
1431                         /* NUM_TARGETS is defined... and non-zero */
1432                         bConstraintTarget *ct;
1433                         
1434                         /* check if it is valid (just make sure it is not negative)
1435                          *      TODO: PyInt_AsLong may return -1 as sign of invalid input... 
1436                          */
1437                         num = abs(num);
1438                         data->flag |= PYCON_USETARGETS;
1439                         
1440                         /* check if the number of targets has changed */
1441                         if (num < data->tarnum) {
1442                                 /* free a few targets */
1443                                 num= data->tarnum - num;
1444                                 for (i = 0; i < num; i++, data->tarnum--) {
1445                                         ct= data->targets.last;
1446                                         BLI_freelinkN(&data->targets, ct);
1447                                 }
1448                         }
1449                         else if (num > data->tarnum) {
1450                                 /* add a few targets */
1451                                 num = num - data->tarnum;
1452                                 for (i = 0; i < num; i++, data->tarnum++) {
1453                                         ct= MEM_callocN(sizeof(bConstraintTarget), "PyConTarget");
1454                                         BLI_addtail(&data->targets, ct);
1455                                 }
1456                         }
1457                         
1458                         /* validate targets */
1459                         con->flag &= ~CONSTRAINT_DISABLE;
1460                         for (ct= data->targets.first; ct; ct= ct->next) {
1461                                 if (!exist_object(ct->tar)) {
1462                                         ct->tar = NULL;
1463                                         con->flag |= CONSTRAINT_DISABLE;
1464                                         break;
1465                                 }
1466                                 
1467                                 if ((ct->tar == owner) && (ct->subtarget[0] != 0)) {
1468                                         if (get_named_bone(get_armature(owner), ct->subtarget) == NULL) {
1469                                                 con->flag |= CONSTRAINT_DISABLE;
1470                                                 break;
1471                                         }
1472                                 }
1473                         }
1474                         
1475                         /* clear globals */
1476                         ReleaseGlobalDictionary(globals);
1477
1478                         PyGILState_Release(gilstate);
1479
1480                         return;
1481                 }
1482                 else {
1483                         /* NUM_TARGETS is not defined or equals 0 */
1484                         ReleaseGlobalDictionary(globals);
1485                         
1486                         /* free all targets */
1487                         BLI_freelistN(&data->targets);
1488                         data->tarnum = 0;
1489                         data->flag &= ~PYCON_USETARGETS;
1490                         
1491                         PyGILState_Release(gilstate);
1492
1493                         return;
1494                 }
1495         }
1496         else {
1497                 /* no script, so clear any settings/data now */
1498                 data->tarnum = 0;
1499                 data->flag = 0;
1500                 con->flag &= ~CONSTRAINT_DISABLE;
1501                 
1502                 BLI_freelistN(&data->targets);
1503                 
1504                 /* supposedly this should still leave the base struct... */
1505                 IDP_FreeProperty(data->prop);
1506         }
1507 }
1508
1509 /* PyConstraints Evaluation Function (only called from evaluate_constraint)
1510  * This function is responsible for modifying the ownermat that it is passed. 
1511  */
1512 void BPY_pyconstraint_eval(bPythonConstraint *con, bConstraintOb *cob, ListBase *targets)
1513 {
1514         PyObject *srcmat, *tarmat, *tarmats, *idprop;
1515         PyObject *globals;
1516         PyObject *gval;
1517         PyObject *pyargs, *retval;
1518         bConstraintTarget *ct;
1519         MatrixObject *retmat;
1520         int row, col, index;
1521         PyGILState_STATE gilstate;
1522
1523         if (!con->text) return;
1524         if (con->flag & PYCON_SCRIPTERROR) return;
1525
1526         gilstate = PyGILState_Ensure();
1527
1528         globals = CreateGlobalDictionary();
1529         
1530         /* wrap blender-data as PyObjects for evaluation 
1531          *      - we expose the owner's matrix as pymatrix
1532          *      - id-properties are wrapped using the id-properties pyapi
1533          *      - targets are presented as a list of matrices
1534          */
1535         srcmat = newMatrixObject((float *)cob->matrix, 4, 4, Py_NEW);
1536         idprop = BPy_Wrap_IDProperty(NULL, con->prop, NULL);
1537         
1538         tarmats= PyList_New(con->tarnum); 
1539         for (ct=targets->first, index=0; ct; ct=ct->next, index++) {
1540                 tarmat = newMatrixObject((float *)ct->matrix, 4, 4, Py_NEW);
1541                 PyList_SET_ITEM(tarmats, index, tarmat);
1542         }
1543         
1544         if (!setup_armature_weakrefs()) {
1545                 fprintf(stderr, "Oops - weakref dict setup\n");
1546                 PyGILState_Release(gilstate);
1547
1548                 return;
1549         }
1550         
1551         retval = RunPython(con->text, globals);
1552         
1553         if (retval == NULL) {
1554                 BPY_Err_Handle(con->text->id.name);
1555                 con->flag |= PYCON_SCRIPTERROR;
1556                 
1557                 /* free temp objects */
1558                 Py_XDECREF(idprop);
1559                 Py_XDECREF(srcmat);
1560                 Py_XDECREF(tarmats);
1561                 
1562                 ReleaseGlobalDictionary(globals);
1563
1564                 PyGILState_Release(gilstate);
1565
1566                 return;
1567         }
1568
1569         if (retval) {Py_XDECREF( retval );}
1570         retval = NULL;
1571         
1572         gval = PyDict_GetItemString(globals, "doConstraint");
1573         if (!gval) {
1574                 printf("ERROR: no doConstraint function in constraint!\n");
1575                 
1576                 /* free temp objects */
1577                 Py_XDECREF(idprop);
1578                 Py_XDECREF(srcmat);
1579                 Py_XDECREF(tarmats);
1580                 
1581                 ReleaseGlobalDictionary(globals);
1582
1583                 PyGILState_Release(gilstate);
1584
1585                 return;
1586         }
1587         
1588         /* Now for the fun part! Try and find the functions we need. */
1589         if (PyFunction_Check(gval)) {
1590                 pyargs = Py_BuildValue("OOO", srcmat, tarmats, idprop);
1591                 retval = PyObject_CallObject(gval, pyargs);
1592                 Py_XDECREF(pyargs);
1593         } 
1594         else {
1595                 printf("ERROR: doConstraint is supposed to be a function!\n");
1596                 con->flag |= PYCON_SCRIPTERROR;
1597                 
1598                 Py_XDECREF(idprop);
1599                 Py_XDECREF(srcmat);
1600                 Py_XDECREF(tarmats);
1601                 
1602                 ReleaseGlobalDictionary(globals);
1603
1604                 PyGILState_Release(gilstate);
1605
1606                 return;
1607         }
1608         
1609         if (!retval) {
1610                 BPY_Err_Handle(con->text->id.name);
1611                 con->flag |= PYCON_SCRIPTERROR;
1612                 
1613                 /* free temp objects */
1614                 Py_XDECREF(idprop);
1615                 Py_XDECREF(srcmat);
1616                 Py_XDECREF(tarmats);
1617                 
1618                 ReleaseGlobalDictionary(globals);
1619
1620                 PyGILState_Release(gilstate);
1621
1622                 return;
1623         }
1624         
1625         
1626         if (!PyObject_TypeCheck(retval, &matrix_Type)) {
1627                 printf("Error in PyConstraint - doConstraint: Function not returning a matrix!\n");
1628                 con->flag |= PYCON_SCRIPTERROR;
1629                 
1630                 Py_XDECREF(idprop);
1631                 Py_XDECREF(srcmat);
1632                 Py_XDECREF(tarmats);
1633                 Py_XDECREF(retval);
1634                 
1635                 ReleaseGlobalDictionary(globals);
1636
1637                 PyGILState_Release(gilstate);
1638
1639                 return;
1640         }
1641         
1642         retmat = (MatrixObject *)retval;
1643         if (retmat->rowSize != 4 || retmat->colSize != 4) {
1644                 printf("Error in PyConstraint - doConstraint: Matrix returned is the wrong size!\n");
1645                 con->flag |= PYCON_SCRIPTERROR;
1646                 
1647                 Py_XDECREF(idprop);
1648                 Py_XDECREF(srcmat);
1649                 Py_XDECREF(tarmats);
1650                 Py_XDECREF(retval);
1651                 
1652                 ReleaseGlobalDictionary(globals);
1653
1654                 PyGILState_Release(gilstate);
1655
1656                 return;
1657         }       
1658
1659         /* this is the reverse of code taken from newMatrix() */
1660         for(row = 0; row < 4; row++) {
1661                 for(col = 0; col < 4; col++) {
1662                         cob->matrix[row][col] = retmat->contigPtr[row*4+col];
1663                 }
1664         }
1665         
1666         /* free temp objects */
1667         Py_XDECREF(idprop);
1668         Py_XDECREF(srcmat);
1669         Py_XDECREF(tarmats);
1670         Py_XDECREF(retval);
1671         
1672         /* clear globals */
1673         ReleaseGlobalDictionary(globals);
1674
1675         PyGILState_Release(gilstate);
1676 }
1677
1678 /* This evaluates the target matrix for each target the PyConstraint uses.
1679  * NOTE: it only does one target at a time!
1680  */
1681 void BPY_pyconstraint_target(bPythonConstraint *con, bConstraintTarget *ct)
1682 {
1683         PyObject *tar, *subtar;
1684         PyObject *tarmat, *idprop;
1685         PyObject *globals;
1686         PyObject *gval;
1687         PyObject *pyargs, *retval;
1688         MatrixObject *retmat;
1689         int row, col;
1690         PyGILState_STATE gilstate;
1691
1692         if (!con->text) return;
1693         if (con->flag & PYCON_SCRIPTERROR) return;
1694         if (!ct) return;
1695         
1696         gilstate = PyGILState_Ensure();
1697
1698         globals = CreateGlobalDictionary();
1699         
1700         tar = Object_CreatePyObject(ct->tar);
1701         if ((ct->tar) && (ct->tar->type==OB_ARMATURE)) {
1702                 bPoseChannel *pchan;
1703                 pchan = get_pose_channel(ct->tar->pose, ct->subtarget);
1704                 subtar = PyPoseBone_FromPosechannel(pchan);
1705         }
1706         else
1707                 subtar = PyString_FromString(ct->subtarget);
1708         
1709         tarmat = newMatrixObject((float *)ct->matrix, 4, 4, Py_NEW);
1710         idprop = BPy_Wrap_IDProperty( NULL, con->prop, NULL);
1711         
1712         if (!setup_armature_weakrefs()) {
1713                 fprintf(stderr, "Oops - weakref dict setup\n");
1714                 PyGILState_Release(gilstate);
1715                 return;
1716         }
1717         
1718         retval = RunPython(con->text, globals);
1719
1720         if (retval == NULL) {
1721                 BPY_Err_Handle(con->text->id.name);
1722                 con->flag |= PYCON_SCRIPTERROR;
1723                 
1724                 /* free temp objects */
1725                 Py_XDECREF(tar);
1726                 Py_XDECREF(subtar);
1727                 Py_XDECREF(idprop);
1728                 Py_XDECREF(tarmat);
1729                 
1730                 ReleaseGlobalDictionary(globals);
1731
1732                 PyGILState_Release(gilstate);
1733
1734                 return;
1735         }
1736
1737         Py_XDECREF(retval);
1738         retval = NULL;
1739         
1740         /* try to find doTarget function to set the target matrix */
1741         gval = PyDict_GetItemString(globals, "doTarget");
1742         if (!gval) {
1743                 /* free temp objects */
1744                 Py_XDECREF(tar);
1745                 Py_XDECREF(subtar);
1746                 Py_XDECREF(idprop);
1747                 Py_XDECREF(tarmat);
1748                 
1749                 ReleaseGlobalDictionary(globals);
1750
1751                 PyGILState_Release(gilstate);
1752
1753                 return;
1754         }
1755         
1756         /* Now for the fun part! Try and find the functions we need.*/
1757         if (PyFunction_Check(gval)) {
1758                 pyargs = Py_BuildValue("OOOO", tar, subtar, tarmat, idprop);
1759                 retval = PyObject_CallObject(gval, pyargs);
1760                 Py_XDECREF(pyargs);
1761         } 
1762         else {
1763                 printf("ERROR: doTarget is supposed to be a function!\n");
1764                 con->flag |= PYCON_SCRIPTERROR;
1765                 
1766                 Py_XDECREF(tar);
1767                 Py_XDECREF(subtar);
1768                 Py_XDECREF(idprop);
1769                 Py_XDECREF(tarmat);
1770                 
1771                 ReleaseGlobalDictionary(globals);
1772
1773                 PyGILState_Release(gilstate);
1774
1775                 return;
1776         }
1777         
1778         if (!retval) {
1779                 BPY_Err_Handle(con->text->id.name);
1780                 con->flag |= PYCON_SCRIPTERROR;
1781                 
1782                 
1783                 /* free temp objects */
1784                 Py_XDECREF(tar);
1785                 Py_XDECREF(subtar);
1786                 Py_XDECREF(idprop);
1787                 Py_XDECREF(tarmat);
1788                 
1789                 ReleaseGlobalDictionary(globals);
1790
1791                 PyGILState_Release(gilstate);
1792
1793                 return;
1794         }
1795         
1796         if (!PyObject_TypeCheck(retval, &matrix_Type)) {
1797                 con->flag |= PYCON_SCRIPTERROR;
1798                 
1799                 Py_XDECREF(tar);
1800                 Py_XDECREF(subtar);
1801                 Py_XDECREF(idprop);
1802                 Py_XDECREF(tarmat);
1803                 Py_XDECREF(retval);
1804                 
1805                 ReleaseGlobalDictionary(globals);
1806
1807                 PyGILState_Release(gilstate);
1808
1809                 return;
1810         }
1811         
1812         retmat = (MatrixObject *)retval;
1813         if (retmat->rowSize != 4 || retmat->colSize != 4) {
1814                 printf("Error in PyConstraint - doTarget: Matrix returned is the wrong size!\n");
1815                 con->flag |= PYCON_SCRIPTERROR;
1816                 
1817                 Py_XDECREF(tar);
1818                 Py_XDECREF(subtar);
1819                 Py_XDECREF(idprop);
1820                 Py_XDECREF(tarmat);
1821                 Py_XDECREF(retval);
1822                 
1823                 ReleaseGlobalDictionary(globals);
1824
1825                 PyGILState_Release(gilstate);
1826
1827                 return;
1828         }       
1829
1830         /* this is the reverse of code taken from newMatrix() */
1831         for(row = 0; row < 4; row++) {
1832                 for(col = 0; col < 4; col++) {
1833                         ct->matrix[row][col] = retmat->contigPtr[row*4+col];
1834                 }
1835         }
1836         
1837         /* free temp objects */
1838         Py_XDECREF(tar);
1839         Py_XDECREF(subtar);
1840         Py_XDECREF(idprop);
1841         Py_XDECREF(tarmat);
1842         Py_XDECREF(retval);
1843         
1844         /* clear globals */
1845         ReleaseGlobalDictionary(globals);
1846
1847         PyGILState_Release(gilstate);
1848 }
1849
1850 /* This draws+handles the user-defined interface for editing pyconstraints idprops */
1851 void BPY_pyconstraint_settings(void *arg1, void *arg2)
1852 {
1853         bPythonConstraint *con= (bPythonConstraint *)arg1;
1854         PyObject *idprop;
1855         PyObject *globals;
1856         PyObject *gval;
1857         PyObject *retval;
1858         PyGILState_STATE gilstate;
1859         
1860         if (!con->text) return;
1861         if (con->flag & PYCON_SCRIPTERROR) return;
1862         
1863         gilstate = PyGILState_Ensure();
1864         
1865         globals = CreateGlobalDictionary();
1866         
1867         idprop = BPy_Wrap_IDProperty( NULL, con->prop, NULL);
1868         
1869         retval = RunPython(con->text, globals);
1870
1871         if (retval == NULL) {
1872                 BPY_Err_Handle(con->text->id.name);
1873                 ReleaseGlobalDictionary(globals);
1874                 con->flag |= PYCON_SCRIPTERROR;
1875                 
1876                 /* free temp objects */
1877                 Py_XDECREF(idprop);
1878                 
1879                 PyGILState_Release(gilstate);
1880                 
1881                 return;
1882         }
1883
1884         if (retval) {Py_XDECREF( retval );}
1885         retval = NULL;
1886         
1887         gval = PyDict_GetItemString(globals, "getSettings");
1888         if (!gval) {
1889                 printf("ERROR: no getSettings function in constraint!\n");
1890                 
1891                 /* free temp objects */
1892                 ReleaseGlobalDictionary( globals );
1893                 Py_XDECREF(idprop);
1894
1895                 PyGILState_Release(gilstate);
1896
1897                 return;
1898         }
1899         
1900         /* Now for the fun part! Try and find the functions we need. */
1901         if (PyFunction_Check(gval)) {
1902                 retval = PyObject_CallFunction(gval, "O", idprop);
1903         } 
1904         else {
1905                 printf("ERROR: getSettings is supposed to be a function!\n");
1906                 ReleaseGlobalDictionary( globals );
1907                 
1908                 Py_XDECREF(idprop);
1909                 
1910                 PyGILState_Release(gilstate);
1911                 
1912                 return;
1913         }
1914         
1915         if (!retval) {
1916                 BPY_Err_Handle(con->text->id.name);
1917                 con->flag |= PYCON_SCRIPTERROR;
1918                 
1919                 /* free temp objects */
1920                 ReleaseGlobalDictionary(globals);
1921                 Py_XDECREF(idprop);
1922                 
1923                 PyGILState_Release(gilstate);
1924                 
1925                 return;
1926         }
1927         else {
1928                 /* clear globals */
1929                 ReleaseGlobalDictionary(globals);
1930                 
1931                 /* free temp objects */
1932                 Py_XDECREF(idprop);
1933                 Py_DECREF(retval);
1934                 
1935                 PyGILState_Release(gilstate);
1936                 
1937                 return;
1938         }
1939 }
1940
1941 /* Update function, it gets rid of pydrivers global dictionary, forcing
1942  * BPY_pydriver_eval to recreate it. This function is used to force
1943  * reloading the Blender text module "pydrivers.py", if available, so
1944  * updates in it reach pydriver evaluation. */
1945 void BPY_pydriver_update(void)
1946 {
1947         PyGILState_STATE gilstate = PyGILState_Ensure();
1948
1949         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
1950                 PyDict_Clear(bpy_pydriver_Dict);
1951                 Py_DECREF(bpy_pydriver_Dict);
1952                 bpy_pydriver_Dict = NULL;
1953         }
1954
1955         PyGILState_Release(gilstate);
1956
1957         return;
1958 }
1959
1960 /* for depsgraph.c, runs py expr once to collect all refs. made
1961  * to objects (self refs. to the object that owns the py driver
1962  * are not allowed). */
1963 struct Object **BPY_pydriver_get_objects(IpoDriver *driver)
1964 {
1965         /*if (!driver || !driver->ob || driver->name[0] == '\0')
1966                 return NULL;*/
1967
1968         /*PyErr_Clear();*/
1969
1970         /* clear the flag that marks invalid python expressions */
1971         driver->flag &= ~IPO_DRIVER_FLAG_INVALID;
1972
1973         /* tell we're running a pydriver, so Get() functions know they need
1974          * to add the requested obj to our list */
1975         bpy_pydriver_running(1);
1976
1977         /* append driver owner object as the 1st ob in the list;
1978          * we put it there to make sure it is not itself referenced in
1979          * its pydriver expression */
1980         bpy_pydriver_appendToList(driver->ob);
1981
1982         /* this will append any other ob referenced in expr (driver->name)
1983          * or set the driver's error flag if driver's py expression fails */
1984         BPY_pydriver_eval(driver);
1985
1986         bpy_pydriver_running(0); /* ok, we're done */
1987
1988         return bpy_pydriver_obArrayFromList(); /* NULL if eval failed */
1989 }
1990
1991 /* This evals py driver expressions, 'expr' is a Python expression that
1992  * should evaluate to a float number, which is returned. */
1993 float BPY_pydriver_eval(IpoDriver *driver)
1994 {
1995         char *expr = NULL;
1996         PyObject *retval, *bpy_ob = NULL;
1997         float result = 0.0f; /* default return */
1998         int setitem_retval;
1999         PyGILState_STATE gilstate;
2000
2001         if (!driver ||  (G.f&G_DOSCRIPTLINKS)==0) return result;
2002
2003         expr = driver->name; /* the py expression to be evaluated */
2004         if (!expr || expr[0]=='\0') return result;
2005
2006         gilstate = PyGILState_Ensure();
2007
2008         if (!bpy_pydriver_Dict) {
2009                 if (bpy_pydriver_create_dict() != 0) {
2010                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
2011                         PyGILState_Release(gilstate);
2012                         return result;
2013                 }
2014         }
2015
2016         if (driver->ob)
2017                 bpy_ob = Object_CreatePyObject(driver->ob);
2018
2019         if (!bpy_ob) {
2020                 Py_INCREF(Py_None);
2021                 bpy_ob = Py_None;
2022         }
2023
2024         setitem_retval = EXPP_dict_set_item_str(bpy_pydriver_Dict, "self", bpy_ob);
2025
2026         if( !setup_armature_weakrefs()){
2027                 fprintf( stderr, "Oops - weakref dict setup\n");
2028                 PyGILState_Release(gilstate);
2029                 return result;
2030         }
2031
2032         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict,
2033                 bpy_pydriver_Dict);
2034
2035         if (retval == NULL) {
2036                 result = pydriver_error(driver);
2037                 PyGILState_Release(gilstate);
2038                 return result;
2039         }
2040
2041         result = ( float )PyFloat_AsDouble( retval );
2042         Py_DECREF(retval);
2043         
2044         if (result == -1 && PyErr_Occurred()) {
2045                 result = pydriver_error(driver);
2046                 PyGILState_Release(gilstate);
2047                 return result;
2048         }
2049
2050         /* remove 'self', since this dict is also used by py buttons */
2051         if (setitem_retval == 0) PyDict_DelItemString(bpy_pydriver_Dict, "self");
2052
2053         /* all fine, make sure the "invalid expression" flag is cleared */
2054         driver->flag &= ~IPO_DRIVER_FLAG_INVALID;
2055
2056         PyGILState_Release(gilstate);
2057
2058         return result;
2059 }
2060
2061 /* Button Python Evaluation */
2062
2063 /* Python evaluation for gui buttons:
2064  *      users can write any valid Python expression (that evals to an int or float)
2065  *      inside Blender's gui number buttons and have them evaluated to their
2066  *      actual int or float value.
2067  *
2068  *      The global dict used for pydrivers is also used here, so all imported
2069  *      modules for pydrivers (including the pydrivers.py Blender text) are
2070  *      available for button py eval, too. */
2071
2072 static int bpy_button_eval_error(char *expr) {
2073
2074         if (bpy_pydriver_oblist)
2075                 bpy_pydriver_freeList();
2076
2077         if (bpy_pydriver_Dict) { /* free the persistent global dict */
2078                 /* it's the same dict used by pydrivers */
2079                 PyDict_Clear(bpy_pydriver_Dict);
2080                 Py_DECREF(bpy_pydriver_Dict);
2081                 bpy_pydriver_Dict = NULL;
2082         }
2083
2084         fprintf(stderr, "\nError in button evaluation:\nThis is the failed Python expression:\n'%s'\n\n", expr);
2085
2086         PyErr_Print();
2087
2088         return -1;
2089 }
2090
2091 int BPY_button_eval(char *expr, double *value)
2092 {
2093         PyObject *retval, *floatval;
2094         PyGILState_STATE gilstate;
2095         int ret;
2096
2097         if (!value || !expr || expr[0]=='\0') return -1;
2098
2099         *value = 0.0; /* default value */
2100
2101         gilstate = PyGILState_Ensure();
2102
2103         if (!bpy_pydriver_Dict) {
2104                 if (bpy_pydriver_create_dict() != 0) {
2105                         fprintf(stderr,
2106                                 "Button Python Eval error: couldn't create Python dictionary \n");
2107                         PyGILState_Release(gilstate);
2108                         return -1;
2109                 }
2110         }
2111
2112
2113         if( !setup_armature_weakrefs()){
2114                 fprintf(stderr, "Oops - weakref dict\n");
2115                 PyGILState_Release(gilstate);
2116                 return -1;
2117         }
2118
2119         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict,
2120                 bpy_pydriver_Dict);
2121
2122         if (retval == NULL) {
2123                 ret = bpy_button_eval_error(expr);
2124                 PyGILState_Release(gilstate);
2125                 return ret;
2126         }
2127         else {
2128                 floatval = PyNumber_Float(retval);
2129                 Py_DECREF(retval);
2130         }
2131
2132         if (floatval == NULL) {
2133                 ret = bpy_button_eval_error(expr);
2134                 PyGILState_Release(gilstate);
2135                 return ret;
2136         } else {
2137                 *value = (float)PyFloat_AsDouble(floatval);
2138                 Py_DECREF(floatval);
2139         }
2140
2141         PyGILState_Release(gilstate);
2142
2143         return 0; /* successful exit */
2144 }
2145
2146
2147 /*****************************************************************************/
2148 /* ScriptLinks                                                        */
2149 /*****************************************************************************/
2150
2151 /*****************************************************************************/
2152 /* Description:                                                          */
2153 /* Notes:                               Not implemented yet      */
2154 /*****************************************************************************/
2155 void BPY_clear_bad_scriptlinks( struct Text *byebye )
2156 {
2157 /*
2158         BPY_clear_bad_scriptlist(getObjectList(), byebye);
2159         BPY_clear_bad_scriptlist(getLampList(), byebye);
2160         BPY_clear_bad_scriptlist(getCameraList(), byebye);
2161         BPY_clear_bad_scriptlist(getMaterialList(), byebye);
2162         BPY_clear_bad_scriptlist(getWorldList(),        byebye);
2163         BPY_clear_bad_scriptlink(&scene_getCurrent()->id, byebye);
2164
2165         allqueue(REDRAWBUTSSCRIPT, 0);
2166 */
2167         return;
2168 }
2169
2170 /*****************************************************************************
2171 * Description: Loop through all scripts of a list of object types, and 
2172 *       execute these scripts.  
2173 *       For the scene, only the current active scene the scripts are 
2174 *       executed (if any).
2175 *****************************************************************************/
2176 void BPY_do_all_scripts( short event )
2177 {
2178         DoAllScriptsFromList( &( G.main->object ), event );
2179         DoAllScriptsFromList( &( G.main->lamp ), event );
2180         DoAllScriptsFromList( &( G.main->camera ), event );
2181         DoAllScriptsFromList( &( G.main->mat ), event );
2182         DoAllScriptsFromList( &( G.main->world ), event );
2183
2184         BPY_do_pyscript( &( G.scene->id ), event );
2185
2186         /* Don't allow the Python Interpreter to release the GIL on
2187          * its own, to guarantee PyNodes work properly. For Blender this
2188          * is currently the best default behavior.
2189          * The following code in C is equivalent in Python to:
2190          * "import sys; sys.setcheckinterval(sys.maxint)" */
2191         if (event == SCRIPT_RENDER) {
2192                 _Py_CheckInterval = PyInt_GetMax();
2193         }
2194         else if (event == SCRIPT_POSTRENDER) {
2195                 _Py_CheckInterval = 100; /* Python default */
2196         }
2197
2198         return;
2199 }
2200
2201 /*****************************************************************************
2202 * Description: Execute a Python script when an event occurs. The following  
2203 *               events are possible: frame changed, load script and redraw.  
2204 *               Only events happening to one of the following object types   
2205 *               are handled: Object, Lamp, Camera, Material, World and      
2206 *               Scene.                  
2207 *****************************************************************************/
2208
2209 static ScriptLink *ID_getScriptlink( ID * id )
2210 {
2211         switch ( MAKE_ID2( id->name[0], id->name[1] ) ) {
2212         case ID_OB:
2213                 return &( ( Object * ) id )->scriptlink;
2214         case ID_LA:
2215                 return &( ( Lamp * ) id )->scriptlink;
2216         case ID_CA:
2217                 return &( ( Camera * ) id )->scriptlink;
2218         case ID_MA:
2219                 return &( ( Material * ) id )->scriptlink;
2220         case ID_WO:
2221                 return &( ( World * ) id )->scriptlink;
2222         case ID_SCE:
2223                 return &( ( Scene * ) id )->scriptlink;
2224         default:
2225                 return NULL;
2226         }
2227 }
2228
2229 int BPY_has_onload_script( void )
2230 {
2231         ScriptLink *slink = &G.scene->scriptlink;
2232         int i;
2233
2234         if( !slink || !slink->totscript )
2235                 return 0;
2236
2237         for( i = 0; i < slink->totscript; i++ ) {
2238                 if( ( slink->flag[i] == SCRIPT_ONLOAD )
2239                     && ( slink->scripts[i] != NULL ) )
2240                         return 1;
2241         }
2242
2243         return 0;
2244 }
2245
2246 void BPY_do_pyscript( ID * id, short event )
2247 {
2248         ScriptLink *scriptlink;
2249
2250         if( !id ) return;
2251
2252         scriptlink = ID_getScriptlink( id );
2253
2254         if( scriptlink && scriptlink->totscript ) {
2255                 PyObject *value;
2256                 PyObject *dict;
2257                 PyObject *ret;
2258                 int index, during_slink = during_scriptlink(  );
2259                 PyGILState_STATE gilstate;
2260
2261                 /* invalid scriptlinks (new .blend was just loaded), return */
2262                 if( during_slink < 0 )
2263                         return;
2264
2265                 gilstate = PyGILState_Ensure();
2266
2267                 if( !setup_armature_weakrefs()){
2268                         printf("Oops - weakref dict, this is a bug\n");
2269                         PyGILState_Release(gilstate);
2270                         return;
2271                 }
2272                 
2273                 value = GetPyObjectFromID( id );
2274                 if( !value){
2275                         printf("Oops - could not get a valid python object for Blender.link, this is a bug\n");
2276                         PyGILState_Release(gilstate);
2277                         return;
2278                 }
2279                 
2280                 /* tell we're running a scriptlink.  The sum also tells if this
2281                  * script is running nested inside another.  Blender.Load needs
2282                  * this info to avoid trouble with invalid slink pointers. */
2283                 during_slink++;
2284                 disable_where_scriptlink( (short)during_slink );
2285
2286                 /* set globals in Blender module to identify scriptlink */
2287                 PyDict_SetItemString(   g_blenderdict, "bylink", Py_True);
2288                 EXPP_dict_set_item_str( g_blenderdict, "link", value );
2289                 EXPP_dict_set_item_str( g_blenderdict, "event",
2290                                       PyString_FromString( event_to_name
2291                                                            ( event ) ) );
2292                 if (event == SCRIPT_POSTRENDER) event = SCRIPT_RENDER;
2293
2294                 for( index = 0; index < scriptlink->totscript; index++ ) {
2295                         if( ( scriptlink->flag[index] == event ) &&
2296                             ( scriptlink->scripts[index] != NULL ) ) {
2297                                 dict = CreateGlobalDictionary(  );
2298                                 ret = RunPython( ( Text * ) scriptlink->
2299                                                  scripts[index], dict );
2300                                 ReleaseGlobalDictionary( dict );
2301
2302                                 if( !ret ) {
2303                                         /* Failed execution of the script */
2304                                         BPY_Err_Handle( scriptlink->
2305                                                         scripts[index]->name +
2306                                                         2 );
2307                                         //BPY_end_python ();
2308                                         //BPY_start_python ();
2309                                 } else {
2310                                         Py_DECREF( ret );
2311                                 }
2312                                 /* If a scriptlink has just loaded a new .blend file, the
2313                                  * scriptlink pointer became invalid (see api2_2x/Blender.c),
2314                                  * so we stop here. */
2315                                 if( during_scriptlink(  ) == -1 ) {
2316                                         during_slink = 1;
2317                                         break;
2318                                 }
2319                         }
2320                 }
2321
2322                 disable_where_scriptlink( (short)(during_slink - 1) );
2323
2324                 /* cleanup bylink flag and clear link so PyObject
2325                  * can be released 
2326                  */
2327                 PyDict_SetItemString(g_blenderdict, "bylink", Py_False);
2328                 PyDict_SetItemString( g_blenderdict, "link", Py_None );
2329                 EXPP_dict_set_item_str( g_blenderdict, "event", PyString_FromString( "" ) );
2330
2331                 PyGILState_Release(gilstate);
2332         }
2333 }
2334
2335
2336 /* SPACE HANDLERS */
2337
2338 /* These are special script links that can be assigned to ScrArea's to
2339  * (EVENT type) receive events sent to a given space (and use or ignore them) or
2340  * (DRAW type) be called after the space is drawn, to draw anything on top of
2341  * the space area. */
2342
2343 /* How to add space handlers to other spaces:
2344  * - add the space event defines to DNA_scriptlink_types.h, as done for
2345  *   3d view: SPACEHANDLER_VIEW3D_EVENT, for example;
2346  * - add the new defines to Blender.SpaceHandler dictionary in Blender.c;
2347  * - check space.c for how to call the event handlers;
2348  * - check drawview.c for how to call the draw handlers;
2349  * - check header_view3d.c for how to add the "Space Handler Scripts" menu.
2350  * Note: DRAW handlers should be called with 'event = 0', chech drawview.c */
2351
2352 int BPY_has_spacehandler(Text *text, ScrArea *sa)
2353 {
2354         ScriptLink *slink;
2355         int index;
2356
2357         if (!sa || !text) return 0;
2358
2359         slink = &sa->scriptlink;
2360
2361         for (index = 0; index < slink->totscript; index++) {
2362                 if (slink->scripts[index] && (slink->scripts[index] == (ID *)text))
2363                         return 1;
2364         }
2365
2366         return 0;       
2367 }
2368
2369 int BPY_is_spacehandler(Text *text, char spacetype)
2370 {
2371         TextLine *tline = text->lines.first;
2372         unsigned short type = 0;
2373
2374         if (tline && (tline->len > 10)) {
2375                 char *line = tline->line;
2376
2377                 /* Expected format: # SPACEHANDLER.SPACE.TYPE
2378                  * Ex: # SPACEHANDLER.VIEW3D.DRAW
2379                  * The actual checks are forgiving, so slight variations also work. */
2380                 if (line && line[0] == '#' && strstr(line, "HANDLER")) {
2381                         line++; /* skip '#' */
2382
2383                         /* only done for 3D View right now, trivial to add for others: */
2384                         switch (spacetype) {
2385                                 case SPACE_VIEW3D:
2386                                         if (strstr(line, "3D")) { /* VIEW3D, 3DVIEW */
2387                                                 if (strstr(line, "DRAW")) type = SPACEHANDLER_VIEW3D_DRAW;
2388                                                 else if (strstr(line, "EVENT")) type = SPACEHANDLER_VIEW3D_EVENT;
2389                                         }
2390                                         break;
2391                         }
2392                 }
2393         }
2394         return type; /* 0 if not a space handler */
2395 }
2396
2397 int BPY_del_spacehandler(Text *text, ScrArea *sa)
2398 {
2399         ScriptLink *slink;
2400         int i, j;
2401
2402         if (!sa || !text) return -1;
2403
2404         slink = &sa->scriptlink;
2405         if (slink->totscript < 1) return -1;
2406
2407         for (i = 0; i < slink->totscript; i++) {
2408                 if (text == (Text *)slink->scripts[i]) {
2409
2410                         for (j = i; j < slink->totscript - 1; j++) {
2411                                 slink->flag[j] = slink->flag[j+1];
2412                                 slink->scripts[j] = slink->scripts[j+1];
2413                         }
2414                         slink->totscript--;
2415                         /* like done in buttons_script.c we just free memory
2416                          * if all slinks have been removed -- less fragmentation,
2417                          * these should be quite small arrays */
2418                         if (slink->totscript == 0) {
2419                                 if (slink->scripts) MEM_freeN(slink->scripts);
2420                                 if (slink->flag) MEM_freeN(slink->flag);
2421                                 break;
2422                         }
2423                 }
2424         }
2425         return 0;
2426 }
2427
2428 int BPY_add_spacehandler(Text *text, ScrArea *sa, char spacetype)
2429 {
2430         unsigned short handlertype;
2431
2432         if (!sa || !text) return -1;
2433
2434         handlertype = (unsigned short)BPY_is_spacehandler(text, spacetype);
2435
2436         if (handlertype) {
2437                 ScriptLink *slink = &sa->scriptlink;
2438                 void *stmp, *ftmp;
2439                 unsigned short space_event = SPACEHANDLER_VIEW3D_EVENT;
2440
2441                 /* extend slink */
2442
2443                 stmp= slink->scripts;           
2444                 slink->scripts= MEM_mallocN(sizeof(ID*)*(slink->totscript+1),
2445                         "spacehandlerscripts");
2446         
2447                 ftmp= slink->flag;              
2448                 slink->flag= MEM_mallocN(sizeof(short*)*(slink->totscript+1),
2449                         "spacehandlerflags");
2450         
2451                 if (slink->totscript) {
2452                         memcpy(slink->scripts, stmp, sizeof(ID*)*(slink->totscript));
2453                         MEM_freeN(stmp);
2454
2455                         memcpy(slink->flag, ftmp, sizeof(short)*(slink->totscript));
2456                         MEM_freeN(ftmp);
2457                 }
2458
2459                 switch (spacetype) {
2460                         case SPACE_VIEW3D:
2461                                 if (handlertype == 1) space_event = SPACEHANDLER_VIEW3D_EVENT;
2462                                 else space_event = SPACEHANDLER_VIEW3D_DRAW;
2463                                 break;
2464                         default:
2465                                 break;
2466                 }
2467
2468                 slink->scripts[slink->totscript] = (ID *)text;
2469                 slink->flag[slink->totscript]= space_event;
2470
2471                 slink->totscript++;
2472                 slink->actscript = slink->totscript;
2473
2474         }
2475         return 0;
2476 }
2477
2478 int BPY_do_spacehandlers( ScrArea *sa, unsigned short event,
2479         unsigned short space_event )
2480 {
2481         ScriptLink *scriptlink;
2482         int retval = 0;
2483         PyGILState_STATE gilstate;
2484         
2485         if (!sa || !(G.f & G_DOSCRIPTLINKS)) return 0;
2486         
2487         scriptlink = &sa->scriptlink;
2488
2489         if (scriptlink->totscript > 0) {
2490                 PyObject *dict;
2491                 PyObject *ret;
2492                 int index, during_slink = during_scriptlink();
2493
2494                 /* invalid scriptlinks (new .blend was just loaded), return */
2495                 if (during_slink < 0) return 0;
2496
2497                 /* tell we're running a scriptlink.  The sum also tells if this script
2498                  * is running nested inside another.  Blender.Load needs this info to
2499                  * avoid trouble with invalid slink pointers.
2500                  * Update (test): allow EVENT space handlers to call file/image selectors,
2501                  * still disabled for DRAW space handlers: */
2502                 if (event == 0) { /* event = 0: DRAW space handler */
2503                         during_slink++;
2504                         disable_where_scriptlink( (short)during_slink );
2505                 }
2506                 
2507                 gilstate = PyGILState_Ensure();
2508                 
2509                 if( !setup_armature_weakrefs()){
2510                         printf("Oops - weakref dict, this is a bug\n");
2511                         PyGILState_Release(gilstate);
2512                         return 0;
2513                 }
2514                 
2515                 /* set globals in Blender module to identify space handler scriptlink */
2516                 PyDict_SetItemString(g_blenderdict, "bylink", Py_True);
2517                 /* unlike normal scriptlinks, here Blender.link is int (space event type) */
2518                 EXPP_dict_set_item_str(g_blenderdict, "link", PyInt_FromLong(space_event));
2519                 /* note: DRAW space_events set event to 0 */
2520                 EXPP_dict_set_item_str(g_blenderdict, "event", PyInt_FromLong(event));
2521                 /* now run all assigned space handlers for this space and space_event */
2522                 for( index = 0; index < scriptlink->totscript; index++ ) {
2523                         
2524                         /* for DRAW handlers: */
2525                         if (event == 0) {
2526                                 glPushAttrib(GL_ALL_ATTRIB_BITS);
2527                                 glMatrixMode(GL_PROJECTION);
2528                                 glPushMatrix();
2529                                 glMatrixMode(GL_MODELVIEW);
2530                                 glPushMatrix();
2531                         }
2532                         
2533                         if( ( scriptlink->flag[index] == space_event ) &&
2534                             ( scriptlink->scripts[index] != NULL ) ) {
2535                                 dict = CreateGlobalDictionary();
2536                                 ret = RunPython( ( Text * ) scriptlink->scripts[index], dict );
2537                                 ReleaseGlobalDictionary( dict );
2538
2539                                 if (!ret) { /* Failed execution of the script */
2540                                         BPY_Err_Handle( scriptlink->scripts[index]->name+2 );
2541                                 } else {
2542                                         Py_DECREF(ret);
2543
2544                                         /* an EVENT type (event != 0) script can either accept an event or
2545                                          * ignore it:
2546                                          * if the script sets Blender.event to None it accepted it;
2547                                          * otherwise the space's event handling callback that called us
2548                                          * can go on processing the event */
2549                                         if (event && (PyDict_GetItemString(g_blenderdict,"event") == Py_None))
2550                                                 retval = 1; /* event was swallowed */
2551                                 }
2552                                 
2553                                 /* If a scriptlink has just loaded a new .blend file, the
2554                                  * scriptlink pointer became invalid (see api2_2x/Blender.c),
2555                                  * so we stop here. */
2556                                 if( during_scriptlink(  ) == -1 ) {
2557                                         during_slink = 1;
2558                                         if (event == 0) glPopAttrib();
2559                                         break;
2560                                 }
2561                         }
2562                         
2563                         /* for DRAW handlers: */
2564                         if (event == 0) {
2565                                 glMatrixMode(GL_PROJECTION);
2566                                 glPopMatrix();
2567                                 glMatrixMode(GL_MODELVIEW);
2568                                 glPopMatrix();
2569                                 glPopAttrib();
2570                                 disable_where_scriptlink( (short)(during_slink - 1) );
2571                         }
2572                 
2573                 }
2574                 
2575                 PyDict_SetItemString(g_blenderdict, "bylink", Py_False);
2576                 PyDict_SetItemString(g_blenderdict, "link", Py_None );
2577                 EXPP_dict_set_item_str(g_blenderdict, "event", PyString_FromString(""));
2578                 
2579                 PyGILState_Release(gilstate);
2580         }
2581         
2582         /* retval:
2583          * space_event is of type EVENT:
2584          * 0 - event was returned,
2585          * 1 - event was processed;
2586          * space_event is of type DRAW:
2587          * 0 always */
2588
2589         return retval;
2590 }
2591
2592 /*****************************************************************************
2593 * Description:  
2594 * Notes:
2595 *****************************************************************************/
2596 void BPY_free_scriptlink( struct ScriptLink *slink )
2597 {
2598         if( slink->totscript ) {
2599                 if( slink->flag ) {
2600                         MEM_freeN( slink->flag );
2601                         slink->flag= NULL;
2602                 }
2603                 if( slink->scripts ) {
2604                         MEM_freeN( slink->scripts );
2605                         slink->scripts= NULL;
2606                 }
2607         }
2608
2609         return;
2610 }
2611
2612 static int CheckAllSpaceHandlers(Text *text)
2613 {
2614         bScreen *screen;
2615         ScrArea *sa;
2616         ScriptLink *slink;
2617         int fixed = 0;
2618
2619         for (screen = G.main->screen.first; screen; screen = screen->id.next) {
2620                 for (sa = screen->areabase.first; sa; sa = sa->next) {
2621                         slink = &sa->scriptlink;
2622                         if (!slink->totscript) continue;
2623                         if (BPY_del_spacehandler(text, sa) == 0) fixed++;
2624                 }
2625         }
2626         return fixed;
2627 }
2628
2629 static int CheckAllScriptsFromList( ListBase * list, Text * text )
2630 {
2631         ID *id;
2632         ScriptLink *scriptlink;
2633         int index;
2634         int fixed = 0;
2635
2636         id = list->first;
2637
2638         while( id != NULL ) {
2639                 scriptlink = ID_getScriptlink( id );
2640                 if( scriptlink && scriptlink->totscript ) {
2641                         for( index = 0; index < scriptlink->totscript; index++) {
2642                                 if ((Text *)scriptlink->scripts[index] == text) {
2643                                         scriptlink->scripts[index] = NULL;
2644                                         fixed++;
2645                                 }
2646                         }
2647                 }
2648                 id = id->next;
2649         }
2650
2651         return fixed;
2652 }
2653
2654 /* When a Text is deleted, we need to unlink it from eventual scriptlinks */
2655 int BPY_check_all_scriptlinks( Text * text )
2656 {
2657         int fixed = 0;
2658         fixed += CheckAllScriptsFromList( &( G.main->object ), text );
2659         fixed += CheckAllScriptsFromList( &( G.main->lamp ), text );
2660         fixed += CheckAllScriptsFromList( &( G.main->camera ), text );
2661         fixed += CheckAllScriptsFromList( &( G.main->mat ), text );
2662         fixed += CheckAllScriptsFromList( &( G.main->world ), text );
2663         fixed += CheckAllScriptsFromList( &( G.main->scene ), text );
2664         fixed += CheckAllSpaceHandlers(text);
2665
2666         return fixed;
2667 }
2668
2669 /*****************************************************************************
2670 * Description: 
2671 * Notes:
2672 *****************************************************************************/
2673 void BPY_copy_scriptlink( struct ScriptLink *scriptlink )
2674 {
2675         void *tmp;
2676
2677         if( scriptlink->totscript ) {
2678
2679                 tmp = scriptlink->scripts;
2680                 scriptlink->scripts =
2681                         MEM_mallocN( sizeof( ID * ) * scriptlink->totscript,
2682                                      "scriptlistL" );
2683                 memcpy( scriptlink->scripts, tmp,
2684                         sizeof( ID * ) * scriptlink->totscript );
2685
2686                 tmp = scriptlink->flag;
2687                 scriptlink->flag =
2688                         MEM_mallocN( sizeof( short ) * scriptlink->totscript,
2689                                      "scriptlistF" );
2690                 memcpy( scriptlink->flag, tmp,
2691                         sizeof( short ) * scriptlink->totscript );
2692         }
2693
2694         return;
2695 }
2696
2697 /****************************************************************************
2698 * Description:
2699 * Notes:                Not implemented yet
2700 *****************************************************************************/
2701 int BPY_call_importloader( char *name )
2702 {                       /* XXX Should this function go away from Blender? */
2703         printf( "In BPY_call_importloader(name=%s)\n", name );
2704         return ( 0 );
2705 }
2706
2707 /*****************************************************************************
2708 * Private functions
2709 *****************************************************************************/
2710
2711 /*****************************************************************************
2712 * Description: This function executes the python script passed by text. 
2713 *               The Python dictionary containing global variables needs to
2714 *               be passed in globaldict.
2715 *****************************************************************************/
2716 PyObject *RunPython( Text * text, PyObject * globaldict )
2717 {
2718         char *buf = NULL;
2719
2720 /* The script text is compiled to Python bytecode and saved at text->compiled
2721  * to speed-up execution if the user executes the script multiple times */
2722
2723         if( !text->compiled ) { /* if it wasn't already compiled, do it now */
2724                 buf = txt_to_buf( text );
2725
2726                 text->compiled =
2727                         Py_CompileString( buf, GetName( text ),
2728                                           Py_file_input );
2729
2730                 MEM_freeN( buf );
2731
2732                 if( PyErr_Occurred(  ) ) {
2733                         BPY_free_compiled_text( text );
2734                         return NULL;
2735                 }
2736
2737         }
2738
2739         return PyEval_EvalCode( text->compiled, globaldict, globaldict );
2740 }
2741
2742 /*****************************************************************************
2743 * Description: This function returns the value of the name field of the 
2744 *       given Text struct.
2745 *****************************************************************************/
2746 char *GetName( Text * text )
2747 {
2748         return ( text->id.name + 2 );
2749 }
2750
2751 /*****************************************************************************
2752 * Description: This function creates a new Python dictionary object.
2753 *****************************************************************************/
2754 PyObject *CreateGlobalDictionary( void )
2755 {
2756         PyObject *dict = PyDict_New(  );
2757
2758         PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins(  ) );
2759         EXPP_dict_set_item_str( dict, "__name__",
2760                               PyString_FromString( "__main__" ) );
2761
2762         return dict;
2763 }
2764
2765 /*****************************************************************************
2766 * Description: This function deletes a given Python dictionary object.
2767 *****************************************************************************/
2768 void ReleaseGlobalDictionary( PyObject * dict )
2769 {
2770         PyDict_Clear( dict );
2771         Py_DECREF( dict );      /* Release dictionary. */
2772
2773         return;
2774 }
2775
2776 /***************************************************************************
2777 * Description: This function runs all scripts (if any) present in the
2778 *               list argument. The event by which the function has been 
2779 *               called, is passed in the event argument.
2780 *****************************************************************************/
2781 void DoAllScriptsFromList( ListBase * list, short event )
2782 {
2783         ID *id;
2784
2785         id = list->first;
2786
2787         while( id != NULL ) {
2788                 BPY_do_pyscript( id, event );
2789                 id = id->next;
2790         }
2791
2792         return;
2793 }
2794
2795 PyObject *importText( char *name )
2796 {
2797         Text *text;
2798         char *txtname;
2799         char *buf = NULL;
2800         int namelen = strlen( name );
2801
2802         txtname = malloc( namelen + 3 + 1 );
2803         if( !txtname )
2804                 return NULL;
2805
2806         memcpy( txtname, name, namelen );
2807         memcpy( &txtname[namelen], ".py", 4 );
2808
2809         text = ( Text * ) & ( G.main->text.first );
2810
2811         while( text ) {
2812                 if( !strcmp( txtname, GetName( text ) ) )
2813                         break;
2814                 text = text->id.next;
2815         }
2816
2817         if( !text ) {
2818                 free( txtname );
2819                 return NULL;
2820         }
2821
2822         if( !text->compiled ) {
2823                 buf = txt_to_buf( text );
2824                 text->compiled =
2825                         Py_CompileString( buf, GetName( text ),
2826                                           Py_file_input );
2827                 MEM_freeN( buf );
2828
2829                 if( PyErr_Occurred(  ) ) {
2830                         PyErr_Print(  );
2831                         BPY_free_compiled_text( text );
2832                         free( txtname );
2833                         return NULL;
2834                 }
2835         }
2836
2837         free( txtname );
2838         return PyImport_ExecCodeModule( name, text->compiled );
2839 }
2840
2841 static PyMethodDef bimport[] = {
2842         {"blimport", blender_import, METH_VARARGS, "our own import"}
2843 };
2844
2845 PyObject *blender_import( PyObject * self, PyObject * args )
2846 {
2847         PyObject *exception, *err, *tb;
2848         char *name;
2849         PyObject *globals = NULL, *locals = NULL, *fromlist = NULL;
2850         PyObject *m;
2851
2852         if( !PyArg_ParseTuple( args, "s|OOO:bimport",
2853                                &name, &globals, &locals, &fromlist ) )
2854                 return NULL;
2855
2856         m = PyImport_ImportModuleEx( name, globals, locals, fromlist );
2857
2858         if( m )
2859                 return m;
2860         else
2861                 PyErr_Fetch( &exception, &err, &tb );   /*restore for probable later use */
2862
2863         m = importText( name );
2864         if( m ) {               /* found module, ignore above exception */
2865                 PyErr_Clear(  );
2866                 Py_XDECREF( exception );
2867                 Py_XDECREF( err );
2868                 Py_XDECREF( tb );
2869                 printf( "imported from text buffer...\n" );
2870         } else {
2871                 PyErr_Restore( exception, err, tb );
2872         }
2873         return m;
2874 }
2875
2876 void init_ourImport( void )
2877 {
2878         PyObject *m, *d;
2879         PyObject *import = PyCFunction_New( bimport, NULL );
2880
2881         m = PyImport_AddModule( "__builtin__" );
2882         d = PyModule_GetDict( m );
2883         
2884         EXPP_dict_set_item_str( d, "__import__", import );
2885 }
2886
2887 /*
2888  * find in-memory module and recompile
2889  */
2890
2891 static PyObject *reimportText( PyObject *module )
2892 {
2893         Text *text;
2894         char *txtname;
2895         char *name;
2896         char *buf = NULL;
2897
2898         /* get name, filename from the module itself */
2899
2900         txtname = PyModule_GetFilename( module );
2901         name = PyModule_GetName( module );
2902         if( !txtname || !name)
2903                 return NULL;
2904
2905         /* look up the text object */
2906         text = ( Text * ) & ( G.main->text.first );
2907         while( text ) {
2908                 if( !strcmp( txtname, GetName( text ) ) )
2909                         break;
2910                 text = text->id.next;
2911         }
2912
2913         /* uh-oh.... didn't find it */
2914         if( !text )
2915                 return NULL;
2916
2917         /* if previously compiled, free the object */
2918         /* (can't see how could be NULL, but check just in case) */ 
2919         if( text->compiled ){
2920                 Py_DECREF( (PyObject *)text->compiled );
2921         }
2922
2923         /* compile the buffer */
2924         buf = txt_to_buf( text );
2925         text->compiled = Py_CompileString( buf, GetName( text ),
2926                         Py_file_input );
2927         MEM_freeN( buf );
2928
2929         /* if compile failed.... return this error */
2930         if( PyErr_Occurred(  ) ) {
2931                 PyErr_Print(  );
2932                 BPY_free_compiled_text( text );
2933                 return NULL;
2934         }
2935
2936         /* make into a module */
2937         return PyImport_ExecCodeModule( name, text->compiled );
2938 }
2939
2940 /*
2941  * our reload() module, to handle reloading in-memory scripts
2942  */
2943
2944 static PyObject *blender_reload( PyObject * self, PyObject * args )
2945 {
2946         PyObject *exception, *err, *tb;
2947         PyObject *module = NULL;
2948         PyObject *newmodule = NULL;
2949
2950         /* check for a module arg */
2951         if( !PyArg_ParseTuple( args, "O:breload", &module ) )
2952                 return NULL;
2953
2954         /* try reimporting from file */
2955         newmodule = PyImport_ReloadModule( module );
2956         if( newmodule )
2957                 return newmodule;
2958
2959         /* no file, try importing from memory */
2960         PyErr_Fetch( &exception, &err, &tb );   /*restore for probable later use */
2961
2962         newmodule = reimportText( module );
2963         if( newmodule ) {               /* found module, ignore above exception */
2964                 PyErr_Clear(  );
2965                 Py_XDECREF( exception );
2966                 Py_XDECREF( err );
2967                 Py_XDECREF( tb );
2968         } else
2969                 PyErr_Restore( exception, err, tb );
2970
2971         return newmodule;
2972 }
2973
2974 static PyMethodDef breload[] = {
2975         {"blreload", blender_reload, METH_VARARGS, "our own reload"}
2976 };
2977
2978 void init_ourReload( void )
2979 {
2980         PyObject *m, *d;
2981         PyObject *reload = PyCFunction_New( breload, NULL );
2982
2983         m = PyImport_AddModule( "__builtin__" );
2984         d = PyModule_GetDict( m );
2985         EXPP_dict_set_item_str( d, "reload", reload );
2986 }
2987
2988
2989 void BPY_scripts_clear_pyobjects( void )
2990 {
2991         Script *script;
2992         for (script=G.main->script.first; script; script=script->id.next) {
2993                 Py_XDECREF((PyObject *)script->py_draw);
2994                 Py_XDECREF((PyObject *)script->py_event);
2995                 Py_XDECREF((PyObject *)script->py_button);
2996                 Py_XDECREF((PyObject *)script->py_browsercallback);
2997                 Py_XDECREF((PyObject *)script->py_globaldict); 
2998                 SCRIPT_SET_NULL(script)
2999         }
3000 }
3001 void error_pyscript( void )
3002 {
3003         error("Python script error: check console");
3004 }