Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BPY_main.c « intern « bpython « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 179954767493e4a3e10a910437d3749487ad5391 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/**
 * blenkernel/py_main.c
 * (cleaned up somewhat nzc apr-2001)

 * $Id$
 *
 * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version. The Blender
 * Foundation also sells licenses for use in proprietary software under
 * the Blender License.  See http://www.blender.org/BL/ for information
 * about this.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
 * All rights reserved.
 *
 * The Original Code is: all of this file.
 *
 * Contributor(s): none yet.
 *
 * ***** END GPL/BL DUAL LICENSE BLOCK *****
 *
 */

/* NOTE: all externally callable routines have the prefix BPY_
 -- see also ../include/BPY_extern.h */

#include "BPY_main.h"
#include "BPY_modules.h"
#include "BPY_macros.h"
#include "DNA_space_types.h"

#include "b_interface.h"
#include "mydevice.h"
#include "import.h"

/* PROTOS */

extern void init_frozenmodules(void);  // frozen module library
extern void initmxTextTools(void);
extern void inittess(void);            // tesselator module

void init_ourImport(void);


/* GLOBALS */

PyObject* ErrorObject     = NULL;
PyObject* callback        = NULL;
PyObject* callbackArgs    = NULL;
PyObject* blenderprogname = NULL;
ID*       script_link_id  = NULL;

/*------------------------------------------------------------------------*/ 
/* START PYTHON (from creator.c)                                          */

void INITMODULE(BLENDERMODULE)(void);

struct _inittab blendermodules[] = {
#ifndef SHAREDMODULE         // Blender module can alternatively be compiled shared
	#ifdef STATIC_TEXTTOOLS  // see api.h
	{ "mxTextTools" , initmxTextTools },
	#endif
	{ MODNAME(BLENDERMODULE) , INITMODULE(BLENDERMODULE) },
#endif
#ifdef NO_RELEASE
	{ "tess" , inittess }, // GLU tesselator wrapper module
#endif
	{ 0, 0}
};

/* hack to make sure, inittab is extended only first time */

static short g_is_extended = 0;

/** (Re)initializes the Python Interpreter.
  * This function should be only called if the Python interpreter
  * was not yet initialized (check Py_IsInitialized() )
  */

static void initBPythonInterpreter(void)
{
	Py_Initialize();

	init_ourImport(); /* our own import, later: security */
	if (!BPY_CHECKFLAG(G_NOFROZEN)) {
		init_frozenmodules(); /* initialize frozen modules unless disabled */
	}
	init_syspath();
}

/** This function initializes Blender Python. It should be called only
  * once at start, which is currently not the case (GameEngine Python).
  * Therefore, it contains some dirty workarounds. They will be thrown
  * into the grachten once the different APIs are merged into something
  * more consistent.
  *
  */

void BPY_start_python(void)
{
	Py_SetProgramName("blender");
	if (BPY_DEBUGFLAG) {

		Py_VerboseFlag = 1;
		Py_DebugFlag = 1;
	} else {
#ifndef EXPERIMENTAL 		
		Py_FrozenFlag = 1; /* no warnings about non set PYTHONHOME */
		Py_NoSiteFlag = 1; /* disable auto site module import */
#endif		
	}	

	if (!g_is_extended) {
		g_is_extended = 1;
		PyImport_ExtendInittab(blendermodules); /* extend builtin module table */
	}	

	initBPythonInterpreter();
#ifdef NO_RELEASE
	if (PyRun_SimpleString("import startup"))
	{
		BPY_warn(("init script not found, continuing anyway\n"));
		PyErr_Clear();
		return;
	}	
#endif	
}

/** Ends the Python interpreter. This cleans up all global variables
  * Blender-Python descriptor objects will (MUST!) decref on their
  * raw blender objects, so this function should be called more or less
  * immediately before garbage collection actions.
  */

void BPY_end_python(void)
{
	Py_Finalize();
}

void BPY_free_compiled_text(Text* text)
{
	if (!text->compiled) return;
	Py_DECREF((PyObject*) text->compiled);
	text->compiled = NULL;
}

void syspath_append(PyObject *dir)
{
	PyObject *m, *d;
	PyObject *o;

	PyErr_Clear();
	m = PyImport_ImportModule("sys");
	d = PyModule_GetDict(m);
	o = PyDict_GetItemString(d, "path");
	if (!PyList_Check(o)) {
		return;
	}
	PyList_Append(o, dir);
	if (PyErr_Occurred()) {
		Py_FatalError("could not build sys.path");
	}	
	Py_DECREF(m);
}

/* build blender specific system path for external modules */

