Commits

Maciej Fijalkowski committed 4493578 Merge

merge

Comments (0)

Files changed (26)

pypy/module/micronumpy/interp_boxes.py

 MIXIN_32 = (int_typedef,) if LONG_BIT == 32 else ()
 MIXIN_64 = (int_typedef,) if LONG_BIT == 64 else ()
 
+
 def new_dtype_getter(name):
     def _get_dtype(space):
         from pypy.module.micronumpy.interp_dtype import get_dtype_cache
         return getattr(get_dtype_cache(space), "w_%sdtype" % name)
+
     def new(space, w_subtype, w_value):
         dtype = _get_dtype(space)
         return dtype.itemtype.coerce_subtype(space, w_subtype, w_value)
     return func_with_new_name(new, name + "_box_new"), staticmethod(_get_dtype)
 
+
 class PrimitiveBox(object):
     _mixin_ = True
 
     def convert_to(self, dtype):
         return dtype.box(self.value)
 
+
 class W_GenericBox(Wrappable):
     _attrs_ = ()
 
     def _binop_right_impl(ufunc_name):
         def impl(self, space, w_other, w_out=None):
             from pypy.module.micronumpy import interp_ufuncs
-            return getattr(interp_ufuncs.get(space), ufunc_name).call(space, 
+            return getattr(interp_ufuncs.get(space), ufunc_name).call(space,
                                                             [w_other, self, w_out])
         return func_with_new_name(impl, "binop_right_%s_impl" % ufunc_name)
 
         w_remainder = self.descr_rmod(space, w_other)
         return space.newtuple([w_quotient, w_remainder])
 
+    def descr_hash(self, space):
+        return space.hash(self.item(space))
+
     def item(self, space):
         return self.get_dtype(space).itemtype.to_builtin_type(space, self)
 
     __abs__ = interp2app(W_GenericBox.descr_abs),
     __invert__ = interp2app(W_GenericBox.descr_invert),
 
+    __hash__ = interp2app(W_GenericBox.descr_hash),
+
     tolist = interp2app(W_GenericBox.item),
 )
 
     __module__ = "numpypy",
     __new__ = interp2app(W_UnicodeBox.descr__new__unicode_box.im_func),
 )
-                                          
+

pypy/module/micronumpy/interp_numarray.py

         return self.getitem(offset).convert_to(longdtype).item(
             space)
 
+    @jit.unroll_safe
     def descr_item(self, space, w_arg=None):
         if space.is_w(w_arg, space.w_None):
             if isinstance(self, Scalar):

pypy/module/micronumpy/test/test_dtypes.py

 
         a = array(range(10), dtype=int64)
         b = array([0] * 10, dtype=int64)
-        for idx in b: a[idx] += 1
+        for idx in b:
+            a[idx] += 1
 
-    def test_hash_int8(self):
-        from _numpypy import int8
+    def test_hash(self):
+        import _numpypy as numpy
+        for tp, value in [
+            (numpy.int8, 4),
+            (numpy.int16, 5),
+            (numpy.uint32, 7),
+            (numpy.int64, 3),
+            (numpy.float32, 2.0),
+            (numpy.float64, 4.32),
+        ]:
+            assert hash(tp(value)) == hash(value)
 
-        hash(int8(0))
-        d = {int8(5):99}
 
-    def test_hash_int16(self):
-        from _numpypy import int16
-
-        hash(int16(0))
-        d = {int16(99):42}
-
-    def test_hash_int32(self):
-        from _numpypy import int32
-
-        hash(int32(0))
-        d = {int32(5):99}
-
-    def test_hash_int64(self):
-        from _numpypy import int64
-
-        hash(int64(0))
-        d = {int64(99):42}
-
-class AppTestTypes(BaseNumpyAppTest):    
+class AppTestTypes(BaseNumpyAppTest):
     def test_abstract_types(self):
         import _numpypy as numpy
         raises(TypeError, numpy.generic, 0)
     def test_various_types(self):
         import _numpypy as numpy
         import sys
-        
+
         assert numpy.int16 is numpy.short
         assert numpy.int8 is numpy.byte
         assert numpy.bool_ is numpy.bool8
 
     def test_mro(self):
         import _numpypy as numpy
-        
+
         assert numpy.int16.__mro__ == (numpy.int16, numpy.signedinteger,
                                        numpy.integer, numpy.number,
                                        numpy.generic, object)
 class AppTestStrUnicodeDtypes(BaseNumpyAppTest):
     def test_str_unicode(self):
         from _numpypy import str_, unicode_, character, flexible, generic
-        
+
         assert str_.mro() == [str_, str, basestring, character, flexible, generic, object]
         assert unicode_.mro() == [unicode_, unicode, basestring, character, flexible, generic, object]
 
         from _numpypy import dtype
         d = dtype({'names': ['a', 'b', 'c'],
                    })
