Source

pygame / src / event.c

Full commit
  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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
/*
  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
*/

/*
 *  pygame event module
 */
#define PYGAMEAPI_EVENT_INTERNAL
#include "pygame.h"
#include "pygamedocs.h"

// FIXME: The system message code is only tested on windows, so only
//          include it there for now.
#include <SDL_syswm.h>

/*this user event object is for safely passing
 *objects through the event queue.
 */

#define USEROBJECT_CHECK1 0xDEADBEEF
#define USEROBJECT_CHECK2 0xFEEDF00D

typedef struct UserEventObject
{
    struct UserEventObject* next;
    PyObject* object;
} UserEventObject;

static UserEventObject* user_event_objects = NULL;

/*must pass dictionary as this object*/
static UserEventObject*
user_event_addobject (PyObject* obj)
{
    UserEventObject* userobj = PyMem_New (UserEventObject, 1);
    if (!userobj)
        return NULL;

    Py_INCREF (obj);
    userobj->next = user_event_objects;
    userobj->object = obj;
    user_event_objects = userobj;

    return userobj;
}

/*note, we doublecheck to make sure the pointer is in our list,
 *not just some random pointer. this will keep us safe(r).
 */
static PyObject*
user_event_getobject (UserEventObject* userobj)
{
    PyObject* obj = NULL;
    if (!user_event_objects) /*fail in most common case*/
        return NULL;
    if (user_event_objects == userobj)
    {
        obj = userobj->object;
        user_event_objects = userobj->next;
    }
    else
    {
        UserEventObject* hunt = user_event_objects;
        while (hunt && hunt->next != userobj)
            hunt = hunt->next;
        if (hunt)
        {
            hunt->next = userobj->next;
            obj = userobj->object;
        }
    }
    if (obj)
        PyMem_Del (userobj);
    return obj;
}

static void
user_event_cleanup (void)
{
    if (user_event_objects)
    {
        UserEventObject *hunt, *kill;
        hunt = user_event_objects;
        while (hunt)
        {
            kill = hunt;
            hunt = hunt->next;
            Py_DECREF (kill->object);
            PyMem_Del (kill);
        }
        user_event_objects = NULL;
    }
}

static int PyEvent_FillUserEvent (PyEventObject *e, SDL_Event *event)
{
    UserEventObject *userobj = user_event_addobject (e->dict);
    if (!userobj)
        return -1;

    event->type = e->type;
    event->user.code = USEROBJECT_CHECK1;
    event->user.data1 = (void*)USEROBJECT_CHECK2;
    event->user.data2 = userobj;
    return 0;
}

staticforward PyTypeObject PyEvent_Type;
static PyObject* PyEvent_New (SDL_Event*);
static PyObject* PyEvent_New2 (int, PyObject*);
#define PyEvent_Check(x) ((x)->ob_type == &PyEvent_Type)

static char*
name_from_eventtype (int type)
{
    switch (type)
    {
    case SDL_ACTIVEEVENT:
	return "ActiveEvent";
    case SDL_KEYDOWN:
        return "KeyDown";
    case SDL_KEYUP:
        return "KeyUp";
    case SDL_MOUSEMOTION:
	return "MouseMotion";
    case SDL_MOUSEBUTTONDOWN:
        return "MouseButtonDown";
    case SDL_MOUSEBUTTONUP:
        return "MouseButtonUp";
    case SDL_JOYAXISMOTION:
        return "JoyAxisMotion";
    case SDL_JOYBALLMOTION:
        return "JoyBallMotion";
    case SDL_JOYHATMOTION:
	return "JoyHatMotion";
    case SDL_JOYBUTTONUP:
	return "JoyButtonUp";
    case SDL_JOYBUTTONDOWN:
        return "JoyButtonDown";
    case SDL_QUIT:
        return "Quit";
    case SDL_SYSWMEVENT:
	return "SysWMEvent";
    case SDL_VIDEORESIZE:
	return "VideoResize";
    case SDL_VIDEOEXPOSE:
	return "VideoExpose";
    case SDL_NOEVENT:
        return "NoEvent";
    }
    if (type >= SDL_USEREVENT && type < SDL_NUMEVENTS)
        return "UserEvent";
    return "Unknown";
}