void init_syspath(void)
{
	PyObject *path;
	PyObject *m, *d;
	PyObject *p;
	char *c;


	char execdir[PATH_MAXCHAR], *progname;

	int n;
	
	path = Py_BuildValue("s", bprogname);

	m = PyImport_ImportModule(MODNAME(BLENDERMODULE) ".sys");
	if (m) {
		d = PyModule_GetDict(m);
		PyDict_SetItemString(d, "progname", path);
		Py_DECREF(m);
	} else {
		BPY_debug(("Warning: could not set Blender.sys.progname\n"));
	}	

	progname = BLI_last_slash(bprogname); /* looks for the last dir separator */

	c = Py_GetPath(); /* get python system path */
	PySys_SetPath(c); /* initialize */

	n = progname - bprogname; 
	if (n > 0) {
		strncpy(execdir, bprogname, n);
		execdir[n] = '\0';

		p = Py_BuildValue("s", execdir);
		syspath_append(p);  /* append to module search path */

		/* set Blender.sys.progname */
	} else {	
		BPY_debug(("Warning: could not determine argv[0] path\n"));
	}
	/* TODO look for the blender executable in the search path */
	BPY_debug(("append to syspath: %s\n", U.pythondir));
	if (U.pythondir) {
		p = Py_BuildValue("s", U.pythondir);
		syspath_append(p);  /* append to module search path */
	}
	BPY_debug(("append done\n"));
}


#define FILENAME_LENGTH 24
typedef struct _ScriptError {
	char filename[FILENAME_LENGTH];
	int lineno;
} ScriptError;

ScriptError g_script_error;

int BPY_Err_getLinenumber()
{
	return g_script_error.lineno;
}	

const char *BPY_Err_getFilename()
{
	return g_script_error.filename;
}

/** Returns (PyString) filename from a traceback object */

PyObject *traceback_getFilename(PyObject *tb)
{
	PyObject *v;

	v = PyObject_GetAttrString(tb, "tb_frame"); Py_DECREF(v);
	v = PyObject_GetAttrString(v, "f_code"); Py_DECREF(v);
	v = PyObject_GetAttrString(v, "co_filename"); 
	return v;
}

/** Blender Python error handler. This catches the error and stores
  * filename and line number in a global
  */

void BPY_Err_Handle(Text *text)
{
	PyObject *exception, *err, *tb, *v;

	PyErr_Fetch(&exception, &err, &tb);

	if (!exception && !tb) {
		printf("FATAL: spurious exception\n");
		return;
	}

	strcpy(g_script_error.filename, getName(text));

	if (exception && PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError)) {
		// no traceback available when SyntaxError
		PyErr_Restore(exception, err, tb); // takes away reference!
		PyErr_Print();
		v = PyObject_GetAttrString(err, "lineno");
		g_script_error.lineno = PyInt_AsLong(v);
		Py_XDECREF(v);
		return; 
	} else {
		PyErr_NormalizeException(&exception, &err, &tb);
		PyErr_Restore(exception, err, tb); // takes away reference!
		PyErr_Print();
		tb = PySys_GetObject("last_traceback");
		Py_INCREF(tb);

// check traceback objects and look for last traceback in the
// same text file. This is used to jump to the line of where the
// error occured. If the error occured in another text file or module,
// the last frame in the current file is adressed

		while (1) {	
			v = PyObject_GetAttrString(tb, "tb_next");
			if (v == Py_None || 
			  strcmp(PyString_AsString(traceback_getFilename(v)), getName(text)))
				break;
			Py_DECREF(tb);
			tb = v;
		}

		v = PyObject_GetAttrString(tb, "tb_lineno");
		g_script_error.lineno = PyInt_AsLong(v);
		Py_XDECREF(v);
		v = traceback_getFilename(tb);
		strncpy(g_script_error.filename, PyString_AsString(v), FILENAME_LENGTH);
		Py_XDECREF(v);
		Py_DECREF(tb);
	}
}

/** Runs a Python string in the global name space of the given dictionary
    'globaldict' */

static PyObject *newGlobalDictionary(void)
{
	PyObject *d = PyDict_New();
	PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
	PyDict_SetItemString(d, "__name__", PyString_FromString("__main__"));
	return d;
}	

static void releaseGlobalDictionary(PyObject *d)
{
	BPY_debug(("--- CLEAR namespace\n"));
	PyDict_Clear(d);
	Py_DECREF(d); // release dictionary
}

PyObject *BPY_runPython(Text *text, PyObject *globaldict)
{
	PyObject *ret;
	char* buf = NULL;

	if (!text->compiled)
	{
		buf = txt_to_buf(text);
		/* bah, what a filthy hack -- removed */
		/*      strcat(buf, "\n"); */
		text->compiled = Py_CompileString(buf, getName(text), Py_file_input);
		MEM_freeN(buf);
		if (PyErr_Occurred())
		{
			BPY_free_compiled_text(text);
			return 0;
		}
	}
	BPY_debug(("Run Python script \"%s\" ...\n", getName(text)));
	ret = PyEval_EvalCode(text->compiled, globaldict, globaldict);
	return ret;
}