-        
+
 class AppTestNotDirect(BaseNumpyAppTest):
     def setup_class(cls):
         BaseNumpyAppTest.setup_class.im_func(cls)

pypy/module/micronumpy/types.py

 from pypy.tool.sourcetools import func_with_new_name
 from pypy.rlib import jit
 
+
 VOID_STORAGE = lltype.Array(lltype.Char, hints={'nolength': True,
                                                 'render_as_void': True})
 degToRad = math.pi / 180.0
 log2 = math.log(2)
-log2e = 1./log2
+log2e = 1. / log2
+
 
 def simple_unary_op(func):
     specialize.argtype(1)(func)
 
 class BaseType(object):
     _attrs_ = ()
-    
+
     def _unimplemented_ufunc(self, *args):
         raise NotImplementedError
 
                                  width, storage, i, offset, value)
         else:
             libffi.array_setitem_T(self.T, width, storage, i, offset, value)
-        
+
 
     def store(self, arr, width, i, offset, box):
         self._write(arr.storage, width, i, offset, self.unbox(box))
 
 class NonNativePrimitive(Primitive):
     _mixin_ = True
-    
+
     def _read(self, storage, width, i, offset):
         if we_are_translated():
             res = libffi.array_getitem(clibffi.cast_type_to_ffitype(self.T),
 
     T = rffi.LONGLONG
     BoxType = interp_boxes.W_Int64Box
-    format_code = "q"    
+    format_code = "q"
 
     _coerce = func_with_new_name(_int64_coerce, '_coerce')
 
 
     T = rffi.FLOAT
     BoxType = interp_boxes.W_Float32Box
-    format_code = "f"    
+    format_code = "f"
 
 class Float64(BaseType, Float):
     _attrs_ = ()
 
 class BaseStringType(object):
     _mixin_ = True
-    
+
     def __init__(self, size=0):
         self.size = size
 
 
     def get_element_size(self):
         return self.size
-    
+
     def read(self, arr, width, i, offset, dtype=None):
         if dtype is None:
             dtype = arr.dtype
         return interp_boxes.W_VoidBox(arr, i + offset, dtype)
 
     @jit.unroll_safe
-    def coerce(self, space, dtype, w_item): 
+    def coerce(self, space, dtype, w_item):
         from pypy.module.micronumpy.interp_numarray import W_NDimArray
 
         if isinstance(w_item, interp_boxes.W_VoidBox):

pypy/rlib/rsdl/RIMG.py

-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 pypy.rlib.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)

pypy/rlib/rsdl/RMix.py

-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 pypy.rlib.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)

pypy/rlib/rsdl/RMix_helper.py

-from pypy.rpython.lltypesystem import lltype, rffi
-from pypy.rlib.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

pypy/rlib/rsdl/RSDL.py

-from pypy.rpython.lltypesystem import lltype, rffi
-from pypy.rpython.tool import rffi_platform as platform
-from pypy.rlib.rsdl.constants import _constants
-from pypy.rlib.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
-    
-    
-    

pypy/rlib/rsdl/RSDL_helper.py

-from pypy.rpython.lltypesystem import lltype, rffi
-from pypy.rlib.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')
-

pypy/rlib/rsdl/__init__.py

Empty file removed.

pypy/rlib/rsdl/constants.py

-
-_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",
-        ],
-    }

pypy/rlib/rsdl/eci.py

-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)

pypy/rlib/rsdl/macosx-sdl-main/SDLMain.h

-/*   SDLMain.m - main entry point for our Cocoa-ized SDL app
-       Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
-       Non-NIB-Code & other changes: Max Horn <max@quendi.de>
-
-    Feel free to customize this file to suit your needs
-*/
-
-#import <Cocoa/Cocoa.h>
-
-@interface SDLMain : NSObject
-@end

pypy/rlib/rsdl/macosx-sdl-main/SDLMain.m

-/*   SDLMain.m - main entry point for our Cocoa-ized SDL app
-       Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
-       Non-NIB-Code & other changes: Max Horn <max@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. */
-@interface NSApplication(SDL_Missing_Methods)
-- (void)setAppleMenu:(NSMenu *)menu;
-@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 */
-@interface NSString (ReplaceSubString)
-- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
-@end
-#endif
-
-@interface SDLApplication : NSApplication
-@end
-
-@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);
-}
-@end
-
-/* The main class of the application, the application's delegate */
-@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);
-}
-@end
-
-
-@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;
-}
-
-@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;
-}
-

pypy/rlib/rsdl/test/__init__.py

Empty file removed.

pypy/rlib/rsdl/test/applause.wav

Binary file removed.

pypy/rlib/rsdl/test/autopath.py

