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