/** This function is executed whenever ALT+PKEY is pressed -> drawtext.c 
    It returns the global namespace dictionary of the script context
	(which is created newly when CLEAR_NAMESPACE is defined).
	This may be stored in the SpaceText instance to give control over
	namespace persistence. Remember that the same script may be executed
	in several windows..
	Namespace persistence is desired for scripts that use the GUI and
	store callbacks to the current script.
*/

PyObject  *BPY_txt_do_python(SpaceText *st)
{
	PyObject* d = NULL;
	PyObject *ret;
	Text *text = st->text;

	if (!text)
	{
	  return NULL;
	}

	/* TODO: make this an option: */
#ifdef CLEAR_NAMESPACE	
	BPY_debug(("--- enable clear namespace\n"));
	st->flags |= ST_CLEAR_NAMESPACE;
#endif

#ifdef CLEAR_NAMESPACE
	d = newGlobalDictionary();
#else
	d = PyModule_GetDict(PyImport_AddModule("__main__"));
#endif	
	
	ret = BPY_runPython(text, d);

	if (!ret) {
#ifdef CLEAR_NAMESPACE			
		releaseGlobalDictionary(d);
#endif
		BPY_Err_Handle(text);
		Py_Finalize();
		initBPythonInterpreter();
		return NULL;
	}	
	else
		Py_DECREF(ret);


	/* The following lines clear the global name space of the python
	 * interpreter. This is desired to release objects after execution
	 * of a script (remember that each wrapper object increments the refcount
	 * of the Blender Object. 

	 * Exception: scripts that use the GUI rely on the
	 * persistent global namespace, so they need a workaround: The namespace
	 * is released when the GUI is exit.
	 * See opy_draw.c:Method_Register()
	 *
	 */

#ifdef CLEAR_NAMESPACE	
	if (st->flags & ST_CLEAR_NAMESPACE) {
		releaseGlobalDictionary(d);
		garbage_collect(getGlobal()->main); 
	}
#endif	
	
	return d;
}

/****************************************/
/* SCRIPTLINKS                          */

static void do_all_scriptlist(ListBase* list, short event)
{
	ID *id;

	id = list->first;
	while (id)
	{
		BPY_do_pyscript (id, event);
		id = id->next;
	}
}

void BPY_do_all_scripts(short event)
{
	do_all_scriptlist(getObjectList(), event);
	do_all_scriptlist(getLampList(),   event);
	do_all_scriptlist(getCameraList(), event);
	do_all_scriptlist(getMaterialList(), event);
	do_all_scriptlist(getWorldList(),  event);

	BPY_do_pyscript(&scene_getCurrent()->id, event);
}


char *event_to_name(short event)
{
	switch (event) {
	case SCRIPT_FRAMECHANGED:
		return "FrameChanged";
	case SCRIPT_ONLOAD:
		return "OnLoad";
	case SCRIPT_REDRAW:
		return "Redraw";
	default:
		return "Unknown";
	}
}	


void BPY_do_pyscript(ID *id, short event)
{
	int         i, offset;
	char        evName[24] = "";
	char*       structname = NULL;
	ScriptLink* scriptlink;
	PyObject *globaldict;

	switch(GET_ID_TYPE(id)) {
	case ID_OB: structname= "Object"; break;
	case ID_LA:  structname= "Lamp"; break;
	case ID_CA:  structname= "Camera"; break;
	case ID_MA:  structname= "Material"; break;
	case ID_WO:  structname= "World"; break;
	case ID_SCE: structname= "Scene"; break;
	default: return;
	}

	offset = BLO_findstruct_offset(structname, "scriptlink");
	if (offset < 0)
	{
		BPY_warn(("Internal error, unable to find script link\n"));
		return;
	}
	scriptlink = (ScriptLink*) (((char*)id) + offset);

	/* no script provided */
	if (!scriptlink->totscript) return;

/* Debugging output */
	switch (event)
	{
	case SCRIPT_FRAMECHANGED:
		strcpy(evName, "SCRIPT_FRAMECHANGED");
		BPY_debug(("do_pyscript(%s, %s)\n", getIDName(id), evName)); 
		break;
	case SCRIPT_ONLOAD:
		strcpy(evName, "SCRIPT_ONLOAD");
		BPY_debug(("do_pyscript(%s, %s)\n", getIDName(id), evName)); 
		break;
	case SCRIPT_REDRAW:
		strcpy(evName, "SCRIPT_REDRAW");
		BPY_debug(("do_pyscript(%s, %s)\n", getIDName(id), evName));
		break;
	default:
		BPY_debug(("do_pyscript(): This should not happen !!!")); 
		break;
	}

/* END DEBUGGING */
#ifndef SHAREDMODULE
	set_scriptlinks(id, event);
#endif
	disable_where_script(1);
	for (i = 0; i < scriptlink->totscript; i++)
	{
		if (scriptlink->flag[i] == event && scriptlink->scripts[i])
		{
			BPY_debug(("Evaluate script \"%s\" ...\n",
				getIDName(scriptlink->scripts[i])));
			script_link_id = id;
#ifdef CLEAR_NAMESPACE
			globaldict = newGlobalDictionary();
#else
			globaldict = PyModule_GetDict(PyImport_AddModule("__main__"));
#endif			
			BPY_runPython((Text*) scriptlink->scripts[i], globaldict);
#ifdef CLEAR_NAMESPACE
			releaseGlobalDictionary(globaldict);
#endif			
			
			script_link_id = NULL;
			BPY_debug(("... done\n"));
		}
	}
#ifndef SHAREDMODULE
	release_scriptlinks(id);
#endif
	disable_where_script(0);
}