-"""
-self cloning, automatic path configuration 
-
-copy this into any subdirectory of pypy from which scripts need 
-to be run, typically all of the test subdirs. 
-The idea is that any such script simply issues
-
-    import autopath
-
-and this will make sure that the parent directory containing "pypy"
-is in sys.path. 
-
-If you modify the master "autopath.py" version (in pypy/tool/autopath.py) 
-you can directly run it which will copy itself on all autopath.py files
-it finds under the pypy root directory. 
-
-This module always provides these attributes:
-
-    pypydir    pypy root directory path 
-    this_dir   directory where this autopath.py resides 
-
-"""
-
-def __dirinfo(part):
-    """ return (partdir, this_dir) and insert parent of partdir
-    into sys.path.  If the parent directories don't have the part
-    an EnvironmentError is raised."""
-
-    import sys, os
-    try:
-        head = this_dir = os.path.realpath(os.path.dirname(__file__))
-    except NameError:
-        head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0]))
-
-    error = None
-    while head:
-        partdir = head
-        head, tail = os.path.split(head)
-        if tail == part:
-            checkfile = os.path.join(partdir, os.pardir, 'pypy', '__init__.py')
-            if not os.path.exists(checkfile):
-                error = "Cannot find %r" % (os.path.normpath(checkfile),)
-            break
-    else:
-        error = "Cannot find the parent directory %r of the path %r" % (
-            partdir, this_dir)
-    if not error:
-        # check for bogus end-of-line style (e.g. files checked out on
-        # Windows and moved to Unix)
-        f = open(__file__.replace('.pyc', '.py'), 'r')
-        data = f.read()
-        f.close()
-        if data.endswith('\r\n') or data.endswith('\r'):
-            error = ("Bad end-of-line style in the .py files. Typically "
-                     "caused by a zip file or a checkout done on Windows and "
-                     "moved to Unix or vice-versa.")
-    if error:
-        raise EnvironmentError("Invalid source tree - bogus checkout! " +
-                               error)
-    
-    pypy_root = os.path.join(head, '')
-    try:
-        sys.path.remove(head)
-    except ValueError:
-        pass
-    sys.path.insert(0, head)
-
-    munged = {}
-    for name, mod in sys.modules.items():
-        if '.' in name:
-            continue
-        fn = getattr(mod, '__file__', None)
-        if not isinstance(fn, str):
-            continue
-        newname = os.path.splitext(os.path.basename(fn))[0]
-        if not newname.startswith(part + '.'):
-            continue
-        path = os.path.join(os.path.dirname(os.path.realpath(fn)), '')
-        if path.startswith(pypy_root) and newname != part:
-            modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep)
-            if newname != '__init__':
-                modpaths.append(newname)
-            modpath = '.'.join(modpaths)
-            if modpath not in sys.modules:
-                munged[modpath] = mod
-
-    for name, mod in munged.iteritems():
-        if name not in sys.modules:
-            sys.modules[name] = mod
-        if '.' in name:
-            prename = name[:name.rfind('.')]
-            postname = name[len(prename)+1:]
-            if prename not in sys.modules:
-                __import__(prename)
-                if not hasattr(sys.modules[prename], postname):
-                    setattr(sys.modules[prename], postname, mod)
-
-    return partdir, this_dir
-
-def __clone():
-    """ clone master version of autopath.py into all subdirs """
-    from os.path import join, walk
-    if not this_dir.endswith(join('pypy','tool')):
-        raise EnvironmentError("can only clone master version "
-                               "'%s'" % join(pypydir, 'tool',_myname))
-
-
-    def sync_walker(arg, dirname, fnames):
-        if _myname in fnames:
-            fn = join(dirname, _myname)
-            f = open(fn, 'rwb+')
-            try:
-                if f.read() == arg:
-                    print "checkok", fn
-                else:
-                    print "syncing", fn
-                    f = open(fn, 'w')
-                    f.write(arg)
-            finally:
-                f.close()
-    s = open(join(pypydir, 'tool', _myname), 'rb').read()
-    walk(pypydir, sync_walker, s)
-
-_myname = 'autopath.py'
-
-# set guaranteed attributes
-
-pypydir, this_dir = __dirinfo('pypy')
-
-if __name__ == '__main__':
-    __clone()

pypy/rlib/rsdl/test/conftest.py

-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

pypy/rlib/rsdl/test/demo.jpg

Removed
Old image

pypy/rlib/rsdl/test/demo.png

Removed
Old image

pypy/rlib/rsdl/test/test_basic.py

-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()
-    

pypy/rlib/rsdl/test/test_sdl_image.py

-import py, os
-import autopath
-from pypy.rlib.rsdl import RSDL, RIMG, RSDL_helper
-from pypy.rpython.lltypesystem import lltype, rffi
-
-
-def test_load_image():
-    for filename in ["demo.jpg", "demo.png"]:
-        image = RIMG.Load(os.path.join(autopath.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(autopath.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

pypy/rlib/rsdl/test/test_sdl_mixer.py

-import py
-import os
-import time
-import autopath
-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()
-

pypy/rlib/rsdl/test/test_surface.py

-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()
-

pypy/rlib/rsdl/test/test_video.py

-
-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
-from pypy import conftest
-
-#
-#  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.
-#
-
-
-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')