[pypy-commit] lang-gameboy default: Copy rsdl here. It was removed from the pypy tree.

arigo noreply at buildbot.pypy.org
Tue Jun 5 09:57:47 CEST 2012


Author: Armin Rigo <arigo at tunes.org>
Branch: 
Changeset: r4:d08013e51a42
Date: 2012-06-03 17:13 +0200
http://bitbucket.org/pypy/lang-gameboy/changeset/d08013e51a42/

Log:	Copy rsdl here. It was removed from the pypy tree.

diff --git a/pygirl/gameboy_implementation.py b/pygirl/gameboy_implementation.py
--- a/pygirl/gameboy_implementation.py
+++ b/pygirl/gameboy_implementation.py
@@ -15,7 +15,7 @@
 show_metadata = False # Extends the window with windows visualizing meta-data
 
 if constants.USE_RSDL:
-    from pypy.rlib.rsdl import RSDL, RSDL_helper #, RMix
+    from rsdl import RSDL, RSDL_helper #, RMix
     from pypy.rpython.lltypesystem import lltype, rffi
     get_ticks = RSDL.GetTicks
     def delay(secs):
diff --git a/pygirl/test/test_gameboy_implementaton.py b/pygirl/test/test_gameboy_implementaton.py
--- a/pygirl/test/test_gameboy_implementaton.py
+++ b/pygirl/test/test_gameboy_implementaton.py
@@ -1,5 +1,4 @@
 import py, sys
-from pypy import conftest
 
 from pygirl import constants
 
@@ -13,6 +12,7 @@
 #  This test file is skipped unless run with "py.test --view".
 #  If it is run as "py.test --view -s", then it interactively asks
 #  for confirmation that the window looks as expected.
+#  XXX always run for now
 #
 
 if sys.platform == 'darwin':
@@ -25,9 +25,9 @@
 class TestGameBoyImplementation(object):
 
     def setup_method(self, meth):
-        if not conftest.option.view:
-            py.test.skip("'--view' not specified, "
-                         "skipping tests that open a window")
+        #if not conftest.option.view:
+        #    py.test.skip("'--view' not specified, "
+        #                 "skipping tests that open a window")
         self.gameboy = GameBoyImplementation()
         self.is_interactive = sys.stdout.isatty()
 