void BPY_clear_bad_scriptlink(ID *id, Text *byebye)
{
	ScriptLink* scriptlink;
	int         offset = -1;
	char*       structname = NULL;
	int         i;

	switch (GET_ID_TYPE(id)) {
	case ID_OB:  structname = "Object"; break;
	case ID_LA:  structname = "Lamp"; break;
	case ID_CA:  structname = "Camera"; break;
	case ID_MA:  structname = "Material"; break;
	case ID_WO:  structname = "World"; break;
	case ID_SCE: structname = "Scene"; break;
	}

	if (!structname) return;

	offset= BLO_findstruct_offset(structname, "scriptlink");

	if (offset<0) return;

	scriptlink= (ScriptLink *) (((char *)id) + offset);

	for(i=0; i<scriptlink->totscript; i++)
	if ((Text*)scriptlink->scripts[i] == byebye)
		scriptlink->scripts[i] = NULL;
}

void BPY_clear_bad_scriptlist(ListBase *list, Text *byebye)
{
	ID *id;

	id= list->first;
	while (id)
	{
		BPY_clear_bad_scriptlink(id, byebye);
		id= id->next;
	}
}

void BPY_clear_bad_scriptlinks(Text *byebye)
{
	BPY_clear_bad_scriptlist(getObjectList(),	byebye);
	BPY_clear_bad_scriptlist(getLampList(),	byebye);
	BPY_clear_bad_scriptlist(getCameraList(),	byebye);
	BPY_clear_bad_scriptlist(getMaterialList(),	byebye);
	BPY_clear_bad_scriptlist(getWorldList(),	byebye);
	BPY_clear_bad_scriptlink(&scene_getCurrent()->id,    byebye);
	allqueue(REDRAWBUTSSCRIPT, 0);
}

void BPY_free_scriptlink(ScriptLink *slink)
{
	if (slink->totscript)
	{
		if(slink->flag) MEM_freeN(slink->flag);
		if(slink->scripts) MEM_freeN(slink->scripts);
	}
}

void BPY_copy_scriptlink(ScriptLink *scriptlink)
{
	void *tmp;

	if (scriptlink->totscript)
	{
		tmp = scriptlink->scripts;
		scriptlink->scripts = MEM_mallocN(sizeof(ID*)*scriptlink->totscript, "scriptlistL");
		memcpy(scriptlink->scripts, tmp, sizeof(ID*)*scriptlink->totscript);

		tmp = scriptlink->flag;
		scriptlink->flag = MEM_mallocN(sizeof(short)*scriptlink->totscript, "scriptlistF");
		memcpy(scriptlink->flag, tmp, sizeof(short)*scriptlink->totscript);
	}
}

/*
 *  Python alien graphics format conversion framework
 *
 *  $Id$
 *
 *	
 *
 */

/* import importloader module with registered importers */
#include "BPY_extern.h"
#include "Python.h"


int BPY_call_importloader(char *name)
{
	PyObject *mod, *tmp, *meth, *args;
	int i, success = 0;

	init_syspath();
	mod = PyImport_ImportModule("Converter.importloader");
	if (mod) {
		meth = PyObject_GetAttrString(mod, "process"); // new ref
		args = Py_BuildValue("(s)", name);
		tmp = PyEval_CallObject(meth, args);
		Py_DECREF(meth);
		if (PyErr_Occurred()) {
			PyErr_Print();
		}

		if (tmp) { 
			i = PyInt_AsLong(tmp);
			if (i) 
				success = 1;
			Py_DECREF(tmp);
		}
		Py_DECREF(mod);
	} else {
		PyErr_Print();
		BPY_warn(("couldn't import 'importloader' \n"));
	}
	return success;
}

// more to come...