pygame / src / base.c

  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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
/*
    pygame - Python Game Library
    Copyright (C) 2000-2001  Pete Shinners

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Pete Shinners
    pete@shinners.org
*/
#define NO_PYGAME_C_API
#define PYGAMEAPI_BASE_INTERNAL
#include "pygame.h"
#include "pygamedocs.h"
#include <signal.h>


/* This file controls all the initialization of
 * the module and the various SDL subsystems
*/

/*platform specific init stuff*/

#ifdef MS_WIN32 /*python gives us MS_WIN32*/
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include<windows.h>
extern int SDL_RegisterApp(char*, Uint32, void*);
#endif

#if defined(macintosh)
#if(!defined(__MWERKS__) && !TARGET_API_MAC_CARBON)
QDGlobals qd;
#endif
#endif

static PyObject* quitfunctions = NULL;
static PyObject* PyExc_SDLError;
static void install_parachute(void);
static void uninstall_parachute(void);
static void atexit_quit(void);


static int PyGame_Video_AutoInit(void);
static void PyGame_Video_AutoQuit(void);




static int CheckSDLVersions(void) /*compare compiled to linked*/
{
	SDL_version compiled;
	const SDL_version* linked;
	SDL_VERSION(&compiled);
	linked = SDL_Linked_Version();

	/*only check the major and minor version numbers.
	  we will relax any differences in 'patch' version.*/

	if(compiled.major != linked->major || compiled.minor != linked->minor)
	{
		char err[1024];
		sprintf(err, "SDL compiled with version %d.%d.%d, linked to %d.%d.%d",
					compiled.major, compiled.minor, compiled.patch,
					linked->major, linked->minor, linked->patch);
		PyErr_SetString(PyExc_RuntimeError, err);
		return 0;
	}
	return 1;
}


void PyGame_RegisterQuit(void(*func)(void))
{
	PyObject* obj;
	if(!quitfunctions)
	{
		quitfunctions = PyList_New(0);
		if(!quitfunctions) return;
	}
	if(func)
	{
		obj = PyCObject_FromVoidPtr(func, NULL);
		PyList_Append(quitfunctions, obj);
	}
}

static PyObject* register_quit(PyObject* self, PyObject* arg)
{
	PyObject* quitfunc;

	if(!PyArg_ParseTuple(arg, "O", &quitfunc))
		return NULL;

	if(!quitfunctions)
	{
		quitfunctions = PyList_New(0);
		if(!quitfunctions) return NULL;
	}
	PyList_Append(quitfunctions, quitfunc);

	RETURN_NONE
}


static PyObject* init(PyObject* self,PyObject* args)
{
	PyObject *allmodules, *moduleslist, *dict, *func, *result, *mod;
	int loop, num;
	int success=0, fail=0;

	if(!PyArg_ParseTuple(args, ""))
		return NULL;
	if(!CheckSDLVersions())
		return NULL;


	/*nice to initialize timer, so startup time will reflec init() time*/
	SDL_Init(
#if defined(WITH_THREAD) && !defined(MS_WIN32) && defined(SDL_INIT_EVENTTHREAD)
		SDL_INIT_EVENTTHREAD |
#endif
		SDL_INIT_TIMER |
		SDL_INIT_NOPARACHUTE);


/* initialize all pygame modules */
	allmodules = PyImport_GetModuleDict();
	moduleslist = PyDict_Values(allmodules);
	if(!allmodules || !moduleslist)
		return Py_BuildValue("(ii)", 0, 0);

	if(PyGame_Video_AutoInit())
		++success;
	else
		++fail;

	num = PyList_Size(moduleslist);
	for(loop = 0; loop < num; ++loop)
	{
		mod = PyList_GET_ITEM(moduleslist, loop);
		if(!mod || !PyModule_Check(mod))
			continue;
		dict = PyModule_GetDict(mod);
		func = PyDict_GetItemString(dict, "__PYGAMEinit__");
		if(func && PyCallable_Check(func))
		{
			result = PyObject_CallObject(func, NULL);
			if(result && PyObject_IsTrue(result))
				++success;
			else
			{
				PyErr_Clear();
				++fail;
			}
			Py_XDECREF(result);
		}
	}
	Py_DECREF(moduleslist);

	return Py_BuildValue("(ii)", success, fail);
}


static void atexit_quit(void)
{
	PyObject* quit;
	PyObject* privatefuncs;
	int num;

	if(!quitfunctions)
		return;

	privatefuncs = quitfunctions;
	quitfunctions = NULL;

	uninstall_parachute();
	num = PyList_Size(privatefuncs);

	while(num--) /*quit in reverse order*/
	{
		quit = PyList_GET_ITEM(privatefuncs, num);
		if(PyCallable_Check(quit))
			PyObject_CallObject(quit, NULL);
		else if(PyCObject_Check(quit))
		{
			void* ptr = PyCObject_AsVoidPtr(quit);
			(*(void(*)(void))ptr)();
		}
	}
	Py_DECREF(privatefuncs);

        PyGame_Video_AutoQuit();
	SDL_Quit();
}