/* Helper for adding objects to dictionaries. Check for errors with
   PyErr_Occurred() */
static void
insobj (PyObject *dict, char *name, PyObject *v)
{
    if(v)
    {
        PyDict_SetItemString (dict, name, v);
        Py_DECREF (v);
    }
}

#ifdef Py_USING_UNICODE

static PyObject*
our_unichr (long uni)
{
    static PyObject* bltin_unichr = NULL;

    if (bltin_unichr == NULL)
    {
        PyObject* bltins;

        bltins = PyImport_ImportModule ("__builtin__");
        bltin_unichr = PyObject_GetAttrString (bltins, "unichr");
        Py_DECREF (bltins);
    }
    return PyEval_CallFunction (bltin_unichr, "(l)", uni);
}

static PyObject*
our_empty_ustr (void)
{
    static PyObject* empty_ustr = NULL;

    if (empty_ustr == NULL)
    {
        PyObject* bltins;
        PyObject* bltin_unicode;

        bltins = PyImport_ImportModule ("__builtin__");
        bltin_unicode = PyObject_GetAttrString (bltins, "unicode");
        empty_ustr = PyEval_CallFunction (bltin_unicode, "(s)", "");
        Py_DECREF (bltin_unicode);
        Py_DECREF (bltins);
    }

    Py_INCREF (empty_ustr);

    return empty_ustr;
}

#else

static PyObject*
our_unichr (long uni)
{
    return PyInt_FromLong (uni);
}

static PyObject*
our_empty_ustr (void)
{
    return PyInt_FromLong (0);
}

#endif /* Py_USING_UNICODE */

