Example #1
0
def get_caption():
    """ get_caption() -> (title, icontitle)
    Get the current window caption
    """
    title = ffi.new("char*[1]")
    icon = ffi.new("char*[1]")

    sdl.SDL_WM_GetCaption(title, icon)
    return ffi.string(title[0]), ffi.string(icon[0])
Example #2
0
def save_png(surf, filename):
    alpha = bool(surf.format.Amask)
    if get_sdl_byteorder() == sdl.SDL_LIL_ENDIAN:
        rmask, gmask, bmask, amask = 0xff, 0xff00, 0xff0000, 0xff000000
    else:
        rmask, gmask, bmask, amask = 0xff00, 0xff0000, 0xff, 0x000000ff
    ss_surf = sdl.SDL_CreateRGBSurface(sdl.SDL_SWSURFACE | sdl.SDL_SRCALPHA,
                                       surf.w, surf.h, 32 if alpha else 24,
                                       rmask, gmask, bmask, amask)
    if not ss_surf:
        return -1
    with opaque(surf):
        rect = ffi.new('SDL_Rect*')
        rect.w = surf.w
        rect.h = surf.h
        sdl.SDL_BlitSurface(surf, rect, ss_surf, ffi.NULL)

    ss_rows = ffi.new('unsigned char*[]', surf.h)
    ss_pixels = ffi.cast('unsigned char*', ss_surf.pixels)
    for i in range(surf.h):
        ss_rows[i] = ss_pixels + i * ss_surf.pitch
    err_msg = ffi.new('char**')
    result = pnglib.write_png(filename, ss_rows, surf.w, surf.h,
                              (pnglib.PNG_COLOR_TYPE_RGB_ALPHA if alpha else
                               pnglib.PNG_COLOR_TYPE_RGB), 8, err_msg)

    sdl.SDL_FreeSurface(ss_surf)
    if result == -1:
        raise IOError("PNGError: %s" % ffi.string(err_msg[0]))
    return result
Example #3
0
def load(filename, namehint=""):
    try:
        filename = rwops_encode_file_path(filename)
        c_surface = sdl.IMG_Load(filename)
    except SDLError:
        # filename is not a string, try as file object
        try:
            rwops = rwops_from_file(filename)
            if namehint:
                name, ext = path.splitext(namehint)
            elif hasattr(filename, 'name'):
                name, ext = path.splitext(filename.name)
            else:
                # No name info, so we pass an empty extension to
                # SDL to indicate we can only load files with
                # suitable magic format markers in the file.
                name, ext = '', ''
            if len(ext) == 0:
                ext = name
            ext = rwops_encode_file_path(ext)
            c_surface = sdl.IMG_LoadTyped_RW(rwops, 1, ext)
        except TypeError:
            raise TypeError("file argument must be a valid path "
                            "string or file object")
    if not c_surface:
        raise SDLError(ffi.string(sdl.IMG_GetError()))
    return Surface._from_sdl_surface(c_surface)
Example #4
0
def save_jpg(surf, filename):
    if (surf.format.BytesPerPixel == 3
            and not (surf.flags & sdl.SDL_SRCALPHA)
            and surf.format.Rshift == 0):
        ss_surf = surf
    else:
        if get_sdl_byteorder() == sdl.SDL_LIL_ENDIAN:
            rmask, gmask, bmask, amask = 0xff, 0xff00, 0xff0000, 0xff000000
        else:
            rmask, gmask, bmask, amask = 0xff00, 0xff, 0xff0000, 0xff000000
        ss_surf = sdl.SDL_CreateRGBSurface(sdl.SDL_SWSURFACE, surf.w, surf.h,
                                           24, rmask, gmask, bmask, amask)
        if not ss_surf:
            return -1
        rect = ffi.new('SDL_Rect*')
        rect.w = surf.w
        rect.h = surf.h
        sdl.SDL_BlitSurface(surf, rect, ss_surf, ffi.NULL)

    ss_rows = ffi.new('unsigned char*[]', surf.h)
    ss_pixels = ffi.cast('unsigned char*', ss_surf.pixels)
    for i in range(surf.h):
        ss_rows[i] = ss_pixels + i * ss_surf.pitch
    err_msg = ffi.new('char**')
    result = jpglib.write_jpeg(filename, ss_rows, surf.w, surf.h, 85, err_msg)

    if ss_surf is not surf:
        sdl.SDL_FreeSurface(ss_surf)
    if result == -1:
        raise IOError("JPGError: %s" % ffi.string(err_msg[0]))
    return result