static PyObject* get_sdl_version(PyObject* self, PyObject* args)
{
	const SDL_version *v;
	if(!PyArg_ParseTuple(args, ""))
		return NULL;
	
	v = SDL_Linked_Version();
	return Py_BuildValue("iii", v->major, v->minor, v->patch);
}


static PyObject* quit(PyObject* self, PyObject* args)
{
	if(!PyArg_ParseTuple(args, ""))
		return NULL;

	atexit_quit();

	Py_INCREF(Py_None);
	return Py_None;
}




/* internal C API utility functions */
static int IntFromObj(PyObject* obj, int* val)
{
	PyObject* intobj;

	if(PyNumber_Check(obj))
	{
		if(!(intobj = PyNumber_Int(obj)))
                {
                        PyErr_Clear();
			return 0;
                }
		*val = PyInt_AsLong(intobj);
		Py_DECREF(intobj);
                if(PyErr_Occurred())
                {
                    PyErr_Clear();
                    return 0;
                }
		return 1;
	}
	return 0;
}

static int IntFromObjIndex(PyObject* obj, int index, int* val)
{
	int result = 0;
	PyObject* item;
	item = PySequence_GetItem(obj, index);
	if(item)
	{
		result = IntFromObj(item, val);
		Py_DECREF(item);
	}
	return result;
}

static int TwoIntsFromObj(PyObject* obj, int* val1, int* val2)
{
	if(PyTuple_Check(obj) && PyTuple_Size(obj)==1)
		return TwoIntsFromObj(PyTuple_GET_ITEM(obj, 0), val1, val2);

	if(!PySequence_Check(obj) || PySequence_Length(obj) != 2)
		return 0;

	if(!IntFromObjIndex(obj, 0, val1) || !IntFromObjIndex(obj, 1, val2))
		return 0;

	return 1;
}


static int FloatFromObj(PyObject* obj, float* val)
{
	PyObject* floatobj;

	if(PyNumber_Check(obj))
	{
		if(!(floatobj = PyNumber_Float(obj)))
			return 0;
		*val = (float)PyFloat_AsDouble(floatobj);
		Py_DECREF(floatobj);
		return 1;
	}
	return 0;
}

static int FloatFromObjIndex(PyObject* obj, int index, float* val)
{
	int result = 0;
	PyObject* item;
	item = PySequence_GetItem(obj, index);
	if(item)
	{
		result = FloatFromObj(item, val);
		Py_DECREF(item);
	}
	return result;
}

static int TwoFloatsFromObj(PyObject* obj, float* val1, float* val2)
{
	if(PyTuple_Check(obj) && PyTuple_Size(obj)==1)
		return TwoFloatsFromObj(PyTuple_GET_ITEM(obj, 0), val1, val2);

	if(!PySequence_Check(obj) || PySequence_Length(obj) != 2)
		return 0;

	if(!FloatFromObjIndex(obj, 0, val1) || !FloatFromObjIndex(obj, 1, val2))
		return 0;

	return 1;
}


static int UintFromObj(PyObject* obj, Uint32* val)
{
	PyObject* intobj;

	if(PyNumber_Check(obj))
	{
		if(!(intobj = PyNumber_Int(obj)))
			return 0;
		*val = (Uint32)PyInt_AsLong(intobj);
		Py_DECREF(intobj);
		return 1;
	}
	return 0;
}

static Uint32 UintFromObjIndex(PyObject* obj, int index, Uint32* val)
{
	int result = 0;
	PyObject* item;
	item = PySequence_GetItem(obj, index);
	if(item)
	{
		result = UintFromObj(item, val);
		Py_DECREF(item);
	}
	return result;
}

static int RGBAFromObj(PyObject* obj, Uint8* RGBA)
{
	int length;
	Uint32 val;
	if(PyTuple_Check(obj) && PyTuple_Size(obj)==1)
		return RGBAFromObj(PyTuple_GET_ITEM(obj, 0), RGBA);

	if(!PySequence_Check(obj))
		return 0;

	length = PySequence_Length(obj);
	if(length < 3 || length > 4)
		return 0;

	if(!UintFromObjIndex(obj, 0, &val) || val > 255)
		return 0;
	RGBA[0] = (Uint8)val;
	if(!UintFromObjIndex(obj, 1, &val) || val > 255)
		return 0;
	RGBA[1] = (Uint8)val;
	if(!UintFromObjIndex(obj, 2, &val) || val > 255)
		return 0;
	RGBA[2] = (Uint8)val;
	if(length == 4)
	{
		if(!UintFromObjIndex(obj, 3, &val) || val > 255)
			return 0;
		RGBA[3] = (Uint8)val;
	}
	else RGBA[3] = (Uint8)255;

	return 1;
}