static PyObject*
dict_from_event (SDL_Event* event)
{
    PyObject *dict=NULL, *tuple, *obj;
    int hx, hy;

    /*check if it is an event the user posted*/
    if (event->user.code == USEROBJECT_CHECK1
        && event->user.data1 == (void*)USEROBJECT_CHECK2)
    {
        dict = user_event_getobject ((UserEventObject*)event->user.data2);
        if (dict)
            return dict;
    }

    if (!(dict = PyDict_New ()))
        return NULL;
    switch (event->type)
    {
    case SDL_ACTIVEEVENT:
        insobj (dict, "gain", PyInt_FromLong (event->active.gain));
        insobj (dict, "state", PyInt_FromLong (event->active.state));
        break;
    case SDL_KEYDOWN:
        if (event->key.keysym.unicode)
            insobj (dict, "unicode", our_unichr (event->key.keysym.unicode));
        else
            insobj (dict, "unicode", our_empty_ustr ());
    case SDL_KEYUP:
        insobj (dict, "key", PyInt_FromLong (event->key.keysym.sym));
        insobj (dict, "mod", PyInt_FromLong (event->key.keysym.mod));
        insobj (dict, "scancode", PyInt_FromLong (event->key.keysym.scancode));
        break;
    case SDL_MOUSEMOTION:
        obj = Py_BuildValue ("(ii)", event->motion.x, event->motion.y);
        insobj (dict, "pos", obj);
        obj = Py_BuildValue ("(ii)", event->motion.xrel, event->motion.yrel);
        insobj (dict, "rel", obj);
        if ((tuple = PyTuple_New (3)))
        {
            PyTuple_SET_ITEM
                (tuple, 0,
                 PyInt_FromLong ((event->motion.state&SDL_BUTTON(1)) != 0));
            PyTuple_SET_ITEM
                (tuple, 1,
                 PyInt_FromLong ((event->motion.state&SDL_BUTTON(2)) != 0));
            PyTuple_SET_ITEM
                (tuple, 2,
                 PyInt_FromLong ((event->motion.state&SDL_BUTTON(3)) != 0));
            insobj (dict, "buttons", tuple);
        }
        break;
    case SDL_MOUSEBUTTONDOWN:
    case SDL_MOUSEBUTTONUP:
        obj = Py_BuildValue ("(ii)", event->button.x, event->button.y);
        insobj (dict, "pos", obj);
        insobj (dict, "button", PyInt_FromLong (event->button.button));
        break;
    case SDL_JOYAXISMOTION:
        insobj (dict, "joy", PyInt_FromLong (event->jaxis.which));
        insobj (dict, "axis", PyInt_FromLong (event->jaxis.axis));
        insobj (dict, "value", PyFloat_FromDouble (event->jaxis.value/32767.0));
        break;
    case SDL_JOYBALLMOTION:
        insobj (dict, "joy", PyInt_FromLong (event->jball.which));
        insobj (dict, "ball", PyInt_FromLong (event->jball.ball));
        obj = Py_BuildValue ("(ii)", event->jball.xrel, event->jball.yrel);
        insobj (dict, "rel", obj);
        break;
    case SDL_JOYHATMOTION:
        insobj (dict, "joy", PyInt_FromLong (event->jhat.which));
        insobj (dict, "hat", PyInt_FromLong (event->jhat.hat));
        hx = hy = 0;
        if (event->jhat.value&SDL_HAT_UP)
            hy = 1;
        else if (event->jhat.value&SDL_HAT_DOWN)
            hy = -1;
        if (event->jhat.value&SDL_HAT_RIGHT)
            hx = 1;
        else if (event->jhat.value&SDL_HAT_LEFT)
            hx = -1;
        insobj (dict, "value", Py_BuildValue ("(ii)", hx, hy));
        break;
    case SDL_JOYBUTTONUP:
    case SDL_JOYBUTTONDOWN:
        insobj (dict, "joy", PyInt_FromLong (event->jbutton.which));
        insobj (dict, "button", PyInt_FromLong (event->jbutton.button));
        break;
    case SDL_VIDEORESIZE:
        obj = Py_BuildValue ("(ii)", event->resize.w, event->resize.h);
        insobj (dict, "size", obj);
        insobj (dict, "w", PyInt_FromLong (event->resize.w));
        insobj (dict, "h", PyInt_FromLong (event->resize.h));
        break;
    case SDL_SYSWMEVENT:
#ifdef WIN32
        insobj (dict, "hwnd", PyInt_FromLong ((long)(event-> syswm.msg->hwnd)));
        insobj (dict, "msg", PyInt_FromLong (event-> syswm.msg->msg));
        insobj (dict, "wparam", PyInt_FromLong (event-> syswm.msg->wParam));
        insobj (dict, "lparam", PyInt_FromLong (event-> syswm.msg->lParam));
#endif
        /*
         * Make the event
         */
#if (defined(unix) || defined(__unix__) || defined(_AIX)        \
     || defined(__OpenBSD__)) &&                                \
    (!defined(DISABLE_X11) && !defined(__CYGWIN32__) &&         \
     !defined(ENABLE_NANOX) && !defined(__QNXNTO__))

        //printf("asdf :%d:", event->syswm.msg->event.xevent.type);
        insobj (dict,  "event",
               PyString_FromStringAndSize
                ((char*) & (event->syswm.msg->event.xevent), sizeof (XEvent)));
#endif

        break;
/* SDL_VIDEOEXPOSE and SDL_QUIT have no attributes */
    }
    if (event->type >= SDL_USEREVENT && event->type < SDL_NUMEVENTS)
        insobj (dict, "code", PyInt_FromLong (event->user.code));

    return dict;
}

/* event object internals */

static void
event_dealloc (PyObject* self)
{
    PyEventObject* e = (PyEventObject*)self;
    Py_XDECREF (e->dict);
    PyObject_DEL (self);
}

static PyObject*
event_getattr (PyObject *self, char *name)
{
    PyEventObject* e = (PyEventObject*)self;
    PyObject* item;

    if (!strcmp (name, "type"))
        return PyInt_FromLong (e->type);

    if (!strcmp (name, "dict"))
    {
        Py_INCREF (e->dict);
        return e->dict;
    }

    item = PyDict_GetItemString (e->dict, name);
    if(item)
        Py_INCREF (item);
    else
        RAISE (PyExc_AttributeError, "event member not defined");
    return item;
}

PyObject*
event_str (PyObject* self)
{
    PyEventObject* e = (PyEventObject*)self;
    char str[1024];
    PyObject *strobj;

    strobj = PyObject_Str (e->dict);
    sprintf (str, "<Event(%d-%s %s)>", e->type, name_from_eventtype (e->type),
             PyString_AsString (strobj));

    Py_DECREF (strobj);
    return PyString_FromString (str);
}