diff --git a/rsdl/RIMG.py b/rsdl/RIMG.py
new file mode 100644
--- /dev/null
+++ b/rsdl/RIMG.py
@@ -0,0 +1,25 @@
+import sys
+from pypy.rpython.lltypesystem import lltype, rffi
+from pypy.rpython.tool import rffi_platform as platform
+from pypy.translator.tool.cbuild import ExternalCompilationInfo
+from rsdl import RSDL
+
+
+if sys.platform == 'darwin':
+    eci = ExternalCompilationInfo(
+        includes = ['SDL_image.h'],
+        frameworks = ['SDL_image'],
+        include_dirs = ['/Library/Frameworks/SDL_image.framework/Headers']
+    )
+else:
+    eci = ExternalCompilationInfo(
+        includes=['SDL_image.h'],
+        libraries=['SDL_image'],
+    )
+
+eci = eci.merge(RSDL.eci)
+
+def external(name, args, result):
+    return rffi.llexternal(name, args, result, compilation_info=eci)
+
+Load = external('IMG_Load', [rffi.CCHARP], RSDL.SurfacePtr)
diff --git a/rsdl/RMix.py b/rsdl/RMix.py
new file mode 100644
--- /dev/null
+++ b/rsdl/RMix.py
@@ -0,0 +1,68 @@
+import sys
+from pypy.rpython.lltypesystem import lltype, rffi
+from pypy.rpython.tool import rffi_platform as platform
+from pypy.translator.tool.cbuild import ExternalCompilationInfo
+from rsdl import RSDL
+
+
+if sys.platform == 'darwin':
+    eci = ExternalCompilationInfo(
+        includes = ['SDL_mixer.h'],
+        frameworks = ['SDL_mixer'],
+        include_dirs = ['/Library/Frameworks/SDL_Mixer.framework/Headers']
+    )
+else:
+    eci = ExternalCompilationInfo(
+        includes=['SDL_mixer.h'],
+        libraries=['SDL_mixer'],
+    )
+
+eci = eci.merge(RSDL.eci)
+eci = eci.merge(eci)
+eci = eci.merge(eci)
+
+ChunkPtr             = lltype.Ptr(lltype.ForwardReference())
+
+class CConfig:
+    _compilation_info_ = eci
+
+    Chunk              = platform.Struct('Mix_Chunk', [('allocated', rffi.INT),
+                                                       ('abuf', RSDL.Uint8P),
+                                                       ('alen', RSDL.Uint32),
+                                                       ('volume', RSDL.Uint8)])
+
+globals().update(platform.configure(CConfig))
+
+ChunkPtr.TO.become(Chunk)
+
+
+Buffer = rffi.CArray(RSDL.Uint8)
+
+def external(name, args, result):
+    return rffi.llexternal(name, args, result, compilation_info=eci)
+
+OpenAudio           = external('Mix_OpenAudio',
+                               [rffi.INT, RSDL.Uint16, rffi.INT, rffi.INT],
+                               rffi.INT)
+
+CloseAudio          = external('Mix_CloseAudio', [], lltype.Void)
+
+LoadWAV_RW          = external('Mix_LoadWAV_RW',
+                               [RSDL.RWopsPtr, rffi.INT],
+                               ChunkPtr)
+
+def LoadWAV(filename_ccharp):
+    with rffi.scoped_str2charp('rb') as mode:
+        return LoadWAV_RW(RSDL.RWFromFile(filename_ccharp, mode), 1)
+
+
+PlayChannelTimed    = external('Mix_PlayChannelTimed',
+                               [rffi.INT, ChunkPtr, rffi.INT, rffi.INT],
+                               rffi.INT)
+
+def PlayChannel(channel,chunk,loops):
+    return PlayChannelTimed(channel, chunk, loops, -1)
+
+"""Returns zero if the channel is not playing. 
+Otherwise if you passed in -1, the number of channels playing is returned"""
+ChannelPlaying  = external('Mix_Playing', [rffi.INT], rffi.INT)
diff --git a/rsdl/RMix_helper.py b/rsdl/RMix_helper.py
new file mode 100644
--- /dev/null
+++ b/rsdl/RMix_helper.py
@@ -0,0 +1,24 @@
+from pypy.rpython.lltypesystem import lltype, rffi
+from rsdl import RMix, RSDL
+from pypy.rpython.tool import rffi_platform as platform
+
+
+def malloc_buffer_chunk(has_own_allocated_buffer, length_bytes, volume):
+    buffer_pointer = lltype.malloc(RMix.Buffer, length_bytes, flavor='raw')
+    return malloc_chunk(has_own_allocated_buffer, length_bytes, volume)
+
+def malloc_chunk(has_own_allocated_buffer, buffer_pointer, length_bytes, volume):
+    """
+    Creates a new Mix_Chunk.
+    has_own_allocated_buffer:  if 1 struct has its own allocated buffer, 
+                                if 0 abuf should not be freed
+    buffer_pointer:             pointer to audio data
+    length_bytes:               length of audio data in bytes
+    volume:                     Per-sample volume, 0-128 (normally 
+                                MIX_MAX_VOLUME after loading)"""
+    p = lltype.malloc(RMix.Chunk, flavor='raw')
+    rffi.setintfield(p, 'c_allocated', has_own_allocated_buffer)
+    rffi.setintfield(p, 'c_abuf', buffer_pointer)
+    rffi.setintfield(p, 'c_alen', length_bytes)
+    rffi.setintfield(p, 'c_volume', volume)
+    return p
diff --git a/rsdl/RSDL.py b/rsdl/RSDL.py
new file mode 100644
--- /dev/null
+++ b/rsdl/RSDL.py
@@ -0,0 +1,249 @@
+from pypy.rpython.lltypesystem import lltype, rffi
+from pypy.rpython.tool import rffi_platform as platform
+from rsdl.constants import _constants
+from rsdl.eci import get_rsdl_compilation_info
+from pypy.rlib.objectmodel import we_are_translated
+import py
+import sys
+
+# ------------------------------------------------------------------------------
+
+eci = get_rsdl_compilation_info()
+
+def external(name, args, result):
+    return rffi.llexternal(name, args, result, compilation_info=eci)
+
+# ------------------------------------------------------------------------------
+
+RectPtr             = lltype.Ptr(lltype.ForwardReference())
+SurfacePtr          = lltype.Ptr(lltype.ForwardReference())
+PixelFormatPtr      = lltype.Ptr(lltype.ForwardReference())
+EventPtr            = lltype.Ptr(lltype.ForwardReference())
+KeyboardEventPtr    = lltype.Ptr(lltype.ForwardReference())
+MouseButtonEventPtr = lltype.Ptr(lltype.ForwardReference())
+MouseMotionEventPtr = lltype.Ptr(lltype.ForwardReference())
+KeyPtr              = lltype.Ptr(lltype.ForwardReference())
+RWopsPtr            = lltype.Ptr(lltype.ForwardReference())
+
+# ------------------------------------------------------------------------------
+
+class CConfig:
+    _compilation_info_ = eci
+
+    Uint8  = platform.SimpleType('Uint8',  rffi.INT)
+    Uint16 = platform.SimpleType('Uint16', rffi.INT)
+    Sint16 = platform.SimpleType('Sint16', rffi.INT)
+    Uint32 = platform.SimpleType('Uint32', rffi.INT)
+
+    Rect             = platform.Struct('SDL_Rect', 
+                                    [('x', rffi.INT),
+                                     ('y', rffi.INT),
+                                     ('w', rffi.INT),
+                                     ('h', rffi.INT)])
+    
+    Surface          = platform.Struct('SDL_Surface', 
+                                    [('w', rffi.INT),
+                                     ('h', rffi.INT),
+                                     ('format', PixelFormatPtr),
+                                     ('pitch', rffi.INT),
+                                     ('pixels', rffi.UCHARP)])
+    
+    PixelFormat      = platform.Struct('SDL_PixelFormat',
+                                    [('BitsPerPixel', rffi.INT),
+                                     ('BytesPerPixel', rffi.INT),
+                                     ('Rmask', rffi.INT),
+                                     ('Gmask', rffi.INT),
+                                     ('Bmask', rffi.INT),
+                                     ('Amask', rffi.INT)])
+
+    Event            = platform.Struct('SDL_Event',
+                                    [('type', rffi.INT)])
+    
+    keysym           = platform.Struct('SDL_keysym', 
+                                    [('scancode', rffi.INT),
+                                     ('sym', rffi.INT),
+                                     ('mod', rffi.INT),
+                                     ('unicode', rffi.INT)])
+    
+    KeyboardEvent    = platform.Struct('SDL_KeyboardEvent',
+                                    [('type', rffi.INT),
+                                     ('state', rffi.INT),
+                                     ('keysym', keysym)])
+    
+    MouseButtonEvent = platform.Struct('SDL_MouseButtonEvent',
+                                    [('type', rffi.INT),
+                                     ('button', rffi.INT),
+                                     ('state', rffi.INT),
+                                     ('x', rffi.INT),
+                                     ('y', rffi.INT)])
+    
+    MouseMotionEvent = platform.Struct('SDL_MouseMotionEvent',
+                                    [('type', rffi.INT),
+                                     ('state', rffi.INT),
+                                     ('x', rffi.INT),
+                                     ('y', rffi.INT),
+                                     ('xrel', rffi.INT),
+                                     ('yrel', rffi.INT)])
+    
+    QuitEvent        = platform.Struct('SDL_QuitEvent',
+                                    [('type', rffi.INT)])
+    
+    RWops = platform.Struct('SDL_RWops', [])
+
+# ------------------------------------------------------------------------------
+
+for _prefix, _list in _constants.items():
+    for _name in _list:
+        setattr(CConfig, _name, platform.ConstantInteger(_prefix+_name))
+
+# ------------------------------------------------------------------------------
+
+globals().update(platform.configure(CConfig))
+
+# ------------------------------------------------------------------------------
+
+RectPtr.TO.become(Rect)
+SurfacePtr.TO.become(Surface)
+PixelFormatPtr.TO.become(PixelFormat)
+EventPtr.TO.become(Event)
+KeyboardEventPtr.TO.become(KeyboardEvent)
+MouseButtonEventPtr.TO.become(MouseButtonEvent)
+MouseMotionEventPtr.TO.become(MouseMotionEvent)
+RWopsPtr.TO.become(RWops)
+
+# ------------------------------------------------------------------------------
+
+Uint8P  = lltype.Ptr(lltype.Array(Uint8, hints={'nolength': True}))
+Uint16P = lltype.Ptr(lltype.Array(Uint16, hints={'nolength': True}))
+# need to add signed hint here
+Sint16P = lltype.Ptr(lltype.Array(Sint16, hints={'nolength': True}))
+Uint32P = lltype.Ptr(lltype.Array(Uint32, hints={'nolength': True}))
+
+
+# ------------------------------------------------------------------------------
+
+_Init            = external('SDL_Init', 
+                             [Uint32], 
+                             rffi.INT)
+                                  
+Mac_Init        = external('SDL_Init', 
+                             [Uint32], 
+                             rffi.INT)
+
+Quit             = external('SDL_Quit', [], 
+                            lltype.Void)
+
+SetVideoMode     = external('SDL_SetVideoMode', 
+                             [rffi.INT, rffi.INT, rffi.INT, Uint32],
+                             SurfacePtr)
+
+WM_SetCaption    = external('SDL_WM_SetCaption', 
+                             [rffi.CCHARP, rffi.CCHARP],
+                             lltype.Void)
+
+EnableUNICODE    = external('SDL_EnableUNICODE', 
+                             [rffi.INT], 
+                             rffi.INT)
+
+WaitEvent        = external('SDL_WaitEvent', 
+                             [EventPtr], 
+                             rffi.INT)
+
+PollEvent        = external('SDL_PollEvent',
+                             [EventPtr], 
+                             rffi.INT)
+
+Flip             = external('SDL_Flip', 
+                             [SurfacePtr], 
+                             rffi.INT)
+
+CreateRGBSurface = external('SDL_CreateRGBSurface', 
+                             [Uint32, rffi.INT, rffi.INT, rffi.INT,
+                              Uint32, Uint32, Uint32, Uint32],
+                             SurfacePtr)
+
+LockSurface      = external('SDL_LockSurface', 
+                             [SurfacePtr], 
+                             rffi.INT)
+
+UnlockSurface    = external('SDL_UnlockSurface', 
+                             [SurfacePtr],
+                             lltype.Void)
+
+FreeSurface      = external('SDL_FreeSurface', 
+                             [SurfacePtr],
+                             lltype.Void)
+
+MapRGB           = external('SDL_MapRGB', 
+                             [PixelFormatPtr, Uint8, Uint8,  Uint8], 
+                             Uint32)
+
+GetRGB           = external('SDL_GetRGB',
+                             [Uint32, PixelFormatPtr, Uint8P, Uint8P, Uint8P], 
+                             lltype.Void)
+
+GetRGBA          = external('SDL_GetRGBA', 
+                             [Uint32, PixelFormatPtr, Uint8P, Uint8P, 
+                             Uint8P, Uint8P], 
+                             lltype.Void)
+
+FillRect         = external('SDL_FillRect', 
+                             [SurfacePtr, RectPtr, Uint32], 
+                             rffi.INT)
+
+BlitSurface      = external('SDL_UpperBlit', 
+                             [SurfacePtr, RectPtr, SurfacePtr,  RectPtr], 
+                             rffi.INT)
+
+SetAlpha         = external('SDL_SetAlpha', 
+                             [SurfacePtr, Uint32, Uint8], 
+                             rffi.INT)
+
+SetColorKey      = external('SDL_SetColorKey',
+                            [SurfacePtr, Uint32, Uint32],
+                            rffi.INT)
+
+ShowCursor       = external('SDL_ShowCursor',
+                            [rffi.INT],
+                            rffi.INT)
+
+GetTicks         = external('SDL_GetTicks',
+                            [],
+                            Uint32)
+
+Delay            = external('SDL_Delay',
+                            [Uint32],
+                            lltype.Void)
+
+UpdateRect       = external('SDL_UpdateRect',
+                            [SurfacePtr, rffi.INT, rffi.INT, rffi.INT],
+                            lltype.Void)
+
+GetKeyName       = external('SDL_GetKeyName',
+                            [rffi.INT], 
+                            rffi.CCHARP)
+
+GetError         = external('SDL_GetError',
+                            [],
+                            rffi.CCHARP)
+
+RWFromFile       = external('SDL_RWFromFile',
+                            [rffi.CCHARP, rffi.CCHARP],
+                            RWopsPtr)
+
+# ------------------------------------------------------------------------------
+
+
+if sys.platform == 'darwin':
+    def Init(flags):
+        if not we_are_translated():
+            from AppKit import NSApplication
+            NSApplication.sharedApplication()
+        #CustomApplicationMain(0, " ")
+        return _Init(flags)
+        #Mac_Init()
+else:
+    Init = _Init
+    
+    
+    
diff --git a/rsdl/RSDL_helper.py b/rsdl/RSDL_helper.py
new file mode 100644
--- /dev/null
+++ b/rsdl/RSDL_helper.py
@@ -0,0 +1,108 @@
+from pypy.rpython.lltypesystem import lltype, rffi
+from rsdl import RSDL
+
+def get_rgb(color, format):
+    rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 3, flavor='raw')
+    try:
+        RSDL.GetRGB(color,
+                    format,
+                    rffi.ptradd(rgb, 0),
+                    rffi.ptradd(rgb, 1),
+                    rffi.ptradd(rgb, 2))
+        r = rffi.cast(lltype.Signed, rgb[0])
+        g = rffi.cast(lltype.Signed, rgb[1])
+        b = rffi.cast(lltype.Signed, rgb[2])
+        result = r, g, b
+    finally:
+        lltype.free(rgb, flavor='raw')
+
+    return result
+
+def get_rgba(color, format):
+    rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 4, flavor='raw')
+    try:
+        RSDL.GetRGBA(color,
+                    format,
+                    rffi.ptradd(rgb, 0),
+                    rffi.ptradd(rgb, 1),
+                    rffi.ptradd(rgb, 2),
+                    rffi.ptradd(rgb, 3))
+        r = rffi.cast(lltype.Signed, rgb[0])
+        g = rffi.cast(lltype.Signed, rgb[1])
+        b = rffi.cast(lltype.Signed, rgb[2])
+        a = rffi.cast(lltype.Signed, rgb[3])
+        result = r, g, b, a
+    finally:
+        lltype.free(rgb, flavor='raw')
+
+    return result
+
+def get_pixel(image, x, y):
+    """Return the pixel value at (x, y)
+    NOTE: The surface must be locked before calling this!
+    """
+    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
+    pitch = rffi.getintfield(image, 'c_pitch')
+    # Here p is the address to the pixel we want to retrieve
+    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
+    if bpp == 1:
+        return rffi.cast(RSDL.Uint32, p[0])
+    elif bpp == 2:
+        p = rffi.cast(RSDL.Uint16P, p)
+        return rffi.cast(RSDL.Uint32, p[0])
+    elif bpp == 3:
+        p0 = rffi.cast(lltype.Signed, p[0])
+        p1 = rffi.cast(lltype.Signed, p[1])
+        p2 = rffi.cast(lltype.Signed, p[2])
+        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
+            result = p0 << 16 | p1 << 8 | p2
+        else:
+            result = p0 | p1 << 8 | p2 << 16
+        return rffi.cast(RSDL.Uint32, result)
+    elif bpp == 4:
+        p = rffi.cast(RSDL.Uint32P, p)
+        return p[0]
+    else:
+        raise ValueError("bad BytesPerPixel")
+
+def set_pixel(image, x, y, pixel):
+    """Return the pixel value at (x, y)
+    NOTE: The surface must be locked before calling this!
+    """
+    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
+    pitch = rffi.getintfield(image, 'c_pitch')
+    # Here p is the address to the pixel we want to retrieve
+    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
+    if bpp == 1:
+        p[0] = rffi.cast(rffi.UCHAR,pixel)
+    elif bpp == 2:
+        p = rffi.cast(RSDL.Uint16P, p)
+        p[0] = rffi.cast(RSDL.Uint16,pixel) 
+    elif bpp == 3:
+        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
+            p[0] = rffi.cast(rffi.UCHAR,(pixel >> 16) & 0xFF)
+            p[1] = rffi.cast(rffi.UCHAR,(pixel >> 8 ) & 0xFF)
+            p[2] = rffi.cast(rffi.UCHAR,pixel & 0xFF)
+        else:
+            p[0] = rffi.cast(rffi.UCHAR,pixel & 0xFF)
+            p[1] = rffi.cast(rffi.UCHAR,(pixel >> 8 ) & 0xFF)
+            p[2] = rffi.cast(rffi.UCHAR,(pixel >> 16) & 0xFF)
+    elif bpp == 4:
+        p = rffi.cast(RSDL.Uint32P, p)
+        p[0] = rffi.cast(RSDL.Uint32, pixel)
+    else:
+        raise ValueError("bad BytesPerPixel")
+
+def mallocrect(x, y, w, h):
+    p = lltype.malloc(RSDL.Rect, flavor='raw')
+    rffi.setintfield(p, 'c_x', x)
+    rffi.setintfield(p, 'c_y', y)
+    rffi.setintfield(p, 'c_w', w)
+    rffi.setintfield(p, 'c_h', h)
+    return p
+
+def blit_complete_surface(src, dst, x, y):
+    dstrect = mallocrect(x, y, rffi.getintfield(src, 'c_w'), rffi.getintfield(src, 'c_w'))
+    RSDL.BlitSurface(src, lltype.nullptr(RSDL.Rect), dst, dstrect)
+    lltype.free(dstrect, flavor='raw')
+
diff --git a/rsdl/__init__.py b/rsdl/__init__.py
new file mode 100644
diff --git a/rsdl/constants.py b/rsdl/constants.py
new file mode 100644
--- /dev/null
+++ b/rsdl/constants.py
@@ -0,0 +1,261 @@
+
+_constants = {
+    'SDL_': [      # constants with the 'SDL_' prefix in C
+        "YV12_OVERLAY",
+        "IYUV_OVERLAY",
+        "YUY2_OVERLAY",
+        "UYVY_OVERLAY",
+        "YVYU_OVERLAY",
+
+        "SWSURFACE",
+        "HWSURFACE",
+        "RESIZABLE",
+        "ASYNCBLIT",
+        "OPENGL",
+        "OPENGLBLIT",
+        "ANYFORMAT",
+        "HWPALETTE",
+        "DOUBLEBUF",
+        "FULLSCREEN",
+        "HWACCEL",
+        "SRCCOLORKEY",
+        "RLEACCELOK",
+        "RLEACCEL",
+        "SRCALPHA",
+        "PREALLOC",
+        "NOFRAME",
+
+        "GL_RED_SIZE",
+        "GL_GREEN_SIZE",
+        "GL_BLUE_SIZE",
+        "GL_ALPHA_SIZE",
+        "GL_BUFFER_SIZE",
+        "GL_DOUBLEBUFFER",
+        "GL_DEPTH_SIZE",
+        "GL_STENCIL_SIZE",
+        "GL_ACCUM_RED_SIZE",
+        "GL_ACCUM_GREEN_SIZE",
+        "GL_ACCUM_BLUE_SIZE",
+        "GL_ACCUM_ALPHA_SIZE",
+        "GL_STEREO",              #if SDL_VERSION_ATLEAST(1, 2, 5)
+        "GL_MULTISAMPLEBUFFERS",  #if SDL_VERSION_ATLEAST(1, 2, 6)
+        "GL_MULTISAMPLESAMPLES",  #if SDL_VERSION_ATLEAST(1, 2, 6)
+
+        "NOEVENT",
+        "ACTIVEEVENT",
+        "KEYDOWN",
+        "KEYUP",
+        "MOUSEMOTION",
+        "MOUSEBUTTONDOWN",
+        "MOUSEBUTTONUP",
+        "BUTTON_LEFT",
+        "BUTTON_MIDDLE", 
+        "BUTTON_RIGHT",
+        "BUTTON_WHEELUP", 
+        "BUTTON_WHEELDOWN", 
+        "JOYAXISMOTION",
+        "JOYBALLMOTION",
+        "JOYHATMOTION",
+        "JOYBUTTONDOWN",
+        "JOYBUTTONUP",
+        "VIDEORESIZE",
+        "VIDEOEXPOSE",
+        "QUIT",
+        "SYSWMEVENT",
+        "USEREVENT",
+        "NUMEVENTS",
+
+        "HAT_CENTERED",
+        "HAT_UP",
+        "HAT_RIGHTUP",
+        "HAT_RIGHT",
+        "HAT_RIGHTDOWN",
+        "HAT_DOWN",
+        "HAT_LEFTDOWN",
+        "HAT_LEFT",
+        "HAT_LEFTUP",
+        
+        "DISABLE",
+        "ENABLE",
+
+        # the following ones are not exposed in Pygame
+        "INIT_VIDEO",
+        "BYTEORDER",
+        "BIG_ENDIAN",
+        "LIL_ENDIAN",
+        ],
+
+    '': [      # constants with no prefix in C
+        "TIMER_RESOLUTION",
+        "AUDIO_U8",
+        "AUDIO_S8",
+        "AUDIO_U16LSB",
+        "AUDIO_S16LSB",
+        "AUDIO_U16MSB",
+        "AUDIO_S16MSB",
+        "AUDIO_U16",
+        "AUDIO_S16",
+        "AUDIO_U16SYS",
+        "AUDIO_S16SYS",
+
+        "KMOD_NONE",
+        "KMOD_LSHIFT",
+        "KMOD_RSHIFT",
+        "KMOD_LCTRL",
+        "KMOD_RCTRL",
+        "KMOD_LALT",
+        "KMOD_RALT",
+        "KMOD_LMETA",
+        "KMOD_RMETA",
+        "KMOD_NUM",
+        "KMOD_CAPS",
+        "KMOD_MODE",
+
+        "KMOD_CTRL",
+        "KMOD_SHIFT",
+        "KMOD_ALT",
+        "KMOD_META",
+        ],
+
+    'SDL': [      # constants with the 'SDL' prefix in C
+        "K_UNKNOWN",
+        "K_FIRST",
+        "K_BACKSPACE",
+        "K_TAB",
+        "K_CLEAR",
+        "K_RETURN",
+        "K_PAUSE",
+        "K_ESCAPE",
+        "K_SPACE",
+        "K_EXCLAIM",
+        "K_QUOTEDBL",
+        "K_HASH",
+        "K_DOLLAR",
+        "K_AMPERSAND",
+        "K_QUOTE",
+        "K_LEFTPAREN",
+        "K_RIGHTPAREN",
+        "K_ASTERISK",
+        "K_PLUS",
+        "K_COMMA",
+        "K_MINUS",
+        "K_PERIOD",
+        "K_SLASH",
+        "K_0",
+        "K_1",
+        "K_2",
+        "K_3",
+        "K_4",
+        "K_5",
+        "K_6",
+        "K_7",
+        "K_8",
+        "K_9",
+        "K_COLON",
+        "K_SEMICOLON",
+        "K_LESS",
+        "K_EQUALS",
+        "K_GREATER",
+        "K_QUESTION",
+        "K_AT",
+        "K_LEFTBRACKET",
+        "K_BACKSLASH",
+        "K_RIGHTBRACKET",
+        "K_CARET",
+        "K_UNDERSCORE",
+        "K_BACKQUOTE",
+        "K_a",
+        "K_b",
+        "K_c",
+        "K_d",
+        "K_e",
+        "K_f",
+        "K_g",
+        "K_h",
+        "K_i",
+        "K_j",
+        "K_k",
+        "K_l",
+        "K_m",
+        "K_n",
+        "K_o",
+        "K_p",
+        "K_q",
+        "K_r",
+        "K_s",
+        "K_t",
+        "K_u",
+        "K_v",
+        "K_w",
+        "K_x",
+        "K_y",
+        "K_z",
+        "K_DELETE",
+
+        "K_KP0",
+        "K_KP1",
+        "K_KP2",
+        "K_KP3",
+        "K_KP4",
+        "K_KP5",
+        "K_KP6",
+        "K_KP7",
+        "K_KP8",
+        "K_KP9",
+        "K_KP_PERIOD",
+        "K_KP_DIVIDE",
+        "K_KP_MULTIPLY",
+        "K_KP_MINUS",
+        "K_KP_PLUS",
+        "K_KP_ENTER",
+        "K_KP_EQUALS",
+        "K_UP",
+        "K_DOWN",
+        "K_RIGHT",
+        "K_LEFT",
+        "K_INSERT",
+        "K_HOME",
+        "K_END",
+        "K_PAGEUP",
+        "K_PAGEDOWN",
+        "K_F1",
+        "K_F2",
+        "K_F3",
+        "K_F4",
+        "K_F5",
+        "K_F6",
+        "K_F7",
+        "K_F8",
+        "K_F9",
+        "K_F10",
+        "K_F11",
+        "K_F12",
+        "K_F13",
+        "K_F14",
+        "K_F15",
+
+        "K_NUMLOCK",
+        "K_CAPSLOCK",
+        "K_SCROLLOCK",
+        "K_RSHIFT",
+        "K_LSHIFT",
+        "K_RCTRL",
+        "K_LCTRL",
+        "K_RALT",
+        "K_LALT",
+        "K_RMETA",
+        "K_LMETA",
+        "K_LSUPER",
+        "K_RSUPER",
+        "K_MODE",
+
+        "K_HELP",
+        "K_PRINT",
+        "K_SYSREQ",
+        "K_BREAK",
+        "K_MENU",
+        "K_POWER",
+        "K_EURO",
+        "K_LAST",
+        ],
+    }
diff --git a/rsdl/eci.py b/rsdl/eci.py
new file mode 100644
--- /dev/null
+++ b/rsdl/eci.py
@@ -0,0 +1,27 @@
+from pypy.translator.tool.cbuild import ExternalCompilationInfo
+from pypy.translator.platform import CompilationError
+import py
+import sys
+
+def get_rsdl_compilation_info():
+    if sys.platform == 'darwin':
+        eci = ExternalCompilationInfo(
+            includes = ['SDL.h'],
+            include_dirs = ['/Library/Frameworks/SDL.framework/Headers'],
+            link_files = [
+                str(py.path.local(__file__).dirpath().join('macosx-sdl-main/SDLMain.m')),
+            ],
+            frameworks = ['SDL', 'Cocoa']
+        )
+    else:
+        eci = ExternalCompilationInfo(
+            includes=['SDL.h'],
+            )
+        eci = eci.merge(ExternalCompilationInfo.from_config_tool('sdl-config'))
+    return eci
+
+def check_sdl_installation():
+    from pypy.rpython.tool import rffi_platform as platform
+    platform.verify_eci(get_rsdl_compilation_info())
+
+SDLNotInstalled = (ImportError, CompilationError)
diff --git a/rsdl/macosx-sdl-main/SDLMain.h b/rsdl/macosx-sdl-main/SDLMain.h
new file mode 100644
--- /dev/null
+++ b/rsdl/macosx-sdl-main/SDLMain.h
@@ -0,0 +1,11 @@
+/*   SDLMain.m - main entry point for our Cocoa-ized SDL app
+       Initial Version: Darrell Walisser <dwaliss1 at purdue.edu>
+       Non-NIB-Code & other changes: Max Horn <max at quendi.de>
+
+    Feel free to customize this file to suit your needs
+*/
+
+#import <Cocoa/Cocoa.h>
+
+ at interface SDLMain : NSObject
+ at end
diff --git a/rsdl/macosx-sdl-main/SDLMain.m b/rsdl/macosx-sdl-main/SDLMain.m
new file mode 100644
--- /dev/null
+++ b/rsdl/macosx-sdl-main/SDLMain.m
@@ -0,0 +1,384 @@
+/*   SDLMain.m - main entry point for our Cocoa-ized SDL app
+       Initial Version: Darrell Walisser <dwaliss1 at purdue.edu>
+       Non-NIB-Code & other changes: Max Horn <max at quendi.de>
+
+    Feel free to customize this file to suit your needs
+*/
+
+#import "SDL.h"
+#import "SDLMain.h"
+#import <sys/param.h> /* for MAXPATHLEN */
+#import <unistd.h>
+
+/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
+ but the method still is there and works. To avoid warnings, we declare
+ it ourselves here. */
+ at interface NSApplication(SDL_Missing_Methods)
+- (void)setAppleMenu:(NSMenu *)menu;
+ at end
+
+/* Use this flag to determine whether we use SDLMain.nib or not */
+#define		SDL_USE_NIB_FILE	0
+
+/* Use this flag to determine whether we use CPS (docking) or not */
+#define		SDL_USE_CPS		1
+#ifdef SDL_USE_CPS
+/* Portions of CPS.h */
+typedef struct CPSProcessSerNum
+{
+	UInt32		lo;
+	UInt32		hi;
+} CPSProcessSerNum;
+
+extern OSErr	CPSGetCurrentProcess( CPSProcessSerNum *psn);
+extern OSErr 	CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
+extern OSErr	CPSSetFrontProcess( CPSProcessSerNum *psn);
+
+#endif /* SDL_USE_CPS */
+
+static int    gArgc;
+static char  **gArgv;
+static BOOL   gFinderLaunch;
+static BOOL   gCalledAppMainline = FALSE;
+
+static NSString *getApplicationName(void)
+{
+    NSDictionary *dict;
+    NSString *appName = 0;
+
+    /* Determine the application name */
+    dict = (NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
+    if (dict)
+        appName = [dict objectForKey: @"CFBundleName"];
+    
+    if (![appName length])
+        appName = [[NSProcessInfo processInfo] processName];
+
+    return appName;
+}
+
+#if SDL_USE_NIB_FILE
+/* A helper category for NSString */
+ at interface NSString (ReplaceSubString)
+- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
+ at end
+#endif
+
+ at interface SDLApplication : NSApplication
+ at end
+
+ at implementation SDLApplication
+/* Invoked from the Quit menu item */
+- (void)terminate:(id)sender
+{
+    /* Post a SDL_QUIT event */
+    SDL_Event event;
+    event.type = SDL_QUIT;
+    SDL_PushEvent(&event);
+}
+ at end
+
+/* The main class of the application, the application's delegate */
+ at implementation SDLMain
+
+/* Set the working directory to the .app's parent directory */
+- (void) setupWorkingDirectory:(BOOL)shouldChdir
+{
+    if (shouldChdir)
+    {
+        char parentdir[MAXPATHLEN];
+		CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
+		CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
+		if (CFURLGetFileSystemRepresentation(url2, true, (UInt8 *)parentdir, MAXPATHLEN)) {
+	        assert ( chdir (parentdir) == 0 );   /* chdir to the binary app's parent */
+		}
+		CFRelease(url);
+		CFRelease(url2);
+	}
+
+}
+
+#if SDL_USE_NIB_FILE
+
+/* Fix menu to contain the real app name instead of "SDL App" */
+- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
+{
+    NSRange aRange;
+    NSEnumerator *enumerator;
+    NSMenuItem *menuItem;
+
+    aRange = [[aMenu title] rangeOfString:@"SDL App"];
+    if (aRange.length != 0)
+        [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
+
+    enumerator = [[aMenu itemArray] objectEnumerator];
+    while ((menuItem = [enumerator nextObject]))
+    {
+        aRange = [[menuItem title] rangeOfString:@"SDL App"];
+        if (aRange.length != 0)
+            [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
+        if ([menuItem hasSubmenu])
+            [self fixMenu:[menuItem submenu] withAppName:appName];
+    }
+    [ aMenu sizeToFit ];
+}
+
+#else
+
+static void setApplicationMenu(void)
+{
+    /* warning: this code is very odd */
+    NSMenu *appleMenu;
+    NSMenuItem *menuItem;
+    NSString *title;
+    NSString *appName;
+    
+    appName = getApplicationName();
+    appleMenu = [[NSMenu alloc] initWithTitle:@""];
+    
+    /* Add menu items */
+    title = [@"About " stringByAppendingString:appName];
+    [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
+
+    [appleMenu addItem:[NSMenuItem separatorItem]];
+
+    title = [@"Hide " stringByAppendingString:appName];
+    [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
+
+    menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
+    [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
+
+    [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
+
+    [appleMenu addItem:[NSMenuItem separatorItem]];
+
+    title = [@"Quit " stringByAppendingString:appName];
+    [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
+
+    
+    /* Put menu into the menubar */
+    menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
+    [menuItem setSubmenu:appleMenu];
+    [[NSApp mainMenu] addItem:menuItem];
+
+    /* Tell the application object that this is now the application menu */
+    [NSApp setAppleMenu:appleMenu];
+
+    /* Finally give up our references to the objects */
+    [appleMenu release];
+    [menuItem release];
+}
+
+/* Create a window menu */
+static void setupWindowMenu(void)
+{
+    NSMenu      *windowMenu;
+    NSMenuItem  *windowMenuItem;
+    NSMenuItem  *menuItem;
+
+    windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
+    
+    /* "Minimize" item */
+    menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
+    [windowMenu addItem:menuItem];
+    [menuItem release];
+    
+    /* Put menu into the menubar */
+    windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
+    [windowMenuItem setSubmenu:windowMenu];
+    [[NSApp mainMenu] addItem:windowMenuItem];
+    
+    /* Tell the application object that this is now the window menu */
+    [NSApp setWindowsMenu:windowMenu];
+
+    /* Finally give up our references to the objects */
+    [windowMenu release];
+    [windowMenuItem release];
+}
+
+/* Replacement for NSApplicationMain */
+static void CustomApplicationMain (int argc, char **argv)
+{
+    NSAutoreleasePool	*pool = [[NSAutoreleasePool alloc] init];
+    SDLMain				*sdlMain;
+
+    /* Ensure the application object is initialised */
+    [SDLApplication sharedApplication];
+    
+#ifdef SDL_USE_CPS
+    {
+        CPSProcessSerNum PSN;
+        /* Tell the dock about us */
+        if (!CPSGetCurrentProcess(&PSN))
+            if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
+                if (!CPSSetFrontProcess(&PSN))
+                    [SDLApplication sharedApplication];
+    }
+#endif /* SDL_USE_CPS */
+
+    /* Set up the menubar */
+    [NSApp setMainMenu:[[NSMenu alloc] init]];
+    setApplicationMenu();
+    setupWindowMenu();
+
+    /* Create SDLMain and make it the app delegate */
+    sdlMain = [[SDLMain alloc] init];
+    [NSApp setDelegate:sdlMain];
+    
+    /* Start the main event loop */
+    [NSApp run];
+    
+    [sdlMain release];
+    [pool release];
+}
+
+#endif
+
+
+/*
+ * Catch document open requests...this lets us notice files when the app
+ *  was launched by double-clicking a document, or when a document was
+ *  dragged/dropped on the app's icon. You need to have a
+ *  CFBundleDocumentsType section in your Info.plist to get this message,
+ *  apparently.
+ *
+ * Files are added to gArgv, so to the app, they'll look like command line
+ *  arguments. Previously, apps launched from the finder had nothing but
+ *  an argv[0].
+ *
+ * This message may be received multiple times to open several docs on launch.
+ *
+ * This message is ignored once the app's mainline has been called.
+ */
+- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
+{
+    const char *temparg;
+    size_t arglen;
+    char *arg;
+    char **newargv;
+
+    if (!gFinderLaunch)  /* MacOS is passing command line args. */
+        return FALSE;
+
+    if (gCalledAppMainline)  /* app has started, ignore this document. */
+        return FALSE;
+
+    temparg = [filename UTF8String];
+    arglen = SDL_strlen(temparg) + 1;
+    arg = (char *) SDL_malloc(arglen);
+    if (arg == NULL)
+        return FALSE;
+
+    newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));
+    if (newargv == NULL)
+    {
+        SDL_free(arg);
+        return FALSE;
+    }
+    gArgv = newargv;
+
+    SDL_strlcpy(arg, temparg, arglen);
+    gArgv[gArgc++] = arg;
+    gArgv[gArgc] = NULL;
+    return TRUE;
+}
+
+
+/* Called when the internal event loop has just started running */
+- (void) applicationDidFinishLaunching: (NSNotification *) note
+{
+    int status;
+
+    /* Set the working directory to the .app's parent directory */
+    [self setupWorkingDirectory:gFinderLaunch];
+
+#if SDL_USE_NIB_FILE
+    /* Set the main menu to contain the real app name instead of "SDL App" */
+    [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
+#endif
+
+    /* Hand off to main application code */
+    gCalledAppMainline = TRUE;
+    status = SDL_main (gArgc, gArgv);
+
+    /* We're done, thank you for playing */
+    exit(status);
+}
+ at end
+
+
+ at implementation NSString (ReplaceSubString)
+
+- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
+{
+    unsigned int bufferSize;
+    unsigned int selfLen = [self length];
+    unsigned int aStringLen = [aString length];
+    unichar *buffer;
+    NSRange localRange;
+    NSString *result;
+
+    bufferSize = selfLen + aStringLen - aRange.length;
+    buffer = NSAllocateMemoryPages(bufferSize*sizeof(unichar));
+    
+    /* Get first part into buffer */
+    localRange.location = 0;
+    localRange.length = aRange.location;
+    [self getCharacters:buffer range:localRange];
+    
+    /* Get middle part into buffer */
+    localRange.location = 0;
+    localRange.length = aStringLen;
+    [aString getCharacters:(buffer+aRange.location) range:localRange];
+     
+    /* Get last part into buffer */
+    localRange.location = aRange.location + aRange.length;
+    localRange.length = selfLen - localRange.location;
+    [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
+    
+    /* Build output string */
+    result = [NSString stringWithCharacters:buffer length:bufferSize];
+    
+    NSDeallocateMemoryPages(buffer, bufferSize);
+    
+    return result;
+}
+
+ at end
+
+
+
+#ifdef main
+#  undef main
+#endif
+
+
+/* Main entry point to executable - should *not* be SDL_main! */
+int main (int argc, char **argv)
+{
+    /* Copy the arguments into a global variable */
+    /* This is passed if we are launched by double-clicking */
+    if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
+        gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
+        gArgv[0] = argv[0];
+        gArgv[1] = NULL;
+        gArgc = 1;
+        gFinderLaunch = YES;
+    } else {
+        int i;
+        gArgc = argc;
+        gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
+        for (i = 0; i <= argc; i++)
+            gArgv[i] = argv[i];
+        gFinderLaunch = NO;
+    }
+
+#if SDL_USE_NIB_FILE
+    [SDLApplication poseAsClass:[NSApplication class]];
+    NSApplicationMain (argc, argv);
+#else
+    CustomApplicationMain (argc, argv);
+#endif
+    return 0;
+}
+
diff --git a/rsdl/test/__init__.py b/rsdl/test/__init__.py
new file mode 100644
diff --git a/rsdl/test/applause.wav b/rsdl/test/applause.wav
new file mode 100644
index 0000000000000000000000000000000000000000..6d8358339785e5c31dfad2a89b3531abe8b9dae5
GIT binary patch

[cut]

diff --git a/rsdl/test/conftest.py b/rsdl/test/conftest.py
new file mode 100644
--- /dev/null
+++ b/rsdl/test/conftest.py
@@ -0,0 +1,10 @@
+from pypy.rlib.rsdl.eci import check_sdl_installation, SDLNotInstalled
+import py
+
+def pytest_ignore_collect(path):
+    try:
+        check_sdl_installation()
+    except SDLNotInstalled, e:
+        return True
+    else:
+        return False
diff --git a/rsdl/test/demo.jpg b/rsdl/test/demo.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..0a7e1c2f43f25d28ace66c06736f3422c5d8e8c0
GIT binary patch

[cut]

diff --git a/rsdl/test/demo.png b/rsdl/test/demo.png
new file mode 100644
index 0000000000000000000000000000000000000000..fa06ef56cce7e4d62edc180fb562b6350e4bb3bc
GIT binary patch

[cut]

diff --git a/rsdl/test/test_basic.py b/rsdl/test/test_basic.py
new file mode 100644
--- /dev/null
+++ b/rsdl/test/test_basic.py
@@ -0,0 +1,37 @@
+import py
+from pypy.rlib.rsdl import RSDL
+from pypy.rlib.rarithmetic import r_uint
+from pypy.rpython.lltypesystem import rffi
+
+
+def test_sdl_init():
+    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
+    RSDL.Quit()
+
+def test_surface_basic():
+    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
+    surface = RSDL.CreateRGBSurface(0, 150, 50, 32,
+                                    r_uint(0x000000FF),
+                                    r_uint(0x0000FF00),
+                                    r_uint(0x00FF0000),
+                                    r_uint(0xFF000000))
+    assert surface
+    assert rffi.getintfield(surface, 'c_w') == 150
+    assert rffi.getintfield(surface, 'c_h') == 50
+    RSDL.FreeSurface(surface)
+    RSDL.Quit()
+    
+    
+def test_get_keyname():
+    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
+    assert RSDL.GetKeyName(RSDL.K_PLUS)[0] == '+'
+    assert RSDL.GetKeyName(RSDL.K_RIGHTPAREN)[0] == ')'
+    assert RSDL.GetKeyName(RSDL.K_z)[0] == 'z'
+    
+def test_delay_getticks():
+    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
+    RSDL.Delay(10)
+    i = RSDL.GetTicks()
+    assert i >= 10
+    RSDL.Quit()
+    
\ No newline at end of file
diff --git a/rsdl/test/test_sdl_image.py b/rsdl/test/test_sdl_image.py
new file mode 100644
--- /dev/null
+++ b/rsdl/test/test_sdl_image.py
@@ -0,0 +1,50 @@
+import py, os
+from rsdl import RSDL, RIMG, RSDL_helper, test
+from pypy.rpython.lltypesystem import lltype, rffi
+this_dir = test.__path__[0]
+
+
+def test_load_image():
+    for filename in ["demo.jpg", "demo.png"]:
+        image = RIMG.Load(os.path.join(this_dir, filename))
+        assert image
+        assert rffi.getintfield(image, 'c_w') == 17
+        assert rffi.getintfield(image, 'c_h') == 23
+        RSDL.FreeSurface(image)
+
+def test_image_pixels():
+    for filename in ["demo.jpg", "demo.png"]:
+        image = RIMG.Load(os.path.join(this_dir, filename))
+        assert image
+        assert rffi.getintfield(image.c_format, 'c_BytesPerPixel') in (3, 4)
+        RSDL.LockSurface(image)
+        result = {}
+        try:
+            rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 3, flavor='raw')
+            try:
+                for y in range(23):
+                    for x in range(y % 13, 17, 13):
+                        color = RSDL_helper.get_pixel(image, x, y)
+                        RSDL.GetRGB(color,
+                                    image.c_format,
+                                    rffi.ptradd(rgb, 0),
+                                    rffi.ptradd(rgb, 1),
+                                    rffi.ptradd(rgb, 2))
+                        r = rffi.cast(lltype.Signed, rgb[0])
+                        g = rffi.cast(lltype.Signed, rgb[1])
+                        b = rffi.cast(lltype.Signed, rgb[2])
+                        result[x, y] = r, g, b
+            finally:
+                lltype.free(rgb, flavor='raw')
+        finally:
+            RSDL.UnlockSurface(image)
+        RSDL.FreeSurface(image)
+        for x, y in result:
+            f = (x*17 + y*23) / float(17*17+23*23)
+            expected_r = int(255.0 * (1.0-f))
+            expected_g = 0
+            expected_b = int(255.0 * f)
+            r, g, b = result[x, y]
+            assert abs(r-expected_r) < 10
+            assert abs(g-expected_g) < 10
+            assert abs(b-expected_b) < 10
diff --git a/rsdl/test/test_sdl_mixer.py b/rsdl/test/test_sdl_mixer.py
new file mode 100644
--- /dev/null
+++ b/rsdl/test/test_sdl_mixer.py
@@ -0,0 +1,32 @@
+import py
+import os
+import time
+from pypy.rlib.rsdl import RSDL, RMix, RSDL_helper
+from pypy.rpython.lltypesystem import lltype, rffi
+
+def test_open_mixer():
+    if RMix.OpenAudio(22050, RSDL.AUDIO_S16LSB, 2, 1024) != 0:
+        error = rffi.charp2str(RSDL.GetError())
+        raise Exception(error)
+    RMix.CloseAudio()
+
+def test_load_wav():
+    if RMix.OpenAudio(22050, RSDL.AUDIO_S16LSB, 2, 1024) != 0:
+        error = rffi.charp2str(RSDL.GetError())
+        raise Exception(error)
+    filename = rffi.str2charp('applause.wav')
+    RMix.LoadWAV(filename)
+    rffi.free_charp(filename)
+    RMix.CloseAudio()
+
+def test_play_wav():
+    if RMix.OpenAudio(22050, RSDL.AUDIO_S16LSB, 2, 1024) != 0:
+        error = rffi.charp2str(RSDL.GetError())
+        raise Exception(error)
+    filename = rffi.str2charp('applause.wav')
+    applause = RMix.LoadWAV(filename)
+    rffi.free_charp(filename)
+    RMix.PlayChannel(-1, applause, -1)
+    time.sleep(1)
+    RMix.CloseAudio()
+
diff --git a/rsdl/test/test_surface.py b/rsdl/test/test_surface.py
new file mode 100644
--- /dev/null
+++ b/rsdl/test/test_surface.py
@@ -0,0 +1,75 @@
+import py, sys
+from pypy.rlib.rsdl import RSDL, RSDL_helper
+from pypy.rlib.rarithmetic import r_uint
+from pypy.rpython.lltypesystem import lltype, rffi
+
+class TestSurface:
+
+    def setup_method(self, meth):
+        self.dst_surf = RSDL.CreateRGBSurface(0, 300, 300, 32,
+                                        r_uint(0x000000FF),
+                                        r_uint(0x0000FF00),
+                                        r_uint(0x00FF0000),
+                                        r_uint(0x00000000))
+        self.src_surf = RSDL.CreateRGBSurface(0, 50, 50, 32,
+                                        r_uint(0x000000FF),
+                                        r_uint(0x0000FF00),
+                                        r_uint(0x00FF0000),
+                                        r_uint(0x00000000))
+        fmt = self.src_surf.c_format
+        self.black = RSDL.MapRGB(fmt, 0, 0, 0)
+        self.red = RSDL.MapRGB(fmt, 255, 0, 0)
+        self.blue = RSDL.MapRGB(fmt, 0, 0, 255)
+        RSDL.FillRect(self.src_surf, lltype.nullptr(RSDL.Rect), self.red)
+
+    def test_simple(self):
+        pass   # only checks that creating the surfaces works
+
+    def test_set_alpha(self):
+        # prepare
+        assert RSDL.SetAlpha(self.src_surf, RSDL.SRCALPHA, 128) == 0
+
+        # draw
+        RSDL_helper.blit_complete_surface(
+            self.src_surf,
+            self.dst_surf,
+            10, 10)
+        RSDL_helper.blit_complete_surface(
+            self.src_surf,
+            self.dst_surf,
+            20, 20)
+
+        # check
+        for position, color in (
+                (( 0, 0), (  0,0,0)), # no rect
+                ((10,10), (127,0,0)), # one rect
+                ((20,20), (191,0,0))  # two overlapping rects
+            ):
+            fetched_color = RSDL_helper.get_pixel(self.dst_surf, position[0], position[1])
+            assert RSDL_helper.get_rgb(fetched_color, self.dst_surf.c_format) == color 
+
+    def test_set_color_key(self):
+        # prepare
+        fillrect = RSDL_helper.mallocrect(10, 10, 30, 30)
+        RSDL.FillRect(self.src_surf, fillrect, self.blue)
+        lltype.free(fillrect, flavor='raw')
+        assert RSDL.SetColorKey(self.src_surf, RSDL.SRCCOLORKEY, self.blue) == 0
+
+        # draw
+        RSDL_helper.blit_complete_surface(self.src_surf, self.dst_surf, 0, 0)
+
+        # check
+        for position, color in (
+                (( 0, 0), self.red),
+                ((10,10), self.black),
+                ((20,20), self.black),
+                ((40,40), self.red)
+            ):
+            fetched_color = RSDL_helper.get_pixel(self.dst_surf, position[0], position[1])
+            assert fetched_color == color
+
+    def teardown_method(self, meth):
+        RSDL.FreeSurface(self.src_surf)
+        RSDL.FreeSurface(self.dst_surf)
+        RSDL.Quit()
+
diff --git a/rsdl/test/test_video.py b/rsdl/test/test_video.py
new file mode 100644
--- /dev/null
+++ b/rsdl/test/test_video.py
@@ -0,0 +1,241 @@
+
+import py, sys
+from pypy.rlib.rsdl import RSDL, RSDL_helper
+from pypy.rlib.rarithmetic import r_uint
+from pypy.rpython.lltypesystem import lltype, rffi
+
+#
+#  This test file is skipped unless run with "py.test --view".
+#  If it is run as "py.test --view -s", then it interactively asks
+#  for confirmation that the window looks as expected.
+#  XXX always run for now.
+#
+
+
+class TestVideo:
+
+    def setup_method(self, meth):
+        #if not conftest.option.view:
+        #    py.test.skip("'--view' not specified, "
+        #                 "skipping tests that open a window")
+        assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
+        self.screen = RSDL.SetVideoMode(640, 480, 32, 0)
+        assert self.screen
+        self.is_interactive = sys.stdout.isatty()
+
+    def check(self, msg):
+        if self.is_interactive:
+            print
+            answer = raw_input('Interactive test: %s - ok? [Y] ' % msg)
+            if answer and not answer.upper().startswith('Y'):
+                py.test.fail(msg)
+        else:
+            print msg
+
+    def test_simple(self):
+        pass   # only checks that opening and closing the window works
+
+    def test_fillrect_full(self):
+        fmt = self.screen.c_format
+        for colorname, r, g, b in [('dark red', 128, 0, 0),
+                                   ('yellow', 255, 255, 0),
+                                   ('blue', 0, 0, 255)]:
+            color = RSDL.MapRGB(fmt, r, g, b)
+            RSDL.FillRect(self.screen, lltype.nullptr(RSDL.Rect), color)
+            RSDL.Flip(self.screen)
+            self.check("Screen filled with %s" % colorname)
+
+    def test_caption(self):
+        RSDL.WM_SetCaption("Hello World!", "Hello World!")
+        self.check('The window caption is "Hello World!"')
+
+    def test_keypresses(self):
+        if not self.is_interactive:
+            py.test.skip("interactive test only")
+        RSDL.EnableUNICODE(1)
+        print
+        print "Keys pressed in the Pygame window should be printed below."
+        print "    Use Escape to quit."
+        event = lltype.malloc(RSDL.Event, flavor='raw')
+        try:
+            while True:
+                    ok = RSDL.WaitEvent(event)
+                    assert rffi.cast(lltype.Signed, ok) == 1
+                    c_type = rffi.getintfield(event, 'c_type')
+                    if c_type == RSDL.KEYDOWN:
+                        p = rffi.cast(RSDL.KeyboardEventPtr, event)
+                        if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
+                            print 'Escape key'
+                            break
+                        char = rffi.getintfield(p.c_keysym, 'c_unicode')
+                        if char != 0:
+                            print 'Key:', unichr(char).encode('utf-8')
+                        else:
+                            print 'Some special key'
+                    else:
+                        print '(event of type %d)' % c_type
+        finally:
+            lltype.free(event, flavor='raw')
+
+    def test_poll(self):
+        if not self.is_interactive:
+            py.test.skip("interactive test only")
+        import time, sys
+        RSDL.EnableUNICODE(1)
+        print
+        print "Keys pressed in the Pygame window give a dot."
+        print "    Wait 3 seconds to quit."
+        timeout = time.time() + 3
+        event = lltype.malloc(RSDL.Event, flavor='raw')
+        try:
+            while True:
+                # busy polling
+                ok = RSDL.PollEvent(event)
+                ok = rffi.cast(lltype.Signed, ok)
+                assert ok >= 0
+                if ok > 0:
+                    c_type = rffi.getintfield(event, 'c_type')
+                    if c_type == RSDL.KEYDOWN:
+                        sys.stderr.write('.')
+                        p = rffi.cast(RSDL.KeyboardEventPtr, event)
+                        if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
+                            print 'Escape key'
+                            break
+                        timeout = time.time() + 3
+                else:
+                    if time.time() > timeout:
+                        break
+                time.sleep(0.05)
+        finally:
+            lltype.free(event, flavor='raw')
+
+    def test_mousemove(self):
+        if not self.is_interactive:
+            py.test.skip("interactive test only")
+        print
+        print "Move the Mouse up and down:"
+        print "    Use Escape to quit."
+        event = lltype.malloc(RSDL.Event, flavor="raw")
+        directions = [False]*4
+        try:
+            while True:
+                ok = RSDL.WaitEvent(event)
+                assert rffi.cast(lltype.Signed, ok) == 1
+                c_type = rffi.getintfield(event, "c_type")
+                if c_type == RSDL.MOUSEMOTION:
+                    m = rffi.cast(RSDL.MouseMotionEventPtr, event)
+                    assert rffi.getintfield(m, "c_x") >= 0
+                    assert rffi.getintfield(m, "c_y") >= 0
+                    print rffi.getintfield(m, "c_xrel")
+                    directions[0] |= rffi.getintfield(m, "c_xrel")>0
+                    directions[1] |= rffi.getintfield(m, "c_xrel")<0
+                    directions[2] |= rffi.getintfield(m, "c_yrel")>0
+                    directions[3] |= rffi.getintfield(m, "c_yrel")<0
+                    if False not in directions:
+                        break
+                elif c_type == RSDL.KEYUP:
+                    p = rffi.cast(RSDL.KeyboardEventPtr, event)
+                    if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
+                        print "    test manually aborted"
+                        py.test.fail(" mousemovement test aborted")
+                        break  
+        finally:
+            lltype.free(event, flavor='raw')
+                
+
+    def test_mousebutton_wheel(self):
+        if not self.is_interactive:
+            py.test.skip("interactive test only")
+        print
+        print "Press the given MouseButtons:"
+        print "        Use Escape to pass tests."
+        
+        event_tests = [("left button",   RSDL.BUTTON_LEFT),
+                       ("middle button", RSDL.BUTTON_MIDDLE),
+                       ("right button",  RSDL.BUTTON_RIGHT),
+                       ("scroll up",     RSDL.BUTTON_WHEELUP),
+                       ("scroll down",   RSDL.BUTTON_WHEELDOWN)]
+        test_success = []
+        event = lltype.malloc(RSDL.Event, flavor='raw')
+        try:
+            for button_test in event_tests:
+                print "    press %s:" % button_test[0]
+                while True:
+                    ok = RSDL.WaitEvent(event)
+                    assert rffi.cast(lltype.Signed, ok) == 1
+                    c_type = rffi.getintfield(event, 'c_type')
+                    if c_type == RSDL.MOUSEBUTTONDOWN:
+                        pass
+                    elif c_type == RSDL.MOUSEBUTTONUP:
+                        b = rffi.cast(RSDL.MouseButtonEventPtr, event)
+                        if rffi.getintfield(b, 'c_button') == button_test[1]:
+                            test_success.append(True)
+                            break
+                    elif c_type == RSDL.KEYUP:
+                        p = rffi.cast(RSDL.KeyboardEventPtr, event)
+                        if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
+                            test_success.append(False) 
+                            print "        manually aborted"
+                            break
+                        #break
+            if False in test_success:
+                py.test.fail("")
+        finally:
+            lltype.free(event, flavor='raw')
+            
+            
+    def test_show_hide_cursor(self):
+        RSDL.ShowCursor(RSDL.DISABLE)
+        self.check("Is the cursor hidden? ")
+        RSDL.ShowCursor(RSDL.ENABLE)
+        self.check("Is the cursor shown? ")
+        
+    def test_bit_pattern(self):
+        HEIGHT = WIDTH = 10
+        fmt = self.screen.c_format
+        white = RSDL.MapRGB(fmt, 255, 255, 255)
+        black = RSDL.MapRGB(fmt, 0, 0, 0)
+        RSDL.LockSurface(self.screen)
+        for i in xrange(WIDTH):
+            for j in xrange(HEIGHT):
+                k = j*WIDTH + i
+                if k % 2:
+                    c = white
+                else:
+                    c = black
+                RSDL_helper.set_pixel(self.screen, i, j, c)
+        RSDL.UnlockSurface(self.screen)
+        RSDL.Flip(self.screen)
+        self.check("Upper left corner 10x10 field with vertical black/white stripes")
+
+    def test_blit_rect(self):
+        surface = RSDL.CreateRGBSurface(0, 150, 50, 32,
+                                        r_uint(0x000000FF),
+                                        r_uint(0x0000FF00),
+                                        r_uint(0x00FF0000),
+                                        r_uint(0xFF000000))
+        fmt = surface.c_format
+        color = RSDL.MapRGB(fmt, 255, 0, 0)
+        RSDL.FillRect(surface, lltype.nullptr(RSDL.Rect), color)
+        
+        paintrect = RSDL_helper.mallocrect(75, 0, 150, 50)
+        dstrect = lltype.malloc(RSDL.Rect, flavor='raw')
+        try:
+            color = RSDL.MapRGB(fmt, 255, 128, 0)
+            RSDL.FillRect(surface, paintrect, color)
+
+            rffi.setintfield(dstrect, 'c_x',  10)
+            rffi.setintfield(dstrect, 'c_y',  10)
+            rffi.setintfield(dstrect, 'c_w', 150)
+            rffi.setintfield(dstrect, 'c_h',  50)
+            RSDL.BlitSurface(surface, lltype.nullptr(RSDL.Rect), self.screen, dstrect)
+            RSDL.Flip(self.screen)
+        finally:
+            lltype.free(dstrect, flavor='raw')
+            lltype.free(paintrect, flavor='raw')
+        RSDL.FreeSurface(surface)
+        self.check("Half Red/Orange rectangle(150px * 50px) at the top left, 10 pixels from the border")
+
+    def teardown_method(self, meth):
+        RSDL.Quit()
+


More information about the pypy-commit mailing list