static PyObject* get_error(PyObject* self, PyObject* arg)
{
	if(!PyArg_ParseTuple(arg, ""))
		return NULL;
	return PyString_FromString(SDL_GetError());
}




/*video init needs to be here, because of it's
 *important init order priority
 */
static void PyGame_Video_AutoQuit(void)
{
	if(SDL_WasInit(SDL_INIT_VIDEO))
		SDL_QuitSubSystem(SDL_INIT_VIDEO);
}

static int PyGame_Video_AutoInit(void)
{
	if(!SDL_WasInit(SDL_INIT_VIDEO))
	{
		int status;
#if defined(__APPLE__) && defined(darwin)
		PyObject *module;
		PyObject *rval;
		module = PyImport_ImportModule("pygame.macosx");
		if (!module) {
			return -1;
		}
		rval = PyObject_CallMethod(module, "init", "");
		Py_DECREF(module);
		if (!rval) {
			return -1;
		}
		status = PyObject_IsTrue(rval);
		Py_DECREF(rval);
		if (status != 1) {
			return 0;
		}
#endif
		status = SDL_InitSubSystem(SDL_INIT_VIDEO);
		if(status)
			return 0;
		SDL_EnableUNICODE(1);
                /*we special case the video quit to last now*/
		/*PyGame_RegisterQuit(PyGame_Video_AutoQuit);*/
	}
	return 1;
}


#if 0
#include<pystate.h>
#include<compile.h>
#include<frameobject.h>

#ifdef MPW
	/* This is needed by MPW's File and Line commands */
#define FMT "  File \"%.500s\"; line %d # in %.500s\n"
#else
	/* This is needed by Emacs' compile command */
#define FMT "  File \"%.500s\", line %d, in %.500s\n"
#endif

static void print_traceback(PyObject *tb)
{
    PyObject *next;
    while(tb && tb != Py_None)
    {
	    PyFrameObject *frame;
	    PyObject *getobj;
	    int line, lasti;
	    const char *filename, *name;

	    frame = (PyFrameObject*)PyObject_GetAttrString(tb, "tb_frame");
	    Py_DECREF(frame); //won't really kill it
	    getobj = PyObject_GetAttrString(tb, "tb_lineno");
	    line = PyInt_AsLong(getobj);
	    Py_DECREF(getobj);

	    filename = PyString_AsString(frame->f_code->co_filename);
	    name = PyString_AsString(frame->f_code->co_name);
	    if (Py_OptimizeFlag)
	    {
		    getobj = PyObject_GetAttrString(tb, "tb_lasti");
		    lasti = PyInt_AsLong(getobj);
		    Py_DECREF(getobj);
		    line = PyCode_Addr2Line(frame->f_code, lasti);
	    }
	    fprintf(stderr, FMT, filename, line, name);
	    next = PyObject_GetAttrString(tb, "tb_next");
	    Py_DECREF(tb);
	    tb = next;
    }
}
#endif

/*error signal handlers (replacing SDL parachute)*/
static void pygame_parachute(int sig)
{
	char* signaltype;
#if 0
	PyThreadState* thread;
	PyInterpreterState *interp;
	int thread_id;
#endif
    
	signal(sig, SIG_DFL);
	switch (sig)
	{
		case SIGSEGV:
			signaltype = "(pygame parachute) Segmentation Fault"; break;
#ifdef SIGBUS
#if SIGBUS != SIGSEGV
		case SIGBUS:
			signaltype = "(pygame parachute) Bus Error"; break;
#endif
#endif
#ifdef SIGFPE
		case SIGFPE:
			signaltype = "(pygame parachute) Floating Point Exception"; break;
#endif
#ifdef SIGQUIT
		case SIGQUIT:
			signaltype = "(pygame parachute) Keyboard Abort"; break;
#endif
		default:
			signaltype = "(pygame parachute) Unknown Signal"; break;
	}

#if 0
/*this traceback hacking has gotten a bit treacherous*/
	printf("Pygame Parachute Traceback:\n");
	interp = PyInterpreterState_Head();
	thread=PyInterpreterState_ThreadHead(interp);
	if(PyThreadState_Next(thread)) /*multithreaded*/
	    thread_id = 0;
	else
	    thread_id = -1; /*no threads, don't print thread info*/
	for(; thread; thread = PyThreadState_Next(thread))
	{
	    if(thread_id >= 0)
	    {
		printf("Thread-%p\n", thread);
		thread_id++;
	    }
	    PyTraceBack_Here(thread->frame);
	    Py_INCREF(thread->curexc_traceback);
	    print_traceback(thread->curexc_traceback);
	}
#endif
	atexit_quit();
	Py_FatalError(signaltype);
}