static int
event_nonzero (PyEventObject *self)
{
    return self->type != SDL_NOEVENT;
}

static PyNumberMethods event_as_number = {
    (binaryfunc)NULL,		/*add*/
    (binaryfunc)NULL,		/*subtract*/
    (binaryfunc)NULL,		/*multiply*/
    (binaryfunc)NULL,		/*divide*/
    (binaryfunc)NULL,		/*remainder*/
    (binaryfunc)NULL,		/*divmod*/
    (ternaryfunc)NULL,		/*power*/
    (unaryfunc)NULL,		/*negative*/
    (unaryfunc)NULL,		/*pos*/
    (unaryfunc)NULL,		/*abs*/
    (inquiry)event_nonzero,	/*nonzero*/
    (unaryfunc)NULL,		/*invert*/
    (binaryfunc)NULL,		/*lshift*/
    (binaryfunc)NULL,		/*rshift*/
    (binaryfunc)NULL,		/*and*/
    (binaryfunc)NULL,		/*xor*/
    (binaryfunc)NULL,		/*or*/
    (coercion)NULL,			/*coerce*/
    (unaryfunc)NULL,		/*int*/
    (unaryfunc)NULL,		/*long*/
    (unaryfunc)NULL,		/*float*/
    (unaryfunc)NULL,		/*oct*/
    (unaryfunc)NULL,		/*hex*/
};


static PyTypeObject PyEvent_Type =
{
    PyObject_HEAD_INIT(NULL)
    0,						/*size*/
    "Event",				/*name*/
    sizeof(PyEventObject),	/*basic size*/
    0,						/*itemsize*/
    event_dealloc,			/*dealloc*/
    0,						/*print*/
    event_getattr,			/*getattr*/
    NULL,					/*setattr*/
    NULL,					/*compare*/
    event_str,				/*repr*/
    &event_as_number,		/*as_number*/
    NULL,					/*as_sequence*/
    NULL,					/*as_mapping*/
    (hashfunc)NULL, 		/*hash*/
    (ternaryfunc)NULL,		/*call*/
    (reprfunc)NULL, 		/*str*/
    0L,0L,0L,0L,
    DOC_PYGAMEEVENTEVENT /* Documentation string */
};

static PyObject*
PyEvent_New (SDL_Event* event)
{
    PyEventObject* e;
    e = PyObject_NEW (PyEventObject, &PyEvent_Type);
    if(!e)
        return NULL;

    if (event)
    {
        e->type = event->type;
        e->dict = dict_from_event (event);
    }
    else
    {
        e->type = SDL_NOEVENT;
        e->dict = PyDict_New ();
    }
    return (PyObject*)e;
}

static PyObject*
PyEvent_New2 (int type, PyObject* dict)
{
    PyEventObject* e;
    e = PyObject_NEW (PyEventObject, &PyEvent_Type);
    if (e)
    {
        e->type = type;
        if (!dict)
            dict = PyDict_New ();
        else
            Py_INCREF (dict);
        e->dict = dict;
    }
    return (PyObject*)e;
}

/* event module functions */
static PyObject*
Event (PyObject* self, PyObject* arg, PyObject* keywords)
{
    PyObject* dict = NULL;
    PyObject* event;
    int type;
    if (!PyArg_ParseTuple (arg, "i|O!", &type, &PyDict_Type, &dict))
        return NULL;

    if (!dict)
        dict = PyDict_New ();
    else
        Py_INCREF (dict);

    if (keywords)
    {
        PyObject *key, *value;
        Py_ssize_t pos  = 0;
        while (PyDict_Next (keywords, &pos, &key, &value))
            PyDict_SetItem (dict, key, value);
    }

    event = PyEvent_New2 (type, dict);

    Py_DECREF (dict);
    return event;
}

static PyObject*
event_name (PyObject* self, PyObject* arg)
{
    int type;

    if (!PyArg_ParseTuple (arg, "i", &type))
        return NULL;

    return PyString_FromString (name_from_eventtype (type));
}