Example #5
0
    def render(self, text, antialias, color, background=None):
        """Font.render(text, antialias, color, background=None): return Surface
           draw text on a new Surface"""
        color = Color(color)
        fg = ffi.new("SDL_Color [1]")
        bg = ffi.new("SDL_Color [1]")
        fg[0].r = color.r
        fg[0].g = color.g
        fg[0].b = color.b
        if background:
            try:
                background = Color(background)
                bg[0].r = background.r
                bg[0].g = background.g
                bg[0].b = background.b
            except (TypeError, ValueError):
                # Same error behaviour as pygame
                bg[0].r = 0
                bg[0].g = 0
                bg[0].b = 0
        else:
            bg[0].r = 0
            bg[0].g = 0
            bg[0].b = 0

        if text is None or text == "":
            # Just return a surface of width 1 x font height
            height = sdl.TTF_FontHeight(self._sdl_font)
            surf = Surface((1, height))
            if background and isinstance(background, Color):
                surf.fill(background)
            else:
                # clear the colorkey
                surf.set_colorkey(flags=sdl.SDL_SRCCOLORKEY)
            return surf

        if not isinstance(text, basestring):
            raise TypeError("text must be a string or unicode")
        if "\x00" in text:
            raise ValueError("A null character was found in the text")
        if isinstance(text, unicode):
            text = text.encode("utf-8", "replace")
            if utf_8_needs_UCS_4(text):
                raise UnicodeError("A Unicode character above '\\uFFFF' was found;" " not supported")
        if antialias:
            if background is None:
                sdl_surf = sdl.TTF_RenderUTF8_Blended(self._sdl_font, text, fg[0])
            else:
                sdl_surf = sdl.TTF_RenderUTF8_Shaded(self._sdl_font, text, fg[0], bg[0])
        else:
            sdl_surf = sdl.TTF_RenderUTF8_Solid(self._sdl_font, text, fg[0])
        if not sdl_surf:
            raise SDLError(ffi.string(sdl.TTF_GetError()))
        surf = Surface._from_sdl_surface(sdl_surf)
        if not antialias and background is not None:
            surf.set_colorkey()
            surf.set_palette([(bg[0].r, bg[0].g, bg[0].b)])
        return surf
Example #6
0
def get_driver():
    """ get_driver() -> name
    Get the name of the pygame display backend
    """
    check_video()

    buffer_len = 256
    buf = ffi.new('char[]', buffer_len)
    if not sdl.SDL_VideoDriverName(buf, buffer_len):
        return None
    return ffi.string(buf)
Example #7
0
    def size(self, text):
        """Font.size(text): return (width, height)
           determine the amount of space needed to render text"""
        if not isinstance(text, (bytes_, unicode_)):
            raise TypeError("text must be a string or unicode")
        if isinstance(text, unicode_):
            text = text.encode('utf-8', 'replace')
        w = ffi.new("int*")
        h = ffi.new("int*")
        ecode = sdl.TTF_SizeUTF8(self._sdl_font, text, w, h)
        if ecode == -1:
            raise SDLError(ffi.string(sdl.TTF_GetError()))

        return int(w[0]), int(h[0])
Example #8
0
def load(filename, namehint=""):
    try:
        filename = rwops_encode_file_path(filename)
        c_surface = sdl.IMG_Load(filename)
    except SDLError:
        # filename is not a string, try as file object
        try:
            rwops = rwops_from_file(filename)
            if namehint:  
                name, ext = path.splitext(namehint)
            else:
                name, ext = path.splitext(filename.name)
            if len(ext) == 0:
                ext = name
            c_surface = sdl.IMG_LoadTyped_RW(rwops, 1, ext)
        except TypeError:
            raise TypeError("file argument must be a valid path "
                            "string or file object")
    if not c_surface:
        raise SDLError(ffi.string(sdl.IMG_GetError()))
    return Surface._from_sdl_surface(c_surface)
Example #9
0
 def get_name(self):
     """ get_name() -> string
     get the Joystick system name
     """
     return ffi.string(sdl.SDL_JoystickName(self._id))
