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