static PyObject*
set_grab (PyObject* self, PyObject* arg)
{
    int doit;
    if (!PyArg_ParseTuple (arg, "i", &doit))
        return NULL;
    VIDEO_INIT_CHECK ();

    if (doit)
        SDL_WM_GrabInput (SDL_GRAB_ON);
    else
        SDL_WM_GrabInput (SDL_GRAB_OFF);

    Py_RETURN_NONE;
}

static PyObject*
get_grab (PyObject* self, PyObject* arg)
{
    int mode;

    VIDEO_INIT_CHECK ();
    mode = SDL_WM_GrabInput (SDL_GRAB_QUERY);
    return PyInt_FromLong (mode == SDL_GRAB_ON);
}

static PyObject*
pygame_pump (PyObject* self, PyObject* args)
{
    VIDEO_INIT_CHECK ();
    SDL_PumpEvents ();
    Py_RETURN_NONE;
}

static PyObject*
pygame_wait (PyObject* self, PyObject* args)
{
    SDL_Event event;
    int status;

    VIDEO_INIT_CHECK ();

    Py_BEGIN_ALLOW_THREADS;
    status = SDL_WaitEvent (&event);
    Py_END_ALLOW_THREADS;

    if (!status)
        return RAISE (PyExc_SDLError, SDL_GetError ());

    return PyEvent_New (&event);
}

static PyObject*
pygame_poll (PyObject* self, PyObject* args)
{
    SDL_Event event;

    VIDEO_INIT_CHECK ();

    if (SDL_PollEvent (&event))
        return PyEvent_New (&event);
    return PyEvent_New (NULL);
}

static PyObject*
event_clear (PyObject* self, PyObject* args)
{
    SDL_Event event;
    int mask = 0;
    int loop, num;
    PyObject* type;
    int val;

    if (PyTuple_Size (args) != 0 && PyTuple_Size (args) != 1)
        return RAISE (PyExc_ValueError, "get requires 0 or 1 argument");

    VIDEO_INIT_CHECK ();

    if (PyTuple_Size (args) == 0)
        mask = SDL_ALLEVENTS;
    else
    {
        type = PyTuple_GET_ITEM (args, 0);
        if(PySequence_Check (type))
        {
            num = PySequence_Size (type);
            for(loop = 0; loop < num; ++loop)
            {
                if (!IntFromObjIndex (type, loop, &val))
                    return RAISE
                        (PyExc_TypeError,
                         "type sequence must contain valid event types");
                mask |= SDL_EVENTMASK (val);
            }
        }
        else if (IntFromObj (type, &val))
            mask = SDL_EVENTMASK (val);
        else
            return RAISE (PyExc_TypeError,
                          "get type must be numeric or a sequence");
    }

    SDL_PumpEvents ();

    while (SDL_PeepEvents (&event, 1, SDL_GETEVENT, mask) == 1)
    {}

    Py_RETURN_NONE;
}

static PyObject*
event_get (PyObject* self, PyObject* args)
{
    SDL_Event event;
    int mask = 0;
    int loop, num;
    PyObject* type, *list, *e;
    int val;

    if (PyTuple_Size (args) != 0 && PyTuple_Size (args) != 1)
        return RAISE (PyExc_ValueError, "get requires 0 or 1 argument");

    VIDEO_INIT_CHECK ();

    if (PyTuple_Size (args) == 0)
        mask = SDL_ALLEVENTS;
    else
    {
        type = PyTuple_GET_ITEM (args, 0);
        if (PySequence_Check (type))
        {
            num = PySequence_Size (type);
            for(loop = 0; loop < num; ++loop)
            {
                if (!IntFromObjIndex (type, loop, &val))
                    return RAISE
                        (PyExc_TypeError,
                         "type sequence must contain valid event types");
                mask |= SDL_EVENTMASK (val);
            }
        }
        else if (IntFromObj (type, &val))
            mask = SDL_EVENTMASK (val);
        else
            return RAISE (PyExc_TypeError,
                          "get type must be numeric or a sequence");
    }

    list = PyList_New (0);
    if (!list)
        return NULL;

    SDL_PumpEvents ();

    while (SDL_PeepEvents (&event, 1, SDL_GETEVENT, mask) == 1)
    {
        e = PyEvent_New (&event);
        if (!e)
        {
            Py_DECREF (list);
            return NULL;
        }

        PyList_Append (list, e);
        Py_DECREF (e);
    }
    return list;
}