Example #10
0
    def __init__(self, sdlevent, d=None, **kwargs):
        self._sdlevent = sdlevent
        if isinstance(sdlevent, int):
            # User specificed event with kwargs
            self.type = sdlevent
            # XXX: Pygame manipulates __dict__, we're currently don't
            # this causes a failure in test_Event
            if d:
                self._dict = d.copy()
            else:
                self._dict = {}
            if kwargs:
                self._dict.update(kwargs)
            for attr, value in self._dict.items():
                setattr(self, attr, value)
            return
        if not sdlevent:
            self.type = sdl.SDL_NOEVENT
            return
        self.type = self._sdlevent.type

        if (sdlevent.user.code == int(_USEROBJECT_CHECK1) and
                sdlevent.user.data1 == _USEROBJECT_CHECK2):
            eventkey = ffi.cast("SDL_Event *", sdlevent.user.data2)
            if eventkey in _user_events:
                self._dict = _user_events[eventkey]._dict
                del _user_events[eventkey]
                for attr, value in self._dict.items():
                    setattr(self, attr, value)
                return
            raise NotImplementedError("TODO: Error handling for user-posted events.")

        if self.type == ACTIVEEVENT:
            self.gain = sdlevent.active.gain
            self.state = sdlevent.active.state

        elif self.type == KEYDOWN:
            self.unicode = sdlevent.key.keysym.unicode
            self.key = sdlevent.key.keysym.sym
            self.mod = sdlevent.key.keysym.mod
            self.scancode = sdlevent.key.keysym.scancode
        elif self.type == KEYUP:
            self.key = sdlevent.key.keysym.sym
            self.mod = sdlevent.key.keysym.mod
            self.scancode = sdlevent.key.keysym.scancode

        elif self.type == MOUSEMOTION:
            self.pos = (sdlevent.motion.x, sdlevent.motion.y)
            self.rel = (sdlevent.motion.xrel, sdlevent.motion.yrel)
            self.buttons = (_button_state(sdlevent.motion.state, 1),
                            _button_state(sdlevent.motion.state, 2),
                            _button_state(sdlevent.motion.state, 3))
        elif self.type in (MOUSEBUTTONDOWN, MOUSEBUTTONUP):
            self.pos = (sdlevent.button.x, sdlevent.button.y)
            self.button = sdlevent.button.button

        elif self.type == JOYAXISMOTION:
            self.joy = sdlevent.jaxis.which
            self.axis = sdlevent.jaxis.axis
            self.value = sdlevent.jaxis.value / 32767.0
        elif self.type == JOYBALLMOTION:
            self.joy = sdlevent.jball.which
            self.ball = sdlevent.jball.ball
            self.rel = (sdlevent.jball.xrel, sdlevent.jball.yrel)
        elif self.type == JOYHATMOTION:
            self.joy = sdlevent.jhat.which
            self.hat = sdlevent.jhat.hat
            hx = hy = 0
            if sdlevent.jhat.value & sdl.SDL_HAT_UP:
                hy = 1
            elif sdlevent.jhat.value & sdl.SDL_HAT_DOWN:
                hy = -1
            if sdlevent.jhat.value & sdl.SDL_HAT_RIGHT:
                hx = 1
            elif sdlevent.jhat.value & sdl.SDL_HAT_LEFT:
                hx = -1
            self.value = (hx, hy)
        elif self.type in (JOYBUTTONUP, JOYBUTTONDOWN):
            self.joy = sdlevent.jbutton.which
            self.button = sdlevent.jbutton.button

        elif self.type == VIDEORESIZE:
            self.size = (sdlevent.resize.w, sdlevent.resize.h)
            self.w = sdlevent.resize.w
            self.h = sdlevent.resize.h

        elif self.type == SYSWMEVENT:
            raise NotImplementedError("SYSWMEVENT not properly supported yet.")

        elif self.type in (VIDEOEXPOSE, QUIT):
            pass  # No attributes here.

        elif USEREVENT <= self.type < NUMEVENTS:
            self.code = sdlevent.user.code
            if self.type == USEREVENT and sdlevent.user.code == USEREVENT_DROPFILE:
                # mirrors what pygame does - not sure if correct
                self.filename = ffi.string(sdlevent.user.data1)
                sdl.free(sdlevent.user.data1)
                sdlevent.user.data1 = ffi.NULL
Example #11
0
def name(key):
    """ name(key) -> string
    get the name of a key identifier
    """
    return ffi.string(sdl.SDL_GetKeyName(int(key)))
Example #12
0
def get_error():
    err = ffi.string(sdl.SDL_GetError())
    if not isinstance(err, str):
        return err.decode('utf8')
    return err
Example #13
0
 def from_sdl_error(cls):
     return cls(ffi.string(sdl.SDL_GetError()))
Example #14
0
def get_error():
    return ffi.string(sdl.SDL_GetError())