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