static PyObject*
event_peek (PyObject* self, PyObject* args)
{
    SDL_Event event;
    int result;
    int mask = 0;
    int loop, num, noargs=0;
    PyObject* type;
    int val;

    if (PyTuple_Size (args) != 0 && PyTuple_Size (args) != 1)
        return RAISE (PyExc_ValueError, "peek requires 0 or 1 argument");

    VIDEO_INIT_CHECK ();

    if (PyTuple_Size (args) == 0)
    {
        mask = SDL_ALLEVENTS;
        noargs=1;
    }
    else
    {
        type = PyTuple_GET_ITEM (args, 0);
        if(PySequence_Check (type))
        {
            num = PySequence_Size (type);
            for(loop = 0; loop < num; ++loop)
            {
                if (!IntFromObjIndex (type, loop, &val))
                    return RAISE
                        (PyExc_TypeError,
                         "type sequence must contain valid event types");
                mask |= SDL_EVENTMASK (val);
            }
        }
        else if (IntFromObj (type, &val))
            mask = SDL_EVENTMASK (val);
        else
            return RAISE (PyExc_TypeError,
                          "peek type must be numeric or a sequence");
    }

    SDL_PumpEvents ();
    result = SDL_PeepEvents (&event, 1, SDL_PEEKEVENT, mask);

    if (noargs)
        return PyEvent_New (&event);
    return PyInt_FromLong (result == 1);
}

static PyObject*
event_post (PyObject* self, PyObject* args)
{
    PyEventObject* e;
    SDL_Event event;

    if (!PyArg_ParseTuple (args, "O!", &PyEvent_Type, &e))
        return NULL;

    VIDEO_INIT_CHECK ();

    if (PyEvent_FillUserEvent (e, &event))
        return NULL;

    if (SDL_PushEvent (&event) == -1)
        return RAISE (PyExc_SDLError, "Event queue full");

    Py_RETURN_NONE;
}

static int
CheckEventInRange(int evt)
{
    return evt >= 0 && evt < SDL_NUMEVENTS;
}

static PyObject*
set_allowed (PyObject* self, PyObject* args)
{
    int loop, num;
    PyObject* type;
    int val;

    if (PyTuple_Size (args) != 1)
        return RAISE (PyExc_ValueError, "set_allowed requires 1 argument");

    VIDEO_INIT_CHECK ();

    type = PyTuple_GET_ITEM (args, 0);
    if (PySequence_Check (type))
    {
        num = PySequence_Length (type);
        for(loop = 0; loop < num; ++loop)
        {
            if (!IntFromObjIndex (type, loop, &val))
                return RAISE (PyExc_TypeError,
                              "type sequence must contain valid event types");
            if(!CheckEventInRange(val))
                return RAISE (PyExc_ValueError, "Invalid event in sequence");
            SDL_EventState ((Uint8)val, SDL_ENABLE);
        }
    }
    else if (type == Py_None)
        SDL_EventState ((Uint8)0xFF, SDL_IGNORE);
    else if (IntFromObj (type, &val))
    {
        if(!CheckEventInRange (val))
            return RAISE (PyExc_ValueError, "Invalid event");
        SDL_EventState ((Uint8)val, SDL_ENABLE);
    }
    else
        return RAISE (PyExc_TypeError, "type must be numeric or a sequence");

    Py_RETURN_NONE;
}

static PyObject*
set_blocked (PyObject* self, PyObject* args)
{
    int loop, num;
    PyObject* type;
    int val;

    if (PyTuple_Size (args) != 1)
        return RAISE (PyExc_ValueError, "set_blocked requires 1 argument");

    VIDEO_INIT_CHECK ();

    type = PyTuple_GET_ITEM (args, 0);
    if (PySequence_Check (type))
    {
        num = PySequence_Length (type);
        for(loop = 0; loop < num; ++loop)
        {
            if (!IntFromObjIndex (type, loop, &val))
                return RAISE (PyExc_TypeError,
                              "type sequence must contain valid event types");
            if(!CheckEventInRange(val))
                return RAISE (PyExc_ValueError, "Invalid event in sequence");
            SDL_EventState ((Uint8)val, SDL_IGNORE);
        }
    }
    else if (type == Py_None)
        SDL_EventState ((Uint8)0xFF, SDL_IGNORE);
    else if (IntFromObj (type, &val))
    {
        if(!CheckEventInRange (val))
            return RAISE (PyExc_ValueError, "Invalid event");
        SDL_EventState ((Uint8)val, SDL_IGNORE);
    }
    else
        return RAISE (PyExc_TypeError, "type must be numeric or a sequence");

    Py_RETURN_NONE;
}

