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