static int fatal_signals[] =
{
	SIGSEGV,
#ifdef SIGBUS
	SIGBUS,
#endif
#ifdef SIGFPE
	SIGFPE,
#endif
#ifdef SIGQUIT
	SIGQUIT,
#endif
	0 /*end of list*/
};

static int parachute_installed = 0;
static void install_parachute(void)
{
	int i;
	void (*ohandler)(int);

	if(parachute_installed)
	    return;
	parachute_installed = 1;

	/* Set a handler for any fatal signal not already handled */
	for ( i=0; fatal_signals[i]; ++i )
	{
		ohandler = signal(fatal_signals[i], pygame_parachute);
		if ( ohandler != SIG_DFL )
			signal(fatal_signals[i], ohandler);
	}
#ifdef SIGALRM
	{/* Set SIGALRM to be ignored -- necessary on Solaris */
		struct sigaction action, oaction;
		/* Set SIG_IGN action */
		memset(&action, 0, (sizeof action));
		action.sa_handler = SIG_IGN;
		sigaction(SIGALRM, &action, &oaction);
		/* Reset original action if it was already being handled */
		if ( oaction.sa_handler != SIG_DFL )
			sigaction(SIGALRM, &oaction, NULL);
	}
#endif
	return;
}


static void uninstall_parachute(void)
{
	int i;
	void (*ohandler)(int);

	if(!parachute_installed)
	    return;
	parachute_installed = 0;

	/* Remove a handler for any fatal signal handled */
	for ( i=0; fatal_signals[i]; ++i ) {
		ohandler = signal(fatal_signals[i], SIG_DFL);
		if ( ohandler != pygame_parachute )
			signal(fatal_signals[i], ohandler);
	}
}




/* bind functions to python */

static PyObject* do_segfault(PyObject* self, PyObject* args)
{
    //force crash
    *((int*)1) = 45;
    memcpy((char*)2, (char*)3, 10);
    RETURN_NONE
}


static PyMethodDef init__builtins__[] =
{
	{ "init", init, 1, DOC_PYGAMEINIT },
	{ "quit", quit, 1, DOC_PYGAMEQUIT },
	{ "register_quit", register_quit, 1, DOC_PYGAMEREGISTERQUIT },
	{ "get_error", get_error, 1, DOC_PYGAMEGETERROR },
	{ "get_sdl_version", get_sdl_version, 1, DOC_PYGAMEGETSDLVERSION },

	{ "segfault", do_segfault, 1, "crash" },
	{ NULL, NULL }
};



PYGAME_EXPORT
void initbase(void)
{
	PyObject *module, *dict, *apiobj;
	static void* c_api[PYGAMEAPI_BASE_NUMSLOTS];

    /* create the module */
	module = Py_InitModule3("base", init__builtins__, DOC_PYGAME);
	dict = PyModule_GetDict(module);

	/* create the exceptions */
	PyExc_SDLError = PyErr_NewException("pygame.error", PyExc_RuntimeError, NULL);
	PyDict_SetItemString(dict, "error", PyExc_SDLError);
	Py_DECREF(PyExc_SDLError);

	/* export the c api */
	c_api[0] = PyExc_SDLError;
	c_api[1] = PyGame_RegisterQuit;
	c_api[2] = IntFromObj;
	c_api[3] = IntFromObjIndex;
	c_api[4] = TwoIntsFromObj;
	c_api[5] = FloatFromObj;
	c_api[6] = FloatFromObjIndex;
	c_api[7] = TwoFloatsFromObj;
	c_api[8] = UintFromObj;
	c_api[9] = UintFromObjIndex;
	c_api[10] = PyGame_Video_AutoQuit;
	c_api[11] = PyGame_Video_AutoInit;
	c_api[12] = RGBAFromObj;
	apiobj = PyCObject_FromVoidPtr(c_api, NULL);
	PyDict_SetItemString(dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
	Py_DECREF(apiobj);

	/*some intiialization*/
	Py_AtExit(atexit_quit);
	install_parachute();
#ifdef MS_WIN32
	SDL_RegisterApp("pygame", 0, GetModuleHandle(NULL));
#endif
#if defined(macintosh)
#if(!defined(__MWERKS__) && !TARGET_API_MAC_CARBON)
	SDL_InitQuickDraw(&qd);
#endif
#endif
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.