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