static PyObject*
get_blocked (PyObject* self, PyObject* args)
{
    int loop, num;
    PyObject* type;
    int val;
    int isblocked = 0;

    if (PyTuple_Size (args) != 1)
        return RAISE (PyExc_ValueError, "get_blocked requires 1 argument");

    VIDEO_INIT_CHECK ();

    type = PyTuple_GET_ITEM (args, 0);
    if (PySequence_Check (type))
    {
        num = PySequence_Length (type);
        for (loop = 0; loop < num; ++loop)
        {
            if (!IntFromObjIndex (type, loop, &val))
                return RAISE (PyExc_TypeError,
                              "type sequence must contain valid event types");
            if(!CheckEventInRange(val))
                return RAISE (PyExc_ValueError, "Invalid event in sequence");
            isblocked |= SDL_EventState ((Uint8)val, SDL_QUERY) == SDL_IGNORE;
        }
    }
    else if (IntFromObj (type, &val))
    {
        if(!CheckEventInRange (val))
            return RAISE (PyExc_ValueError, "Invalid event");
        isblocked = SDL_EventState ((Uint8)val, SDL_QUERY) == SDL_IGNORE;
    }
    else
        return RAISE (PyExc_TypeError, "type must be numeric or a sequence");

    return PyInt_FromLong (isblocked);
}

static PyMethodDef event_builtins[] =
{
    { "Event", (PyCFunction)Event, 3, DOC_PYGAMEEVENTEVENT },
    { "event_name", event_name, METH_VARARGS, DOC_PYGAMEEVENTEVENTNAME },

    { "set_grab", set_grab, METH_VARARGS, DOC_PYGAMEEVENTSETGRAB },
    { "get_grab", (PyCFunction) get_grab, METH_NOARGS, DOC_PYGAMEEVENTGETGRAB },

    { "pump", (PyCFunction) pygame_pump, METH_NOARGS, DOC_PYGAMEEVENTPUMP },
    { "wait", (PyCFunction) pygame_wait, METH_NOARGS, DOC_PYGAMEEVENTWAIT },
    { "poll", (PyCFunction) pygame_poll, METH_NOARGS, DOC_PYGAMEEVENTPOLL },
    { "clear", event_clear, METH_VARARGS, DOC_PYGAMEEVENTCLEAR },
    { "get", event_get, METH_VARARGS, DOC_PYGAMEEVENTGET },
    { "peek", event_peek, METH_VARARGS, DOC_PYGAMEEVENTPEEK },
    { "post", event_post, METH_VARARGS, DOC_PYGAMEEVENTPOST },

    { "set_allowed", set_allowed, METH_VARARGS, DOC_PYGAMEEVENTSETALLOWED },
    { "set_blocked", set_blocked, METH_VARARGS, DOC_PYGAMEEVENTSETBLOCKED },
    { "get_blocked", get_blocked, METH_VARARGS, DOC_PYGAMEEVENTGETBLOCKED },

    { NULL, NULL, 0, NULL }
};

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

    PyType_Init (PyEvent_Type);

    /* create the module */
    module = Py_InitModule3 ("event", event_builtins, DOC_PYGAMEEVENT);
    dict = PyModule_GetDict (module);

    PyDict_SetItemString (dict, "EventType", (PyObject *)&PyEvent_Type);

    /* export the c api */
    c_api[0] = &PyEvent_Type;
    c_api[1] = PyEvent_New;
    c_api[2] = PyEvent_New2;
    c_api[3] = PyEvent_FillUserEvent;
    apiobj = PyCObject_FromVoidPtr (c_api, NULL);
    PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
    Py_DECREF (apiobj);

    /*imported needed apis*/
    import_pygame_base ();
    PyGame_RegisterQuit (user_event_cleanup);
}